Prepare published copy of draft prior to saving it
341517
def publishing_prepare_published_copy(self, draft_obj):
        
        # We call super here, somewhat perversely, to ensure this method will
        # be called on publishable subclasses if implemented there.
        mysuper = super(PublishingModel, self)
        if hasattr(mysuper, 'publishing_prepare_published_copy'):
            mysuper.publishing_prepare_published_copy(draft_obj)
665449
def save(self, *args, **kwargs):
        
        from bakery import tasks
        from django.contrib.contenttypes.models import ContentType
        # if obj.save(publish=False) has been passed, we skip everything.
        if not kwargs.pop('publish', True):
            super(AutoPublishingBuildableModel, self).save(*args, **kwargs)
        # Otherwise, for the standard obj.save(), here we go...
        else:
            # First figure out if the record is an addition, or an edit of
            # a preexisting record.
            try:
                preexisting = self.__class__.objects.get(pk=self.pk)
            except self.__class__.DoesNotExist:
                preexisting = None
            # If this is an addition...
            if not preexisting:
                # We will publish if that's the boolean
                if self.get_publication_status():
                    action = 'publish'
                # Otherwise we will do nothing do nothing
                else:
                    action = None
            # If this is an edit...
            else:
                # If it's being unpublished...
                if not self.get_publication_status() and \
                        preexisting.get_publication_status():
                    action = 'unpublish'
                # If it's being published...
                elif self.get_publication_status():
                    action = 'publish'
                # If it's remaining unpublished...
                else:
                    action = None
            # Now, no matter what, save it normally inside of a dedicated
            # database transaction so that we are sure that the save will
            # be complete before we trigger any task
            with transaction.atomic():
                super(AutoPublishingBuildableModel, self).save(*args, **kwargs)
            # Finally, depending on the action, fire off a task
            ct = ContentType.objects.get_for_model(self.__class__)
            if action == 'publish':
                tasks.publish_object.delay(ct.pk, self.pk)
            elif action == 'unpublish':
                tasks.unpublish_object.delay(ct.pk, self.pk)
48575
public function make_draft()
    {
        if (!userHasPermission('admin:invoice:invoice:edit')) {
            unauthorised();
        }

        // --------------------------------------------------------------------------

        $oUri     = Factory::service('Uri');
        $oInvoice = $this->oInvoiceModel->getById($oUri->segment(5));
        if (!$oInvoice) {
            show404();
        }

        // --------------------------------------------------------------------------

        //  Allow getting a constant
        $oInvoiceModel = $this->oInvoiceModel;

        $aData = [
            'state' => $oInvoiceModel::STATE_DRAFT,
        ];
        if ($this->oInvoiceModel->update($oInvoice->id, $aData)) {
            $sStatus  = 'success';
            $sMessage = 'Invoice updated successfully!';
        } else {
            $sStatus  = 'error';
            $sMessage = 'Invoice failed to update invoice. ' . $this->oInvoiceModel->lastError();
        }

        $oSession = Factory::service('Session', 'nails/module-auth');
        $oSession->setFlashData($sStatus, $sMessage);

        redirect('admin/invoice/invoice/edit/' . $oInvoice->id);
    }
1360488
def publish
      @options['date'] ||= read_post_yaml('date') || Time.now.iso8601
      @options['title'] = read_post_yaml('title')

      post_options = {
        'title'     => @options['title'],
        'date'      => @options['date'],
        'slug'      => path_slug(@options['path']),
        'extension' => File.extname(@options['path']).sub(/^\./, ''),
        'content'   => read_post_content,
        'dir'       => @options['dir'],
        'type'      => "post from draft",
        'write_message' => "Published: #{relative_path(path)} →",
        'force'     => @options['force']
      }

      # Create a new post file
      #
      Post.new(site, post_options).write
      
      # Remove the old draft file
      #
      FileUtils.rm @options['path']

    end
1146976
def drafts(self):
        """"""
        pub = self.on_site().filter(status=self.model.DRAFT)
        if settings.PAGE_SHOW_START_DATE:
            pub = pub.filter(publication_date__gte=get_now())
        return pub
57741
def publish(self):
        
        publisher_doc = self.get_publisher_doc()

        with self.published_context():
            # Select the published document
            published = self.one(Q._uid == self._uid)

            # If there's no published version of the document create one
            if not published:
                published = self.__class__()

            # Update the document
            for field, value in publisher_doc.items():
                setattr(published, field, value)

            # Save published version
            published.upsert()

        # Set the revisions number for draft/published version, we use PyMongo
        # directly as it's more convienent to use the shared `_uid`.
        now = datetime.now()

        with self.draft_context():
            self.get_collection().update(
                {'_uid': self._uid},
                {'$set': {'revision': now}}
                )

        with self.published_context():
            self.get_collection().update(
                {'_uid': self._uid},
                {'$set': {'revision': now}}
                )
26353
def saveCopy(self) :
        ""
        old_key = self._key
        self.reset(self.collection)
        self.save()
        return (old_key, self._key)
