Completed
Pull Request — master (#1574)
by Damian
03:03
created

SiteTreeLinkTracking::getParser()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace SilverStripe\CMS\Model;
4
5
/**
6
 * @package cms
7
 * @subpackage model
8
 */
9
10
use DOMElement;
11
use SilverStripe\ORM\ManyManyList;
12
use SilverStripe\ORM\Versioning\Versioned;
13
use SilverStripe\ORM\FieldType\DBHTMLText;
14
use SilverStripe\ORM\DataExtension;
15
use SilverStripe\ORM\DataObject;
16
use Injector;
17
use SS_HTMLValue;
18
use Director;
19
20
/**
21
 * Adds tracking of links in any HTMLText fields which reference SiteTree or File items.
22
 *
23
 * Attaching this to any DataObject will add four fields which contain all links to SiteTree and File items
24
 * referenced in any HTMLText fields, and two booleans to indicate if there are any broken links. Call
25
 * augmentSyncLinkTracking to update those fields with any changes to those fields.
26
 *
27
 * Note that since both SiteTree and File are versioned, LinkTracking and ImageTracking will
28
 * only be enabled for the Stage record.
29
 *
30
 * {@see SiteTreeFileExtension} for the extension applied to {@see File}
31
 *
32
 * @property SiteTree $owner
33
 *
34
 * @property bool $HasBrokenFile
35
 * @property bool $HasBrokenLink
36
 *
37
 * @method ManyManyList LinkTracking() List of site pages linked on this page.
38
 * @method ManyManyList ImageTracking() List of Images linked on this page.
39
 * @method ManyManyList BackLinkTracking List of site pages that link to this page.
40
 */
41
class SiteTreeLinkTracking extends DataExtension {
42
43
	/**
44
	 * @var SiteTreeLinkTracking_Parser
45
	 */
46
	protected $parser;
47
48
	/**
49
	 * Inject parser for each page
50
	 *
51
	 * @var array
52
	 * @config
53
	 */
54
	private static $dependencies = array(
55
		'Parser' => '%$SiteTreeLinkTracking_Parser'
56
	);
57
58
	/**
59
	 * Parser for link tracking
60
	 *
61
	 * @return SiteTreeLinkTracking_Parser
62
	 */
63
	public function getParser() {
64
		return $this->parser;
65
	}
66
67
	/**
68
	 * @param SiteTreeLinkTracking_Parser $parser
69
	 * @return $this
70
	 */
71
	public function setParser($parser) {
72
		$this->parser = $parser;
73
		return $this;
74
	}
75
76
	private static $db = array(
77
		"HasBrokenFile" => "Boolean",
78
		"HasBrokenLink" => "Boolean"
79
	);
80
81
	private static $many_many = array(
82
		"LinkTracking" => "SilverStripe\\CMS\\Model\\SiteTree",
83
		"ImageTracking" => "File"  // {@see SiteTreeFileExtension}
84
	);
85
86
	private static $belongs_many_many = array(
87
		"BackLinkTracking" => "SilverStripe\\CMS\\Model\\SiteTree.LinkTracking"
88
	);
89
90
	/**
91
	 * Tracked images are considered owned by this page
92
	 *
93
	 * @config
94
	 * @var array
95
	 */
96
	private static $owns = array(
97
		"ImageTracking"
98
	);
99
100
	private static $many_many_extraFields = array(
101
		"LinkTracking" => array("FieldName" => "Varchar"),
102
		"ImageTracking" => array("FieldName" => "Varchar")
103
	);
104
105
	/**
106
	 * Scrape the content of a field to detect anly links to local SiteTree pages or files
107
	 *
108
	 * @param string $fieldName The name of the field on {@link @owner} to scrape
109
	 */
110
	public function trackLinksInField($fieldName) {
111
		$record = $this->owner;
112
113
		$linkedPages = array();
114
		$linkedFiles = array();
115
116
		$htmlValue = Injector::inst()->create('HTMLValue', $record->$fieldName);
117
		$links = $this->parser->process($htmlValue);
118
119
		// Highlight broken links in the content.
120
		foreach ($links as $link) {
121
			// Skip links without domelements
122
			if(!isset($link['DOMReference'])) {
123
				continue;
124
			}
125
126
			/** @var DOMElement $domReference */
127
			$domReference = $link['DOMReference'];
128
			$classStr = trim($domReference->getAttribute('class'));
129
			if (!$classStr) {
130
				$classes = array();
131
			} else {
132
				$classes = explode(' ', $classStr);
133
			}
134
135
			// Add or remove the broken class from the link, depending on the link status.
136
			if ($link['Broken']) {
137
				$classes = array_unique(array_merge($classes, array('ss-broken')));
138
			} else {
139
				$classes = array_diff($classes, array('ss-broken'));
140
			}
141
142
			if (!empty($classes)) {
143
				$domReference->setAttribute('class', implode(' ', $classes));
144
			} else {
145
				$domReference->removeAttribute('class');
146
			}
147
		}
148
		$record->$fieldName = $htmlValue->getContent();
149
150
		// Populate link tracking for internal links & links to asset files.
151
		foreach ($links as $link) {
152
			switch ($link['Type']) {
153
				case 'sitetree':
154
					if ($link['Broken']) {
155
						$record->HasBrokenLink = true;
0 ignored issues
show
Documentation introduced by
The property HasBrokenLink does not exist on object<SilverStripe\CMS\Model\SiteTree>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
156
					} else {
157
						$linkedPages[] = $link['Target'];
158
					}
159
					break;
160
161
				case 'file':
162
				case 'image':
163
					if ($link['Broken']) {
164
						$record->HasBrokenFile = true;
0 ignored issues
show
Documentation introduced by
The property HasBrokenFile does not exist on object<SilverStripe\CMS\Model\SiteTree>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
165
					} else {
166
						$linkedFiles[] = $link['Target'];
167
					}
168
					break;
169
170
				default:
171
					if ($link['Broken']) {
172
						$record->HasBrokenLink = true;
0 ignored issues
show
Documentation introduced by
The property HasBrokenLink does not exist on object<SilverStripe\CMS\Model\SiteTree>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
173
					}
174
					break;
175
			}
176
		}
177
178
		// Update the "LinkTracking" many_many
179 View Code Duplication
		if($record->ID && $record->manyManyComponent('LinkTracking') && ($tracker = $record->LinkTracking())) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
Bug introduced by
The method LinkTracking() does not exist on SilverStripe\CMS\Model\SiteTree. Did you maybe mean syncLinkTracking()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
180
			$tracker->removeByFilter(array(
181
				sprintf('"FieldName" = ? AND "%s" = ?', $tracker->getForeignKey())
182
					=> array($fieldName, $record->ID)
183
			));
184
185
			if($linkedPages) foreach($linkedPages as $item) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $linkedPages of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
186
				$tracker->add($item, array('FieldName' => $fieldName));
187
			}
188
		}
189
190
		// Update the "ImageTracking" many_many
191 View Code Duplication
		if($record->ID && $record->manyManyComponent('ImageTracking') && ($tracker = $record->ImageTracking())) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
Documentation Bug introduced by
The method ImageTracking does not exist on object<SilverStripe\CMS\Model\SiteTree>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
192
			$tracker->removeByFilter(array(
193
				sprintf('"FieldName" = ? AND "%s" = ?', $tracker->getForeignKey())
194
					=> array($fieldName, $record->ID)
195
			));
196
197
			if($linkedFiles) foreach($linkedFiles as $item) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $linkedFiles of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
198
				$tracker->add($item, array('FieldName' => $fieldName));
199
			}
