Live Scoreboard generation.

@param \Drupal\node\Entity\Node $node

@return array|bool
9496
public function generateLiveScorecard(Node $node) {
    if ($node->bundle() != 'campaign') {
      return FALSE;
    }

    // Prepare dates of campaign.
    $campaignTimezone = new \DateTime($node->get('field_campaign_timezone')->getString());
    $campaignTimezone = $campaignTimezone->getTimezone();

    // All time of campaign.
    $localeCampaignStart = OpenYLocaleDate::createDateFromFormat($node->get('field_campaign_start_date')->getString());
    $localeCampaignStart->convertTimezone($campaignTimezone);

    $localeCampaignEnd = OpenYLocaleDate::createDateFromFormat($node->get('field_campaign_end_date')->getString());
    $localeCampaignEnd->convertTimezone($campaignTimezone);

    // Time of early registration.
    $localeRegistrationStart = OpenYLocaleDate::createDateFromFormat($node->get('field_campaign_reg_start_date')->getString());
    $localeRegistrationStart->convertTimezone($campaignTimezone);

    $localeRegistrationEnd = OpenYLocaleDate::createDateFromFormat($node->get('field_campaign_reg_end_date')->getString());
    $localeRegistrationEnd->convertTimezone($campaignTimezone);

    $result['dates']['registration_start'] = $localeRegistrationStart->getDate()->format('m/d');
    $result['dates']['registration_end'] = $localeRegistrationEnd->getDate()->format('m/d');
    $result['dates']['campaign_start'] = $localeCampaignStart->getDate()->format('m/d');
    $result['dates']['campaign_end'] = $localeCampaignEnd->getDate()->format('m/d');

    // Current dates. + labels with dates.
    $localTime = OpenYLocaleDate::createDateFromFormat(date('c'));
    $localTime->convertTimezone($campaignTimezone);

    if ($localTime > $localeRegistrationEnd) {
      $actual_early_date = $localeRegistrationEnd->getDate()->format('m/d') . ' at ' . $localeRegistrationEnd->getDate()->format('h:ia');
    }
    else {
      $actual_early_date = $localTime->getDate()->format('m/d');
    }

    if ($localTime > $localeCampaignEnd) {
      $actual_campaign_date = $localeCampaignEnd->getDate()->format('m/d') . ' at ' . $localeCampaignEnd->getDate()->format('h:ia');
    }
    else {
      $actual_campaign_date = $localTime->getDate()->format('m/d');
    }

    $result['dates']['actual_date'] = $localTime->getDate()->format('m/d');
    $result['dates']['actual_early_date'] = $actual_early_date;
    $result['dates']['actual_campaign_date'] = $actual_campaign_date;

    // Get branches for current campaign.
    $branches = $this->getCampaignBranches($node);

    if (!empty($branches['branches'])) {

      $branchIds = [];
      foreach ($branches['branches'] as $branch) {
        $branchIds[] = $branch->branch;
      }

      $targets = $branches['targets'];
      $branchList = $branches['branches'];
      // Calculate registered members by branch, Early registration and During all campain.
      $earlyActualMembers = $this->calculateRegisteredMembersByBranch($node, $branchIds, $localeRegistrationStart->getTimestamp(), $localeRegistrationEnd->getTimestamp());
      $challengeRegistrationOfMembers = $this->calculateRegisteredMembersByBranch($node, $branchIds, $localeRegistrationStart->getTimestamp(), $localeCampaignEnd->getTimestamp());

      // Prepare render array.
      $result['registration']['early'] = [];
      $result['registration']['challenge'] = [];
      $result['utilization'] = [];

      $register_goal = $node->get('field_campaign_registration_goal')->getValue();
      $utilization_goal = $node->get('field_campaign_utilization_goal')->getValue();
      $registerGoal = !empty($register_goal) ? $register_goal[0]['value'] : 5;
      $utilizationGoal = !empty($utilization_goal) ? $utilization_goal[0]['value'] : 45;

      $result['goals']['registration_goal'] = $registerGoal;
      $result['goals']['utilization_goal'] = $utilizationGoal;

      $util_by_branch = $this->getCampaignUtilizationActivitiesByBranches($node);

      foreach ($branchList as $id => $branch) {

        $result['branches'][$id]['nid'] = $branch->personify_branch;
        $result['branches'][$id]['title'] = $branch->title;
        $target = $targets[$id];
        $result['branches'][$id]['target'] = $target;

        // Early registration calculation.
        $goal = number_format($target * $registerGoal / 100);

        $result['registration']['early'][$id]['registration_goal'] = $goal;

        $actual = !empty($earlyActualMembers[$id]->count_id) ? $earlyActualMembers[$id]->count_id : 0;
        $result['registration']['early'][$id]['actual'] = $actual;

        $of_members = number_format($actual / $targets[$id] * 100, 1);
        $result['registration']['early'][$id]['of_members'] = $of_members;

        $of_goal = $goal ? number_format($actual / $goal * 100, 1) : 0;
        $result['registration']['early'][$id]['of_goal'] = $of_goal;
        if (!array_key_exists('total', $result)) {
          $result['total'] = [];
        }
        // Total Early registration calculation.
        if (!array_key_exists('target', $result['total'])){
          $result['total']['target'] = 0;
        }
        $result['total']['target'] += $target;
        if (!array_key_exists('registration_goal', $result['total'])){
          $result['total']['registration_goal'] = 0;
        }
        $result['total']['registration_goal'] += $goal;
        if (!array_key_exists('actual', $result['total'])){
          $result['total']['actual'] = 0;
        }
        $result['total']['actual'] += $actual;
        if (!array_key_exists('of_members', $result['total'])){
          $result['total']['of_members'] = 0;
        }
        $result['total']['of_members'] += $of_members;
        if (!array_key_exists('of_goal', $result['total'])){
          $result['total']['of_goal'] = 0;
        }
        $result['total']['of_goal'] += $of_goal;

        // Challenge registration calculation.
        $result['registration']['challenge'][$id]['registration_goal'] = $goal;

        $reg_actual = !empty($challengeRegistrationOfMembers[$id]->count_id) ? $challengeRegistrationOfMembers[$id]->count_id : 0;
        $result['registration']['challenge'][$id]['actual'] = $reg_actual;

        $reg_of_member = number_format($reg_actual / $target * 100, 1);
        $result['registration']['challenge'][$id]['of_members'] = $reg_of_member;

        $reg_of_goal = $goal ? number_format($reg_actual / $goal * 100, 1) : 0;
        $result['registration']['challenge'][$id]['of_goal'] = $reg_of_goal;
        if (!array_key_exists('reg_registration_goal', $result['total'])){
          $result['total']['reg_registration_goal'] = 0;
        }
        $result['total']['reg_registration_goal'] += $goal;
        if (!array_key_exists('reg_actual', $result['total'])){
          $result['total']['reg_actual'] = 0;
        }
        $result['total']['reg_actual'] += $reg_actual;
        if (!array_key_exists('reg_of_members', $result['total'])){
          $result['total']['reg_of_members'] = 0;
        }
        $result['total']['reg_of_members'] += $reg_of_member;
        if (!array_key_exists('reg_of_goal', $result['total'])){
          $result['total']['reg_of_goal'] = 0;
        }
        $result['total']['reg_of_goal'] += $reg_of_goal;

        // Utilization calculation.
        if ($actual >= $goal) {
          $util_goal = number_format($actual * $utilizationGoal / 100);
        }
        else {
          $util_goal = number_format($goal * $utilizationGoal / 100);
        }

        $result['utilization'][$id]['goal'] = $util_goal;

        $util_actual = isset($util_by_branch[$id]) ? $util_by_branch[$id] : 0;
        $result['utilization'][$id]['actual'] = $util_actual;

        if (!empty($reg_actual)) {
          $util_of_member = number_format($util_actual / $reg_actual * 100, 1);
        }
        else {
          $util_of_member = 0;
        }

        $result['utilization'][$id]['of_members'] = $util_of_member;

        $util_of_goal = $util_goal ? number_format($util_actual / $util_goal * 100, 1) : 0;

        $result['utilization'][$id]['of_goal'] = $util_of_goal;

        // Utilization total.
        if (!array_key_exists('util_registration_goal', $result['total'])){
          $result['total']['util_registration_goal'] = 0;
        }
        $result['total']['util_registration_goal'] += $util_goal;
        // Doesn't include results for members without branch ($id = 0 or '').
        if (!array_key_exists('util_actual', $result['total'])){
          $result['total']['util_actual'] = 0;
        }
        if (!array_key_exists('util_of_members', $result['total'])){
          $result['total']['util_of_members'] = 0;
        }
        $result['total']['util_of_members'] += $util_of_member;
        if (!array_key_exists('util_of_goal', $result['total'])){
          $result['total']['util_of_goal'] = 0;
        }
        $result['total']['util_of_goal'] += $util_of_goal;

      }

      $result['total']['of_members'] = number_format($result['total']['of_members'] / count($targets), 1);
      $result['total']['of_goal'] = number_format($result['total']['of_goal'] / count($targets), 1);
      $result['total']['reg_of_members'] = number_format($result['total']['reg_of_members'] / count($targets), 1);
      $result['total']['reg_of_goal'] = number_format($result['total']['reg_of_goal'] / count($targets), 1);
      $result['total']['util_of_members'] = number_format($result['total']['util_of_members'] / count($targets), 1);
      $result['total']['util_of_goal'] = number_format($result['total']['util_of_goal'] / count($targets), 1);
    }
    else {
      $result['empty'] = t('Campaign @campaign has no active branches. Please edit current campaign', ['@campaign' => $node->label()]);
    }
    $build = [
      '#theme' => 'openy_campaign_scorecard',
      '#result' => $result
    ];

    return $build;
  }
