Spawn a new Delivery Execution

@param string $label
@param string $deliveryId
@param string $userId
@param string $status
@return \oat\taoDelivery\model\execution\DeliveryExecution
174959
public function spawnDeliveryExecution($label, $deliveryId, $userId, $status)
    {
        $identifier = self::DELIVERY_EXECUTION_PREFIX . \common_Utils::getNewUri();
        $data = array(
            OntologyRdfs::RDFS_LABEL => $label,
            OntologyDeliveryExecution::PROPERTY_DELIVERY  => $deliveryId,
            OntologyDeliveryExecution::PROPERTY_SUBJECT => $userId,
            OntologyDeliveryExecution::PROPERTY_TIME_START => microtime(),
            OntologyDeliveryExecution::PROPERTY_STATUS => $status
        );
        $kvDe = new KVDeliveryExecution($this, $identifier, $data);
        $this->updateDeliveryExecutionStatus($kvDe, null, $status);
        $this->addDeliveryToUserExecutionList($userId, $deliveryId, $kvDe->getIdentifier());
        return $this->propagate(new DeliveryExecutionWrapper($kvDe));
    }
236878
public function newInstance(
        string $createdByUserId,
        string $createdReason = Tracking::UNKNOWN_REASON
    ) {
        /** @var static $new */
        $new = parent::newInstance(
            $createdByUserId,
            $createdReason
        );

        // if no id, then it has not been save and can be returned
        if (empty($new->revisionId)) {
            return $new;
        }

        $new->revisionId = null;
        $new->createdDate = new \DateTime();

        $new->published = false;
        $new->publishedDate = null;

        /* Clone Plugins */
        $pluginWrappers = $new->pluginWrappers;
        $clonedPluginWrappers = new ArrayCollection();

        /** @var \Rcm\Entity\PluginWrapper $pluginWrapper */
        foreach ($pluginWrappers as $pluginWrapper) {
            $clonedPluginWrapper = $pluginWrapper->newInstance(
                $createdByUserId,
                $createdReason
            );
            $clonedPluginWrappers->add($clonedPluginWrapper);
        }

        $new->pluginWrappers = $clonedPluginWrappers;

        return $new;
    }
201559
protected function _initDeliveryExecution() {
        $compiledDelivery  = new \core_kernel_classes_Resource(\tao_helpers_Uri::decode($this->getRequestParameter('uri')));
        $user              = common_session_SessionManager::getSession()->getUser();

        $assignmentService = $this->getServiceLocator()->get(AssignmentService::SERVICE_ID);

        $this->verifyDeliveryStartAuthorized($compiledDelivery->getUri());

        //check if the assignment allows the user to start the delivery and the authorization provider
        if (!$assignmentService->isDeliveryExecutionAllowed($compiledDelivery->getUri(), $user) ) {
            throw new common_exception_Unauthorized();
        }
        $stateService = $this->getServiceLocator()->get(StateServiceInterface::SERVICE_ID);
        /** @var DeliveryExecution $deliveryExecution */
        $deliveryExecution = $stateService->createDeliveryExecution($compiledDelivery->getUri(), $user, $compiledDelivery->getLabel());


        return $deliveryExecution;
    }
154962
public function getResponsibleService(User $user, $deliveryId = null)
    {
        if (!isset($this->service))
        {
            /** @var DelegatedServiceHandler $handler */
            foreach ($this->getOption(self::SERVICE_HANDLERS) as $handler) {
                if (!is_a($handler, DelegatedServiceHandler::class)) {
                    throw new \common_exception_NoImplementation('Handler should be instance of DelegatorServiceHandler.');
                }
                $handler->setServiceLocator($this->getServiceLocator());
                if ($handler->isSuitable($user, $deliveryId)) {
                    $this->service = $handler;
                    break;
                }
            }
        }
        return $this->service;
    }
566514
public function initResultServer($compiledDelivery, $executionIdentifier, $userUri) {
        $this->getServiceManager()->get(\oat\taoResultServer\models\classes\ResultServerService::SERVICE_ID)
            ->initResultServer($compiledDelivery, $executionIdentifier, $userUri);
    }
