Proyectos de Subversion Moodle

Rev

Rev 379 | Rev 383 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

<?php

class StaticsBlocks
{
    public $user;
    public $userID;
    public $currentUser;
    public $blockManager;
    public $blockExists;
    public $blockNames;
    public $regionName;

    public function __construct($blockNames, $regionName)
    {
        global $USER, $PAGE;
        require_login(null, false);

        if (isguestuser()) {
            throw new require_login_exception('Guests are not allowed here.');
        }

        $this->userID = optional_param('userid', $USER->id, PARAM_INT);
        $this->currentUser = $this->userID == $USER->id;
        $this->user = core_user::get_user($this->userID);
        $this->blockManager = $PAGE->blocks;
        $this->blockNames = $blockNames;
        $this->regionName = $regionName;

        if (!$this->user || !core_user::is_real_user($this->userID)) {
            throw new moodle_exception('invaliduser', 'error');
        }
    }

    public function addRegion()
    {
        if (!in_array($this->regionName, $this->blockManager->get_regions())) {
            $this->blockManager->add_region($this->regionName);
        }
    }

    public function validateIfExistBlocks()
    {
        $blocks = $this->blockManager->get_blocks_for_region($this->regionName);
        $this->blockExists = true;

        foreach ($this->blockNames as $blockName) {
            $blockFound = false;
            foreach ($blocks as $block) {
                $blockclass = get_class($block);
                if ($blockclass == 'block_' . $blockName) {
                    $blockFound = true;
                    break;
                }
            }
            if (!$blockFound) {
                $this->blockExists = false;
                break; // Si un bloque no existe, no es necesario seguir buscando
            }
        }

        return $this->blockExists;
    }

    public function addBlocksIfNotExist()
    {
        if (!$this->blockExists) {
            foreach ($this->blockNames as $blockName) {
                $this->blockManager->add_block($blockName, $this->regionName, 1, true);
            }
        }
    }

    public function renderBlocks()
    {
        global $OUTPUT;

        $blocksView = '';

        $this->addRegion(); // Validar si la región existe y añadirla en caso de no existir

        $this->blockManager->load_blocks(true); // Cargar bloques en la región

        $this->validateIfExistBlocks(); // Valida si el listado de bloques pasados por parametros coincide con los bloques cargados
        $this->addBlocksIfNotExist(); // Agrega los bloques en caso de no coincidir

        $blocksView .= $OUTPUT->blocks_for_region($this->regionName); // Renderizar los bloques de la región

        return $blocksView; // Devolver bloques renderizados
    }
}