673957
protected function generateNodeMarkup(Node $node) : string
    {
        if ($node instanceof TagNode) {
            // Find tad definition.
            $tag = $node->getTag();
            $tagName = $tag->getTagName();
            $tagDef = $this->tagDefs->get($tagName);

            // Recursive generate markup for the inner content.
            $children = $node->getChildren();
            $content = $this->generateMarkup($children);

            // Generate markup for this tag.
            $attribute = $tag->getAttribute();
            return $tagDef->generateMarkup($attribute, $content);
        } else {
            /** @var TextNode $node */
            return $node->getText();
        }
    }
454800
public function getChildren(Node $node, $includeHiddenFromNav = true)
    {
        $this->init();
        $children = array();

        if (array_key_exists($node->getId(), $this->childNodes)) {
            $nodes = $this->childNodes[$node->getId()];
            /* @var Node $childNode */
            foreach ($nodes as $childNode) {
                $nodeTranslation = $childNode->getNodeTranslation(
                    $this->locale,
                    $this->includeOffline
                );
                if (!is_null($nodeTranslation)) {
                    $children[] = new NodeMenuItem(
                        $childNode,
                        $nodeTranslation,
                        false,
                        $this
                    );
                }
            }

            $children = array_filter(
                $children,
                function (NodeMenuItem $entry) use ($includeHiddenFromNav) {
                    if ($entry->getNode()->isHiddenFromNav(
                        ) && !$includeHiddenFromNav
                    ) {
                        return false;
                    }

                    return true;
                }
            );
        }

        return $children;
    }
