8 – How to programmatically grant access to private files?

I was working under the idea that i could use hook_file_download to grant access to private files; but it seems that this hook can only be used to restrict access to files, not to grant access.

I have seen suggestions of other hooks like file_access and file_access_alter; but none of these exist any more.

Drupal CDN file copy programmatically

With CDN installed pointed to AWS, it appears that using the file_unmanaged_copy function doesn’t replace the existing file.

file_unmanaged_copy($replacement->getFileUri(), $file_uri, FILE_EXISTS_REPLACE)

However, I don’t see this issue documented anywhere. Is this true? What is the workaround?

7 – get translation programmatically of field value in specific language

I have created a content type (pdf_form) to which I added a field_gender_languagetest with two options, male and female. I translated both the options in German using the translation tab.

Now I am generating a report of the data filled by users using that content type.

Is there any way to programmatically get that translation?

I am trying this code, but it doesn’t work.

t('male', array(), array('langcode' => 'de')); 

I am trying this query, but it only returns the link.

SELECT s.lid, t.translation, s.version 
    FROM locales_source s LEFT JOIN locales_target t
    ON s.lid = t.lid AND t.language = 'de' 
    WHERE  s.context = 'field_gender_languagetest:node2pdf_language:label' AND s.textgroup = 'field'

sharepoint online – Programmatically extract who has viewed a shared file?

I am wondering if there is a way to get at the list of users who have downloaded a file, programmatically, like the information that is already given to us over the web:

https://i.stack.imgur.com/UJ6CC.png

I noticed this older post, but I am wondering if anyone is aware of ways to get at this information: Listing of Users who have viewed a file

magento2 – Image not showing on product page of programmatically created products

Magento 2.4.2

I’m creating products programmatically with this code:

<?php

namespace VendorBaseHelperProduct;


use MagentoCatalogModelProductFactory;
use MagentoCatalogModelProductRepository;
use MagentoFrameworkExceptionCouldNotSaveException;
use MagentoFrameworkExceptionInputException;
use MagentoFrameworkExceptionNoSuchEntityException;
use MagentoFrameworkExceptionStateException;
use MagentoFrameworkValidationValidationException;
use MagentoInventoryApiApiDataSourceItemInterfaceFactory;
use MagentoInventoryApiApiSourceItemsSaveInterface;

class CreateProduct
{
    protected $productFactory;
    protected $productRepository;
    protected $_sourceItemsSaveInterface;
    protected $_sourceItemFactory;


    public function __construct(
        ProductFactory $productFactory,
        ProductRepository $productRepository,
        SourceItemsSaveInterface $sourceItemsSaveInterface,
        SourceItemInterfaceFactory $sourceItemFactory

    ) {
        $this->productFactory = $productFactory;
        $this->productRepository = $productRepository;
        $this->_sourceItemsSaveInterface = $sourceItemsSaveInterface;
        $this->_sourceItemFactory = $sourceItemFactory;
    }

    public function createProduct()
    {

        if ($this->doesProductExist('totallyUniqueSku')) {
            return 'totallyUniqueSku';
        }
        if (!$productDetails->isValid()) {
            return false;
        }

        $product = $this->productFactory->create();

        $product->setSku('totallyUniqueSku');
        $product->setData('attribute_set_id', 4);//default = 4
        $product->setData('website_ids', (1));
        $product->setData('status', MagentoCatalogModelProductAttributeSourceStatus::STATUS_ENABLED);
        $product->setData('visibility', 1);//1 = not vis individually
        $product->setName('coolProductName');
        $product->setData('category_ids', (1,2,3));//just an example of the ids. this works fine.
        $product->setWeight('21');
        $product->setData('price', '123.00');
        $product->setData('type_id', 'simple'));
        $product->setData('tax_class_id', 1);
        $product->setData('description', 'super cool description');
        $product->setData('short_description', 'super cool short desc');
        
        
        $product->setData('stock_data', (  // set product quantity
                'use_config_manage_stock' => 0,
                'manage_stock' => 1,
                'is_in_stock' => 1,
                'qty' => 1
            ));
        
        
        $url = $product->formatUrlKey('TotallyUniqueURLKey');
        $product->setUrlKey($url);
        
        //-------------- Code in question --------------