834192
private function HandleApplicant($Action, $UserID) {
      $this->Permission('Garden.Users.Approve');
      
      //$this->_DeliveryType = DELIVERY_TYPE_BOOL;
      if (!in_array($Action, array('Approve', 'Decline')) || !is_numeric($UserID)) {
         $this->Form->AddError('ErrorInput');
         $Result = FALSE;
      } else {
         $Session = Gdn::Session();
         $UserModel = new UserModel();
         if (is_numeric($UserID)) {
            try {
               $this->EventArguments['UserID'] = $UserID;
               $this->FireEvent("Before{$Action}User");
               
               $Email = new Gdn_Email();
               $Result = $UserModel->$Action($UserID, $Email);
               
               // Re-calculate applicant count
               $RoleModel = new RoleModel();
               $RoleModel->GetApplicantCount(TRUE);
               
               $this->FireEvent("After{$Action}User");
            } catch(Exception $ex) {
               $Result = FALSE;
               $this->Form->AddError(strip_tags($ex->getMessage()));
            }
         }
      }
   }
501106
static function create( $orderID, $statusID, $userID = false, $timestamp = false )
    {
        if ( $timestamp === false )
        {
            $timestamp = time();
        }
        if ( $userID === false )
        {
            $userID = eZUser::currentUserID();
        }
        $row = array( 'id' => null,
                      'order_id' => $orderID,
                      'status_id' => $statusID,
                      'modifier_id' => $userID,
                      'modified' => $timestamp );
        return new eZOrderStatusHistory( $row );
    }
1040698
public static function init($id, $label = 'Index'){
		if( !isset(self::$instances[$id]) ){
			self::$instances[$id] = new Toc($label, '', true);
		}
		return self::$instances[$id];
	}
1166398
public function execute($userId = 0)
    {
        $batch = $this->getBatch();
        if ($batch->getCounter('movestarted') === 0) {
            $batch->addToCounter('movestarted');
            $select = $this->loader->getTracker()->getTokenSelect(['total' => new \Zend_Db_Expr('count(*)')])->andReceptionCodes([])->onlyCompleted()->onlySucces()->forSurveyId($this->sourceSurveyId)->getSelect();
            $count = $this->db->fetchOne($select);
            $batch->addStepCount($count - 1);   // For progressbar
            $batch->resetCounter('movesteps');
            $batch->addToCounter('movesteps', $count);
        }
        $this->executeIteration($userId);
    }
932080
public void createProductDelivery(final String productLogicalName, final Delivery delivery, final String user, final String password) throws GrapesCommunicationException, AuthenticationException {      
    	final Client client = getClient(user, password);
        final WebResource resource = client.resource(serverURL).path(RequestUtils.getProductDelivery(productLogicalName));
        final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, delivery);

        client.destroy();
        if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){
            final String message = "Failed to create a delivery";
            if(LOG.isErrorEnabled()) {
                LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));
            }
            throw new GrapesCommunicationException(message, response.getStatus());
        }
    }
1275290
public function execute($sourceId = null, $userId = null)
    {
        $now    = new \MUtil_Db_Expr_CurrentTimestamp();
        $values = array('gso_last_synch' => $now, 'gso_changed' => $now, 'gso_changed_by' => $userId);
        $where  = $this->db->quoteInto('gso_id_source = ?', $sourceId);

        $this->db->update('gems__sources', $values, $where);
    }
