$config The configuration for the Table. * @return void */ public function initialize(array $config): void { parent::initialize($config); $this->setTable('polls'); $this->setDisplayField('title'); $this->setPrimaryKey('id'); $this->addBehavior('Timestamp'); $this->hasMany('Slides', [ 'foreignKey' => 'poll_id', 'sort' => ['Slides.position' => 'ASC', 'Slides.id' => 'ASC'], 'dependent' => true, // Delete slide by slide so their options and responses go too. Do not rely on // ON DELETE CASCADE: SQLite does not enforce foreign keys by default. 'cascadeCallbacks' => true, ]); } /** * After the poll is gone for good, so are the image files of its slides (the slides remove * their own; this also sweeps what a crash left behind). * * @param \Cake\Event\EventInterface<\Cake\ORM\Table> $event Event * @param \Cake\Datasource\EntityInterface $entity Deleted poll * @param \ArrayObject $options Options * @return void */ public function afterDeleteCommit(EventInterface $event, EntityInterface $entity, ArrayObject $options): void { (new ImageService())->deletePoll((int)$entity->get('id')); } /** * @param \Cake\Validation\Validator $validator Validator instance. * @return \Cake\Validation\Validator */ public function validationDefault(Validator $validator): Validator { $validator ->scalar('title') ->maxLength('title', 200, __('Der Titel darf maximal 200 Zeichen lang sein.')) ->requirePresence('title', 'create') ->notEmptyString('title', __('Bitte gib einen Titel ein.')); $validator ->email('email', false, __('Bitte gib eine gültige E-Mail-Adresse ein.')) ->maxLength('email', 255) ->requirePresence('email', 'create') ->notEmptyString('email', __('Bitte gib deine E-Mail-Adresse ein.')); $validator->boolean('is_active'); $validator ->integer('comment_speed') ->inList('comment_speed', Poll::COMMENT_SPEEDS, __('Bitte wähle eine der angebotenen Geschwindigkeiten.')); return $validator; } /** * @param \Cake\ORM\RulesChecker $rules The rules object to be modified. * @return \Cake\ORM\RulesChecker */ public function buildRules(RulesChecker $rules): RulesChecker { $rules->add($rules->isUnique(['join_code']), ['errorField' => 'join_code']); $rules->add($rules->isUnique(['admin_token_hash']), ['errorField' => 'admin_token_hash']); return $rules; } /** * Creates a new admin token: URL safe, 256 bit entropy. * * @return string */ public static function generateToken(): string { return rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '='); } /** * @param string $token Plain admin token * @return string sha256 hex digest */ public static function hashToken(string $token): string { return hash('sha256', $token); } /** * Assigns a fresh admin token to the poll (hash + encrypted copy). * * @param \App\Model\Entity\Poll $poll Poll entity * @return string The plain token (only ever shown in the admin URL / mail) */ public function assignNewToken(Poll $poll): string { $token = static::generateToken(); $poll->admin_token_hash = static::hashToken($token); $poll->admin_token_encrypted = base64_encode(Security::encrypt($token, static::encryptionKey())); return $token; } /** * Decrypts the stored admin token (used by the recovery mail). * * @param \App\Model\Entity\Poll $poll Poll entity * @return string|null */ public function decryptToken(Poll $poll): ?string { $raw = base64_decode((string)$poll->admin_token_encrypted, true); if ($raw === false) { return null; } $token = Security::decrypt($raw, static::encryptionKey()); if ($token === null || static::hashToken($token) !== $poll->admin_token_hash) { return null; } return $token; } /** * @return string 32 byte key derived from Security.salt */ protected static function encryptionKey(): string { return hash('sha256', 'plenario-admin-token|' . Security::getSalt()); } /** * Generates a join code that is not yet in use. * * @return string */ public function generateJoinCode(): string { $alphabet = self::JOIN_CODE_ALPHABET; $max = strlen($alphabet) - 1; for ($attempt = 0; $attempt < 50; $attempt++) { $code = ''; for ($i = 0; $i < self::JOIN_CODE_LENGTH; $i++) { $code .= $alphabet[random_int(0, $max)]; } if (!$this->exists(['join_code' => $code])) { return $code; } } throw new RuntimeException('Could not generate a unique join code.'); } /** * Normalises user input like " k7p-2qx " to "K7P2QX". * * @param string $code Raw user input * @return string */ public static function normalizeJoinCode(string $code): string { return (string)preg_replace('/[^A-Z0-9]/', '', strtoupper($code)); } /** * Builds and validates a new, not yet saved poll from form input (title + email, normalised). * * @param array $data Request data * @return \App\Model\Entity\Poll Check getErrors() */ public function newPoll(array $data): Poll { $field = fn(string $key): string => is_scalar($data[$key] ?? null) ? trim((string)$data[$key]) : ''; return $this->newEntity([ 'title' => $field('title'), 'email' => strtolower($field('email')), ], ['fields' => ['title', 'email']]); } /** * Creates and persists a new poll. * * @param array $data title + email * @return array{0: \App\Model\Entity\Poll, 1: string|null} The entity (check getErrors()) and the plain token on success */ public function createPoll(array $data): array { return $this->insertPoll($this->newPoll($data)); } /** * Assigns token and join code and saves a poll built by newPoll(). * * @param \App\Model\Entity\Poll $poll New poll * @return array{0: \App\Model\Entity\Poll, 1: string|null} The entity (check getErrors()) and the plain token on success */ public function insertPoll(Poll $poll): array { if ($poll->hasErrors()) { return [$poll, null]; } $token = $this->assignNewToken($poll); $poll->join_code = $this->generateJoinCode(); $poll->is_active = true; if (!$this->save($poll)) { return [$poll, null]; } return [$poll, $token]; } /** * @param \Cake\ORM\Query\SelectQuery $query Query * @param string $token Plain admin token * @return \Cake\ORM\Query\SelectQuery */ public function findByAdminToken(SelectQuery $query, string $token): SelectQuery { return $query->where(['Polls.admin_token_hash' => static::hashToken($token)]); } /** * @param \Cake\ORM\Query\SelectQuery $query Query * @param string $code Join code (will be normalised) * @return \Cake\ORM\Query\SelectQuery */ public function findByJoinCode(SelectQuery $query, string $code): SelectQuery { return $query->where(['Polls.join_code' => static::normalizeJoinCode($code)]); } /** * Polls past their expiry date (created + retention, see Poll::expiresAt()); none if the retention is 0. * * @param \Cake\ORM\Query\SelectQuery $query Query * @return \Cake\ORM\Query\SelectQuery */ public function findExpired(SelectQuery $query): SelectQuery { $days = (int)Configure::read('Plenario.retention.days', 90); if ($days <= 0) { return $query->where('1 = 0'); } return $query->where(['Polls.created <' => DateTime::now()->subDays($days)]); } /** * Polls whose reminder is due and not yet sent: inside the last `reminderDays` before the expiry, * but not expired yet (then it is too late, they are deleted). * * @param \Cake\ORM\Query\SelectQuery $query Query * @return \Cake\ORM\Query\SelectQuery */ public function findReminderDue(SelectQuery $query): SelectQuery { $lead = Poll::reminderLeadDays(); if ($lead === 0) { return $query->where('1 = 0'); } $days = (int)Configure::read('Plenario.retention.days', 90); $now = DateTime::now(); return $query->where([ 'Polls.expiry_reminded_at IS' => null, 'Polls.created <=' => $now->subDays($days - $lead), 'Polls.created >=' => $now->subDays($days), ]); } /** * @param \Cake\ORM\Query\SelectQuery $query Query * @param string $key Embed key * @return \Cake\ORM\Query\SelectQuery */ public function findByEmbedKey(SelectQuery $query, string $key): SelectQuery { // Never match polls without key (null) and never compare against an empty string. return $query->where(['Polls.embed_key' => $key === '' ? '-' : $key]); } /** * Creates the embed key on first use; keeps an existing one (idempotent). * * @param \App\Model\Entity\Poll $poll Poll * @return string */ public function ensureEmbedKey(Poll $poll): string { if ($poll->embed_key === null || $poll->embed_key === '') { return $this->rotateEmbedKey($poll); } return $poll->embed_key; } /** * New embed key, all previous embed URLs stop working. * * @param \App\Model\Entity\Poll $poll Poll * @return string */ public function rotateEmbedKey(Poll $poll): string { // Only the key column, so the rest of the entity (e.g. live slide) is not overwritten. $key = static::generateToken(); $this->updateAll(['embed_key' => $key], ['id' => $poll->id]); $poll->embed_key = $key; $poll->setDirty('embed_key', false); return $key; } /** * Pauses the poll when the embedded slide that made itself live has stopped reporting * (presentation moved on to a non-PlenarIO slide, or was closed without a pause beacon). * Called lazily whenever the state is read, like SlidesTable::closeIfExpired(). * * @param \App\Model\Entity\Poll $poll Poll * @return \App\Model\Entity\Poll */ public function pauseIfEmbedStale(Poll $poll): Poll { $timeout = max(1, (int)Configure::read('Plenario.embed.timeoutSeconds', 20)); if ( $poll->embed_seen_at === null || $poll->current_slide_id === null || $poll->embed_seen_at->wasWithinLast($timeout . ' seconds') ) { return $poll; } // Conditional update: a concurrent heartbeat or slide change wins. $this->updateAll( ['current_slide_id' => null, 'paused_slide_id' => $poll->current_slide_id, 'embed_seen_at' => null], ['id' => $poll->id, 'current_slide_id' => $poll->current_slide_id, 'embed_seen_at' => $poll->embed_seen_at], ); /** @var \App\Model\Entity\Poll $fresh */ $fresh = $this->get($poll->id); foreach (['current_slide_id', 'paused_slide_id', 'embed_seen_at'] as $field) { $poll->set($field, $fresh->get($field)); $poll->setDirty($field, false); } return $poll; } }