Updated to Drupal 8.6.4, which is PHP 7.3 friendly. Also updated HTMLaw library....
[yaffs-website] / web / core / modules / aggregator / src / Tests / AggregatorTestBase.php
1 <?php
2
3 namespace Drupal\aggregator\Tests;
4
5 use Drupal\aggregator\Entity\Feed;
6 use Drupal\Component\Utility\Html;
7 use Drupal\simpletest\WebTestBase;
8 use Drupal\aggregator\FeedInterface;
9
10 /**
11  * Defines a base class for testing the Aggregator module.
12  *
13  * @deprecated Scheduled for removal in Drupal 9.0.0.
14  *   Use \Drupal\Tests\aggregator\Functional\AggregatorTestBase instead.
15  */
16 abstract class AggregatorTestBase extends WebTestBase {
17
18   /**
19    * A user with permission to administer feeds and create content.
20    *
21    * @var \Drupal\user\Entity\User
22    */
23   protected $adminUser;
24
25   /**
26    * Modules to install.
27    *
28    * @var array
29    */
30   public static $modules = ['block', 'node', 'aggregator', 'aggregator_test', 'views'];
31
32   /**
33    * {@inheritdoc}
34    */
35   protected function setUp() {
36     parent::setUp();
37
38     // Create an Article node type.
39     if ($this->profile != 'standard') {
40       $this->drupalCreateContentType(['type' => 'article', 'name' => 'Article']);
41     }
42
43     $this->adminUser = $this->drupalCreateUser(['access administration pages', 'administer news feeds', 'access news feeds', 'create article content']);
44     $this->drupalLogin($this->adminUser);
45     $this->drupalPlaceBlock('local_tasks_block');
46   }
47
48   /**
49    * Creates an aggregator feed.
50    *
51    * This method simulates the form submission on path aggregator/sources/add.
52    *
53    * @param string $feed_url
54    *   (optional) If given, feed will be created with this URL, otherwise
55    *   /rss.xml will be used. Defaults to NULL.
56    * @param array $edit
57    *   Array with additional form fields.
58    *
59    * @return \Drupal\aggregator\FeedInterface
60    *   Full feed object if possible.
61    *
62    * @see getFeedEditArray()
63    */
64   public function createFeed($feed_url = NULL, array $edit = []) {
65     $edit = $this->getFeedEditArray($feed_url, $edit);
66     $this->drupalPostForm('aggregator/sources/add', $edit, t('Save'));
67     $this->assertText(t('The feed @name has been added.', ['@name' => $edit['title[0][value]']]), format_string('The feed @name has been added.', ['@name' => $edit['title[0][value]']]));
68
69     // Verify that the creation message contains a link to a feed.
70     $view_link = $this->xpath('//div[@class="messages"]//a[contains(@href, :href)]', [':href' => 'aggregator/sources/']);
71     $this->assert(isset($view_link), 'The message area contains a link to a feed');
72
73     $fid = db_query("SELECT fid FROM {aggregator_feed} WHERE title = :title AND url = :url", [':title' => $edit['title[0][value]'], ':url' => $edit['url[0][value]']])->fetchField();
74     $this->assertTrue(!empty($fid), 'The feed found in database.');
75     return Feed::load($fid);
76   }
77
78   /**
79    * Deletes an aggregator feed.
80    *
81    * @param \Drupal\aggregator\FeedInterface $feed
82    *   Feed object representing the feed.
83    */
84   public function deleteFeed(FeedInterface $feed) {
85     $this->drupalPostForm('aggregator/sources/' . $feed->id() . '/delete', [], t('Delete'));
86     $this->assertRaw(t('The feed %title has been deleted.', ['%title' => $feed->label()]), 'Feed deleted successfully.');
87   }
88
89   /**
90    * Returns a randomly generated feed edit array.
91    *
92    * @param string $feed_url
93    *   (optional) If given, feed will be created with this URL, otherwise
94    *   /rss.xml will be used. Defaults to NULL.
95    * @param array $edit
96    *   Array with additional form fields.
97    *
98    * @return array
99    *   A feed array.
100    */
101   public function getFeedEditArray($feed_url = NULL, array $edit = []) {
102     $feed_name = $this->randomMachineName(10);
103     if (!$feed_url) {
104       $feed_url = \Drupal::url('view.frontpage.feed_1', [], [
105         'query' => ['feed' => $feed_name],
106         'absolute' => TRUE,
107       ]);
108     }
109     $edit += [
110       'title[0][value]' => $feed_name,
111       'url[0][value]' => $feed_url,
112       'refresh' => '900',
113     ];
114     return $edit;
115   }
116
117   /**
118    * Returns a randomly generated feed edit object.
119    *
120    * @param string $feed_url
121    *   (optional) If given, feed will be created with this URL, otherwise
122    *   /rss.xml will be used. Defaults to NULL.
123    * @param array $values
124    *   (optional) Default values to initialize object properties with.
125    *
126    * @return \Drupal\aggregator\FeedInterface
127    *   A feed object.
128    */
129   public function getFeedEditObject($feed_url = NULL, array $values = []) {
130     $feed_name = $this->randomMachineName(10);
131     if (!$feed_url) {
132       $feed_url = \Drupal::url('view.frontpage.feed_1', [
133         'query' => ['feed' => $feed_name],
134         'absolute' => TRUE,
135       ]);
136     }
137     $values += [
138       'title' => $feed_name,
139       'url' => $feed_url,
140       'refresh' => '900',
141     ];
142     return Feed::create($values);
143   }
144
145   /**
146    * Returns the count of the randomly created feed array.
147    *
148    * @return int
149    *   Number of feed items on default feed created by createFeed().
150    */
151   public function getDefaultFeedItemCount() {
152     // Our tests are based off of rss.xml, so let's find out how many elements should be related.
153     $feed_count = db_query_range('SELECT COUNT(DISTINCT nid) FROM {node_field_data} n WHERE n.promote = 1 AND n.status = 1', 0, $this->config('system.rss')->get('items.limit'))->fetchField();
154     return $feed_count > 10 ? 10 : $feed_count;
155   }
156
157   /**
158    * Updates the feed items.
159    *
160    * This method simulates a click to
161    * admin/config/services/aggregator/update/$fid.
162    *
163    * @param \Drupal\aggregator\FeedInterface $feed
164    *   Feed object representing the feed.
165    * @param int|null $expected_count
166    *   Expected number of feed items. If omitted no check will happen.
167    */
168   public function updateFeedItems(FeedInterface $feed, $expected_count = NULL) {
169     // First, let's ensure we can get to the rss xml.
170     $this->drupalGet($feed->getUrl());
171     $this->assertResponse(200, format_string(':url is reachable.', [':url' => $feed->getUrl()]));
172
173     // Attempt to access the update link directly without an access token.
174     $this->drupalGet('admin/config/services/aggregator/update/' . $feed->id());
175     $this->assertResponse(403);
176
177     // Refresh the feed (simulated link click).
178     $this->drupalGet('admin/config/services/aggregator');
179     $this->clickLink('Update items');
180
181     // Ensure we have the right number of items.
182     $result = db_query('SELECT iid FROM {aggregator_item} WHERE fid = :fid', [':fid' => $feed->id()]);
183     $feed->items = [];
184     foreach ($result as $item) {
185       $feed->items[] = $item->iid;
186     }
187
188     if ($expected_count !== NULL) {
189       $feed->item_count = count($feed->items);
190       $this->assertEqual($expected_count, $feed->item_count, format_string('Total items in feed equal to the total items in database (@val1 != @val2)', ['@val1' => $expected_count, '@val2' => $feed->item_count]));
191     }
192   }
193
194   /**
195    * Confirms an item removal from a feed.
196    *
197    * @param \Drupal\aggregator\FeedInterface $feed
198    *   Feed object representing the feed.
199    */
200   public function deleteFeedItems(FeedInterface $feed) {
201     $this->drupalPostForm('admin/config/services/aggregator/delete/' . $feed->id(), [], t('Delete items'));
202     $this->assertRaw(t('The news items from %title have been deleted.', ['%title' => $feed->label()]), 'Feed items deleted.');
203   }
204
205   /**
206    * Adds and deletes feed items and ensure that the count is zero.
207    *
208    * @param \Drupal\aggregator\FeedInterface $feed
209    *   Feed object representing the feed.
210    * @param int $expected_count
211    *   Expected number of feed items.
212    */
213   public function updateAndDelete(FeedInterface $feed, $expected_count) {
214     $this->updateFeedItems($feed, $expected_count);
215     $count = db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', [':fid' => $feed->id()])->fetchField();
216     $this->assertTrue($count);
217     $this->deleteFeedItems($feed);
218     $count = db_query('SELECT COUNT(*) FROM {aggregator_item} WHERE fid = :fid', [':fid' => $feed->id()])->fetchField();
219     $this->assertTrue($count == 0);
220   }
221
222   /**
223    * Checks whether the feed name and URL are unique.
224    *
225    * @param string $feed_name
226    *   String containing the feed name to check.
227    * @param string $feed_url
228    *   String containing the feed url to check.
229    *
230    * @return bool
231    *   TRUE if feed is unique.
232    */
233   public function uniqueFeed($feed_name, $feed_url) {
234     $result = db_query("SELECT COUNT(*) FROM {aggregator_feed} WHERE title = :title AND url = :url", [':title' => $feed_name, ':url' => $feed_url])->fetchField();
235     return (1 == $result);
236   }
237
238   /**
239    * Creates a valid OPML file from an array of feeds.
240    *
241    * @param array $feeds
242    *   An array of feeds.
243    *
244    * @return string
245    *   Path to valid OPML file.
246    */
247   public function getValidOpml(array $feeds) {
248     // Properly escape URLs so that XML parsers don't choke on them.
249     foreach ($feeds as &$feed) {
250       $feed['url[0][value]'] = Html::escape($feed['url[0][value]']);
251     }
252     /**
253      * Does not have an XML declaration, must pass the parser.
254      */
255     $opml = <<<EOF
256 <opml version="1.0">
257   <head></head>
258   <body>
259     <!-- First feed to be imported. -->
260     <outline text="{$feeds[0]['title[0][value]']}" xmlurl="{$feeds[0]['url[0][value]']}" />
261
262     <!-- Second feed. Test string delimitation and attribute order. -->
263     <outline xmlurl='{$feeds[1]['url[0][value]']}' text='{$feeds[1]['title[0][value]']}'/>
264
265     <!-- Test for duplicate URL and title. -->
266     <outline xmlurl="{$feeds[0]['url[0][value]']}" text="Duplicate URL"/>
267     <outline xmlurl="http://duplicate.title" text="{$feeds[1]['title[0][value]']}"/>
268
269     <!-- Test that feeds are only added with required attributes. -->
270     <outline text="{$feeds[2]['title[0][value]']}" />
271     <outline xmlurl="{$feeds[2]['url[0][value]']}" />
272   </body>
273 </opml>
274 EOF;
275
276     $path = 'public://valid-opml.xml';
277     // Add the UTF-8 byte order mark.
278     return file_unmanaged_save_data(chr(239) . chr(187) . chr(191) . $opml, $path);
279   }
280
281   /**
282    * Creates an invalid OPML file.
283    *
284    * @return string
285    *   Path to invalid OPML file.
286    */
287   public function getInvalidOpml() {
288     $opml = <<<EOF
289 <opml>
290   <invalid>
291 </opml>
292 EOF;
293
294     $path = 'public://invalid-opml.xml';
295     return file_unmanaged_save_data($opml, $path);
296   }
297
298   /**
299    * Creates a valid but empty OPML file.
300    *
301    * @return string
302    *   Path to empty OPML file.
303    */
304   public function getEmptyOpml() {
305     $opml = <<<EOF
306 <?xml version="1.0" encoding="utf-8"?>
307 <opml version="1.0">
308   <head></head>
309   <body>
310     <outline text="Sample text" />
311     <outline text="Sample text" url="Sample URL" />
312   </body>
313 </opml>
314 EOF;
315
316     $path = 'public://empty-opml.xml';
317     return file_unmanaged_save_data($opml, $path);
318   }
319
320   /**
321    * Returns a example RSS091 feed.
322    *
323    * @return string
324    *   Path to the feed.
325    */
326   public function getRSS091Sample() {
327     return $GLOBALS['base_url'] . '/' . drupal_get_path('module', 'aggregator') . '/tests/modules/aggregator_test/aggregator_test_rss091.xml';
328   }
329
330   /**
331    * Returns a example Atom feed.
332    *
333    * @return string
334    *   Path to the feed.
335    */
336   public function getAtomSample() {
337     // The content of this sample ATOM feed is based directly off of the
338     // example provided in RFC 4287.
339     return $GLOBALS['base_url'] . '/' . drupal_get_path('module', 'aggregator') . '/tests/modules/aggregator_test/aggregator_test_atom.xml';
340   }
341
342   /**
343    * Returns a example feed.
344    *
345    * @return string
346    *   Path to the feed.
347    */
348   public function getHtmlEntitiesSample() {
349     return $GLOBALS['base_url'] . '/' . drupal_get_path('module', 'aggregator') . '/tests/modules/aggregator_test/aggregator_test_title_entities.xml';
350   }
351
352   /**
353    * Creates sample article nodes.
354    *
355    * @param int $count
356    *   (optional) The number of nodes to generate. Defaults to five.
357    */
358   public function createSampleNodes($count = 5) {
359     // Post $count article nodes.
360     for ($i = 0; $i < $count; $i++) {
361       $edit = [];
362       $edit['title[0][value]'] = $this->randomMachineName();
363       $edit['body[0][value]'] = $this->randomMachineName();
364       $this->drupalPostForm('node/add/article', $edit, t('Save'));
365     }
366   }
367
368   /**
369    * Enable the plugins coming with aggregator_test module.
370    */
371   public function enableTestPlugins() {
372     $this->config('aggregator.settings')
373       ->set('fetcher', 'aggregator_test_fetcher')
374       ->set('parser', 'aggregator_test_parser')
375       ->set('processors', [
376         'aggregator_test_processor' => 'aggregator_test_processor',
377         'aggregator' => 'aggregator',
378       ])
379       ->save();
380   }
381
382 }