923905
public function runDeliveryExecution() {
	    $deliveryExecution = $this->getCurrentDeliveryExecution();

        // Sets the deliveryId to session.
        if (!$this->hasSessionAttribute(DeliveryExecution::getDeliveryIdSessionKey($deliveryExecution->getIdentifier()))) {
            $this->setSessionAttribute(
                DeliveryExecution::getDeliveryIdSessionKey($deliveryExecution->getIdentifier()),
                $deliveryExecution->getDelivery()->getUri()
            );
        }

        try {
            $this->verifyDeliveryExecutionAuthorized($deliveryExecution);
        } catch (UnAuthorizedException $e) {
            return $this->redirect($e->getErrorPage());
        }

	    $userUri = common_session_SessionManager::getSession()->getUserUri();
	    if ($deliveryExecution->getUserIdentifier() != $userUri) {
	        throw new common_exception_Error('User '.$userUri.' is not the owner of the execution '.$deliveryExecution->getIdentifier());
	    }
	    
	    $delivery = $deliveryExecution->getDelivery();
        $this->initResultServer($delivery, $deliveryExecution->getIdentifier(), $userUri);

        $deliveryExecutionStateService = $this->getServiceManager()->get(StateServiceInterface::SERVICE_ID);
        $deliveryExecutionStateService->run($deliveryExecution);

        /**
         * Use particular delivery container
         */
        $container = $this->getDeliveryServer()->getDeliveryContainer($deliveryExecution);

	    // Require JS config
        $container->setData('client_config_url', $this->getClientConfigUrl());
        $container->setData('client_timeout', $this->getClientTimeout());
        // Delivery params
        $container->setData('returnUrl', $this->getReturnUrl());
        $container->setData('finishUrl', $this->getfinishDeliveryExecutionUrl($deliveryExecution));

        $this->setData('additional-header', $container->getContainerHeader());
        $this->setData('container-body', $container->getContainerBody());
        
		
		/**
		 * Delivery header & footer info
		 */
	    $this->setData('userLabel', common_session_SessionManager::getSession()->getUserLabel());
	    $this->setData('showControls', $this->showControls());
        $this->setData('returnUrl', $this->getReturnUrl());

        /* @var $urlRouteService DefaultUrlService */
        $urlRouteService = $this->getServiceManager()->get(DefaultUrlService::SERVICE_ID);
        $this->setData('logout', $urlRouteService->getUrl('logoutDelivery' , []));

        /**
         * Layout template + real template inclusion
         */
        $this->setData('content-template', 'DeliveryServer/runDeliveryExecution.tpl');
        $this->setData('content-extension', 'taoDelivery');
        $this->setView('DeliveryServer/layout.tpl', 'taoDelivery');
	}
3704
public function update($identity, $label = null, $master = null, $status = null)
    {

        $params = array();
        if (! is_null($label)) {
            $params['label'] = $label;
        }
        if (! is_null($master)) {
            $params['master'] = $master;
        }
        if (! is_null($status)) {
            $params['status'] = $status;
        }

        return $this->_user->put('account/identity/' . $identity, $params);
    }
854847
public function setDeliveryStatusForProduct($product, $statusId)
    {
        $status = $this->deliveryStatusRepository->find($statusId);
        if (!$status) {
            throw new ProductDependencyNotFoundException(self::$productStatusEntityName, $statusId);
        }
        $product->setDeliveryStatus($status);
    }
437323
private function createContext($userPublicKey)
    {
        $label = 'P-256';
        // The two length fields are encoded as a two octet unsigned integer in network byte order.
        $recipientPublicLength = chr(0).chr(strlen($userPublicKey));
        $senderPublicLength = chr(0).chr(strlen($this->publicKeyContent));

        return $label.chr(0).$recipientPublicLength.$userPublicKey.$senderPublicLength.$this->publicKeyContent;
    }
809697
public function createInstance(core_kernel_classes_Class $clazz, $label = '')
    {
        $delivery = parent::createInstance($clazz, $label);
        
        // set the default delivery server:
        $defaultServer = taoResultServer_models_classes_ResultServerAuthoringService::singleton()->getDefaultResultServer();
        $delivery->setPropertyValue(new core_kernel_classes_Property(TAO_DELIVERY_RESULTSERVER_PROP), $defaultServer);
        
        // set content model if only 1 available
        $models = $this->getAllContentClasses();
        if (count($models) == 1) {
            $contentClass = new core_kernel_classes_Class(current($models));
            $this->createContent($delivery, $contentClass);
        }
        
        
        return $delivery;
    }
1321732
public static function create_from_ids(int $userfromid, int $usertoid, int $messageid, int $courseid) {
        // We may be sending a message from the 'noreply' address, which means we are not actually sending a
        // message from a valid user. In this case, we will set the userid to 0.
        // Check if the userid is valid.
        if (!\core_user::is_real_user($userfromid)) {
            $userfromid = 0;
        }

        $event = self::create(array(
            'objectid' => $messageid,
            'userid' => $userfromid,
            'context' => \context_system::instance(),
            'relateduserid' => $usertoid,
            'other' => array(
                'courseid' => $courseid
            )
        ));

        return $event;
    }