28670
public function execute(NodeData $node)
    {
        foreach ($node->getNodeType()->getProperties() as $propertyName => $propertyConfiguration) {
            if (isset($propertyConfiguration['type']) && in_array(trim($propertyConfiguration['type']), $this->getHandledObjectTypes())) {
                if (!isset($nodeProperties)) {
                    $nodeRecordQuery = $this->entityManager->getConnection()->prepare('SELECT properties FROM typo3_typo3cr_domain_model_nodedata WHERE persistence_object_identifier=?');
                    $nodeRecordQuery->execute([$this->persistenceManager->getIdentifierByObject($node)]);
                    $nodeRecord = $nodeRecordQuery->fetch(\PDO::FETCH_ASSOC);
                    $nodeProperties = unserialize($nodeRecord['properties']);
                }

                if (!isset($nodeProperties[$propertyName]) || !is_object($nodeProperties[$propertyName])) {
                    continue;
                }

                /** @var Asset $assetObject */
                $assetObject = $nodeProperties[$propertyName];
                $nodeProperties[$propertyName] = null;

                $stream = $assetObject->getResource()->getStream();

                if ($stream === false) {
                    continue;
                }

                fclose($stream);
                $objectType = TypeHandling::getTypeForValue($assetObject);
                $objectIdentifier = ObjectAccess::getProperty($assetObject, 'Persistence_Object_Identifier', true);

                $nodeProperties[$propertyName] = [
                    '__flow_object_type' => $objectType,
                    '__identifier' => $objectIdentifier
                ];
            }
        }

        if (isset($nodeProperties)) {
            $nodeUpdateQuery = $this->entityManager->getConnection()->prepare('UPDATE typo3_typo3cr_domain_model_nodedata SET properties=? WHERE persistence_object_identifier=?');
            $nodeUpdateQuery->execute([serialize($nodeProperties), $this->persistenceManager->getIdentifierByObject($node)]);
        }
    }
