Completed
Pull Request — master (#1415)
by Damian
02:26
created

SiteTreeLinkTracking::getParser()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
/**
4
 * @package cms
5
 * @subpackage model
6
 */
7
8
/**
9
 * Adds tracking of links in any HTMLText fields which reference SiteTree or File items.
10
 *
11
 * Attaching this to any DataObject will add four fields which contain all links to SiteTree and File items
12
 * referenced in any HTMLText fields, and two booleans to indicate if there are any broken links. Call
13
 * augmentSyncLinkTracking to update those fields with any changes to those fields.
14
 *
15
 * Note that since both SiteTree and File are versioned, LinkTracking and ImageTracking will
16
 * only be enabled for the Stage record.
17
 *
18
 * {@see SiteTreeFileExtension} for the extension applied to {@see File}
19
 *
20
 * @property SiteTree $owner
21
 *
22
 * @property bool $HasBrokenFile
23
 * @property bool $HasBrokenLink
24
 *
25
 * @method ManyManyList LinkTracking() List of site pages linked on this page.
26
 * @method ManyManyList ImageTracking() List of Images linked on this page.
27
 * @method ManyManyList BackLinkTracking List of site pages that link to this page.
28
 */
29
class SiteTreeLinkTracking extends DataExtension {
30
31
	/**
32
	 * @var SiteTreeLinkTracking_Parser
33
	 */
34
	protected $parser;
35
36
	/**
37
	 * Inject parser for each page
38
	 *
39
	 * @var array
40
	 * @config
41
	 */
42
	private static $dependencies = array(
43
		'Parser' => '%$SiteTreeLinkTracking_Parser'
44
	);
45
46
	/**
47
	 * Parser for link tracking
48
	 *
49
	 * @return SiteTreeLinkTracking_Parser
50
	 */
51
	public function getParser() {
52
		return $this->parser;
53
	}
54
55
	/**
56
	 * @param SiteTreeLinkTracking_Parser $parser
57
	 * @return $this
58
	 */
59
	public function setParser($parser) {
60
		$this->parser = $parser;
61
		return $this;
62
	}
63
64
	private static $db = array(
65
		"HasBrokenFile" => "Boolean",
66
		"HasBrokenLink" => "Boolean"
67
	);
68
69
	private static $many_many = array(
70
		"LinkTracking" => "SiteTree",
71
		"ImageTracking" => "File"  // {@see SiteTreeFileExtension}
72
	);
73
74
	private static $belongs_many_many = array(
75
		"BackLinkTracking" => "SiteTree.LinkTracking"
76
	);
77
78
	/**
79
	 * Tracked images are considered owned by this page
80
	 *
81
	 * @config
82
	 * @var array
83
	 */
84
	private static $owns = array(
85
		"ImageTracking"
86
	);
87
88
	private static $many_many_extraFields = array(
89
		"LinkTracking" => array("FieldName" => "Varchar"),
90
		"ImageTracking" => array("FieldName" => "Varchar")
91
	);
92
93
	/**
94
	 * Scrape the content of a field to detect anly links to local SiteTree pages or files
95
	 *
96
	 * @todo - Replace image tracking with shortcodes
97
	 *
98
	 * @param string $fieldName The name of the field on {@link @owner} to scrape
99
	 */
100
	public function trackLinksInField($fieldName) {
101
		$record = $this->owner;
102
103
		$linkedPages = array();
104
		$linkedFiles = array();
105
106
		$htmlValue = Injector::inst()->create('HTMLValue', $record->$fieldName);
107
		$links = $this->parser->process($htmlValue);
108
109
		// Highlight broken links in the content.
110
		foreach ($links as $link) {
111
			$classStr = trim($link['DOMReference']->getAttribute('class'));
112
			if (!$classStr) {
113
				$classes = array();
114
			} else {
115
				$classes = explode(' ', $classStr);
116
			}
117
118
			// Add or remove the broken class from the link, depending on the link status.
119
			if ($link['Broken']) {
120
				$classes = array_unique(array_merge($classes, array('ss-broken')));
121
			} else {
122
				$classes = array_diff($classes, array('ss-broken'));
123
			}
124
125
			if (!empty($classes)) {
126
				$link['DOMReference']->setAttribute('class', implode(' ', $classes));
127
			} else {
128
				$link['DOMReference']->removeAttribute('class');
129
			}
130
		}
131
		$record->$fieldName = $htmlValue->getContent();
132
133
		// Populate link tracking for internal links & links to asset files.
134
		foreach ($links as $link) {
135
			switch ($link['Type']) {
136
				case 'sitetree':
137
					if ($link['Broken']) {
138
						$record->HasBrokenLink = true;
0 ignored issues
show
Documentation introduced by
The property HasBrokenLink does not exist on object<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...
139
					} else {
140
						$linkedPages[] = $link['Target'];
141
					}
142
					break;
143
144
				case 'file':
145
					if ($link['Broken']) {
146
						$record->HasBrokenFile = true;
0 ignored issues
show
Documentation introduced by
The property HasBrokenFile does not exist on object<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...
147
					} else {
148
						$linkedFiles[] = $link['Target'];
149
					}
150
					break;
151
152
				default:
153
					if ($link['Broken']) {
154
						$record->HasBrokenLink = true;
0 ignored issues
show
Documentation introduced by
The property HasBrokenLink does not exist on object<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...
155
					}
156
					break;
157
			}
158
		}
159
160
		// Add file tracking for image references
161
		if($images = $htmlValue->getElementsByTagName('img')) foreach($images as $img) {
162
			// {@see HtmlEditorField} for data-fileid source
163
			$fileID = $img->getAttribute('data-fileid');
164
			if(!$fileID) {
165
				continue;
166
			}
167
168
			// Assuming a local file is linked, check if it's valid
169
			if($image = File::get()->byID($fileID)) {
170
				$linkedFiles[] = $image->ID;
171
			} else {
172
				$record->HasBrokenFile = true;
0 ignored issues
show
Documentation introduced by
The property HasBrokenFile does not exist on object<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
		}
175
176
		// Update the "LinkTracking" many_many
177 View Code Duplication
		if($record->ID && $record->manyManyComponent('LinkTracking') && ($tracker = $record->LinkTracking())) {
0 ignored issues
show
Bug introduced by
The method LinkTracking() does not exist on 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...
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...
178
			$tracker->removeByFilter(array(
179
				sprintf('"FieldName" = ? AND "%s" = ?', $tracker->getForeignKey())
180
					=> array($fieldName, $record->ID)
181
			));
182
183
			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...
184
				$tracker->add($item, array('FieldName' => $fieldName));
185
			}
186
		}
187
188
		// Update the "ImageTracking" many_many
189 View Code Duplication
		if($record->ID && $record->manyManyComponent('ImageTracking') && ($tracker = $record->ImageTracking())) {
0 ignored issues
show
Documentation Bug introduced by
The method ImageTracking does not exist on object<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...
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...
190
			$tracker->removeByFilter(array(
191
				sprintf('"FieldName" = ? AND "%s" = ?', $tracker->getForeignKey())
192
					=> array($fieldName, $record->ID)
193
			));
194
195
			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...
196
				$tracker->add($item, array('FieldName' => $fieldName));
197
			}
198
		}
199
	}
200
201
	/**
202
	 * Find HTMLText fields on {@link owner} to scrape for links that need tracking
203
	 *
204
	 * @todo Support versioned many_many for per-stage page link tracking
205
	 */
206
	public function augmentSyncLinkTracking() {
207
		// Skip live tracking
208
		if(\Versioned::get_stage() == \Versioned::LIVE) {
0 ignored issues
show
Bug introduced by
The method get_stage() does not seem to exist on object<Versioned>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
209
			return;
210
		}
211
212
		// Reset boolean broken flags
213
		$this->owner->HasBrokenLink = false;
0 ignored issues
show
Documentation introduced by
The property HasBrokenLink does not exist on object<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...
214
		$this->owner->HasBrokenFile = false;
0 ignored issues
show
Documentation introduced by
The property HasBrokenFile does not exist on object<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...
215
216
		// Build a list of HTMLText fields
217
		$allFields = $this->owner->db();
218
		$htmlFields = array();
219
		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...
220
			if(preg_match('/([^(]+)/', $fieldSpec, $matches)) {
221
				$class = $matches[0];
222
				if(class_exists($class)){
223
					if($class == 'HTMLText' || is_subclass_of($class, 'HTMLText')) $htmlFields[] = $field;
224
				}
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) return $results;
256
257
		foreach($links as $link) {
258
			if (!$link->hasAttribute('href')) continue;
259
260
			$href = Director::makeRelative($link->getAttribute('href'));
261
262
			// Definitely broken links.
263
			if($href == '' || $href[0] == '/') {
264
				$results[] = array(
265
					'Type' => 'broken',
266
					'Target' => null,
267
					'Anchor' => null,
268
					'DOMReference' => $link,
269
					'Broken' => true
270
				);
271
272
				continue;
273
			}
274
275
			// Link to a page on this site.
276
			$matches = array();
277
			if(preg_match('/\[sitetree_link(?:\s*|%20|,)?id=([0-9]+)\](#(.*))?/i', $href, $matches)) {
278
				$page = DataObject::get_by_id('SiteTree', $matches[1]);
279
				$broken = false;
280
281
				if (!$page) {
282
					// Page doesn't exist.
283
					$broken = true;
284
				} else if (!empty($matches[3])) {
285
					$anchor = preg_quote($matches[3], '/');
286
287
					if (!preg_match("/(name|id)=\"{$anchor}\"/", $page->Content)) {
288
						// Broken anchor on the target page.
289
						$broken = true;
290
					}
291
				}
292
293
				$results[] = array(
294
					'Type' => 'sitetree',
295
					'Target' => $matches[1],
296
					'Anchor' => empty($matches[3]) ? null : $matches[3],
297
					'DOMReference' => $link,
298
					'Broken' => $broken
299
				);
300
301
				continue;
302
			}
303
304
			// Link to a file on this site.
305
			$matches = array();
306 View Code Duplication
			if(preg_match('/\[file_link(?:\s*|%20|,)?id=([0-9]+)\]/i', $href, $matches)) {
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...
307
				$results[] = array(
308
					'Type' => 'file',
309
					'Target' => $matches[1],
310
					'Anchor' => null,
311
					'DOMReference' => $link,
312
					'Broken' => !DataObject::get_by_id('File', $matches[1])
313
				);
314
315
				continue;
316
			}
317
318
			// Local anchor.
319
			$matches = array();
320 View Code Duplication
			if(preg_match('/^#(.*)/i', $href, $matches)) {
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...
321
				$results[] = array(
322
					'Type' => 'localanchor',
323
					'Target' => null,
324
					'Anchor' => $matches[1],
325
					'DOMReference' => $link,
326
					'Broken' => !preg_match("#(name|id)=\"{$matches[1]}\"#", $htmlValue->getContent())
327
				);
328
329
				continue;
330
			}
331
332
		}
333
334
		return $results;
335
	}
336
337
}
338