        $images = ('relative/path/to/image.jpeg', 'relative/path/to/image2.jpeg');
        if ($images && (is_array($images) || is_object($images))) {
            $i=0;
            foreach ($images as $image) {
                if ($i < 1) {
                    $mediaAttribute = ('image', 'small_image', 'thumbnail');
                } else {
                    $mediaAttribute = null;
                }

                $product->addImageToMediaGallery($image, $mediaAttribute);
                $i++;
            }
        }
        
        //-------------- End Code in question --------------


        
        try {
            $this->productRepository->save($product);

            return $product->getSku();
        } catch (CouldNotSaveException $e) {
            $this->messageManager->addErrorMessage('Failed to create product. See Error Logs for details #3');
        } catch (InputException $e) {
            $this->messageManager->addErrorMessage('Failed to create product. See Error Logs for details #4');
        } catch (StateException $e) {
            $this->messageManager->addErrorMessage('Failed to create product. See Error Logs for details #5');
        }
        return true;
    }

    protected function doesProductExist($sku): bool
    {
        try {
            $product = $this->productRepository->get($sku);
            if ($product) {
                return true;
            }
            return false;
        } catch (NoSuchEntityException $e) {
            return false;
        }
    }

    

    



    public function log($in)
    {
        $writer = new ZendLogWriterStream(BP . '/var/log/debug.log');
        $logger = new ZendLogLogger();
        $logger->addWriter($writer);
        $logger->debug($in);
    }
}

The product is created successfully, the issue is that the image does not show on the product page. There are no images on the product page, but if I search for the product, the search results show the image correctly. The images are also displayed correctly when editing the product from the admin backend.

Some of the product data in the example code might be off slightly, but the code relating to the images is correct.

Why doesn’t the image show up on the product page?

magento2 – Duplicate orders created when proforma disabled programmatically via Module Magento 2.3

Idea 1 – Calling Method On Null

The only thing so far that stands out about the code posted is the assumption that $customerGetValue->getCustomAttribute('disable_proforma_email') will always return an MagentoFrameworkApiAttributeInterface that you can call AttributeInterface::getValue() on.

See the interface method for that method below. If an attribute happens to not be set, it will return null which you can’t call getValue() on. This is a stretch but maybe that is a culprit? Either way, you will want to do a null check before calling getValue() on what you think is the custom attribute.

Example

$dpe = $customerGetValue->getCustomAttribute('disable_proforma_email')->getValue();
$dpe = ($dpe !== null) ? $dpe->getValue() : null;

enter image description here

Idea 2 – Check the logs