624637
public function enterNode(Node $node)
    {
        if ($node instanceof Namespace_) {
            $this->resetContext($node->name);
        }

        $this->recordDoc($node->getAttribute('comments', []));

        return $node;
    }
171000
public function ajaxCallbackGenerateLiveScorecard($node) {
    $node = $this->entityTypeManager->getStorage('node')->load($node);
    $result = $this->campaignScorecardService->generateLiveScorecard($node);
    return new Response($this->renderer->render($result));
  }
720207
public function compile(Node $node) : string
    {
        $this->head = $this->body = '';
        $node->compile($this);
        return $this->getResult();
    }
1268553
public function addNode(Node $node)
    {
        $node->setNavigation($this);
        $this->nodes[] = $node;

        return $this;
    }
1264080
protected function compileFor(Node $node)
    {

        $subject = $node->subject;
        $phtml = $this->createCode("for ({$subject}) {").$this->newLine();
        $phtml .= $this->compileChildren($node->children).$this->newLine();
        $phtml .= $this->indent().$this->createCode('}').$this->newLine();

        return $phtml;
    }
1270203
public function transform($node)
    {
        $blocksData = $this->transformBlock($node);
        $documentData = array(
            'id' => $node->getNodeId() . '-' . $node->getLanguage(). '-' . $node->getSiteId(),
            'elementId' => $node->getId(),
            'nodeId' => $node->getNodeId(),
            'siteId' => $node->getSiteId(),
            'language' => $node->getLanguage(),
            'name' => $node->getName(),
            'blocks' => $blocksData
        );

        if (!is_null($node->getUpdatedAt())) {
            $documentData['updatedAt'] = $node->getUpdatedAt()->getTimestamp();
        }

        $document = new Document($documentData['id'], $documentData);

        return $document;
    }
170176
public function processUploadResponse($node)
    {
        $id = $node->getAttribute('id');
        $messageNode = @$this->mediaQueue[$id];
        if ($messageNode == null) {
            //message not found, can't send!
            $this->eventManager()->fire('onMediaUploadFailed',
                [
                    $this->phoneNumber,
                    $id,
                    $node,
                    $messageNode,
                    'Message node not found in queue',
                ]);

            return false;
        }

        $duplicate = $node->getChild('duplicate');
        if ($duplicate != null) {
            //file already on whatsapp servers
            $url = $duplicate->getAttribute('url');
            $filesize = $duplicate->getAttribute('size');
//          $mimetype = $duplicate->getAttribute("mimetype");
            $filehash = $duplicate->getAttribute('filehash');
            $filetype = $duplicate->getAttribute('type');
//          $width = $duplicate->getAttribute("width");
//          $height = $duplicate->getAttribute("height");
            $exploded = explode('/', $url);
            $filename = array_pop($exploded);
        } else {
            //upload new file
            $json = WhatsMediaUploader::pushFile($node, $messageNode, $this->mediaFileInfo, $this->phoneNumber);

            if (!$json) {
                //failed upload
                $this->eventManager()->fire('onMediaUploadFailed',
                    [
                        $this->phoneNumber,
                        $id,
                        $node,
                        $messageNode,
                        'Failed to push file to server',
                    ]);

                return false;
            }

            $url = $json->url;
            $filesize = $json->size;
//          $mimetype = $json->mimetype;
            $filehash = $json->filehash;
            $filetype = $json->type;
//          $width = $json->width;
//          $height = $json->height;
            $filename = $json->name;
        }

        $mediaAttribs = [];
        $mediaAttribs['type'] = $filetype;
        $mediaAttribs['url'] = $url;
        $mediaAttribs['encoding'] = 'raw';
        $mediaAttribs['file'] = $filename;
        $mediaAttribs['size'] = $filesize;
        if ($this->mediaQueue[$id]['caption'] != '') {
            $mediaAttribs['caption'] = $this->mediaQueue[$id]['caption'];
        }
        if ($this->voice == true) {
            $mediaAttribs['origin'] = 'live';
            $this->voice = false;
        }

        $filepath = $this->mediaQueue[$id]['filePath'];
        $to = $this->mediaQueue[$id]['to'];

        switch ($filetype) {
            case 'image':
                $caption = $this->mediaQueue[$id]['caption'];
                $icon = createIcon($filepath);
                break;
            case 'video':
                $caption = $this->mediaQueue[$id]['caption'];
                $icon = createVideoIcon($filepath);
                break;
            default:
                $caption = '';
                $icon = '';
                break;
        }
        //Retrieve Message ID
        $message_id = $messageNode['message_id'];

        $mediaNode = new ProtocolNode('media', $mediaAttribs, null, $icon);
        if (is_array($to)) {
            $this->sendBroadcast($to, $mediaNode, 'media');
        } else {
            $this->sendMessageNode($to, $mediaNode, $message_id);
        }
        $this->eventManager()->fire('onMediaMessageSent',
            [
                $this->phoneNumber,
                $to,
                $message_id,
                $filetype,
                $url,
                $filename,
                $filesize,
                $filehash,
                $caption,
                $icon,
            ]);

        return true;
    }
