Importing an entry but some data are missing like
        related entries, start_publication and end_publication.
        start_publication and creation_date will use the same value,
        wich is always in Wordpress $post->post_date.
486479
def import_entry(self, title, content, item_node):
        
        try:
            creation_date = datetime.strptime(
                item_node.find('{%s}post_date_gmt' % WP_NS).text,
                '%Y-%m-%d %H:%M:%S')
        except ValueError as error:
            print 'Import entry error: {}'.format(error)

            creation_date = datetime.now()

        if settings.USE_TZ:
            creation_date = timezone.make_aware(
                creation_date, pytz.timezone('GMT'))

        excerpt = strip_tags(item_node.find(
            '{%sexcerpt/}encoded' % WP_NS).text or '')
        if not excerpt:
            if self.auto_excerpt:
                excerpt = Truncator(strip_tags(content)).words(50)
            else:
                excerpt = ''

        # Prefer use this function than
        # item_node.find('{%s}post_name' % WP_NS).text
        # Because slug can be not well formated
        slug = slugify(title)[:255] or 'post-%s' % item_node.find(
            '{%s}post_id' % WP_NS).text

        entry_dict = {
            'title': title,
            'content': content,
            'excerpt': excerpt,
            'tags': ', '.join(self.get_entry_tags(item_node.findall(
                'category'))),
            'status': self.REVERSE_STATUS[item_node.find(
                '{%s}status' % WP_NS).text],
            'comment_enabled': item_node.find(
                '{%s}comment_status' % WP_NS).text == 'open',
            'pingback_enabled': item_node.find(
                '{%s}ping_status' % WP_NS).text == 'open',
            'featured': item_node.find('{%s}is_sticky' % WP_NS).text == '1',
            'password': item_node.find('{%s}post_password' % WP_NS).text or '',
            'login_required': item_node.find(
                '{%s}status' % WP_NS).text == 'private',
            'last_update': timezone.now()}
        entry_dict['trackback_enabled'] = entry_dict['pingback_enabled']

        entry, created = Entry.objects.get_or_create(
            slug=slug, creation_date=creation_date,
            defaults=entry_dict)
        if created:
            try:
                entry.categories.add(*self.get_entry_categories(
                    item_node.findall('category')))
                entry.authors.add(self.authors[item_node.find(
                    '{http://purl.org/dc/elements/1.1/}creator').text])
                entry.sites.add(self.SITE)
            except KeyError as error:
                print 'Import entry error: {}'.format(error)

        return entry, created
64983
def updateEntry(self):
        
        # form up new entry
        title = str(self.wtitle.text())
        comment = str(self.comment_doc.toPlainText())
        # process comment string -- eliminate single newlines, make double-newlines into separate paragraphs
        # exception are paragraphs that start with "#LOG:", these get special treatment and the single newlines are
        # left intact
        pars = []
        for paragraph in comment.split("\n\n"):
            if paragraph.startswith("LOG:"):
                pars.append(paragraph.replace("\n", "<BR>"))
            else:
                pars.append(paragraph.replace("\n", " "))
        comment = "\n".join(pars)
        # go through data products and decide what to do with each one
        busy = Purr.BusyIndicator()
        # get list of DPs
        dps, updated = self.wdplv.buildDPList()
        # emit signal for all newly-created DPs
        for dp in dps:
            if not dp.archived:
                self.emit(SIGNAL("creatingDataProduct"), dp.sourcepath)
        # update or return new entry
        if self.entry:
            self.entry.update(title=title, comment=comment, dps=dps)
            self.entry.save(refresh_index=updated)
            return self.entry
        else:
            return Purr.LogEntry(time.time(), title, comment, dps)
862176
def valuefrompostdata(self, postdata):
        """"""
        if self.id in postdata and postdata[self.id] != '':
            return float(postdata[self.id])
        else:
            return None