1096565
function prepareRevision(revision) {
  console.log(`🍳  Preparing ${revision}...`);

  if (revision === LOCAL) {
    return babelBuild(LOCAL_DIR());
  } else {
    if (!fs.existsSync(TEMP_DIR())) {
      fs.mkdirSync(TEMP_DIR());
    }

    const hash = hashForRevision(revision);
    const dir = TEMP_DIR(hash);

    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir);
      execSync(`git archive "${hash}" | tar -xC "${dir}"`);
      execSync('yarn install', { cwd: dir });
    }
    for (const file of findFiles(LOCAL_DIR('src'), '*/__tests__/*')) {
      const from = LOCAL_DIR('src', file);
      const to = path.join(dir, 'src', file);
      fs.copyFileSync(from, to);
    }
    execSync(
      `cp -R "${LOCAL_DIR()}/src/__fixtures__/" "${dir}/src/__fixtures__/"`
    );

    return babelBuild(dir);
  }
}
256034
public function savePreset() {
		$key = esc_html($_POST['key']);
		if(empty($key)) {
			json_response([
				              'status' => 'error',
				              'error' => 'Seems that you may have forgotten something.'
			              ]);
		}

		$presets = get_option('ilab-imgix-presets');
		if(!isset($presets[$key])) {
			json_response([
				              'status' => 'error',
				              'error' => 'Seems that you may have forgotten something.'
			              ]);
		}

		$name = $presets[$key]['title'];
		$settings = $_POST['settings'];
		$size = (isset($_POST['size'])) ? esc_html($_POST['size']) : null;
		$makeDefault = (isset($_POST['make_default'])) ? ($_POST['make_default'] == 1) : false;

		$this->doUpdatePresets($key, $name, $settings, $size, $makeDefault);
	}
273875
def revert(self):
        """"""

        with self.draft_context():
            draft = self.one(Q._uid == self._uid)

        with self.published_context():
            published = self.one(Q._uid == self._uid)

        for field, value in draft._document.items():
            if field in self._unpublished_fields:
                continue
            setattr(draft, field, getattr(published, field))

        # Revert the revision
        draft.revision = published.revision

        draft.update()
386135
def save(self, **edgeArgs) :
        """"""

        if not getattr(self, "_from") or not getattr(self, "_to") :
            raise AttributeError("You must specify '_from' and '_to' attributes before saving. You can also use the function 'links()'")

        payload = self._store.getStore()
        payload["_from"] = self._from
        payload["_to"] = self._to
        Document._save(self, payload, **edgeArgs)
45700
def save_related(self, request, form, *args, **kwargs):
        
        result = super(PublishingAdmin, self) \
            .save_related(request, form, *args, **kwargs)
        # Send signal that draft has been saved and all relationships created
        if form.instance:
            publishing_signals.publishing_post_save_related.send(
                sender=type(self), instance=form.instance)
        return result
1280763
def post(self, request, *args, **kwargs):
        
        now = timezone.now()
        data = {
            'title': request.POST.get('title'),
            'slug': slugify(request.POST.get('title')),
            'status': DRAFT if 'save_draft' in request.POST else PUBLISHED,
            'sites': [Site.objects.get_current().pk],
            'authors': [request.user.pk],
            'content_template': 'zinnia/_entry_detail.html',
            'detail_template': 'entry_detail.html',
            'publication_date': now,
            'creation_date': now,
            'last_update': now,
            'content': request.POST.get('content'),
            'tags': request.POST.get('tags')}
        form = QuickEntryForm(data)
        if form.is_valid():
            form.instance.content = self.htmlize(form.cleaned_data['content'])
            entry = form.save()
            return redirect(entry)

        data = {'title': smart_str(request.POST.get('title', '')),
                'content': smart_str(self.htmlize(
                    request.POST.get('content', ''))),
                'tags': smart_str(request.POST.get('tags', '')),
                'slug': slugify(request.POST.get('title', '')),
                'authors': request.user.pk,
                'sites': Site.objects.get_current().pk}
        return redirect('%s?%s' % (reverse('admin:zinnia_entry_add'),
                                   urlencode(data)))
537137
def maybe_automatically_publish_drafts_on_save(sender, instance, **kwargs):
    
    # Skip processing if auto-publishing is not enabled
    if not is_automatic_publishing_enabled(sender):
        return
    # Skip missing or unpublishable instances
    if not instance or not hasattr(instance, 'publishing_linked'):
        return
    # Ignore saves of published copies
    if instance.is_published:
        return
    # Ignore saves of already-published draft copies
    if not instance.is_dirty:
        return
    # Immediately publish saved draft copy
    instance.publish()
188150
def prep_input(self, read_list):
        """"""
        logger.info("Prepping input.")
        i = 0
        for content in read_list:
            # Check the quality of the text, and skip if there are any issues.
            quality_issue = self._check_content(content.get_text())
            if quality_issue is not None:
                logger.warning("Skipping %d due to: %s"
                               % (content.get_id(), quality_issue))
                continue

            # Look for things that are more like file names, rather than ids.
            cid = content.get_id()
            if isinstance(cid, str) and re.match('^\w*?\d+$', cid) is None:
                new_id = 'FILE%06d' % i
                i += 1
                self.id_maps[new_id] = cid
                content.change_id(new_id)
                new_fpath = content.copy_to(self.input_dir)
            else:
                # Put the content in the appropriate directory.
                new_fpath = content.copy_to(self.input_dir)
            self.num_input += 1
            logger.debug('%s saved for reading by reach.'
                         % new_fpath)
        return
521705
def save(self, filename, garbage=0, clean=0, deflate=0, incremental=0, ascii=0, expand=0, linear=0, pretty=0, decrypt=1):
        """"""

        if self.isClosed or self.isEncrypted:
            raise ValueError("operation illegal for closed / encrypted doc")
        if type(filename) == str:
            pass
        elif type(filename) == unicode:
            filename = filename.encode('utf8')
        else:
            raise TypeError("filename must be a string")
        if filename == self.name and not incremental:
            raise ValueError("save to original must be incremental")
        if self.pageCount < 1:
            raise ValueError("cannot save with zero pages")
        if incremental:
            if self.name != filename or self.stream:
                raise ValueError("incremental needs original file")


        return _fitz.Document_save(self, filename, garbage, clean, deflate, incremental, ascii, expand, linear, pretty, decrypt)
451541
def safe_prepend_to_file(relative_path, *args, **options, &block)
      prepend_to_file(relative_path, *args, **(options.merge(force: false)), &block)
    end