200
		}
201
	}
202
203
	/**
204
	 * Find HTMLText fields on {@link owner} to scrape for links that need tracking
205
	 *
206
	 * @todo Support versioned many_many for per-stage page link tracking
207
	 */
208
	public function augmentSyncLinkTracking() {
209
		// Skip live tracking
210
		if(Versioned::get_stage() == Versioned::LIVE) {
211
			return;
212
		}
213
214
		// Reset boolean broken flags
215
		$this->owner->HasBrokenLink = false;
0 ignored issues
show
Documentation introduced by
The property HasBrokenLink does not exist on object<SilverStripe\CMS\Model\SiteTree>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
216
		$this->owner->HasBrokenFile = false;
0 ignored issues
show
Documentation introduced by
The property HasBrokenFile does not exist on object<SilverStripe\CMS\Model\SiteTree>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
217
218
		// Build a list of HTMLText fields
219
		$allFields = $this->owner->db();
220
		$htmlFields = array();
221
		foreach($allFields as $field => $fieldSpec) {
0 ignored issues
show
Bug introduced by
The expression $allFields of type array|string|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
222
			$fieldObj = $this->owner->dbObject($field);
223
			if($fieldObj instanceof DBHTMLText) {
224
				$htmlFields[] = $field;
225
			}
226
		}
227
228
		foreach($htmlFields as $field) {
229
			$this->trackLinksInField($field);
230
		}
231
	}
