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

SiteTreeLinkTracking::augmentSyncLinkTracking()   C

Complexity

Conditions 8
Paths 11

Size

Total Lines 26
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 26
rs 5.3846
cc 8
eloc 14
nc 11
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
	protected $parser;
32
33
	private static $dependencies = array(
34
		'Parser' => '%$SiteTreeLinkTracking_Parser'
35
	);
36
37
	public function getParser() {
38
		return $this->parser;
39
	}
40
41
	public function setParser($parser) {
42
		$this->parser = $parser;
43
	}
44
45
	private static $db = array(
46
		"HasBrokenFile" => "Boolean",
47
		"HasBrokenLink" => "Boolean"
48
	);
49
50
	private static $many_many = array(
51
		"LinkTracking" => "SiteTree",
52
		"ImageTracking" => "File"  // {@see SiteTreeFileExtension}
53
	);
54
55
	private static $belongs_many_many = array(
56
		"BackLinkTracking" => "SiteTree.LinkTracking"
57
	);
58
59
	/**
60
	 * Tracked images are considered owned by this page
61
	 *
62
	 * @config
63
	 * @var array
64
	 */
65
	private static $owns = array(
66
		"ImageTracking"
67
	);
68
69
	private static $many_many_extraFields = array(
70
		"LinkTracking" => array("FieldName" => "Varchar"),
71
		"ImageTracking" => array("FieldName" => "Varchar")
72
	);
73
74
	/**
75
	 * Scrape the content of a field to detect anly links to local SiteTree pages or files
76
	 *
77
	 * @todo - Replace image tracking with shortcodes
78
	 *
79
	 * @param string $fieldName The name of the field on {@link @owner} to scrape
80
	 */
81
	public function trackLinksInField($fieldName) {
82
		$record = $this->owner;
83
84
		$linkedPages = array();
85
		$linkedFiles = array();
86
87
		$htmlValue = Injector::inst()->create('HTMLValue', $record->$fieldName);
88
		$links = $this->parser->process($htmlValue);
89
90
		// Highlight broken links in the content.
91
		foreach ($links as $link) {
92
			$classStr = trim($link['DOMReference']->getAttribute('class'));
93
			if (!$classStr) {
94
				$classes = array();
95
			} else {
96
				$classes = explode(' ', $classStr);
97
			}
98
99
			// Add or remove the broken class from the link, depending on the link status.
100
			if ($link['Broken']) {
101
				$classes = array_unique(array_merge($classes, array('ss-broken')));
102
			} else {
103
				$classes = array_diff($classes, array('ss-broken'));
104
			}
105
106
			if (!empty($classes)) {
107
				$link['DOMReference']->setAttribute('class', implode(' ', $classes));
108
			} else {
109
				$link['DOMReference']->removeAttribute('class');
110
			}
111
		}
112
		$record->$fieldName = $htmlValue->getContent();
113
114
		// Populate link tracking for internal links & links to asset files.
115
		foreach ($links as $link) {
116
			switch ($link['Type']) {
117
				case 'sitetree':
118
					if ($link['Broken']) {
119
						$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...
120
					} else {
121
						$linkedPages[] = $link['Target'];
122
					}
123
					break;
124
125
				case 'file':
126
					if ($link['Broken']) {
127
						$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...
128
					} else {
129
						$linkedFiles[] = $link['Target'];
130
					}
131
					break;
132
133
				default:
134
					if ($link['Broken']) {
135
						$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...
136
					}
137
					break;
138
			}
139
		}
140
141
		// Add file tracking for image references
142
		if($images = $htmlValue->getElementsByTagName('img')) foreach($images as $img) {
143
			// {@see HtmlEditorField} for data-fileid source
144
			$fileID = $img->getAttribute('data-fileid');
145
			if(!$fileID) {
146
				continue;
147
			}
148
149
			// Assuming a local file is linked, check if it's valid
150
			if($image = File::get()->byID($fileID)) {
151
				$linkedFiles[] = $image->ID;
152
			} else {
153
				$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...
154
			}
155
		}
156
157
		// Update the "LinkTracking" many_many
158 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...
159
			$tracker->removeByFilter(array(
160
				sprintf('"FieldName" = ? AND "%s" = ?', $tracker->getForeignKey())
161
					=> array($fieldName, $record->ID)
162
			));
163
164
			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...
165
				$tracker->add($item, array('FieldName' => $fieldName));
166
			}
167
		}
168
169
		// Update the "ImageTracking" many_many
170 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...
171
			$tracker->removeByFilter(array(
172
				sprintf('"FieldName" = ? AND "%s" = ?', $tracker->getForeignKey())
173
					=> array($fieldName, $record->ID)
174
			));