75656
public function enterNode(Node $node)
    {
        if ($node instanceof Class_) {
            $this->class = $node;
            $this->abstractMethods = [];
        } elseif ($node instanceof ClassMethod) {
            if ($node->isAbstract()) {
                $name = \sprintf('%s::%s', $this->class->name, $node->name);
                $this->abstractMethods[] = $name;

                if ($node->stmts !== null) {
                    $msg = \sprintf('Abstract function %s cannot contain body', $name);
                    throw new FatalErrorException($msg, 0, E_ERROR, null, $node->getLine());
                }
            }
        }
    }
519276
public function append(Node $node)
    {

        if (!is_array($this->_children)) {
            $this->_children = [];
        }

        $this->_children[] = $node;
        return $this;
    }
86081
final public function mutate(Node $node)
    {
        foreach ($this->getParameterIndexes($node) as $index) {
            yield $node->args[$index];
        }
    }
498232
public function _body($node) {
		$params = '';
		if (isset($node['@attrib'])) {
			$params = $this->resolveAttr($node['@attrib']);
			unset($node['@attrib']);
		}
		$content = array();
		// bypass inner content nodes
		foreach ($node as $el)
			$content[] = $this->template->build($el);
		return '<body'.$params.'>'.implode("\n", $content)."\n".
			$this->render('footer')."\n".'</body>';
	}
85008
private function getParentTreeParams(\Coral\ContentBundle\Entity\Node $node)
    {
        $params = $this->getDoctrine()->getManager()->createQuery(
                'SELECT n.level, na.name, na.value
                FROM CoralContentBundle:NodeAttribute na
                INNER JOIN na.node n WITH (n.lft < :lft AND n.rgt > :rgt)
                INNER JOIN n.account a WITH (a.id = :account_id)
                WHERE
                    na.name LIKE \'tree_%\'
                ORDER BY n.level ASC'
            )
            ->setParameter('account_id', $this->getAccount()->getId())
            ->setParameter('lft', $node->getLft())
            ->setParameter('rgt', $node->getRgt())
            ->getResult(\Doctrine\ORM\AbstractQuery::HYDRATE_ARRAY);

        $treeParams = array();

        foreach ($params as $param)
        {
            $treeParams[$param['name']] = $param['value'];
        }

        return $treeParams;
    }
818974
public function filter($node)
    {
        $ret = array();
        $items = $this->_combinator->filter($node, $this->_element->getTagName());

        // filters items by element
        foreach ($items as $item) {
            if ($this->_element->match($item)) {
                array_push($ret, $item);
            }
        }

        // filter items by element filters
        $filters = $this->_element->getFilters();
        foreach ($filters as $filter) {
            $items = array();
            foreach ($ret as $i => $item) {
                if ($filter->match($item, $i, $ret)) {
                    array_push($items, $item);
                }
            }
            $ret = $items;
        }

        return $ret;
    }