protected function taskCopy()
{
if (!$this->authorizeTask('copy page', ['admin.pages', 'admin.super'])) {
return false;
}
// Only applies to pages.
if ($this->view != 'pages') {
return false;
}
try {
/** @var Pages $pages */
$pages = $this->grav['pages'];
// Get the current page.
$original_page = $this->admin->page(true);
// Find new parent page in order to build the path.
$parent = $original_page->parent() ?: $pages->root();
// Make a copy of the current page and fill the updated information into it.
$page = $original_page->copy($parent);
$order = 0;
if ($page->order()) {
$order = $this->getNextOrderInFolder($page->parent()->path());
}
$this->preparePage($page);
// Make sure the header is loaded in case content was set through raw() (expert mode)
$page->header();
if ($page->order()) {
$page->order($order);
}
$folder = $this->findFirstAvailable('folder', $page);
$slug = $this->findFirstAvailable('slug', $page);
$page->path($page->parent()->path() . DS . $page->order() . $folder);
$page->route($page->parent()->route() . '/' . $slug);
$page->rawRoute($page->parent()->rawRoute() . '/' . $slug);
// Append progressive number to the copied page title
$match = preg_split('/(\\d+)(?!.*\\d)/', $original_page->title(), 2, PREG_SPLIT_DELIM_CAPTURE);
$header = $page->header();
if (!isset($match[1])) {
$header->title = $match[0] . ' 2';
} else {
$header->title = $match[0] . ((int) $match[1] + 1);
}
$page->header($header);
$page->save(false);
$redirect = $this->view . $page->rawRoute();
$header = $page->header();
if (isset($header->slug)) {
$match = preg_split('/-(\\d+)$/', $header->slug, 2, PREG_SPLIT_DELIM_CAPTURE);
$header->slug = $match[0] . '-' . (isset($match[1]) ? (int) $match[1] + 1 : 2);
}
$page->header($header);
$page->save();
$this->grav->fireEvent('onAdminAfterSave', new Event(['page' => $page]));
// Enqueue message and redirect to new location.
$this->admin->setMessage($this->admin->translate('PLUGIN_ADMIN.SUCCESSFULLY_COPIED'), 'info');
$this->setRedirect($redirect);
} catch (\Exception $e) {
throw new \RuntimeException('Copying page failed on error: ' . $e->getMessage());
}
return true;
}