869671
def post_structure(entry, site):
    
    author = entry.authors.all()[0]
    return {'title': entry.title,
            'description': six.text_type(entry.html_content),
            'link': '%s://%s%s' % (PROTOCOL, site.domain,
                                   entry.get_absolute_url()),
            # Basic Extensions
            'permaLink': '%s://%s%s' % (PROTOCOL, site.domain,
                                        entry.get_absolute_url()),
            'categories': [cat.title for cat in entry.categories.all()],
            'dateCreated': DateTime(entry.creation_date.isoformat()),
            'postid': entry.pk,
            'userid': author.get_username(),
            # Useful Movable Type Extensions
            'mt_excerpt': entry.excerpt,
            'mt_allow_comments': int(entry.comment_enabled),
            'mt_allow_pings': (int(entry.pingback_enabled) or
                               int(entry.trackback_enabled)),
            'mt_keywords': entry.tags,
            # Useful Wordpress Extensions
            'wp_author': author.get_username(),
            'wp_author_id': author.pk,
            'wp_author_display_name': author.__str__(),
            'wp_password': entry.password,
            'wp_slug': entry.slug,
            'sticky': entry.featured}
1125396
function save_post($post_id)
	{
		// do not save if this is an auto save routine
		if( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
		{
			return $post_id;
		}
		
		
		// verify nonce
		if( !isset($_POST['acf_nonce']) || !wp_verify_nonce($_POST['acf_nonce'], 'field_group') )
		{
			return $post_id;
		}
		
		
		// only save once! WordPress save's a revision as well.
		if( wp_is_post_revision($post_id) )
		{
	    	return $post_id;
        }
		
		
		/*
		*  save fields
		*/
		
		// vars
		$dont_delete = array();
		
		if( isset($_POST['fields']) && is_array($_POST['fields']) )
		{
			$i = -1;


			// remove clone field
			unset( $_POST['fields']['field_clone'] );
			
			

			// loop through and save fields
			foreach( $_POST['fields'] as $key => $field )
			{
				$i++;
				
				
				// order + key
				$field['order_no'] = $i;
				$field['key'] = $key;
				
				
				// save
				do_action('acf/update_field', $field, $post_id );
				
				
				// add to dont delete array
				$dont_delete[] = $field['key'];
			}
		}
		unset( $_POST['fields'] );
		
		
		// delete all other field
		$keys = get_post_custom_keys($post_id);
		foreach( $keys as $key )
		{
			if( strpos($key, 'field_') !== false && !in_array($key, $dont_delete) )
			{
				// this is a field, and it wasn't found in the dont_delete array
				do_action('acf/delete_field', $post_id, $key);
			}
		}
		
		
		/*
		*  save location rules
		*/
		
		if( isset($_POST['location']) && is_array($_POST['location']) )
		{
			delete_post_meta( $post_id, 'rule' );
			
			
			// clean array keys
			$_POST['location'] = array_values( $_POST['location'] );
			foreach( $_POST['location'] as $group_id => $group )
			{
				if( is_array($group) )
				{
					// clean array keys
					$group = array_values( $group );
					foreach( $group as $rule_id => $rule )
					{
						$rule['order_no'] = $rule_id;
						$rule['group_no'] = $group_id;
						

						add_post_meta( $post_id, 'rule', $rule );
					}
				}
			}
			
			unset( $_POST['location'] );
		}
		
		
		/*
		*  save options
		*/
		
		if( isset($_POST['options']) && is_array($_POST['options']) )
		{
			update_post_meta($post_id, 'position', $_POST['options']['position']);
			update_post_meta($post_id, 'layout', $_POST['options']['layout']);
			update_post_meta($post_id, 'hide_on_screen', $_POST['options']['hide_on_screen']);
		}

		
		unset( $_POST['options'] );
	
		
	}
936068
protected function initParams () {
		$params = array_merge($this->globalGet);
		if ($this->GetMethod() == self::METHOD_POST) {
			$postValues = [];
			if (count($this->globalPost) > 0) {
				$postValues = $this->globalPost;
			} else {
				$postValues = $this->initParamsCompletePostData();
			}
			$params = array_merge($params, $postValues);
		}
		$this->params = $params;
	}
160330
def process_entry(self, entry):
		''

		from feedjack.models import Post, Tag

		## Construct a Post object from feedparser entry (FeedParserDict)
		post = Post(feed=self.feed)
		post.link = entry.get('link', self.feed.link)
		post.title = entry.get('title', post.link)
		post.guid = self._get_guid(entry)

		if 'author_detail' in entry:
			post.author = entry.author_detail.get('name', '')
			post.author_email = entry.author_detail.get('email', '')
		if not post.author: post.author = entry.get('author', entry.get('creator', ''))
		if not post.author_email: post.author_email = 'nospam@nospam.com'

		try: post.content = entry.content[0].value
		except: post.content = entry.get('summary', entry.get('description', ''))

		# Try to get the post date from "updated" then "published" then "created"
		ts_parsed = ts_raw = None
		for k in self.post_timestamp_keys:
			try:
				post.date_modified = get_modified_date(
					entry.get('{0}_parsed'.format(k)), entry.get(k) )
			except ValueError as err:
				log.warn( 'Failed to process post timestamp:'
					' {0} (feed_id: {1}, post_guid: {2})'.format(err, self.feed.id, post.guid) )
			if post.date_modified: break

		post.comments = entry.get('comments', '')

		enclosures = entry.get('enclosures', list())
		if 'media_content' in entry:
			for mc in entry.media_content:
				if 'url' in mc: e = dict(href=mc['url'], medium=mc.get('medium', 'image'))
				else: e = entry.media_content
				e['type'] = 'application/x-media-content' # special ct for these things
				enclosures.append(e)
			assert enclosures, enclosures
		post.enclosures = enclosures

		## Get a list of tag objects from an entry
		# Note that these objects can't go into m2m field until properly saved
		fcat = list()
		if entry.has_key('tags'):
			for tcat in entry.tags:
				qcat = tcat.label if tcat.label is not None else tcat.term
				if not qcat: continue

				qcat = qcat.strip()
				if ',' in qcat or '/' in qcat: qcat = qcat.replace(',', '/').split('/')
				else: qcat = [qcat]

				for zcat in qcat:
					tagname = ' '.join(zcat.lower().split()).strip()[:255]
					if not tagname: continue
					if not Tag.objects.filter(name=tagname):
						cobj = Tag(name=tagname)
						cobj.save()
					fcat.append(Tag.objects.get(name=tagname))

		## Some feedback
		post_base_fields = 'title link guid author author_email'.split()

		log.debug('[{0}] Entry\n{1}'.format(self.feed.id, '\n'.join(
			['  {0}: {1}'.format(key, getattr(post, key)) for key in post_base_fields]
			+ ['tags: {0}'.format(' '.join(it.imap(op.attrgetter('name'), fcat)))] )))

		## Store / update a post
		if post.guid in self.postdict: # post exists, update if it was modified (and feed is mutable)
			post_old = self.postdict[post.guid]
			changed = post_old.content != post.content or (
				post.date_modified and post_old.date_modified != post.date_modified )

			if not self.feed.immutable and changed:
				retval = ENTRY_UPDATED
				log.extra('[{0}] Updating existing post: {1}'.format(self.feed.id, post.link))
				# Update fields
				for field in post_base_fields + ['content', 'comments']:
					setattr(post_old, field, getattr(post, field))
				post_old.date_modified = post.date_modified or post_old.date_modified
				# Update tags
				post_old.tags.clear()
				for tcat in fcat: post_old.tags.add(tcat)
				post_old.save()
			else:
				retval = ENTRY_SAME
				log.extra( ( '[{0}] Post has not changed: {1}' if not changed else
					'[{0}] Post changed, but feed is marked as immutable: {1}' )\
						.format(self.feed.id, post.link) )

		else: # new post, store it into database
			retval = ENTRY_NEW
			log.extra( '[{0}] Saving new post: {1} (timestamp: {2})'\
				.format(self.feed.id, post.guid, post.date_modified) )

			# Try hard to set date_modified: feed.modified, http.modified and now() as a last resort
			if not post.date_modified and self.fpf:
				try:
					post.date_modified = get_modified_date(
						self.fpf.feed.get('modified_parsed') or self.fpf.get('modified_parsed'),
						self.fpf.feed.get('modified') or self.fpf.get('modified') )
				except ValueError as err:
					log.warn(( 'Failed to process feed/http timestamp: {0} (feed_id: {1},'
						' post_guid: {2}), falling back to "now"' ).format(err, self.feed.id, post.guid))
				if not post.date_modified:
					post.date_modified = timezone.now()
					log.debug(( '[{0}] Using current time for post'
						' ({1}) timestamp' ).format(self.feed.id, post.guid))
				else:
					log.debug(
						'[{0}] Using timestamp from feed/http for post ({1}): {2}'\
						.format(self.feed.id, post.guid, post.date_modified) )

			if self.options.hidden: post.hidden = True
			try: post.save()
			except IntegrityError:
				log.error( 'IntegrityError while saving (supposedly) new'\
					' post with guid: {0.guid}, link: {0.link}, title: {0.title}'.format(post) )
				raise
			for tcat in fcat: post.tags.add(tcat)
			self.postdict[post.guid] = post

		return retval
638569
function getMetadata ($) {
  const image = ($('figure[representativeofpage=true] img').attr('src') ||
                 $('meta[property="og:image"]').attr('content') ||
                 '')

  const dateStr = ($('meta[property="article:modified_time"]').attr('content') ||
                   $('meta[property="article:published_time"]').attr('content') ||
                   $('meta[name="DC.date.issued"]').attr('content') ||
                   $('meta[property=date]').attr('content') ||
                   $('.news-body-date time').attr('datetime') ||
                   '').replace(' ', '')

  const publishedDate = new Date(dateStr)

  const author = ($('meta[name=author]').attr('content') ||
                  $('[itemprop=articleBody] .data [itemprop=author] [itemprop=name]').text().trim() ||
                  $('article .news-author [itemprop=author] [itemprop=name]').text().trim() ||
                  $('article [itemprop=name]').text().trim() ||
                  $('.main [itemprop=author]').text().trim() ||
                  $('.cuerpo-articulo [href^="/autor"]').text().trim() ||
                  $('.news-info-box-author [itemprop=author]').text().trim() ||
                  // For ara - Currently not working
                  // $('#content p.pg-bkn-dateline small').text().trim() ||
                  // For eldiario.es
                  $('#content address.dateline small').text().trim() ||
                  // The following 2 lines are for huffingtonpost
                  $('article .info .thirdparty-logo').text().trim() ||
                  $('article .info .name.fn').text().trim() ||
                  $('.detalleFullTexto .author a').text().trim() ||
                  '')

  const title = ($('meta[property="og:title"]').attr('content') ||
                 '')

  return {
    image,
    publishedDate,
    source: {
      author
    },
    title
  }
}
47553
private function init_wordpress()
    {
        global $wp, $wp_query, $wp_the_query, $wp_rewrite, $wp_did_header;

        // Trick WP into thinking this is an AJAX request. Helps quieten certain plugins.
        \define('DOING_AJAX', true);
        
        \define('SNAP_DOING_COMMAND', true);

        \define('BASE_PATH', $this->find_wordpress_base_path());
        \define('WP_USE_THEMES', false);
        require(BASE_PATH . 'wp-load.php');
    }
23746
def new_post(GITDIRECTORY=CONFIG['output_to'], kind=KINDS['writing']):  # pragma: no coverage # noqa
    

    title = input("Give the title of the post: ")
    while ':' in title:
        title = input("Give the title of the post (':' not allowed): ")

    author = CONFIG['author']
    date = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d')
    tags = input("Give the tags, separated by ', ':")
    published = 'yes'
    chronological = 'yes'
    summary = ("summary: Type your summary here.")

    # make file name
    fname = os.path.join(os.getcwd(), 'content', kind['name_plural'],
                         datetime.datetime.strftime(datetime.datetime.now(),
                                                    '%Y'),
                         date + '-' + title.replace(' ', '-') + '.markdown')
    # first post every year need to create a new directory
    if not os.path.exists(os.path.dirname(fname)):
        os.makedirs(os.path.dirname(fname))

    with open(fname, 'w') as npost:
        npost.write('---\n')
        npost.write('title: %s\n' % title)
        npost.write('author: %s\n' % author)
        npost.write('published: %s\n' % date)
        npost.write('tags: %s\n' % tags)
        npost.write('public: %s\n' % published)
        npost.write('chronological: %s\n' % chronological)
        npost.write('kind: %s\n' % kind['name'])
        npost.write('%s\n' % summary)
        npost.write('---\n')

    os.system('%s %s' % (CONFIG['editor'], fname))
1199373
def import_data(self, data_items):
        
        # keep counts of all actions
        record = {
            'insert': 0, 'update': 0, 'noop': 0,
            'start': utcnow(),
            'records': {
                'insert': [],
                'update': [],
                'noop': [],
            }
        }

        for json_id, data in self._prepare_imports(data_items):
            obj_id, what = self.import_item(data)
            self.json_to_db_id[json_id] = obj_id
            record['records'][what].append(obj_id)
            record[what] += 1

        # all objects are loaded, a perfect time to do inter-object resolution and other tasks
        self.postimport()

        record['end'] = utcnow()

        return {self._type: record}
555576
protected function _insert()
    {
        if (!$this->oxnews__oxdate || \OxidEsales\Eshop\Core\Registry::getUtilsDate()->isEmptyDate($this->oxnews__oxdate->value)) {
            // if date field is empty, assigning current date
            $this->oxnews__oxdate = new \OxidEsales\Eshop\Core\Field(date('Y-m-d'));
        } else {
            $this->oxnews__oxdate = new \OxidEsales\Eshop\Core\Field(\OxidEsales\Eshop\Core\Registry::getUtilsDate()->formatDBDate($this->oxnews__oxdate->value, true));
        }

        return parent::_insert();
    }
1239648
static protected function setImportOptions() {

		if ( ! check_admin_referer( 'pb-import' ) ) {
			return false;
		}

		$overrides = [
			'test_form' => false,
			'test_type' => false,
		];

		if ( ! function_exists( 'wp_handle_upload' ) ) {
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
		}

		// If Import Type is a URL then download and fake $_FILES on success
		//
		// This is redundant for a webbook URL (REST API) but we do it anyway because:
		//  + The select option UI expects us to fallback to the file when not a webbook in the same Submit
		//  + Sanity check verifies that we can access the website like any other
		//
		if ( getset( '_POST', 'import_type' ) === 'url' ) {
			$overrides['action'] = 'pb_handle_url_upload';
			self::createFileFromUrl();
		}
		if ( empty( $_FILES['import_file']['name'] ) ) {
			return false;
		}
		$bad_extensions = '/\.(php([0-9])?|htaccess|htpasswd|cgi|sh|pl|bat|exe|cmd|dll)$/i';
		if ( preg_match( $bad_extensions, $_FILES['import_file']['name'] ) ) {
			$_SESSION['pb_errors'][] = __( 'Sorry, this file type is not permitted for security reasons.' );
			return false;
		}

		// Handle PHP uploads in WordPress
		$upload = wp_handle_upload( $_FILES['import_file'], $overrides );
		$upload['url'] = getset( '_POST', 'import_http' );
		if ( empty( $upload['type'] ) && ! empty( $_FILES['import_file']['type'] ) ) {
			$upload['type'] = $_FILES['import_file']['type'];
		}

		if ( ! empty( $upload['error'] ) ) {
			// Error, redirect back to form
			$_SESSION['pb_notices'][] = $upload['error'];
			return false;
		}

		$ok = false;
		switch ( $_POST['type_of'] ) {

			case Wordpress\Wxr::TYPE_OF:
				$importer = new Wordpress\Wxr();
				$ok = $importer->setCurrentImportOption( $upload );
				break;

			case Epub\Epub201::TYPE_OF:
				$importer = new Epub\Epub201();
				$ok = $importer->setCurrentImportOption( $upload );
				break;

			case Odf\Odt::TYPE_OF:
				$importer = new Odf\Odt();
				$ok = $importer->setCurrentImportOption( $upload );
				break;

			case Ooxml\Docx::TYPE_OF:
				$importer = new Ooxml\Docx();
				$ok = $importer->setCurrentImportOption( $upload );
				break;

			case Api\Api::TYPE_OF:
			case Html\Xhtml::TYPE_OF:
				if ( ! empty( $upload['url'] ) && Cloner::isEnabled() && self::hasApi( $upload ) ) {
					// API (Cloning)
					$importer = new Api\Api();
					$ok = $importer->setCurrentImportOption( $upload );
				} else {
					// HTML
					unset( $_SESSION['pb_errors'] );
					$importer = new Html\Xhtml();
					$ok = $importer->setCurrentImportOption( $upload );
				}
				break;

			default:
				/**
				 * Allows users to add custom import routine for custom import type
				 * via HTTP GET requests
				 *
				 * @since 4.0.0
				 *
				 * @param \Pressbooks\Modules\Import\Import $value
				 */
				$importers = apply_filters( 'pb_initialize_import', [] );
				if ( ! is_array( $importers ) ) {
					$importers = [ $importers ];
				}
				foreach ( $importers as $importer ) {
					if ( is_object( $importer ) ) {
						$class = get_class( $importer );
						if (
							count( $importers ) === 1 ||
							defined( "{$class}::TYPE_OF" ) && $class::TYPE_OF === $_POST['type_of']
						) {
							$ok = $importer->setCurrentImportOption( $upload );
							break;
						}
					}
				}
		}

		if ( ! $ok ) {
			// Not ok?
			$_SESSION['pb_errors'][] = sprintf( __( 'Your file does not appear to be a valid %s.', 'pressbooks' ), strtoupper( $_POST['type_of'] ) );
			unlink( $upload['file'] );
			return false;
		}

		return true;
	}
790623
protected function add_data_for_post($post) {
        if (!isset($this->adhocdata[$post->course])) {
            $this->adhocdata[$post->course] = [];
        }

        if (!isset($this->adhocdata[$post->course][$post->forum])) {
            $this->adhocdata[$post->course][$post->forum] = [];
        }

        if (!isset($this->adhocdata[$post->course][$post->forum][$post->discussion])) {
            $this->adhocdata[$post->course][$post->forum][$post->discussion] = [];
        }

        $this->adhocdata[$post->course][$post->forum][$post->discussion][$post->id] = $post->id;
    }
164902
protected function init()
    {
        if (!defined('ABSPATH')) {
            die('MocaBonita must be loaded along with Wordpress!' . PHP_EOL);
        }

        $timezone = get_option('timezone_string');

        if (!empty($timezone)) {
            date_default_timezone_set($timezone);
        }

        $mbAudit = new MbAudit();
        $mbRequest = MbRequest::capture();
        $mbResponse = MbResponse::create();

        $mbRequest->ajax();

        $mbRequest->setBlogAdmin(is_blog_admin());

        $mbAudit->setRequest($mbRequest);
        $mbResponse->setMbRequest($mbRequest);
        $mbResponse->setMbAudit($mbAudit);

        $this->setPage($mbRequest->query('page'));
        $this->setAction($mbRequest->query('action', 'index'));

        $this->setMbRequest($mbRequest);
        $this->setMbResponse($mbResponse);
        $this->setMbAudit($mbAudit);

        $this->mbAssets = new Collection([
            'plugin'    => new MbAsset(),
            'wordpress' => new MbAsset(),
        ]);

        $this->mbEvents = new Collection();
        $this->mbShortCodes = new Collection();
        $this->mbPages = new Collection();

        MbMigration::enableWpdbConnection();
    }
1142175
def blog__sync_db_post_field(post, db_post_field)
      post_fields = CONFIGS[:lato_blog][:post_fields]
      # search db post field on config file
      content = post_fields[db_post_field.key]
      db_post_field.update(meta_visible: false) && return unless content
      # check category of post field is accepted
      if content[:categories] && !content[:categories].empty?
        db_categories = LatoBlog::Category.where(meta_permalink: content[:categories])
        db_post_field.update(meta_visible: false) && return if (post.categories.pluck(:id) & db_categories.pluck(:id)).empty?
      end
    end
1338469
protected function _importData()
    {
        if (Import::BEHAVIOR_DELETE == $this->getBehavior()) {
            $this->deleteCategories();
        } else {
            $this->saveCategories();
            $this->saveOnTab();
        }

        //$this->reindexImportedCategories();

        $this->eventManager->dispatch('catalog_category_import_finish_before', ['adapter' => $this]);

        return true;
    }