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