Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,8 @@ Capture groups are just used by the standard $1, $2, ect. within your "Redirect

**Redirect To:** "shop$1"

*Note, we do not include the "/" because it will be part of the capture group*
*Note, we do not include the "/" because it will be part of the capture group*

#### Import by CSV
Multiple records can be imported by generating a CSV of redirects.
See 'example.csv' for a starting point.
2 changes: 2 additions & 0 deletions example.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
uri-to-match,/location-to-redirect-to,302
another-uri-to-match,/another-location-to-redirect-to,301
4 changes: 3 additions & 1 deletion redirectmanager/RedirectManagerPlugin.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@ public function registerCpRoutes()
{
return array(
'redirectmanager\/new' => 'redirectmanager/_edit',
'redirectmanager\/(?P<redirectId>\d+)' => 'redirectmanager/_edit'
'redirectmanager\/(?P<redirectId>\d+)' => 'redirectmanager/_edit',
'redirectmanager\/import' => 'redirectmanager/_import',
'redirectmanager\/import/report' => 'redirectmanager/_import-report',
);
}
public function onAfterInstall()
Expand Down
31 changes: 28 additions & 3 deletions redirectmanager/controllers/RedirectManagerController.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,40 @@ public function actionSaveRedirect()
}
}

public function actionImportRedirects()
{
$this->requirePostRequest();

$csvData = craft()->request->getPost('redirectRecord')['csv'];

try {
$arrRedirects = craft()->redirectManager->processCSV($csvData);

$arrResult = craft()->redirectManager->saveRedirects($arrRedirects);

// Save the output to the session
craft()->httpSession->add('redirectmanager.result', $arrResult);

} catch (Exception $e) {

craft()->userSession->setError(Craft::t($e->getMessage()));

return $this->redirect('redirectmanager/import');
}

return $this->redirect('redirectmanager/import/report');

}

public function actionDeleteRedirect()
{

$this->requirePostRequest();
$this->requireAjaxRequest();

$id = craft()->request->getRequiredPost('id');
craft()->redirectManager->deleteRedirectById($id);

$this->returnJson(array('success' => true));
}
}
75 changes: 74 additions & 1 deletion redirectmanager/services/RedirectManagerService.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,20 @@ public function processRedirect($uri)
return (isset($redirectLocation)) ? array("url" => ( strpos($record['location'], "http") === 0 ) ? $redirectLocation : UrlHelper::getSiteUrl($redirectLocation), "type" => $record['type']) : false;
}

public function processCSV($csv)
{
if ($csv == '') {
throw new Exception('The CSV data appears to be missing.');
}
// Replace newlines with commas
$results = preg_replace("/[\n\r]+/", ',', $csv);

// Parse the CSV file and split into an associative array
$results = array_chunk(str_getcsv($results, ','), 3);

return $results;
}

public function newRedirect($attributes = array())
{
$model = new RedirectManagerModel();
Expand Down Expand Up @@ -101,12 +115,71 @@ public function saveRedirect(RedirectManagerModel &$model)
}
}

public function saveRedirects($arrRedirects)
{
// Loop through and save (track the outcome for each record)
$arrResult = [
'success' => [],
'failed' => []
];

foreach ($arrRedirects as $redirect) {

$model = $this->newRedirect([
'uri' => $redirect[0],
'location' => $redirect[1],
'type' => $redirect[2]
]);

if ($this->saveRedirect($model)) {
$arrResult['success'][] = $redirect;
} else {
if ($this->recordExistsAndShouldOverwrite($model)) {

$record = $this->findByAttributes(['uri' => $model->getAttribute('uri')]);

$model->setAttribute('id', $record->getAttribute('id'));

if ($this->saveRedirect($model)) {
$arrResult['success'][] = $redirect;
} else {
$redirect['failureMessageArray'] = $model->getErrors();
$arrResult['failed'][] = $redirect;
}
} else {
$redirect['failureMessageArray'] = $model->getErrors();
$arrResult['failed'][] = $redirect;
}
}


}

return $arrResult;

}

public function deleteRedirectById($id)
{
return $this->redirectRecord->deleteByPk($id);
}

private function _processRegexMatch($uriToMatch, $uri)
public function findByAttributes($attributes,$condition='',$params=array())
{
return $this->redirectRecord->findByAttributes($attributes, $condition, $params);
}

/**
* @param $model
*
* @return bool
*/
public function recordExistsAndShouldOverwrite($model)
{
return ($model->getError('uri') != null && craft()->request->getPost('redirectRecord')['overwrite']);
}