232
}
233
234
/**
235
 * A helper object for extracting information about links.
236
 */
237
class SiteTreeLinkTracking_Parser {
238
239
	/**
240
	 * Finds the links that are of interest for the link tracking automation. Checks for brokenness and attaches
241
	 * extracted metadata so consumers can decide what to do with the DOM element (provided as DOMReference).
242
	 *
243
	 * @param SS_HTMLValue $htmlValue Object to parse the links from.
244
	 * @return array Associative array containing found links with the following field layout:
245
	 *		Type: string, name of the link type
246
	 *		Target: any, a reference to the target object, depends on the Type
247
	 *		Anchor: string, anchor part of the link
248
	 *		DOMReference: DOMElement, reference to the link to apply changes.
249
	 *		Broken: boolean, a flag highlighting whether the link should be treated as broken.
250
	 */
251
	public function process(SS_HTMLValue $htmlValue) {
252
		$results = array();
253
254
		$links = $htmlValue->getElementsByTagName('a');
255
		if(!$links) {
256
			return $results;
257
		}
258
259
		foreach($links as $link) {
260
			if (!$link->hasAttribute('href')) {
261
				continue;
262
			}
263
264
			$href = Director::makeRelative($link->getAttribute('href'));
265
266
			// Definitely broken links.
267
			if($href == '' || $href[0] == '/') {
268
				$results[] = array(
269
					'Type' => 'broken',
270
					'Target' => null,
271
					'Anchor' => null,
272
					'DOMReference' => $link,
273
					'Broken' => true
274
				);
275
276
				continue;
277
			}
278
279
			// Link to a page on this site.
280
			$matches = array();
281
			if(preg_match('/\[sitetree_link(?:\s*|%20|,)?id=(?<id>[0-9]+)\](#(?<anchor>.*))?/i', $href, $matches)) {
282
				$page = DataObject::get_by_id('SilverStripe\\CMS\\Model\\SiteTree', $matches['id']);
283
				$broken = false;
284
285
				if (!$page) {
286
					// Page doesn't exist.
287
					$broken = true;
288
				} else if (!empty($matches['anchor'])) {
289
					$anchor = preg_quote($matches['anchor'], '/');
290
291
					if (!preg_match("/(name|id)=\"{$anchor}\"/", $page->Content)) {
292
						// Broken anchor on the target page.
293
						$broken = true;
294
					}
295
				}
296
297
				$results[] = array(
298
					'Type' => 'sitetree',
299
					'Target' => $matches['id'],
300
					'Anchor' => empty($matches['anchor']) ? null : $matches['anchor'],
301
					'DOMReference' => $link,
302
					'Broken' => $broken
303
				);
304
305
				continue;
306
			}
307
308
			// Link to a file on this site.
309
			$matches = array();
310
			if(preg_match('/\[file_link(?:\s*|%20|,)?id=(?<id>[0-9]+)/i', $href, $matches)) {
311
				$results[] = array(
312
					'Type' => 'file',
313
					'Target' => $matches['id'],
314
					'Anchor' => null,
315
					'DOMReference' => $link,
316
					'Broken' => !DataObject::get_by_id('File', $matches['id'])
317
				);
318
319
				continue;
320
			}
321
322
			// Local anchor.
323
			$matches = array();
324
			if(preg_match('/^#(.*)/i', $href, $matches)) {
325
				$anchor = preg_quote($matches[1], '#');
326
				$results[] = array(
327
					'Type' => 'localanchor',
328
					'Target' => null,
329
					'Anchor' => $matches[1],
330
					'DOMReference' => $link,
331
					'Broken' => !preg_match("#(name|id)=\"{$anchor}\"#", $htmlValue->getContent())
332
				);
333
334
				continue;
335
			}
336
337
		}
338
339
		// Find all [image ] shortcodes (will be inline, not inside attributes)
340
		$content = $htmlValue->getContent();
341
		if(preg_match_all('/\[image([^\]]+)\bid=(["])?(?<id>\d+)\D/i', $content, $matches)) {
342
			foreach($matches['id'] as $id) {
343
				$results[] = array(
344
					'Type' => 'image',
345
					'Target' => (int)$id,
346
					'Anchor' => null,
347
					'DOMReference' => null,
348
					'Broken' => !DataObject::get_by_id('Image', (int)$id)
349
				);
350
			}
351
		}
352
		return $results;
353
	}
354
355
}
356