Check logs in var/log/*.log. I can’t tell you how many times logs have saved me from spending a lot of time tracking down a problem.

Idea 3 – Custom Code “Process of Elimination”

Depending on the number of modules being used, it can be pretty hard to narrow down a problem when there are no obvious errors getting captured in logs. A sometimes useful strategy you can employ is to build a list of all custom modules that are enabled, then disable all of them to see if the problem stops happening.

If you are able to stop the problem with all custom modules being disabled, you can then keep enabling half of the extensions and re-testing in between to determine which batch of extensions is producing the problem.

Build List of All Custom Modules

Use the following command to output all custom modules not made by Magento.

php bin/magento module:status | grep -v 'Magento_'

Disable All Custom Modules

Use the following command to disable all of the custom modules. Some modules might have dependencies on each other so you might have to group them by vendor to have it succeed at disabling.

php bin/magento module:disable Vendor_Module1 Vendor_Module2, Vendor2_Module1 Vendor2_Module2

Re-enable Modules In Batches

Use the following command to keep enabling half of the list of custom modules, testing in between, until you can hopefully reproduce the problem in one of the enabled batches.

php bin/magento module:enable Vendor_Module1 Vendor_Module2, Vendor2_Module1 Vendor2_Module2

Idea 4 – General Thoughts

  • I have experienced Cybersource payment method in the past that caused duplicate orders the way the payment method worked in checkout. Curious if you have any custom payment methods that you could mention that might reveal something of interest.

9 – Programmatically publish unpublished nodes

The code is calling execute() on the object returned from $query->andConditionGroup(), but that object doesn’t implement any execute() method.

The correct way to use andConditionGroup() is shown in QueryBase::andConditionGroup().

$query = Drupal::entityQuery('drawing');
$group = $query->andConditionGroup()
  ->condition('figures.color', 'red')
  ->condition('figures.shape', 'triangle');
$query->condition($group);
$group = $query->andConditionGroup()
  ->condition('figures.color', 'blue')
  ->condition('figures.shape', 'circle');
$query->condition($group);
$entity_ids = $query->execute();

In your case, using andConditionGroup() isn’t necessary, as the query executed by that code will returns all nodes for which:

  • The content type is level3
  • The title is $file_name
  • The status is 0

It doesn’t return all the nodes for which at least one of those conditions is true. It’s similar to what the following code does, which returns all the page nodes where the value of field_some_field is higher than 14.

$query = Drupal::entityQuery('node')
  ->condition('type', 'page')
  ->condition('field_some_field', 14, '>');
$results = $query->execute();

$query->execute() returns an array of entity IDs, not an entity nor an array of entities. $nids = $query->execute(); $nids->setPublished(TRUE)->save(); is still wrong, as an array doesn’t implement the setPublished() method.
Given an array of node IDs $nids, the correct code to load the nodes is the following one.

$nodes = Drupal::entityTypeManager()->getStorage('node')->loadMultiple(array_values($nids));

$nodes will contain an array of entities. Publishing them can be achieved with the following code.

foreach ($nodes as $node) {
  $node->setPublished(TRUE)->save();
}

The object returned from Drupal::entityQuery() verifies the currently logged-in user has view access to the returned nodes. In most of the cases, the user doesn’t have access to unpublished nodes. To avoid the query returns only the nodes the currently logged-in user can view, it’s necessary to call $query->accessCheck(FALSE), as in $query = Drupal::entityQuery('node')->checkAccess(FALSE);

Furthermore, the exists('nid') call isn’t necessary, as the node ID is always saved for nodes.

Leaving out the loop on $i_selected, the code I would use is the following one.

$query = Drupal::entityQuery('node')->checkAccess(FALSE);

$nids = $query->condition('type', 'level3')
  ->condition('title', $file_name)
  ->condition('status', '0')
  ->execute();

$nodes = Drupal::entityTypeManager()->getStorage('node')->loadMultiple(array_values($nids));

foreach ($nodes as $node) {
  $node->setPublished(TRUE)->save();
}

Programmatically list AdSense pages with policy violations


Your privacy


By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.




nodes – How do I programmatically publish the latest revision?

  1. My workflow is draft and publish.
  2. I create and publish a page.
  3. I create a draft of the page.

There is now the published page, but the latest revision is the draft.

How do I programmatically set as published the latest revision?

This code publishes the node.

$node = Node::load(nid);
// Publish and save the node.
if ($node->hasField('moderation_state')) {
  $node->set('moderation_state', 'published');
}
$node->setPublished();
$node->save();

The node is already published. I want to publish the draft/latest revision of the node.

This query has some possibilities.

// Publish the draft of a node.
$query = Drupal::database()->select('content_moderation_state_field_revision', 'cm');
// $query->fields('cm', ('moderation_state'));
$query->fields('cm');
$query->condition('cm.content_entity_id', $node->id());
$query->condition('cm.moderation_state', 'draft');
$result = $query->execute();
$record = $result->fetchAssoc();
print_r($record);

Since nodes can have more than one draft, I could add a LIMIT and an ORDER BY to the query. Simply changing the moderation_state in the content_moderation_state_field_revision table and rebuilding the cache doesn’t publish the latest revision.

This code, altered slightly from EntityModerationForm.php worked once, but then didn’t work again.

/** @var DrupalCoreEntityContentEntityStorageInterface $storage */
$storage = Drupal::entityTypeManager()->getStorage($node->getEntityTypeId());
$entity = $storage->createRevision($node, $node->isDefaultRevision());

$new_state = 'published';

$entity->set('moderation_state', $new_state);

if ($entity instanceof RevisionLogInterface) {
  $entity->setRevisionCreationTime(Drupal::time()->getRequestTime());
  $entity->setRevisionLogMessage('Draft created automatically');
  $entity->setRevisionUserId(Drupal::currentUser()->id());
}
//    $node->setNewRevision(FALSE);
$entity->save();