FeedsNodeProcessor.inc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. <?php
  2. /**
  3. * @file
  4. * Class definition of FeedsNodeProcessor.
  5. */
  6. /**
  7. * Creates nodes from feed items.
  8. */
  9. class FeedsNodeProcessor extends FeedsProcessor {
  10. /**
  11. * Define entity type.
  12. */
  13. public function entityType() {
  14. return 'node';
  15. }
  16. /**
  17. * Implements parent::entityInfo().
  18. */
  19. protected function entityInfo() {
  20. $info = parent::entityInfo();
  21. $info['label plural'] = t('Nodes');
  22. return $info;
  23. }
  24. /**
  25. * Creates a new node in memory and returns it.
  26. */
  27. protected function newEntity(FeedsSource $source) {
  28. $node = new stdClass();
  29. $node->type = $this->config['content_type'];
  30. $node->changed = REQUEST_TIME;
  31. $node->created = REQUEST_TIME;
  32. $node->language = LANGUAGE_NONE;
  33. node_object_prepare($node);
  34. // Populate properties that are set by node_object_prepare().
  35. $node->log = 'Created by FeedsNodeProcessor';
  36. $node->uid = $this->config['author'];
  37. return $node;
  38. }
  39. /**
  40. * Loads an existing node.
  41. *
  42. * If the update existing method is not FEEDS_UPDATE_EXISTING, only the node
  43. * table will be loaded, foregoing the node_load API for better performance.
  44. *
  45. * @todo Reevaluate the use of node_object_prepare().
  46. */
  47. protected function entityLoad(FeedsSource $source, $nid) {
  48. if ($this->config['update_existing'] == FEEDS_UPDATE_EXISTING) {
  49. $node = node_load($nid, NULL, TRUE);
  50. }
  51. else {
  52. // We're replacing the existing node. Only save the absolutely necessary.
  53. $node = db_query("SELECT created, nid, vid, type, status FROM {node} WHERE nid = :nid", array(':nid' => $nid))->fetchObject();
  54. $node->uid = $this->config['author'];
  55. }
  56. node_object_prepare($node);
  57. // Workaround for issue #1247506. See #1245094 for backstory.
  58. if (!empty($node->menu)) {
  59. // If the node has a menu item(with a valid mlid) it must be flagged
  60. // 'enabled'.
  61. $node->menu['enabled'] = (int) (bool) $node->menu['mlid'];
  62. }
  63. // Populate properties that are set by node_object_prepare().
  64. if ($this->config['update_existing'] == FEEDS_UPDATE_EXISTING) {
  65. $node->log = 'Updated by FeedsNodeProcessor';
  66. }
  67. else {
  68. $node->log = 'Replaced by FeedsNodeProcessor';
  69. }
  70. return $node;
  71. }
  72. /**
  73. * Check that the user has permission to save a node.
  74. */
  75. protected function entitySaveAccess($entity) {
  76. // The check will be skipped for anonymous nodes.
  77. if ($this->config['authorize'] && !empty($entity->uid)) {
  78. $author = user_load($entity->uid);
  79. // If the uid was mapped directly, rather than by email or username, it
  80. // could be invalid.
  81. if (!$author) {
  82. $message = 'User %uid is not a valid user.';
  83. throw new FeedsAccessException(t($message, array('%uid' => $entity->uid)));
  84. }
  85. if (empty($entity->nid) || !empty($entity->is_new)) {
  86. $op = 'create';
  87. $access = node_access($op, $entity->type, $author);
  88. }
  89. else {
  90. $op = 'update';
  91. $access = node_access($op, $entity, $author);
  92. }
  93. if (!$access) {
  94. $message = 'User %name is not authorized to %op content type %content_type.';
  95. throw new FeedsAccessException(t($message, array('%name' => $author->name, '%op' => $op, '%content_type' => $entity->type)));
  96. }
  97. }
  98. }
  99. /**
  100. * Save a node.
  101. */
  102. public function entitySave($entity) {
  103. // If nid is set and a node with that id doesn't exist, flag as new.
  104. if (!empty($entity->nid) && !node_load($entity->nid)) {
  105. $entity->is_new = TRUE;
  106. }
  107. node_save($entity);
  108. }
  109. /**
  110. * Delete a series of nodes.
  111. */
  112. protected function entityDeleteMultiple($nids) {
  113. node_delete_multiple($nids);
  114. }
  115. /**
  116. * Implement expire().
  117. *
  118. * @todo: move to processor stage?
  119. */
  120. public function expire($time = NULL) {
  121. if ($time === NULL) {
  122. $time = $this->expiryTime();
  123. }
  124. if ($time == FEEDS_EXPIRE_NEVER) {
  125. return;
  126. }
  127. $count = $this->getLimit();
  128. $nodes = db_query_range("SELECT n.nid FROM {node} n JOIN {feeds_item} fi ON fi.entity_type = 'node' AND n.nid = fi.entity_id WHERE fi.id = :id AND n.created < :created", 0, $count, array(':id' => $this->id, ':created' => REQUEST_TIME - $time));
  129. $nids = array();
  130. foreach ($nodes as $node) {
  131. $nids[$node->nid] = $node->nid;
  132. }
  133. $this->entityDeleteMultiple($nids);
  134. if (db_query_range("SELECT 1 FROM {node} n JOIN {feeds_item} fi ON fi.entity_type = 'node' AND n.nid = fi.entity_id WHERE fi.id = :id AND n.created < :created", 0, 1, array(':id' => $this->id, ':created' => REQUEST_TIME - $time))->fetchField()) {
  135. return FEEDS_BATCH_ACTIVE;
  136. }
  137. return FEEDS_BATCH_COMPLETE;
  138. }
  139. /**
  140. * Return expiry time.
  141. */
  142. public function expiryTime() {
  143. return $this->config['expire'];
  144. }
  145. /**
  146. * Override parent::configDefaults().
  147. */
  148. public function configDefaults() {
  149. $types = node_type_get_names();
  150. $type = isset($types['article']) ? 'article' : key($types);
  151. return array(
  152. 'content_type' => $type,
  153. 'expire' => FEEDS_EXPIRE_NEVER,
  154. 'author' => 0,
  155. 'authorize' => TRUE,
  156. ) + parent::configDefaults();
  157. }
  158. /**
  159. * Override parent::configForm().
  160. */
  161. public function configForm(&$form_state) {
  162. $types = node_type_get_names();
  163. array_walk($types, 'check_plain');
  164. $form = parent::configForm($form_state);
  165. $form['content_type'] = array(
  166. '#type' => 'select',
  167. '#title' => t('Content type'),
  168. '#description' => t('Select the content type for the nodes to be created. <strong>Note:</strong> Users with "import !feed_id feeds" permissions will be able to <strong>import</strong> nodes of the content type selected here regardless of the node level permissions. Further, users with "clear !feed_id permissions" will be able to <strong>delete</strong> imported nodes regardless of their node level permissions.', array('!feed_id' => $this->id)),
  169. '#options' => $types,
  170. '#default_value' => $this->config['content_type'],
  171. );
  172. $author = user_load($this->config['author']);
  173. $form['author'] = array(
  174. '#type' => 'textfield',
  175. '#title' => t('Author'),
  176. '#description' => t('Select the author of the nodes to be created - leave empty to assign "anonymous".'),
  177. '#autocomplete_path' => 'user/autocomplete',
  178. '#default_value' => empty($author->name) ? 'anonymous' : check_plain($author->name),
  179. );
  180. $form['authorize'] = array(
  181. '#type' => 'checkbox',
  182. '#title' => t('Authorize'),
  183. '#description' => t('Check that the author has permission to create the node.'),
  184. '#default_value' => $this->config['authorize'],
  185. );
  186. $period = drupal_map_assoc(array(FEEDS_EXPIRE_NEVER, 3600, 10800, 21600, 43200, 86400, 259200, 604800, 2592000, 2592000 * 3, 2592000 * 6, 31536000), 'feeds_format_expire');
  187. $form['expire'] = array(
  188. '#type' => 'select',
  189. '#title' => t('Expire nodes'),
  190. '#options' => $period,
  191. '#description' => t('Select after how much time nodes should be deleted. The node\'s published date will be used for determining the node\'s age, see Mapping settings.'),
  192. '#default_value' => $this->config['expire'],
  193. );
  194. $form['update_existing']['#options'] = array(
  195. FEEDS_SKIP_EXISTING => 'Do not update existing nodes',
  196. FEEDS_REPLACE_EXISTING => 'Replace existing nodes',
  197. FEEDS_UPDATE_EXISTING => 'Update existing nodes (slower than replacing them)',
  198. );
  199. return $form;
  200. }
  201. /**
  202. * Override parent::configFormValidate().
  203. */
  204. public function configFormValidate(&$values) {
  205. if ($author = user_load_by_name($values['author'])) {
  206. $values['author'] = $author->uid;
  207. }
  208. else {
  209. $values['author'] = 0;
  210. }
  211. }
  212. /**
  213. * Reschedule if expiry time changes.
  214. */
  215. public function configFormSubmit(&$values) {
  216. if ($this->config['expire'] != $values['expire']) {
  217. feeds_reschedule($this->id);
  218. }
  219. parent::configFormSubmit($values);
  220. }
  221. /**
  222. * Override setTargetElement to operate on a target item that is a node.
  223. */
  224. public function setTargetElement(FeedsSource $source, $target_node, $target_element, $value) {
  225. switch ($target_element) {
  226. case 'created':
  227. $target_node->created = feeds_to_unixtime($value, REQUEST_TIME);
  228. break;
  229. case 'feeds_source':
  230. // Get the class of the feed node importer's fetcher and set the source
  231. // property. See feeds_node_update() how $node->feeds gets stored.
  232. if ($id = feeds_get_importer_id($this->config['content_type'])) {
  233. $class = get_class(feeds_importer($id)->fetcher);
  234. $target_node->feeds[$class]['source'] = $value;
  235. // This effectively suppresses 'import on submission' feature.
  236. // See feeds_node_insert().
  237. $target_node->feeds['suppress_import'] = TRUE;
  238. }
  239. break;
  240. case 'user_name':
  241. if ($user = user_load_by_name($value)) {
  242. $target_node->uid = $user->uid;
  243. }
  244. break;
  245. case 'user_mail':
  246. if ($user = user_load_by_mail($value)) {
  247. $target_node->uid = $user->uid;
  248. }
  249. break;
  250. default:
  251. parent::setTargetElement($source, $target_node, $target_element, $value);
  252. break;
  253. }
  254. }
  255. /**
  256. * Return available mapping targets.
  257. */
  258. public function getMappingTargets() {
  259. $type = node_type_get_type($this->config['content_type']);
  260. $targets = parent::getMappingTargets();
  261. if ($type->has_title) {
  262. $targets['title'] = array(
  263. 'name' => t('Title'),
  264. 'description' => t('The title of the node.'),
  265. 'optional_unique' => TRUE,
  266. );
  267. }
  268. $targets['nid'] = array(
  269. 'name' => t('Node ID'),
  270. 'description' => t('The nid of the node. NOTE: use this feature with care, node ids are usually assigned by Drupal.'),
  271. 'optional_unique' => TRUE,
  272. );
  273. $targets['uid'] = array(
  274. 'name' => t('User ID'),
  275. 'description' => t('The Drupal user ID of the node author.'),
  276. );
  277. $targets['user_name'] = array(
  278. 'name' => t('Username'),
  279. 'description' => t('The Drupal username of the node author.'),
  280. );
  281. $targets['user_mail'] = array(
  282. 'name' => t('User email'),
  283. 'description' => t('The email address of the node author.'),
  284. );
  285. $targets['status'] = array(
  286. 'name' => t('Published status'),
  287. 'description' => t('Whether a node is published or not. 1 stands for published, 0 for not published.'),
  288. );
  289. $targets['created'] = array(
  290. 'name' => t('Published date'),
  291. 'description' => t('The UNIX time when a node has been published.'),
  292. );
  293. $targets['promote'] = array(
  294. 'name' => t('Promoted to front page'),
  295. 'description' => t('Boolean value, whether or not node is promoted to front page. (1 = promoted, 0 = not promoted)'),
  296. );
  297. $targets['sticky'] = array(
  298. 'name' => t('Sticky'),
  299. 'description' => t('Boolean value, whether or not node is sticky at top of lists. (1 = sticky, 0 = not sticky)'),
  300. );
  301. // Include language field if Locale module is enabled.
  302. if (module_exists('locale')) {
  303. $targets['language'] = array(
  304. 'name' => t('Language'),
  305. 'description' => t('The two-character language code of the node.'),
  306. );
  307. }
  308. // Include comment field if Comment module is enabled.
  309. if (module_exists('comment')) {
  310. $targets['comment'] = array(
  311. 'name' => t('Comments'),
  312. 'description' => t('Whether comments are allowed on this node: 0 = no, 1 = read only, 2 = read/write.'),
  313. );
  314. }
  315. // If the target content type is a Feed node, expose its source field.
  316. if ($id = feeds_get_importer_id($this->config['content_type'])) {
  317. $name = feeds_importer($id)->config['name'];
  318. $targets['feeds_source'] = array(
  319. 'name' => t('Feed source'),
  320. 'description' => t('The content type created by this processor is a Feed Node, it represents a source itself. Depending on the fetcher selected on the importer "@importer", this field is expected to be for example a URL or a path to a file.', array('@importer' => $name)),
  321. 'optional_unique' => TRUE,
  322. );
  323. }
  324. // Let other modules expose mapping targets.
  325. self::loadMappers();
  326. $entity_type = $this->entityType();
  327. $bundle = $this->config['content_type'];
  328. drupal_alter('feeds_processor_targets', $targets, $entity_type, $bundle);
  329. return $targets;
  330. }
  331. /**
  332. * Get nid of an existing feed item node if available.
  333. */
  334. protected function existingEntityId(FeedsSource $source, FeedsParserResult $result) {
  335. if ($nid = parent::existingEntityId($source, $result)) {
  336. return $nid;
  337. }
  338. // Iterate through all unique targets and test whether they do already
  339. // exist in the database.
  340. foreach ($this->uniqueTargets($source, $result) as $target => $value) {
  341. switch ($target) {
  342. case 'nid':
  343. $nid = db_query("SELECT nid FROM {node} WHERE nid = :nid", array(':nid' => $value))->fetchField();
  344. break;
  345. case 'title':
  346. $nid = db_query("SELECT nid FROM {node} WHERE title = :title AND type = :type", array(':title' => $value, ':type' => $this->config['content_type']))->fetchField();
  347. break;
  348. case 'feeds_source':
  349. if ($id = feeds_get_importer_id($this->config['content_type'])) {
  350. $nid = db_query("SELECT fs.feed_nid FROM {node} n JOIN {feeds_source} fs ON n.nid = fs.feed_nid WHERE fs.id = :id AND fs.source = :source", array(':id' => $id, ':source' => $value))->fetchField();
  351. }
  352. break;
  353. }
  354. if ($nid) {
  355. // Return with the first nid found.
  356. return $nid;
  357. }
  358. }
  359. return 0;
  360. }
  361. }