|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace SilverStripe\CMS\Forms; |
|
4
|
|
|
|
|
5
|
|
|
use Page; |
|
6
|
|
|
use SilverStripe\Control\HTTPRequest; |
|
7
|
|
|
use SilverStripe\Forms\TextField; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* Assists with selecting anchors on a given page |
|
11
|
|
|
*/ |
|
12
|
|
|
class AnchorSelectorField extends TextField |
|
13
|
|
|
{ |
|
14
|
|
|
protected $schemaComponent = 'AnchorSelectorField'; |
|
15
|
|
|
|
|
16
|
|
|
private static $allowed_actions = [ |
|
|
|
|
|
|
17
|
|
|
'anchors', |
|
18
|
|
|
]; |
|
19
|
|
|
|
|
20
|
|
|
private static $url_handlers = [ |
|
|
|
|
|
|
21
|
|
|
'anchors/$PageID' => 'anchors', |
|
22
|
|
|
]; |
|
23
|
|
|
|
|
24
|
|
|
public function getSchemaDataDefaults() |
|
25
|
|
|
{ |
|
26
|
|
|
$schema = parent::getSchemaDataDefaults(); |
|
27
|
|
|
$schema['data']['endpoint'] = $this->Link('anchors/:id'); |
|
28
|
|
|
return $schema; |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* Find all anchors available on the given page. |
|
33
|
|
|
* |
|
34
|
|
|
* @param HTTPRequest $request |
|
35
|
|
|
* @return array |
|
36
|
|
|
*/ |
|
37
|
|
|
public function anchors(HTTPRequest $request) |
|
|
|
|
|
|
38
|
|
|
{ |
|
39
|
|
|
$id = (int)$this->getRequest()->param('PageID'); |
|
40
|
|
|
$anchors = $this->getAnchorsInPage($id); |
|
41
|
|
|
return json_encode($anchors); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
/** |
|
45
|
|
|
* Get anchors in the given page ID |
|
46
|
|
|
* |
|
47
|
|
|
* @param int $id |
|
48
|
|
|
* @return array |
|
49
|
|
|
*/ |
|
50
|
|
|
protected function getAnchorsInPage($id) |
|
51
|
|
|
{ |
|
52
|
|
|
// Check page is accessible |
|
53
|
|
|
$page = Page::get()->byID($id); |
|
54
|
|
|
if (!$page || !$page->canView()) { |
|
55
|
|
|
return []; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
// Similar to the regex found in HtmlEditorField.js / getAnchors method. |
|
59
|
|
|
$parseSuccess = preg_match_all( |
|
60
|
|
|
"/\\s+(name|id)\\s*=\\s*([\"'])([^\\2\\s>]*?)\\2|\\s+(name|id)\\s*=\\s*([^\"']+)[\\s +>]/im", |
|
61
|
|
|
$page->Content, |
|
62
|
|
|
$matches |
|
63
|
|
|
); |
|
64
|
|
|
if (!$parseSuccess) { |
|
65
|
|
|
return []; |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
// Cleanup results |
|
69
|
|
|
return array_values(array_unique(array_filter(array_merge($matches[3], $matches[5])))); |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
|