175
176
			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...
177
				$tracker->add($item, array('FieldName' => $fieldName));
178
			}
179
		}
180
	}
181
182
	/**
183
	 * Find HTMLText fields on {@link owner} to scrape for links that need tracking
184
	 *
185
	 * @todo Support versioned many_many for per-stage page link tracking
186
	 */
187
	public function augmentSyncLinkTracking() {
188
		// Skip live tracking
189
		if(\Versioned::get_stage() == \Versioned::LIVE_STAGE) {
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...
190
			return;
191
		}
192
193
		// Reset boolean broken flags
194
		$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...
195
		$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...
196
197
		// Build a list of HTMLText fields
198
		$allFields = $this->owner->db();
199
		$htmlFields = array();
200
		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...
201
			if(preg_match('/([^(]+)/', $fieldSpec, $matches)) {
202
				$class = $matches[0];
203
				if(class_exists($class)){
204
					if($class == 'HTMLText' || is_subclass_of($class, 'HTMLText')) $htmlFields[] = $field;
205
				}
206
			}
207
		}
208
209
		foreach($htmlFields as $field) {
210
			$this->trackLinksInField($field);
211
		}
212
	}
213
}
214
215
/**
216
 * A helper object for extracting information about links.
217
 */
218
class SiteTreeLinkTracking_Parser {
219
220
	/**
221
	 * Finds the links that are of interest for the link tracking automation. Checks for brokenness and attaches
222
	 * extracted metadata so consumers can decide what to do with the DOM element (provided as DOMReference).
223
	 *
224
	 * @param SS_HTMLValue $htmlValue Object to parse the links from.
225
	 * @return array Associative array containing found links with the following field layout:
226
	 *		Type: string, name of the link type
227
	 *		Target: any, a reference to the target object, depends on the Type
228
	 *		Anchor: string, anchor part of the link
229
	 *		DOMReference: DOMElement, reference to the link to apply changes.
230
	 *		Broken: boolean, a flag highlighting whether the link should be treated as broken.
231
	 */
232
	public function process(SS_HTMLValue $htmlValue) {
233
		$results = array();
234
235
		$links = $htmlValue->getElementsByTagName('a');
236
		if(!$links) return $results;
237
238
		foreach($links as $link) {
239
			if (!$link->hasAttribute('href')) continue;
240
241
			$href = Director::makeRelative($link->getAttribute('href'));
242
243
			// Definitely broken links.
244
			if($href == '' || $href[0] == '/') {
245
				$results[] = array(
246
					'Type' => 'broken',
247
					'Target' => null,
248
					'Anchor' => null,
249
					'DOMReference' => $link,
250
					'Broken' => true
251
				);
252
253
				continue;
254
			}
255
256
			// Link to a page on this site.
257
			$matches = array();
258
			if(preg_match('/\[sitetree_link(?:\s*|%20|,)?id=([0-9]+)\](#(.*))?/i', $href, $matches)) {
259
				$page = DataObject::get_by_id('SiteTree', $matches[1]);
260
				$broken = false;
261
262
				if (!$page) {
263
					// Page doesn't exist.
264
					$broken = true;
265
				} else if (!empty($matches[3])) {
266
					$anchor = preg_quote($matches[3], '/');
267
268
					if (!preg_match("/(name|id)=\"{$anchor}\"/", $page->Content)) {
269
						// Broken anchor on the target page.
270
						$broken = true;
271
					}
272
				}
273
274
				$results[] = array(
275
					'Type' => 'sitetree',
276
					'Target' => $matches[1],
277
					'Anchor' => empty($matches[3]) ? null : $matches[3],
278
					'DOMReference' => $link,
279
					'Broken' => $broken
280
				);
281
282
				continue;
283
			}
284
285
			// Link to a file on this site.
286
			$matches = array();
287 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...
288
				$results[] = array(
289
					'Type' => 'file',
290
					'Target' => $matches[1],
291
					'Anchor' => null,
292
					'DOMReference' => $link,
293
					'Broken' => !DataObject::get_by_id('File', $matches[1])
294
				);
295
296
				continue;
297
			}
298
299
			// Local anchor.
300
			$matches = array();
301 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...
302
				$results[] = array(
303
					'Type' => 'localanchor',
304
					'Target' => null,
305
					'Anchor' => $matches[1],
306
					'DOMReference' => $link,
307
					'Broken' => !preg_match("#(name|id)=\"{$matches[1]}\"#", $htmlValue->getContent())
308
				);
309
310
				continue;
311
			}
312
313
		}
314
315
		return $results;
316
	}
317
318
}
319