private function _processRegexMatch($uriToMatch, $uri)
{
preg_match("/^#(.+)#$/", $uriToMatch, $matches);
// return ($matches[1] == $uri) ;
Expand Down
118 changes: 118 additions & 0 deletions redirectmanager/templates/_import-report.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
{% extends "_layouts/cp" %}
{% import "_includes/forms" as forms %}

{% set redirectId = null %}
{% set redirectRecord = (redirectId) ? craft.redirectManager.getRedirectById(redirectId) : null %}

{% if redirectId and not redirectRecord %}
{% exit 404 %}
{% endif %}

{% set title = "Import Report"|t %}
{% set crumbs = [
{ label: "Redirect Manager"|t, url: url('redirectmanager') },
{ label: "Importer"|t, url: url('redirectmanager/import') }
] %}



{% set content %}
<style>
.msg--success {
color: #32bd2f;
}

.msg--failed {
color: #990000;
}

.table__container {
border-spacing: 1em 0.5em;
width: 100%;
}

.table__col--uri,
.table__col--location,
.table__col--type,
.table__col--reason {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}

.table__col--uri,
.table__col--location {
width: 40%;
max-width: 50px;
}

.table__col--type {
max-width: 5%;
}

.table__col--reason {
max-width: 15%;
}
</style>
{% set arrSuccess = craft.redirectManager.getImportResultSuccess %}
{% set arrFailed = craft.redirectManager.getImportResultFailed %}
<ul>
<li class="msg--success"><strong>{{ arrSuccess | length }}</strong> records imported successfully</li>
<li class="msg--failed"><strong>{{ arrFailed | length }}</strong> records failed to import</li>
</ul>
{% if arrSuccess | length %}
<h2>Redirects imported successfully</h2>
<table class="table__container">
<thead>
<tr>
<th>URI</th>
<th>Location</th>
<th>Type</th>
<th>&nbsp;</th>
</tr>
</thead>
{% for result in arrSuccess %}
<tr>
<td class="table__col--uri" title="{{ result[0] }}">{{ result[0] }}</td>
<td class="table__col--location" title="{{ result[1] }}">{{ result[1] }}</td>
<td class="table__col--type">{{ result[2] }}</td>
<td class="table__col--reason">&nbsp;</td>
</tr>

{% endfor %}
</table>
{% endif %}
{% if arrFailed | length %}
<h2>Redirects failed</h2>
<table class="table__container">
<thead>
<tr>
<th>URI</th>
<th>Location</th>
<th>Type</th>
<th>Reason</th>
</tr>
</thead>
{% for result in arrFailed %}
<tr>
<td class="table__col--uri" title="{{ result[0] }}">{{ result[0] }}</td>
<td class="table__col--location" title="{{ result[1] }}">{{ result[1] }}</td>
<td class="table__col--type">{{ result[2] }}</td>
<td class="table__col--reason">
{% for block in result['failureMessageArray'] %}
{%for error in block|keys %}
{% if error == 'uri' %}
The URI already exists
{% endif %}
{% endfor %}
{% endfor %}
</td>
</tr>

{% endfor %}
</table>
{% endif %}
<div class="buttons">
<a href="{{ url('redirectmanager') }}" class="btn">{{ "Finished"|t }}</a>
</div>
{% endset %}
62 changes: 62 additions & 0 deletions redirectmanager/templates/_import.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
{% extends "_layouts/cp" %}
{% import "_includes/forms" as forms %}

{% set redirectId = null %}
{% set redirectRecord = (redirectId) ? craft.redirectManager.getRedirectById(redirectId) : null %}

{% if redirectId and not redirectRecord %}
{% exit 404 %}
{% endif %}

{% set title = "Import Redirects"|t %}
{% set crumbs = [
{ label: "Redirect Manager"|t, url: url('redirectmanager') }
] %}



{% set content %}

<div class="">
<h2>Instructions</h2>
<p>
Your CSV data should be in the following format:<br>
</p>
<pre style="font-family: Courier">uri-to-match,/location-to-redirect-to,redirect type (301 or 302)
another-uri-to-match,/another-location-to-redirect-to,301
</pre>
</div>

<form method="post" action="" accept-charset="UTF-8" enctype="multipart/form-data">
{{ getCsrfInput() }}
<input type="hidden" name="action" value="redirectManager/importRedirects" />
<input type="hidden" name="redirect" value="redirectmanager" />

<p>
{{ forms.textareaField({
label: 'CSV Data'|t,
required: true,
name: 'redirectRecord[csv]',
value: redirectRecord ? redirectRecord.csv : null,
errors: redirectRecord ? redirectRecord.errors('csv') : null,
instructions: "Paste your CSV data here",
rows: 20,
}) }}
</p>
<p>
{{ forms.lightswitchField({
label: 'Replace Matching Records?'|t,
required: true,
name: 'redirectRecord[overwrite]',
value: redirectRecord ? redirectRecord.overwrite : null,
errors: redirectRecord ? redirectRecord.errors('overwrite') : null,
instructions: "Do you want to overwrite an existing record if the URI matches?",
}) }}
</p>

<div class="buttons">
<input type="submit" class="btn submit" value="{{ 'Import'|t }}">
</div>
</form>

{% endset %}
1 change: 1 addition & 0 deletions redirectmanager/templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@

<div class="buttons">
<a href="{{ url('redirectmanager/new') }}" class="btn add icon">{{ "New Redirect"|t }}</a>
<a href="{{ url('redirectmanager/import') }}" class="btn add icon">{{ "Import Redirect CSV"|t }}</a>
</div>

{% endset %}
Expand Down
11 changes: 10 additions & 1 deletion redirectmanager/variables/RedirectManagerVariable.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,14 @@ public function getRedirectById($id)
{
return craft()->redirectManager->getRedirectById($id);
}


public function getImportResultSuccess()
{
return craft()->httpSession->get('redirectmanager.result')['success'];
}

public function getImportResultFailed()
{
return craft()->httpSession->get('redirectmanager.result')['failed'];
}
}