hide map for Character groups Quest Stations when there are no stations

This commit is contained in:
oliver 2016-04-09 13:44:37 +02:00
commit df14dfafc3
4371 changed files with 1220224 additions and 0 deletions

View file

@ -0,0 +1,24 @@
<?php
/**
* The Legend of Z
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
* @copyright 2014 Heinrich-Heine-Universität Düsseldorf
* @license http://www.gnu.org/licenses/gpl.html
* @link https://bitbucket.org/coderkun/the-legend-of-z
*/
namespace hhu\z\questtypes;
/**
* QuesttypeAgent for a boss-fight.
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
*/
class BossfightQuesttypeAgent extends \hhu\z\agents\QuesttypeAgent
{
}
?>

View file

@ -0,0 +1,292 @@
<?php
/**
* The Legend of Z
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
* @copyright 2014 Heinrich-Heine-Universität Düsseldorf
* @license http://www.gnu.org/licenses/gpl.html
* @link https://bitbucket.org/coderkun/the-legend-of-z
*/
namespace hhu\z\questtypes;
/**
* Controller of the BossfightQuesttypeAgent for a boss-fight.
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
*/
class BossfightQuesttypeController extends \hhu\z\controllers\QuesttypeController
{
/**
* Required models
*
* @var array
*/
public $models = array('media');
/**
* Save the answers of a Character for a Quest.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
* @param array $character Current Character data
* @param array $answers Character answers for the Quest
*/
public function saveAnswersOfCharacter($seminary, $questgroup, $quest, $character, $answers)
{
// Prepare session
$this->prepareSession($quest['id']);
// Remove previous answers
$this->Bossfight->clearCharacterSubmissions($quest['id'], $character['id']);
// Save answers
foreach($_SESSION['quests'][$quest['id']]['stages'] as &$stage) {
$this->Bossfight->setCharacterSubmission($stage['id'], $character['id']);
}
}
/**
* Save additional data for the answers of a Character for a Quest.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
* @param array $character Current Character data
* @param array $data Additional (POST-) data
*/
public function saveDataForCharacterAnswers($seminary, $questgroup, $quest, $character, $data)
{
}
/**
* Check if answers of a Character for a Quest match the correct ones.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
* @param array $character Current Character data
* @param array $answers Character answers for the Quest
* @return boolean True/false for a right/wrong answer or null for moderator evaluation
*/
public function matchAnswersOfCharacter($seminary, $questgroup, $quest, $character, $answers)
{
return true;
}
/**
* Action: quest.
*
* Display a stage with a text and the answers for the following
* stages.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
* @param array $character Current Character data
* @param \Exception $exception Character submission exception
*/
public function quest($seminary, $questgroup, $quest, $character, $exception)
{
// Get Boss-Fight
$fight = $this->Bossfight->getBossFight($quest['id']);
if(!is_null($fight) && !is_null($fight['boss_seminarymedia_id'])) {
$fight['bossmedia'] = $this->Media->getSeminaryMediaById($fight['boss_seminarymedia_id']);
}
// Prepare session
$this->prepareSession($quest['id']);
// Get Stage
if($this->request->getRequestMethod() == 'POST' && !is_null($this->request->getPostParam('submit_stages')))
{
$stages = $this->request->getPostParam('submit_stages');
$stageId = array_keys($stages)[0];
$stage = $this->Bossfight->getStageById($stageId);
}
else
{
$_SESSION['quests'][$quest['id']]['stages'] = array();
$stage = $this->Bossfight->getFirstStage($quest['id']);
}
// Store Stage in session
if(count($_SESSION['quests'][$quest['id']]['stages']) == 0 || $_SESSION['quests'][$quest['id']]['stages'][count($_SESSION['quests'][$quest['id']]['stages'])-1]['id'] != $stage['id']) {
$_SESSION['quests'][$quest['id']]['stages'][] = $stage;
}
// Calculate lives
$lives = array(
'character' => $fight['lives_character'],
'boss' => $fight['lives_boss']
);
foreach($_SESSION['quests'][$quest['id']]['stages'] as &$stage)
{
$lives['character'] += $stage['livedrain_character'];
$lives['boss'] += $stage['livedrain_boss'];
}
// Get Child-Stages
$childStages = $this->Bossfight->getChildStages($stage['id']);
// Get answer of Character
if($this->request->getGetParam('show-answer') == 'true') {
foreach($childStages as &$childStage) {
$childStage['answer'] = $this->Bossfight->getCharacterSubmission($childStage['id'], $character['id']);
}
}
// Pass data to view
$this->set('seminary', $seminary);
$this->set('character', $character);
$this->set('fight', $fight);
$this->set('stage', $stage);
$this->set('lives', $lives);
$this->set('childStages', $childStages);
}
/**
* Action: submission.
*
* Display all stages with the answers the character has
* choosen.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
* @param array $character Current Character data
*/
public function submission($seminary, $questgroup, $quest, $character)
{
// Get Boss-Fight
$fight = $this->Bossfight->getBossFight($quest['id']);
if(!is_null($fight['boss_seminarymedia_id'])) {
$fight['bossmedia'] = $this->Media->getSeminaryMediaById($fight['boss_seminarymedia_id']);
}
// Get stages
$stages = array();
$stage = $this->Bossfight->getFirstStage($quest['id']);
while(!is_null($stage))
{
$stages[] = $stage;
$childStages = $this->Bossfight->getChildStages($stage['id']);
$stage = null;
foreach($childStages as &$childStage)
{
if($this->Bossfight->getCharacterSubmission($childStage['id'], $character['id']))
{
$stage = $childStage;
break;
}
}
}
// Calculate lives
$stages[0]['lives'] = array(
'character' => $fight['lives_character'],
'boss' => $fight['lives_boss']
);
for($i=1; $i<count($stages); $i++)
{
$stages[$i]['lives'] = array(
'character' => $stages[$i-1]['lives']['character'] + $stages[$i]['livedrain_character'],
'boss' => $stages[$i-1]['lives']['boss'] + $stages[$i]['livedrain_boss'],
);
}
// Pass data to view
$this->set('seminary', $seminary);
$this->set('character', $character);
$this->set('fight', $fight);
$this->set('stages', $stages);
}
/**
* TODO Action: edittask.
*
* Edit the task of a Quest.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
*/
public function edittask($seminary, $questgroup, $quest)
{
$fight = $this->Bossfight->getBossFight($quest['id']);
/*
if(!is_null($fight['boss_seminarymedia_id'])) {
$fight['bossmedia'] = $this->Media->getSeminaryMediaById($fight['boss_seminarymedia_id']);
}
*/
// Get stages
$stage = $this->Bossfight->getFirstStage($quest['id']);
$stage['childs'] = $this->getChildStages($stage['id']);
// Pass data to view
$this->set('seminary', $seminary);
$this->set('fight', $fight);
$this->set('stages', $stage);
//print_r($stage);
}
/**
* Prepare the session to store stage information in
*
* @param int $questId ID of Quest
*/
private function prepareSession($questId)
{
if(!array_key_exists('quests', $_SESSION)) {
$_SESSION['quests'] = array();
}
if(!array_key_exists($questId, $_SESSION['quests'])) {
$_SESSION['quests'][$questId] = array();
}
if(!array_key_exists('stages', $_SESSION['quests'][$questId])) {
$_SESSION['quests'][$questId]['stages'] = array();
}
}
/**
* Get all child-stages of a parent-stage.
*
* @param int $stageId ID of parent-stage
* @return array List of child-stages
*/
private function getChildStages($stageId)
{
$childStages = $this->Bossfight->getChildStages($stageId);
if(!empty($childStages)) {
foreach($childStages as &$stage) {
$stage['childs'] = $this->getChildStages($stage['id']);
}
}
return $childStages;
}
}
?>

View file

@ -0,0 +1,286 @@
<?php
/**
* The Legend of Z
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
* @copyright 2014 Heinrich-Heine-Universität Düsseldorf
* @license http://www.gnu.org/licenses/gpl.html
* @link https://bitbucket.org/coderkun/the-legend-of-z
*/
namespace hhu\z\questtypes;
/**
* Model of the BossfightQuesttypeAgent for a boss-fight.
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
*/
class BossfightQuesttypeModel extends \hhu\z\models\QuesttypeModel
{
/**
* Required models
*
* @var array
*/
public $models = array('media');
/**
* Copy a Quest
*
* @param int $userId ID of creating user
* @param int $sourceQuestId ID of Quest to copy from
* @param int $targetQuestId ID of Quest to copy to
* @param int $seminaryMediaIds Mapping of SeminaryMedia-IDs from source Seminary to targetSeminary
*/
public function copyQuest($userId, $sourceQuestId, $targetQuestId, $seminaryMediaIds)
{
// Check Seminary media
if(is_null($seminaryMediaIds)) {
return;
}
// Get boss fight
$bossfight = $this->getBossFight($sourceQuestId);
// Copy media
$this->Media->copyQuestsmedia($userId, $seminaryMediaIds[$bossfight['boss_seminarymedia_id']]);
// Copy boss fight
$this->db->query(
'INSERT INTO questtypes_bossfight '.
'(quest_id, created_user_id, bossname, boss_seminarymedia_id, lives_character, lives_boss) '.
'SELECT ?, ?, bossname, ?, lives_character, lives_boss '.
'FROM questtypes_bossfight '.
'WHERE quest_id = ?',
'iiii',
$targetQuestId, $userId, $seminaryMediaIds[$bossfight['boss_seminarymedia_id']],
$sourceQuestId
);
// Copy stages
$stage = $this->getFirstStage($sourceQuestId);
$this->copyStage($userId, $targetQuestId, $stage);
}
/**
* Delete a Quest.
*
* @param int $questId ID of Quest to delete
*/
public function deleteQuest($questId)
{
$this->db->query('DELETE FROM questtypes_bossfight WHERE quest_id = ?', 'i', $questId);
}
/**
* Get a Boss-Fight.
*
* @param int $questId ID of Quest
* @return array Boss-Fight data
*/
public function getBossFight($questId)
{
$data = $this->db->query(
'SELECT bossname, boss_seminarymedia_id, lives_character, lives_boss '.
'FROM questtypes_bossfight '.
'WHERE quest_id = ?',
'i',
$questId
);
if(!empty($data)) {
return $data[0];
}
return null;
}
/**
* Get the first Stage to begin the Boss-Fight with.
*
* @param int $questId ID of Quest
* @return array Data of first Stage
*/
public function getFirstStage($questId)
{
$data = $this->db->query(
'SELECT id, parent_stage_id, text, question, livedrain_character, livedrain_boss '.
'FROM questtypes_bossfight_stages '.
'WHERE questtypes_bossfight_quest_id = ? AND parent_stage_id IS NULL',
'i',
$questId
);
if(!empty($data)) {
return $data[0];
}
return null;
}
/**
* Get a Stage by its ID.
*
* @param int $stageId ID of Stage
* @return array Stage data or null
*/
public function getStageById($stageId)
{
$data = $this->db->query(
'SELECT id, text, question, livedrain_character, livedrain_boss '.
'FROM questtypes_bossfight_stages '.
'WHERE id = ?',
'i',
$stageId
);
if(!empty($data)) {
return $data[0];
}
return null;
}
/**
* Get the follow-up Stages for a Stage.
*
* @param int $parentStageId ID of Stage to get follow-up Stages for
* @return array List of follow-up Stages
*/
public function getChildStages($parentStageId)
{
return $this->db->query(
'SELECT id, parent_stage_id, text, question, livedrain_character, livedrain_boss '.
'FROM questtypes_bossfight_stages '.
'WHERE parent_stage_id = ?',
'i',
$parentStageId
);
}
/**
* Reset all Character submissions of a Boss-Fight.
*
* @param int $questId ID of Quest
* @param int $characterId ID of Character
*/
public function clearCharacterSubmissions($questId, $characterId)
{
$this->db->query(
'DELETE FROM questtypes_bossfight_stages_characters '.
'WHERE questtypes_bossfight_stage_id IN ('.
'SELECT id '.
'FROM questtypes_bossfight_stages '.
'WHERE questtypes_bossfight_quest_id = ?'.
') AND character_id = ?',
'ii',
$questId,
$characterId
);
}
/**
* Save Characters submitted answer for one Boss-Fight-Stage.
*
* @param int $regexId ID of list
* @param int $characterId ID of Character
*/
public function setCharacterSubmission($stageId, $characterId)
{
$this->db->query(
'INSERT INTO questtypes_bossfight_stages_characters '.
'(questtypes_bossfight_stage_id, character_id) '.
'VALUES '.
'(?, ?) '.
'ON DUPLICATE KEY UPDATE '.
'questtypes_bossfight_stage_id = ?',
'iii',
$stageId, $characterId, $stageId
);
}
/**
* Get answer of one Boss-Fight-Stage submitted by Character.
*
* @param int $regexId ID of list
* @param int $characterId ID of Character
* @return boolean Stage taken
*/
public function getCharacterSubmission($stageId, $characterId)
{
$data = $this->db->query(
'SELECT questtypes_bossfight_stage_id '.
'FROM questtypes_bossfight_stages_characters '.
'WHERE questtypes_bossfight_stage_id = ? AND character_id = ? ',
'ii',
$stageId, $characterId
);
return (!empty($data));
}
/**
* Copy a Bossfight stage and its child-stages.
*
* @param int $userId ID of copying user
* @param int $targetQuestId ID of Quest to copy to
* @param array $stage Data of stage to copy
* @param array $stageIds Mapping of Stage-IDs from source Seminary to target Seminary
*/
private function copyStage($userId, $targetQuestId, $stage, $stageIds=array())
{
// Copy stage
if(is_null($stage['parent_stage_id']))
{
$this->db->query(
'INSERT INTO questtypes_bossfight_stages '.
'(questtypes_bossfight_quest_id, text, question, livedrain_character, livedrain_boss) '.
'SELECT ?, text, question, livedrain_character, livedrain_boss '.
'FROM questtypes_bossfight_stages '.
'WHERE id = ?',
'ii',
$targetQuestId,
$stage['id']
);
}
else
{
$this->db->query(
'INSERT INTO questtypes_bossfight_stages '.
'(questtypes_bossfight_quest_id, parent_stage_id, text, question, livedrain_character, livedrain_boss) '.
'SELECT ?, ?, text, question, livedrain_character, livedrain_boss '.
'FROM questtypes_bossfight_stages '.
'WHERE id = ?',
'iii',
$targetQuestId, $stageIds[$stage['parent_stage_id']],
$stage['id']
);
}
$stageIds[$stage['id']] = $this->db->getInsertId();
// Copy child stages
$childStages = $this->getChildStages($stage['id']);
foreach($childStages as $childStage) {
$this->copyStage($userId, $targetQuestId, $childStage, $stageIds);
}
}
}
?>

View file

@ -0,0 +1,41 @@
<form method="post" enctype="multipart/form-data">
<fieldset>
<legend><?=_('Boss-Fight')?></legend>
<label><?=_('Boss name')?></label>
<input type="text" name="bossname" value="<?=$fight['bossname']?>" /><br />
<label><?=_('Boss image')?></label>
<input type="file" name="bossimage" /><br />
<label><?=_('Boss lives')?></label>
<input type="number" name="lives_boss" value="<?=$fight['lives_boss']?>" /><br />
<label><?=_('Character lives')?></label>
<input type="number" name="lives_character" value="<?=$fight['lives_character']?>" />
</fieldset>
<fieldset>
<legend><?=_('Stages')?></legend>
<?php renderStage($stages, $fight['lives_boss'], $fight['lives_character']); ?>
</fieldset>
<input type="submit" name="save" value="<?=_('save')?>" />
</form>
<?php function renderStage($stage, $livesBoss, $livesCharacter, $level=0, $indices=array()) { ?>
<div style="margin-left:<?=$level?>em">
<h2><?=implode('.', $indices)?></h2>
<?php if(!empty($stage['question'])) : ?>
<p><?=$stage['question']?></p>
<?php endif ?>
<p><?=_('Character')?> <?=$livesCharacter?> vs. <?=$livesBoss?> <?=_('Boss')?></p>
<p><?=$stage['text']?></p>
<?php foreach($stage['childs'] as $index => &$childStage) : ?>
<?php $childIndices = $indices; ?>
<?php $childIndices[] = $index+1; ?>
<?php renderStage($childStage, $livesBoss+$childStage['livedrain_boss'], $livesCharacter+$childStage['livedrain_character'], $level+1, $childIndices); ?>
<?php endforeach ?>
<?php if($livesBoss == 0 && $livesCharacter == 0) : ?>
Bedie verloren
<?php elseif($livesBoss == 0) : ?>
Boss verloren, Character gewonnen
<?php elseif($livesCharacter == 0) : ?>
Boss gewonnen, Character verloren
<?php endif ?>
</div>
<?php } ?>

View file

@ -0,0 +1,54 @@
<?php if(!is_null($fight)) : ?>
<div class="cf">
<section class="opponent">
<p class="fwb"><?=$character['name']?></p>
<p class="portrait"><img src="<?=$linker->link(array('media','avatar',$seminary['url'],$character['charactertype_url'],$character['xplevel']))?>" class="hero" /></p>
<p>
<?php if($lives['character'] > 0) : ?>
<?php foreach(range(1,$lives['character']) as $i) : ?>
<i class="fa fa-heart fa-fw"></i>
<?php endforeach ?>
<?php else : ?>
<?=_('lost')?>
<?php endif ?>
</p>
</section>
<section class="opponent">
<p class="fwb"><?=$fight['bossname']?></p>
<p class="portrait"><img src="<?=$linker->link(array('media','seminary',$seminary['url'],$fight['bossmedia']['url']))?>" class="boss" /></p>
<p>
<?php if($lives['boss'] > 0) : ?>
<?php foreach(range(1,$lives['boss']) as $i) : ?>
<i class="fa fa-heart fa-fw"></i>
<?php endforeach ?>
<?php else : ?>
<b><?=_('lost')?></b>
<?php endif ?>
</p>
</section>
</div>
<?php endif ?>
<?php if(!is_null($stage)) : ?>
<p><?=\hhu\z\Utils::t($stage['text'])?></p>
<form method="post" action="<?=$linker->link(null,0,false,null,true,'task')?>">
<input type="hidden" name="stage" value="<?=$stage['id']?>" />
<ul class="bossfight cf">
<?php foreach($childStages as &$childStage) : ?>
<li class="option">
<p><i>
<?php if(array_key_exists('answer', $childStage) && $childStage['answer']) : ?>→<?php endif ?>
<?=\hhu\z\Utils::t($childStage['question'])?>
</i></p>
<p><input type="submit" name="submit_stages[<?=$childStage['id']?>]" value="<?=_('Choose')?>" /></p>
</li>
<?php endforeach?>
<?php if($lives['character'] == 0 || $lives['boss'] == 0) : ?>
<li>
<input type="hidden" name="answers" value="" />
<input type="submit" name="submit" value="<?=_('solve')?>" />
</li>
<?php endif ?>
</ul>
</form>
<?php endif ?>

View file

@ -0,0 +1,38 @@
<div class="cf">
<section class="opponent">
<p class="portrait"><img src="<?=$linker->link(array('media','avatar',$seminary['url'],$character['charactertype_url'],$character['xplevel']))?>" class="hero" /></p>
</section>
<section class="opponent">
<p class="portrait"><img src="<?=$linker->link(array('media','seminary',$seminary['url'],$fight['bossmedia']['url']))?>" class="boss" /></p>
</section>
</div>
<?php foreach($stages as &$stage) : ?>
<p><?=$stage['question']?></p>
<div class="cf">
<section class="opponent">
<p class="fwb"><?=$character['name']?></p>
<p>
<?php if($stage['lives']['character'] > 0) : ?>
<?php foreach(range(1,$stage['lives']['character']) as $i) : ?>
<i class="fa fa-heart fa-fw"></i>
<?php endforeach ?>
<?php else : ?>
<?=_('lost')?>
<?php endif ?>
</p>
</section>
<section class="opponent">
<p class="fwb"><?=$fight['bossname']?></p>
<p>
<?php if($stage['lives']['boss'] > 0) : ?>
<?php foreach(range(1,$stage['lives']['boss']) as $i) : ?>
<i class="fa fa-heart fa-fw"></i>
<?php endforeach ?>
<?php else : ?>
<b><?=_('lost')?></b>
<?php endif ?>
</p>
</section>
</div>
<?php endforeach ?>

View file

@ -0,0 +1,24 @@
<?php
/**
* The Legend of Z
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
* @copyright 2014 Heinrich-Heine-Universität Düsseldorf
* @license http://www.gnu.org/licenses/gpl.html
* @link https://bitbucket.org/coderkun/the-legend-of-z
*/
namespace hhu\z\questtypes;
/**
* QuesttypeAgent for choosing between predefined input values.
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
*/
class ChoiceinputQuesttypeAgent extends \hhu\z\agents\QuesttypeAgent
{
}
?>

View file

@ -0,0 +1,299 @@
<?php
/**
* The Legend of Z
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
* @copyright 2014 Heinrich-Heine-Universität Düsseldorf
* @license http://www.gnu.org/licenses/gpl.html
* @link https://bitbucket.org/coderkun/the-legend-of-z
*/
namespace hhu\z\questtypes;
/**
* Controller of the ChoiceinputQuesttypeAgent for choosing between
* predefined input values.
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
*/
class ChoiceinputQuesttypeController extends \hhu\z\controllers\QuesttypeController
{
/**
* Required components
*
* @var array
*/
public $components = array('validation');
/**
* Save the answers of a Character for a Quest.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
* @param array $character Current Character data
* @param array $answers Character answers for the Quest
*/
public function saveAnswersOfCharacter($seminary, $questgroup, $quest, $character, $answers)
{
// Get lists
$choiceLists = $this->Choiceinput->getChoiceinputLists($quest['id']);
// Save answers
foreach($choiceLists as &$list)
{
$pos = intval($list['number']) - 1;
$answer = (array_key_exists($pos, $answers)) ? $answers[$pos] : null;
$this->Choiceinput->setCharacterSubmission($list['id'], $character['id'], $answer);
}
}
/**
* Save additional data for the answers of a Character for a Quest.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
* @param array $character Current Character data
* @param array $data Additional (POST-) data
*/
public function saveDataForCharacterAnswers($seminary, $questgroup, $quest, $character, $data)
{
}
/**
* Check if answers of a Character for a Quest match the correct ones.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
* @param array $character Current Character data
* @param array $answers Character answers for the Quest
* @return boolean True/false for a right/wrong answer or null for moderator evaluation
*/
public function matchAnswersOfCharacter($seminary, $questgroup, $quest, $character, $answers)
{
// Get lists
$choiceLists = $this->Choiceinput->getChoiceinputLists($quest['id']);
// Match lists with user answers
foreach($choiceLists as &$list)
{
$pos = intval($list['number']) - 1;
if(!array_key_exists($pos, $answers)) {
return false;
}
if($list['questtypes_choiceinput_choice_id'] != $answers[$pos]) {
return false;
}
}
// All answers right
return true;
}
/**
* Action: quest.
*
* Display a text with lists with predefined values.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
* @param array $character Current Character data
* @param \Exception $exception Character submission exception
*/
public function quest($seminary, $questgroup, $quest, $character, $exception)
{
// Get Task
$task = $this->Choiceinput->getChoiceinputQuest($quest['id']);
// Get lists
$choiceLists = $this->Choiceinput->getChoiceinputLists($quest['id']);
foreach($choiceLists as &$list) {
$list['values'] = $this->Choiceinput->getChoiceinputChoices($list['id']);
}
// Get Character answers
if($this->request->getGetParam('show-answer') == 'true' || !$this->Quests->hasCharacterSolvedQuest($quest['id'], $character['id']) || $this->request->getGetParam('status') == 'solved') {
foreach($choiceLists as &$list) {
$list['answer'] = $this->Choiceinput->getCharacterSubmission($list['id'], $character['id']);
}
}
// Pass data to view
$this->set('task', $task);
$this->set('choiceLists', $choiceLists);
}
/**
* Action: submission.
*
* Show the submission of a Character for a Quest.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
* @param array $character Current Character data
*/
public function submission($seminary, $questgroup, $quest, $character)
{
// Get Task
$task = $this->Choiceinput->getChoiceinputQuest($quest['id']);
// Get lists
$choiceLists = $this->Choiceinput->getChoiceinputLists($quest['id']);
foreach($choiceLists as &$list)
{
$list['values'] = $this->Choiceinput->getChoiceinputChoices($list['id']);
$list['answer'] = $this->Choiceinput->getCharacterSubmission($list['id'], $character['id']);
$list['right'] = ($list['questtypes_choiceinput_choice_id'] == $list['answer']);
}
// Pass data to view
$this->set('task', $task);
$this->set('choiceLists', $choiceLists);
}
/**
* Action: edittask.
*
* Edit the task of a Quest.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
*/
public function edittask($seminary, $questgroup, $quest)
{
// Get Task
$task = $this->Choiceinput->getChoiceinputQuest($quest['id']);
$text = $task['text'];
// Get lists
$choiceLists = $this->Choiceinput->getChoiceinputLists($quest['id']);
foreach($choiceLists as &$list)
{
$list['choices'] = $this->Choiceinput->getChoiceinputChoices($list['id']);
foreach($list['choices'] as $index => &$choice) {
//$choice['correct'] = ($choice['id'] == $list['questtypes_choiceinput_choice_id']);
if($choice['id'] == $list['questtypes_choiceinput_choice_id']) {
$list['answer'] = $index;
}
$choice = $choice['text'];
}
//$list = $list['choices'];
}
// Values
$validations = array();
// Save data
if($this->request->getRequestMethod() == 'POST')
{
if(!is_null($this->request->getPostParam('preview')) || !is_null($this->request->getPostParam('save')))
{
// Get params and validate them
if(is_null($this->request->getPostParam('text'))) {
throw new \nre\exceptions\ParamsNotValidException('text');
}
$text = $this->request->getPostParam('text');
if(is_null($this->request->getPostParam('lists'))) {
throw new \nre\exceptions\ParamsNotValidException('lists');
}
$choiceLists = $this->request->getPostParam('lists');
$choiceLists = array_values($choiceLists);
foreach($choiceLists as $listIndex => &$list)
{
// Validate choices
if(!array_key_exists('choices', $list)) {
throw new \nre\exceptions\ParamsNotValidException('choices');
}
$choiceIndex = 0;
$answer = null;
foreach($list['choices'] as $index => &$choice)
{
// Validate choice
$choiceValidation = $this->Validation->validate($choice, \nre\configs\AppConfig::$validation['choice']);
if($choiceValidation !== true)
{
if(!array_key_exists($listIndex, $validations) || !is_array($validations[$listIndex])) {
$validations[$listIndex] = array();
}
if(!array_key_exists('choices', $validations[$listIndex])) {
$validations[$listIndex]['choices'] = array();
}
$validations[$listIndex]['choices'][$choiceIndex] = $choiceValidation;
}
$choiceIndex++;
if(array_key_exists('answer', $list) && $list['answer'] == $index) {
$answer = $choiceIndex;
}
}
// Validate correct answer
if(is_null($answer))
{
if(!array_key_exists($listIndex, $validations) || !is_array($validations[$listIndex])) {
$validations[$listIndex] = array();
}
if(!array_key_exists('answer', $validations[$listIndex])) {
$validations[$listIndex]['answer'] = array();
}
$validations[$listIndex] = $this->Validation->addValidationResult($validations[$listIndex], 'answer', 'exist', true);
}
}
// Save and redirect
if(!is_null($this->request->getPostParam('save')) && empty($validations))
{
// Save text
$this->Choiceinput->setTextForQuest(
$this->Auth->getUserId(),
$quest['id'],
$text
);
// Save lists and choices
foreach($choiceLists as $listIndex => &$list)
{
// Save list
$this->Choiceinput->setListForText(
$quest['id'],
$listIndex + 1,
$list['choices'],
$list['answer'] + 1
);
}
// Redirect
$this->redirect($this->linker->link(array('quest', $seminary['url'], $questgroup['url'], $quest['url']), 1));
}
}
}
// Pass data to view
$this->set('task', $task);
$this->set('text', $text);
$this->set('choiceLists', $choiceLists);
$this->set('validations', $validations);
}
}
?>

View file

@ -0,0 +1,379 @@
<?php
/**
* The Legend of Z
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
* @copyright 2014 Heinrich-Heine-Universität Düsseldorf
* @license http://www.gnu.org/licenses/gpl.html
* @link https://bitbucket.org/coderkun/the-legend-of-z
*/
namespace hhu\z\questtypes;
/**
* Model of the ChoiceinputQuesttypeAgent for choosing between
* predefined input values.
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
*/
class ChoiceinputQuesttypeModel extends \hhu\z\models\QuesttypeModel
{
/**
* Copy a Quest
*
* @param int $userId ID of creating user
* @param int $sourceQuestId ID of Quest to copy from
* @param int $targetQuestId ID of Quest to copy to
* @param int $seminaryMediaIds Mapping of SeminaryMedia-IDs from source Seminary to targetSeminary
*/
public function copyQuest($userId, $sourceQuestId, $targetQuestId, $seminaryMediaIds)
{
// Copy choiceinput
$this->db->query(
'INSERT INTO questtypes_choiceinput '.
'(quest_id, created_user_id, text) '.
'SELECT ?, ?, text '.
'FROM questtypes_choiceinput '.
'WHERE quest_id = ?',
'iii',
$targetQuestId, $userId,
$sourceQuestId
);
// Copy lists
$lists = $this->getChoiceinputLists($sourceQuestId);
foreach($lists as &$list)
{
// Copy list
$this->db->query(
'INSERT INTO questtypes_choiceinput_lists '.
'(questtypes_choiceinput_quest_id, number) '.
'SELECT ?, number '.
'FROM questtypes_choiceinput_lists '.
'WHERE id = ?',
'ii',
$targetQuestId,
$list['id']
);
$targetListId = $this->db->getInsertId();
// Copy choices
$choiceIds = array();
$choices = $this->getChoiceinputChoices($list['id']);
foreach($choices as $choice)
{
$this->db->query(
'INSERT INTO questtypes_choiceinput_choices '.
'(questtypes_choiceinput_list_id, pos, text) '.
'SELECT ?, pos, text '.
'FROM questtypes_choiceinput_choices '.
'WHERE id = ?',
'ii',
$targetListId,
$choice['id']
);
$choiceIds[$choice['id']] = $this->db->getInsertId();
}
// Set correct choice
if(!is_null($list['questtypes_choiceinput_choice_id']))
{
$this->db->query(
'UPDATE questtypes_choiceinput_lists '.
'SET questtypes_choiceinput_choice_id = ? '.
'WHERE id = ?',
'ii',
$choiceIds[$list['questtypes_choiceinput_choice_id']],
$targetListId
);
}
}
}
/**
* Delete a Quest.
*
* @param int $questId ID of Quest to delete
*/
public function deleteQuest($questId)
{
$this->db->query('DELETE FROM questtypes_choiceinput WHERE quest_id = ?', 'i', $questId);
}
/**
* Get choiceinput-text for a Quest.
*
* @param int $questId ID of Quest
* @return array Choiceinput-text
*/
public function getChoiceinputQuest($questId)
{
$data = $this->db->query(
'SELECT text '.
'FROM questtypes_choiceinput '.
'WHERE quest_id = ?',
'i',
$questId
);
if(!empty($data)) {
return $data[0];
}
return null;
}
/**
* Get all lists of input values for a choiceinput-text.
*
* @param int $questId ID of Quest
* @return array List
*/
public function getChoiceinputLists($questId)
{
return $this->db->query(
'SELECT id, number, questtypes_choiceinput_choice_id '.
'FROM questtypes_choiceinput_lists '.
'WHERE questtypes_choiceinput_quest_id = ? '.
'ORDER BY number ASC',
'i',
$questId
);
}
/**
* Get the list of values for a choiceinput-list.
*
* @param int $listId ID of list
* @return array Input values
*/
public function getChoiceinputChoices($listId)
{
return $this->db->query(
'SELECT id, pos, text '.
'FROM questtypes_choiceinput_choices '.
'WHERE questtypes_choiceinput_list_id = ? '.
'ORDER BY pos ASC',
'i',
$listId
);
}
/**
* Save Characters submitted answer for one choiceinput-list.
*
* @param int $regexId ID of list
* @param int $characterId ID of Character
* @param string $answer Submitted answer for this list
*/
public function setCharacterSubmission($listId, $characterId, $answer)
{
if(is_null($answer))
{
$this->db->query(
'INSERT INTO questtypes_choiceinput_lists_characters '.
'(questtypes_choiceinput_list_id, character_id, questtypes_choiceinput_choice_id) '.
'VALUES '.
'(?, ?, NULL) '.
'ON DUPLICATE KEY UPDATE '.
'questtypes_choiceinput_choice_id = NULL',
'ii',
$listId, $characterId
);
}
else
{
$this->db->query(
'INSERT INTO questtypes_choiceinput_lists_characters '.
'(questtypes_choiceinput_list_id, character_id, questtypes_choiceinput_choice_id) '.
'VALUES '.
'(?, ?, ?) '.
'ON DUPLICATE KEY UPDATE '.
'questtypes_choiceinput_choice_id = ?',
'iiii',
$listId, $characterId, $answer, $answer
);
}
}
/**
* Get answer of one choiceinput-list submitted by Character.
*
* @param int $regexId ID of list
* @param int $characterId ID of Character
* @return int Submitted answer for this list or null
*/
public function getCharacterSubmission($listId, $characterId)
{
$data = $this->db->query(
'SELECT questtypes_choiceinput_choice_id '.
'FROM questtypes_choiceinput_lists_characters '.
'WHERE questtypes_choiceinput_list_id = ? AND character_id = ? ',
'ii',
$listId, $characterId
);
if(!empty($data)) {
return $data[0]['questtypes_choiceinput_choice_id'];
}
return null;
}
/**
* Set the text for a Quest and correct choice input lists count.
*
* @param int $userId ID of user setting text
* @param int $questId ID of Quest to set text for
* @param string $text Text for Quest
*/
public function setTextForQuest($userId, $questId, $text)
{
$this->db->setAutocommit(false);
try {
// Set text
$this->db->query(
'INSERT INTO questtypes_choiceinput '.
'(quest_id, created_user_id, text) '.
'VALUES '.
'(?, ?, ?) '.
'ON DUPLICATE KEY UPDATE '.
'text = ?',
'iiss',
$questId,
$userId,
$text,
$text
);
// Count fields
$listCount = substr_count($text, '[choiceinput]');
// Remove fields
$this->db->query(
'DELETE FROM questtypes_choiceinput_lists '.
'WHERE questtypes_choiceinput_quest_id = ? AND number > ?',
'ii',
$questId,
$listCount
);
// Add fields
for($i=1; $i<=$listCount; $i++)
{
$this->db->query(
'INSERT IGNORE INTO questtypes_choiceinput_lists '.
'(questtypes_choiceinput_quest_id, number, questtypes_choiceinput_choice_id) '.
'VALUES '.
'(?, ?, NULL) ',
'ii',
$questId,
$i
);
}
$this->db->commit();
}
catch(\Exception $e) {
$this->db->rollback();
$this->db->setAutocommit(true);
throw $e;
}
$this->db->setAutocommit(true);
}
/**
* Set list of choices for a text.
*
* @param int $questId ID of Quest to set choices for
* @param int $number List number
* @param array $choices List of choices
* @param int $correctPos Position of correct answer
*/
public function setListForText($questId, $number, $choices, $correctPos)
{
// Get ID of list
$listId = $this->db->query(
'SELECT id '.
'FROM questtypes_choiceinput_lists '.
'WHERE questtypes_choiceinput_quest_id = ? AND number = ?',
'ii',
$questId,
$number
);
$listId = $listId[0]['id'];
// Manage choices
$this->db->setAutocommit(false);
try {
// Remove choices
$this->db->query(
'DELETE FROM questtypes_choiceinput_choices '.
'WHERE questtypes_choiceinput_list_id = ? AND pos > ?',
'ii',
$listId,
count($choices)
);
// Add choices
foreach($choices as $index => &$choice)
{
$this->db->query(
'INSERT INTO questtypes_choiceinput_choices '.
'(questtypes_choiceinput_list_id, pos, text) '.
'VALUES '.
'(?, ?, ?) '.
'ON DUPLICATE KEY UPDATE '.
'text = ?',
'iiss',
$listId,
$index + 1,
$choice,
$choice
);
}
// Set correct choice for list
$this->db->query(
'UPDATE questtypes_choiceinput_lists '.
'SET questtypes_choiceinput_choice_id = ('.
'SELECT id '.
'FROM questtypes_choiceinput_choices '.
'WHERE questtypes_choiceinput_list_id = ? AND pos = ?'.
') '.
'WHERE id = ?',
'iii',
$listId,
$correctPos,
$listId
);
$this->db->commit();
}
catch(\Exception $e) {
$this->db->rollback();
$this->db->setAutocommit(true);
throw $e;
}
$this->db->setAutocommit(true);
}
}
?>

View file

@ -0,0 +1,182 @@
<?php if(!empty($validations)) : ?>
<ul>
<?php foreach($validations as &$list) : ?>
<?php foreach($list as $part => &$choices) : ?>
<li>
<?php if($part == 'choices') : ?>
<?php foreach($choices as $field => &$settings) : ?>
<ul>
<?php foreach($settings as $setting => $value) : ?>
<li>
<?php
switch($setting) {
case 'minlength': printf(_('Choice input is too short (min. %d chars)'), $value);
break;
case 'maxlength': printf(_('Choice input is too long (max. %d chars)'), $value);
break;
default: echo _('Choice input invalid');
}
?>
</li>
<?php endforeach ?>
</ul>
<?php endforeach ?>
<?php elseif($part == 'answer') : ?>
<?php foreach($choices as $setting => &$value) : ?>
<li>
<?php
switch($setting) {
case 'exist': printf(_('Please select correct choice'));
break;
}
?>
</li>
<?php endforeach ?>
<?php endif ?>
</li>
<?php endforeach ?>
<?php endforeach ?>
</ul>
<?php endif ?>
<form method="post">
<fieldset>
<legend><?=_('Text')?></legend>
<button id="add-field" type="button"><?=_('Add field')?></button><br />
<textarea id="text" name="text"><?=$text?></textarea>
</fieldset>
<fieldset>
<legend><?=_('Choice inputs')?></legend>
<ul id="lists">
<?php foreach($choiceLists as $listIndex => &$list) : ?>
<li id="list-<?=$listIndex?>">
<?php if(!empty($validations) && array_key_exists($listIndex, $validations) && !empty($validations[$listIndex]) && array_key_exists('answer', $validations[$listIndex]) && $validations[$listIndex]['answer'] !== true) : ?>
<ul>
<?php foreach($validations[$listIndex]['answer'] as $setting => $value) : ?>
<li>
<?php
switch($setting) {
case 'exist': printf(_('Please select correct choice'));
break;
}
?>
</li>
<?php endforeach ?>
</ul>
<?php endif ?>
<ul>
<?php foreach($list['choices'] as $choiceIndex => &$choice) : ?>
<li>
<input type="radio" name="lists[<?=$listIndex?>][answer]" value="<?=$choiceIndex?>" <?php if($choiceIndex == $list['answer']) : ?>checked="checked"<?php endif ?> />
<input type="text" name="lists[<?=$listIndex?>][choices][<?=$choiceIndex?>]" required="required" value="<?=$choice?>" <?php if(!empty($validations) && array_key_exists($listIndex, $validations) && !empty($validations[$listIndex]) && array_key_exists($choiceIndex, $validations[$listIndex]['choices']) && $validations[$listIndex]['choices'][$choiceInput] !== true) : ?>class="invalid"<?php endif ?> />
<button class="remove-choice" type="button"></button>
</li>
<?php endforeach ?>
<li>
<button class="add-choice" type="button">+</button>
</li>
</ul>
</li>
<?php endforeach ?>
</ul>
</fieldset>
<input type="submit" name="preview" value="<?=_('Preview')?>" />
<input type="submit" name="save" value="<?=_('save')?>" />
</form>
<h2><?=_('Preview')?></h2>
<p>
<?php $posStart = 0; ?>
<?php foreach($choiceLists as &$list) : ?>
<?php $posEnd = mb_strpos($text, '[choiceinput]', $posStart, 'UTF-8'); ?>
<?=$t->t(mb_substr($text, $posStart, $posEnd-$posStart, 'UTF-8'))?>
<select name="answers[]">
<?php foreach($list['choices'] as &$choice) : ?>
<option><?=$choice?></option>
<?php endforeach ?>
</select>
<?php $posStart = $posEnd + mb_strlen('[choiceinput]', 'UTF-8'); ?>
<?php endforeach ?>
<?=$t->t(mb_substr($text, $posStart, mb_strlen($text, 'UTF-8')-$posStart, 'UTF-8'))?>
</p>
<script>
$(function() {
$("#text").markItUp(mySettings);
});
var listIndex = <?=count($choiceLists)?>;
var choiceIndices = new Array(<?=count($choiceLists)?>);
<?php foreach($choiceLists as $index => &$list) : ?>
choiceIndices[<?=$index?>] = <?=count($list)?>;
<?php endforeach?>
var listElement = '<ul><li><button class="add-choice" type="button">+</button></li></ul>';
var inputElement = '<input type="radio" name="lists[LISTINDEX][answer]" value="CHOICEINDEX" />' +
'<input type="text" name="lists[LISTINDEX][choices][CHOICEINDEX]" required="required" />' +
'<button class="remove-choice" type="button"></button>';
$("#add-field").click(function(event) {
event.preventDefault();
var caret = getCaret("text");
insertAtCaret("text", caret, "[choiceinput]");
updateFields();
});
$("#text").on('change keyup paste', function(event) {
updateFields();
});
$(".add-choice").click(addChoice);
$(".remove-choice").click(removeChoice);
function updateFields()
{
var newCount = $("#text").val().split("[choiceinput]").length - 1;
var oldCount = $("#lists > li").length;
var caret = getCaret("text");
var pos = $("#text").val().substring(0, caret).split("[choiceinput]").length - 1;
if(newCount > oldCount)
{
// Add lists
for(var i=oldCount; i<newCount; i++)
{
choiceIndices.push(0);
var element = '<li id="list-'+listIndex+'">' + listElement + '</li>';
if($("#lists > li").length > 0)
{
if($("#lists > li").length > pos-1) {
$($("#lists > li")[pos-1]).before(element);
}
else {
$($("#lists > li")[pos-2]).after(element);
}
}
else {
$("#lists").append(element);
}
$("#list-"+listIndex+" .add-choice").click(addChoice);
listIndex++;
}
}
else if(newCount < oldCount)
{
// Remove lists
for(var i=oldCount; i>newCount; i--) {
$($("#lists > li")[pos]).remove();
}
}
}
function addChoice(event)
{
event.preventDefault();
var parent = $(event.target).parent();
var index = parent.parent().parent().attr('id').substring(5);
var element = '<li>' + inputElement.replace(/LISTINDEX/g, index).replace(/CHOICEINDEX/g, choiceIndices[index]) + '</li>';
$(event.target).parent().before(element);
$(".remove-choice").click(removeChoice);
choiceIndices[index]++;
}
function removeChoice(event)
{
event.preventDefault();
$(event.target).parent().remove();
}
</script>

View file

@ -0,0 +1,17 @@
<form method="post">
<p>
<?php $posStart = 0; ?>
<?php foreach($choiceLists as &$list) : ?>
<?php $posEnd = mb_strpos($task['text'], '[choiceinput]', $posStart, 'UTF-8'); ?>
<?=$t->t(mb_substr($task['text'], $posStart, $posEnd-$posStart, 'UTF-8'))?>
<select name="answers[]">
<?php foreach($list['values'] as &$choice) : ?>
<option value="<?=$choice['id']?>" <?php if(array_key_exists('answer', $list) && $list['answer'] == $choice['id']) : ?>selected="selected"<?php endif ?>><?=$choice['text']?></option>
<?php endforeach ?>
</select>
<?php $posStart = $posEnd + mb_strlen('[choiceinput]', 'UTF-8'); ?>
<?php endforeach ?>
<?=$t->t(mb_substr($task['text'], $posStart, mb_strlen($task['text'], 'UTF-8')-$posStart, 'UTF-8'))?>
</p>
<input type="submit" name="submit" value="<?=_('solve')?>" />
</form>

View file

@ -0,0 +1,14 @@
<p>
<?php $posStart = 0; ?>
<?php foreach($choiceLists as &$list) : ?>
<?php $posEnd = mb_strpos($task['text'], '[choiceinput]', $posStart, 'UTF-8'); ?>
<?=$t->t(mb_substr($task['text'], $posStart, $posEnd-$posStart, 'UTF-8'))?>
<select name="answers[]" disabled="disabled">
<?php foreach($list['values'] as &$choice) : ?>
<option value="<?=$choice['id']?>" <?php if(array_key_exists('answer', $list) && $list['answer'] == $choice['id']) : ?>selected="selected"<?php endif ?>><?=$choice['text']?></option>
<?php endforeach ?>
</select>
<?php $posStart = $posEnd + mb_strlen('[choiceinput]', 'UTF-8'); ?>
<?php endforeach ?>
<?=$t->t(mb_substr($task['text'], $posStart, mb_strlen($task['text'], 'UTF-8')-$posStart, 'UTF-8'))?>
</p>

View file

@ -0,0 +1,24 @@
<?php
/**
* The Legend of Z
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
* @copyright 2014 Heinrich-Heine-Universität Düsseldorf
* @license http://www.gnu.org/licenses/gpl.html
* @link https://bitbucket.org/coderkun/the-legend-of-z
*/
namespace hhu\z\questtypes;
/**
* QuesttypeAgent for solving a crossword.
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
*/
class CrosswordQuesttypeAgent extends \hhu\z\agents\QuesttypeAgent
{
}
?>

View file

@ -0,0 +1,380 @@
<?php
/**
* The Legend of Z
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
* @copyright 2014 Heinrich-Heine-Universität Düsseldorf
* @license http://www.gnu.org/licenses/gpl.html
* @link https://bitbucket.org/coderkun/the-legend-of-z
*/
namespace hhu\z\questtypes;
/**
* Controller of the CrosswordQuesttypeAgent for solving a crossword.
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
*/
class CrosswordQuesttypeController extends \hhu\z\controllers\QuesttypeController
{
/**
* Save the answers of a Character for a Quest.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
* @param array $character Current Character data
* @param array $answers Character answers for the Quest
*/
public function saveAnswersOfCharacter($seminary, $questgroup, $quest, $character, $answers)
{
// Get words
$words = $this->Crossword->getWordsForQuest($quest['id']);
// Iterate words
foreach($words as &$word)
{
// Assemble answer for word
$answer = '';
if($word['vertical'])
{
$x = $word['pos_x'];
$startY = $word['pos_y'];
$endY = $startY + mb_strlen($word['word'], 'UTF-8') - 1;
foreach(range($startY, $endY) as $y)
{
if(array_key_exists($x, $answers) && array_key_exists($y, $answers[$x]) && !empty($answers[$x][$y])) {
$answer .= $answers[$x][$y];
}
else {
$answer .= ' ';
}
}
}
else
{
$startX = $word['pos_x'];
$endX = $startX + mb_strlen($word['word'], 'UTF-8') - 1;
$y = $word['pos_y'];
foreach(range($startX, $endX) as $x)
{
if(array_key_exists($x, $answers) && array_key_exists($y, $answers[$x]) && !empty($answers[$x][$y])) {
$answer .= $answers[$x][$y];
}
else {
$answer .= ' ';
}
}
}
// Save answer
$this->Crossword->setCharacterSubmission($word['id'], $character['id'], $answer);
}
}
/**
* Save additional data for the answers of a Character for a Quest.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
* @param array $character Current Character data
* @param array $data Additional (POST-) data
*/
public function saveDataForCharacterAnswers($seminary, $questgroup, $quest, $character, $data)
{
}
/**
* Check if answers of a Character for a Quest match the correct ones.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
* @param array $character Current Character data
* @param array $answers Character answers for the Quest
* @return boolean True/false for a right/wrong answer or null for moderator evaluation
*/
public function matchAnswersOfCharacter($seminary, $questgroup, $quest, $character, $answers)
{
// Get words
$words = $this->Crossword->getWordsForQuest($quest['id']);
// Iterate words
foreach($words as &$word)
{
// Assemble answer for word
$answer = '';
if($word['vertical'])
{
$x = $word['pos_x'];
$startY = $word['pos_y'];
$endY = $startY + mb_strlen($word['word'], 'UTF-8') - 1;
foreach(range($startY, $endY) as $y)
{
if(array_key_exists($x, $answers) && array_key_exists($y, $answers[$x]) && !empty($answers[$x][$y])) {
$answer .= $answers[$x][$y];
}
else {
$answer .= ' ';
}
}
}
else
{
$startX = $word['pos_x'];
$endX = $startX + mb_strlen($word['word'], 'UTF-8') - 1;
$y = $word['pos_y'];
foreach(range($startX, $endX) as $x)
{
if(array_key_exists($x, $answers) && array_key_exists($y, $answers[$x]) && !empty($answers[$x][$y])) {
$answer .= $answers[$x][$y];
}
else {
$answer .= ' ';
}
}
}
// Check answer
if(mb_strtolower($word['word'], 'UTF-8') != mb_strtolower($answer, 'UTF-8')) {
return false;
}
}
// All answer right
return true;
}
/**
* Action: quest.
*
* Display a text with lists with predefined values.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
* @param array $character Current Character data
* @param \Exception $exception Character submission exception
*/
public function quest($seminary, $questgroup, $quest, $character, $exception)
{
// Get words
$words = $this->Crossword->getWordsForQuest($quest['id']);
// Create 2D-matrix
$matrix = array();
$maxX = 0;
$maxY = 0;
foreach($words as $index => &$word)
{
if($this->request->getGetParam('show-answer') == 'true' || !$this->Quests->hasCharacterSolvedQuest($quest['id'], $character['id']) || $this->request->getGetParam('status') == 'solved') {
$word['answer'] = $this->Crossword->getCharacterSubmission($word['id'], $character['id']);
}
// Insert word
if($word['vertical'])
{
$x = $word['pos_x'];
$startY = $word['pos_y'];
$endY = $startY + mb_strlen($word['word'], 'UTF-8') - 1;
$matrix = array_pad($matrix, $x+1, array());
$matrix[$x] = array_pad($matrix[$x], $endY+1, null);
$maxX = max($maxX, $x);
$maxY = max($maxY, $endY);
foreach(range($startY, $endY) as $y)
{
$matrix[$x][$y] = array(
'char' => mb_substr($word['word'], $y-$startY, 1, 'UTF-8'),
'indices' => (array_key_exists($x, $matrix) && array_key_exists($y, $matrix[$x]) && !is_null($matrix[$x][$y]) && array_key_exists('indices', $matrix[$x][$y])) ? $matrix[$x][$y]['indices'] : array(),
'answer' => null
);
if($y == $startY) {
$matrix[$x][$y]['indices'][] = $index;
}
if(array_key_exists('answer', $word))
{
$answer = mb_substr($word['answer'], $y-$startY, 1, 'UTF-8');
if($answer != ' ') {
$matrix[$x][$y]['answer'] = $answer;
}
}
}
}
else
{
$startX = $word['pos_x'];
$endX = $startX + mb_strlen($word['word'], 'UTF-8') - 1;
$y = $word['pos_y'];
$matrix = array_pad($matrix, $endX+1, array());
$maxX = max($maxX, $endX);
$maxY = max($maxY, $y);
foreach(range($startX, $endX) as $x)
{
$matrix[$x] = array_pad($matrix[$x], $y+1, null);
$matrix[$x][$y] = array(
'char' => mb_substr($word['word'], $x-$startX, 1, 'UTF-8'),
'indices' => (array_key_exists($x, $matrix) && array_key_exists($y, $matrix[$x]) && !is_null($matrix[$x][$y]) && array_key_exists('indices', $matrix[$x][$y])) ? $matrix[$x][$y]['indices'] : array(),
'answer' => null
);
if($x == $startX) {
$matrix[$x][$y]['indices'][] = $index;
}
if(array_key_exists('answer', $word))
{
$answer = mb_substr($word['answer'], $x-$startX, 1, 'UTF-8');
if($answer != ' ') {
$matrix[$x][$y]['answer'] = $answer;
}
}
}
}
}
// Pass data to view
$this->set('words', $words);
$this->set('maxX', $maxX);
$this->set('maxY', $maxY);
$this->set('matrix', $matrix);
}
/**
* Action: submission.
*
* Show the submission of a Character for a Quest.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
* @param array $character Current Character data
*/
public function submission($seminary, $questgroup, $quest, $character)
{
// Get words
$words = $this->Crossword->getWordsForQuest($quest['id']);
// Create 2D-matrix
$matrix = array();
$maxX = 0;
$maxY = 0;
foreach($words as $index => &$word)
{
// Character answer
$word['answer'] = $this->Crossword->getCharacterSubmission($word['id'], $character['id']);
// Insert word
if($word['vertical'])
{
$x = $word['pos_x'];
$startY = $word['pos_y'];
$endY = $startY + mb_strlen($word['word'], 'UTF-8') - 1;
$matrix = array_pad($matrix, $x+1, array());
$matrix[$x] = array_pad($matrix[$x], $endY+1, null);
$maxX = max($maxX, $x);
$maxY = max($maxY, $endY);
foreach(range($startY, $endY) as $y)
{
$matrix[$x][$y] = array(
'char' => mb_substr($word['word'], $y-$startY, 1, 'UTF-8'),
'indices' => (array_key_exists($x, $matrix) && array_key_exists($y, $matrix[$x]) && !is_null($matrix[$x][$y]) && array_key_exists('indices', $matrix[$x][$y])) ? $matrix[$x][$y]['indices'] : array(),
'answer' => null,
'right' => false
);
if($y == $startY) {
$matrix[$x][$y]['indices'][] = $index;
}
if(!is_null($word['answer']))
{
$answer = mb_substr($word['answer'], $y-$startY, 1, 'UTF-8');
if($answer != ' ')
{
$matrix[$x][$y]['answer'] = $answer;
$matrix[$x][$y]['right'] = (mb_strtolower($matrix[$x][$y]['char'], 'UTF-8') == mb_strtolower($answer, 'UTF-8'));
}
}
}
}
else
{
$startX = $word['pos_x'];
$endX = $startX + mb_strlen($word['word'], 'UTF-8') - 1;
$y = $word['pos_y'];
$matrix = array_pad($matrix, $endX+1, array());
$maxX = max($maxX, $endX);
$maxY = max($maxY, $y);
foreach(range($startX, $endX) as $x)
{
$matrix[$x] = array_pad($matrix[$x], $y+1, null);
$matrix[$x][$y] = array(
'char' => mb_substr($word['word'], $x-$startX, 1, 'UTF-8'),
'indices' => (array_key_exists($x, $matrix) && array_key_exists($y, $matrix[$x]) && !is_null($matrix[$x][$y]) && array_key_exists('indices', $matrix[$x][$y])) ? $matrix[$x][$y]['indices'] : array(),
'answer' => null,
'right' => false
);
if($x == $startX) {
$matrix[$x][$y]['indices'][] = $index;
}
if(!is_null($word['answer']))
{
$answer = mb_substr($word['answer'], $x-$startX, 1, 'UTF-8');
if($answer != ' ')
{
$matrix[$x][$y]['answer'] = $answer;
$matrix[$x][$y]['right'] = (mb_strtolower($matrix[$x][$y]['char'], 'UTF-8') == mb_strtolower($answer, 'UTF-8'));
}
}
}
}
}
// Pass data to view
$this->set('words', $words);
$this->set('maxX', $maxX);
$this->set('maxY', $maxY);
$this->set('matrix', $matrix);
}
/**
* TODO Action: edittask.
*
* Edit the task of a Quest.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
*/
public function edittask($seminary, $questgroup, $quest)
{
}
}
?>

View file

@ -0,0 +1,128 @@
<?php
/**
* The Legend of Z
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
* @copyright 2014 Heinrich-Heine-Universität Düsseldorf
* @license http://www.gnu.org/licenses/gpl.html
* @link https://bitbucket.org/coderkun/the-legend-of-z
*/
namespace hhu\z\questtypes;
/**
* Model of the CrosswordQuesttypeAgent for solving a crossword.
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
*/
class CrosswordQuesttypeModel extends \hhu\z\models\QuesttypeModel
{
/**
* Copy a Quest
*
* @param int $userId ID of creating user
* @param int $sourceQuestId ID of Quest to copy from
* @param int $targetQuestId ID of Quest to copy to
* @param int $seminaryMediaIds Mapping of SeminaryMedia-IDs from source Seminary to targetSeminary
*/
public function copyQuest($userId, $sourceQuestId, $targetQuestId, $seminaryMediaIds)
{
// Copy words
$this->db->query(
'INSERT INTO questtypes_crossword_words '.
'(quest_id, question, word, vertical, pos_x, pos_y) '.
'SELECT ?, question, word, vertical, pos_x, pos_y '.
'FROM questtypes_crossword_words '.
'WHERE quest_id = ?',
'ii',
$targetQuestId,
$sourceQuestId
);
}
/**
* Delete a Quest.
*
* @param int $questId ID of Quest to delete
*/
public function deleteQuest($questId)
{
$this->db->query('DELETE FROM questtypes_crossword_words WHERE quest_id = ?', 'i', $questId);
}
/**
* Get all words for a crossword-Quest.
*
* @param int $questId ID of Quest
* @return array Words
*/
public function getWordsForQuest($questId)
{
return $this->db->query(
'SELECT id, question, word, vertical, pos_x, pos_y '.
'FROM questtypes_crossword_words '.
'WHERE quest_id = ? ',
'i',
$questId
);
}
/**
* Save Characters submitted answer for one crossword-word.
*
* @param int $regexId ID of word
* @param int $characterId ID of Character
* @param string $answer Submitted answer for this word
*/
public function setCharacterSubmission($wordId, $characterId, $answer)
{
$this->db->query(
'INSERT INTO questtypes_crossword_words_characters '.
'(questtypes_crossword_word_id, character_id, answer) '.
'VALUES '.
'(?, ?, ?) '.
'ON DUPLICATE KEY UPDATE '.
'answer = ?',
'iiss',
$wordId, $characterId, $answer,
$answer
);
}
/**
* Get answer of one crossword-word submitted by Character.
*
* @param int $regexId ID of lisword
* @param int $characterId ID of Character
* @return int Submitted answer for this word or null
*/
public function getCharacterSubmission($wordId, $characterId)
{
$data = $this->db->query(
'SELECT answer '.
'FROM questtypes_crossword_words_characters '.
'WHERE questtypes_crossword_word_id = ? AND character_id = ? ',
'ii',
$wordId, $characterId
);
if(!empty($data)) {
return $data[0]['answer'];
}
return null;
}
}
?>

View file

@ -0,0 +1 @@
<p>TODO</p>

View file

@ -0,0 +1,136 @@
<form method="post" class="crossword">
<table id="matrix">
<tbody>
<?php foreach(range(0, $maxY) as $y) : ?>
<tr>
<?php foreach(range(0, $maxX) as $x) : ?>
<td>
<?php if(array_key_exists($x, $matrix) && array_key_exists($y, $matrix[$x]) && !is_null($matrix[$x][$y])) : ?>
<?php if(count($matrix[$x][$y]['indices']) > 0) : ?><span class="index"><?=implode('/',array_map(function($e) { return $e+1; }, $matrix[$x][$y]['indices']))?></span><?php endif ?>
<input type="text" name="answers[<?=$x?>][<?=$y?>]" maxlength="1" size="1" value="<?=(!is_null($matrix[$x][$y]['answer'])) ? $matrix[$x][$y]['answer'] : ''?>" />
<?php endif ?>
</td>
<?php endforeach ?>
</tr>
<?php endforeach ?>
</tbody>
</table>
<ol>
<?php foreach($words as &$word) : ?>
<li>
<?php if($word['vertical']) : ?>
<?=_('vertical')?>:
<?php else : ?>
<?=_('horizontal')?>:
<?php endif ?>
<?=\hhu\z\Utils::t($word['question'])?>
</li>
<?php endforeach ?>
</ol>
<input type="submit" name="submit" value="<?=_('solve')?>" />
</form>
<script type="text/javascript">
// Last position
var posX = 0;
var posX = 0;
// Handle key input
$('input:text').keyup(function(event) {
// Determine current position
var row = $(this).closest('tr');
var y = $('#matrix tr').index(row);
var col = $(this).closest('td');
var x = row.children().index(col);
// Determine current direction
var horizontal = (x != posX);
// Set current position
posX = x;
posY = y;
// Next input field
var nextInput = null;
// Hanlde keys
switch(event.keyCode)
{
case 37: // Left
nextInput = getColumnInput(row, x-1);
break;
case 38: // Up
nextInput = getRowInput(x, y-1);
break;
case 39: // Right
nextInput = getColumnInput(row, x+1);
break;
case 40: // Down
nextInput = getRowInput(x, y+1);
break;
default:
// Only handy character input
if(event.key.length != 1) {
break;
}
// Set new character
$(this).val(event.key);
// Go to next input field
if(horizontal) {
nextInput = getColumnInput(row, x+1);
}
else {
nextInput = getRowInput(x, y+1);
}
event.preventDefault();
break;
}
// Select input field
if(nextInput != null) {
nextInput.focus();
}
});
/**
* Get the input field of the column x of the given row.
*/
function getColumnInput(row, x)
{
nextCol = $('td', row)[x];
if(nextCol != null) {
return $('input:text', nextCol)[0];
}
else {
// TODO get next number
}
return null;
}
/**
* Get the input field of the column y of row x.
*/
function getRowInput(x, y)
{
nextRow = $('#matrix tr')[y];
if(nextRow != null)
{
nextCol = $('td', nextRow)[x];
if(nextCol != null) {
return $('input:text', nextCol)[0];
}
}
else {
// TODO get nextnumber
}
return null;
}
</script>

View file

@ -0,0 +1,48 @@
<form method="post" class="crossword">
<table>
<tbody>
<?php foreach(range(0, $maxY) as $y) : ?>
<tr>
<?php foreach(range(0, $maxX) as $x) : ?>
<td>
<?php if(array_key_exists($x, $matrix) && array_key_exists($y, $matrix[$x]) && !is_null($matrix[$x][$y])) : ?>
<?php if(count($matrix[$x][$y]['indices']) > 0) : ?><span class="index"><?=implode('/',array_map(function($e) { return $e+1; }, $matrix[$x][$y]['indices']))?></span><?php endif ?>
<input type="text" name="answers[<?=$x?>][<?=$y?>]" maxlength="1" size="1" disabled="disabled" style="background-color:<?=($matrix[$x][$y]['right']) ? 'green' : 'red'?>" value="<?=(!is_null($matrix[$x][$y]['answer'])) ? $matrix[$x][$y]['answer'] : ''?>" />
<?php endif ?>
</td>
<?php endforeach ?>
</tr>
<?php endforeach ?>
</tbody>
</table>
<ol>
<?php foreach($words as &$word) : ?>
<li>
<?php if($word['vertical']) : ?>
<?=_('vertical')?>:
<?php else : ?>
<?=_('horizontal')?>:
<?php endif ?>
<?=$word['question']?>
</li>
<?php endforeach ?>
</ol>
</form>
<script type="text/javascript">
$('input:text').bind("keyup", function(e) {
var n = $("input:text").length;
if(e.which == 8 || e.which == 46) {
var nextIndex = $('input:text').index(this) - 1;
var del = 1;
}
else {
var nextIndex = $('input:text').index(this) + 1;
}
if(nextIndex < n) {
$('input:text')[nextIndex].focus();
if(del == 1) {
$('input:text')[nextIndex].value = '';
}
}
});
</script>

View file

@ -0,0 +1,24 @@
<?php
/**
* The Legend of Z
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
* @copyright 2014 Heinrich-Heine-Universität Düsseldorf
* @license http://www.gnu.org/licenses/gpl.html
* @link https://bitbucket.org/coderkun/the-legend-of-z
*/
namespace hhu\z\questtypes;
/**
* QuesttypeAgent for Drag&Drop.
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
*/
class DragndropQuesttypeAgent extends \hhu\z\agents\QuesttypeAgent
{
}
?>

View file

@ -0,0 +1,527 @@
<?php
/**
* The Legend of Z
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
* @copyright 2014 Heinrich-Heine-Universität Düsseldorf
* @license http://www.gnu.org/licenses/gpl.html
* @link https://bitbucket.org/coderkun/the-legend-of-z
*/
namespace hhu\z\questtypes;
/**
* Controller of the DragndropQuesttypeAgent for Drag&Drop.
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
*/
class DragndropQuesttypeController extends \hhu\z\controllers\QuesttypeController
{
/**
* Required models
*
* @var array
*/
public $models = array('media');
/**
* Required components
*
* @var array
*/
public $components = array('validation');
/**
* Save the answers of a Character for a Quest.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
* @param array $character Current Character data
* @param array $answers Character answers for the Quest
*/
public function saveAnswersOfCharacter($seminary, $questgroup, $quest, $character, $answers)
{
// Get Drag&Drop field
$dndField = $this->Dragndrop->getDragndrop($quest['id']);
// Get Drops
$drops = $this->Dragndrop->getDrops($dndField['quest_id']);
// Save user answers
foreach($drops as &$drop)
{
// Determine user answer
$answer = null;
if(array_key_exists($drop['id'], $answers) && !empty($answers[$drop['id']]))
{
$a = intval(substr($answers[$drop['id']], 4));
if($a !== false && $a > 0) {
$answer = $a;
}
}
// Update database record
$this->Dragndrop->setCharacterSubmission($drop['id'], $character['id'], $answer);
}
}
/**
* Save additional data for the answers of a Character for a Quest.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
* @param array $character Current Character data
* @param array $data Additional (POST-) data
*/
public function saveDataForCharacterAnswers($seminary, $questgroup, $quest, $character, $data)
{
}
/**
* Check if answers of a Character for a Quest match the correct ones.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
* @param array $character Current Character data
* @param array $answers Character answers for the Quest
* @return boolean True/false for a right/wrong answer or null for moderator evaluation
*/
public function matchAnswersOfCharacter($seminary, $questgroup, $quest, $character, $answers)
{
// Get Drag&Drop field
$dndField = $this->Dragndrop->getDragndrop($quest['id']);
// Get Drags
$drags = $this->Dragndrop->getDrags($dndField['quest_id'], true);
// Match drags with user answers
foreach($drags as &$drag)
{
$founds = array_keys($answers, 'drag'.$drag['id']);
if(count($founds) != 1) {
return false;
}
if(!$this->Dragndrop->dragMatchesDrop($drag['id'], $founds[0])) {
return false;
}
}
// Set status
return true;
}
/**
* Action: quest.
*
* Display a text with input fields and evaluate if user input
* matches with stored regular expressions.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
* @param array $character Current Character data
* @param \Exception $exception Character submission exception
*/
public function quest($seminary, $questgroup, $quest, $character, $exception)
{
// Get Drag&Drop field
$dndField = $this->Dragndrop->getDragndrop($quest['id']);
if(!is_null($dndField) && !is_null($dndField['questmedia_id'])) {
$dndField['media'] = $this->Media->getSeminaryMediaById($dndField['questmedia_id']);
}
// Get Drags
$drags = array();
if(!is_null($dndField))
{
$dragsByIndex = $this->Dragndrop->getDrags($dndField['quest_id']);
foreach($dragsByIndex as &$drag) {
$drag['media'] = $this->Media->getSeminaryMediaById($drag['questmedia_id']);
$drags[$drag['id']] = $drag;
}
}
// Get Drops
$drops = array();
if(!is_null($dndField)) {
$drops = $this->Dragndrop->getDrops($dndField['quest_id']);
}
// Get Character answers
if($this->request->getGetParam('show-answer') == 'true' || !$this->Quests->hasCharacterSolvedQuest($quest['id'], $character['id']) || $this->request->getGetParam('status') == 'solved')
{
foreach($drops as &$drop)
{
$drop['answer'] = $this->Dragndrop->getCharacterSubmission($drop['id'], $character['id']);
if(!is_null($drop['answer']))
{
$drop['answer'] = $drags[$drop['answer']];
unset($drags[$drop['answer']['id']]);
}
}
}
// Pass data to view
$this->set('seminary', $seminary);
$this->set('field', $dndField);
$this->set('drops', $drops);
$this->set('drags', $drags);
}
/**
* Action: submission.
*
* Show the submission of a Character for a Quest.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
* @param array $character Current Character data
*/
public function submission($seminary, $questgroup, $quest, $character)
{
// Get Drag&Drop field
$dndField = $this->Dragndrop->getDragndrop($quest['id']);
$dndField['media'] = $this->Media->getSeminaryMediaById($dndField['questmedia_id']);
// Get Drags
$drags = array();
$dragsByIndex = $this->Dragndrop->getDrags($dndField['quest_id']);
foreach($dragsByIndex as &$drag) {
$drag['media'] = $this->Media->getSeminaryMediaById($drag['questmedia_id']);
$drags[$drag['id']] = $drag;
}
// Get Drops
$drops = $this->Dragndrop->getDrops($dndField['quest_id']);
// Get Character answers
foreach($drops as &$drop)
{
$drop['answer'] = $this->Dragndrop->getCharacterSubmission($drop['id'], $character['id']);
if(!is_null($drop['answer']))
{
$drop['answer'] = $drags[$drop['answer']];
unset($drags[$drop['answer']['id']]);
}
}
// Pass data to view
$this->set('seminary', $seminary);
$this->set('field', $dndField);
$this->set('drops', $drops);
$this->set('drags', $drags);
}
/**
* Action: edittask.
*
* Edit the task of a Quest.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
*/
public function edittask($seminary, $questgroup, $quest)
{
// Get Drag&Drop field
$dndField = $this->Dragndrop->getDragndrop($quest['id']);
if(!is_null($dndField)) {
$dndField['media'] = $this->Media->getSeminaryMediaById($dndField['questmedia_id']);
}
// Get Drop-items
$drops = array();
if(!is_null($dndField)) {
$drops = $this->Dragndrop->getDrops($dndField['quest_id']);
}
// Get Drag-items
$drags = array();
if(!is_null($dndField))
{
$drags = $this->Dragndrop->getDrags($dndField['quest_id']);
foreach($drags as &$drag)
{
$drag['media'] = $this->Media->getSeminaryMediaById($drag['questmedia_id']);
$drag['drops'] = array_map(function($d) { return $d['id']; }, $this->Dragndrop->getDropsForDrag($drag['id']));
}
}
// Get allowed mimetypes
$mimetypes = \nre\configs\AppConfig::$mimetypes['questtypes'];
// Values
$step = 0;
$steps = 2;
$validation = true;
$dragsValidation = true;
// Save submitted data
if($this->request->getRequestMethod() == 'POST')
{
// Get current step
$step = max(0, min($steps, intval($this->request->getPostParam('step'))));
// Drag&Drop-field (background image)
if($step == 0)
{
// Validate zone
$zone = null;
if(!empty($_FILES) && array_key_exists('zone', $_FILES) && $_FILES['zone']['error'] != UPLOAD_ERR_NO_FILE)
{
$zone = $_FILES['zone'];
// Check error
if($zone['error'] !== UPLOAD_ERR_OK) {
$validation = $this->Validation->addValidationResult($validation, 'zone', 'error', $zone['error']);
}
// Check mimetype
$mediaMimetype = null;
$zone['mimetype'] = \hhu\z\Utils::getMimetype($zone['tmp_name'], $zone['type']);
foreach($mimetypes as &$mimetype) {
if($mimetype['mimetype'] == $zone['mimetype']) {
$mediaMimetype = $mimetype;
break;
}
}
if(is_null($mediaMimetype)) {
$validation = $this->Validation->addValidationResult($validation, 'zone', 'mimetype', $zone['mimetype']);
}
elseif($zone['size'] > $mediaMimetype['size']) {
$validation = $this->Validation->addValidationResult($validation, 'zone', 'size', $mediaMimetype['size']);
}
}
// Set zone
if($validation === true)
{
// Upload background image
$mediaId = $this->Media->createQuestMedia(
$this->Auth->getUserId(),
$seminary['id'],
sprintf('quest-dnd-%s', $quest['url']),
'',
$zone['mimetype'],
$zone['tmp_name']
);
if($mediaId !== false)
{
// Create Drag&Drop zone
$this->Dragndrop->createDragndrop(
$this->Auth->getUserId(),
$quest['id'],
$mediaId
);
}
// Reload Drag&Drop field
$dndField = $this->Dragndrop->getDragndrop($quest['id']);
$dndField['media'] = $this->Media->getSeminaryMediaById($dndField['questmedia_id']);
}
}
// Drop-items
elseif($step == 1)
{
// Get new Drop-items and organize them
$dropsNew = array();
$dropsUpdate = array();
foreach($this->request->getPostParam('drops') as $drop)
{
if(array_key_exists('id', $drop)) {
$dropsUpdate[$drop['id']] = $drop;
}
else {
$dropsNew[] = $drop;
}
}
// Update Drop-items
foreach($drops as $drop)
{
if(array_key_exists($drop['id'], $dropsUpdate))
{
$drop = $dropsUpdate[$drop['id']];
$this->Dragndrop->editDrop($drop['id'], $drop['width'], $drop['height'], $drop['x'], $drop['y']);
}
else {
$this->Dragndrop->deleteDrop($drop['id']);
}
}
// Add new Drop-items
foreach($dropsNew as $drop) {
$this->Dragndrop->addDrop($dndField['quest_id'], $drop['width'], $drop['height'], $drop['x'], $drop['y']);
}
// Reload Drop-items
$drops = $this->Dragndrop->getDrops($dndField['quest_id']);
}
// Drag-items
elseif($step == 2)
{
// Get new Drop-items and organize them
$dragsNew = array();
$dragsUpdate = array();
foreach($this->request->getPostParam('drags') as $index => $drag)
{
// Get file
if(array_key_exists($index, $_FILES['drags']['error']) && $_FILES['drags']['error'][$index] !== UPLOAD_ERR_NO_FILE)
{
$drag['file'] = array(
'name' => $_FILES['drags']['name'][$index],
'type' => $_FILES['drags']['type'][$index],
'tmp_name' => $_FILES['drags']['tmp_name'][$index],
'error' => $_FILES['drags']['error'][$index],
'size' => $_FILES['drags']['size'][$index]
);
// Validate file
$dragValidation = true;
// Check error
if($drag['file']['error'] !== UPLOAD_ERR_OK) {
$dragValidation = $this->Validation->addValidationResult($dragValidation, 'file', 'error', $drag['file']['error']);
}
// Check mimetype
$dragMimetype = null;
$drag['file']['mimetype'] = \hhu\z\Utils::getMimetype($drag['file']['tmp_name'], $drag['file']['type']);
foreach($mimetypes as &$mimetype) {
if($mimetype['mimetype'] == $drag['file']['mimetype']) {
$dragMimetype = $mimetype;
break;
}
}
if(is_null($dragMimetype)) {
$dragValidation = $this->Validation->addValidationResult($dragValidation, 'file', 'mimetype', $drag['file']['mimetype']);
}
elseif($drag['file']['size'] > $dragMimetype['size']) {
$dragValidation = $this->Validation->addValidationResult($dragValidation, 'file', 'size', $dragMimetype['size']);
}
// Add validation result
if($dragValidation !== true)
{
if(!is_array($dragsValidation)) {
$dragsValidation = array();
}
$dragsValidation[$index] = $dragValidation;
}
// Upload Drag-item file
if($dragValidation === true)
{
$drag['file']['media_id'] = $this->Media->createQuestMedia(
$this->Auth->getUserId(),
$seminary['id'],
sprintf('quest-dnd-%s-%s', substr($quest['url'], 0, 25), substr($drag['file']['name'], 0, 25)),
'',
$drag['file']['mimetype'],
$drag['file']['tmp_name']
);
}
}
// Add to array
if(array_key_exists('id', $drag)) {
$dragsUpdate[$drag['id']] = $drag;
}
else {
$dragsNew[] = $drag;
}
}
// Update Drag-items
foreach($drags as $drag)
{
if(array_key_exists($drag['id'], $dragsUpdate))
{
$drag = $dragsUpdate[$drag['id']];
// Edit Drag-items
if(array_key_exists('file', $drag) && array_key_exists('media_id', $drag['file'])) {
$this->Dragndrop->editDrag($drag['id'], $drag['file']['media_id']);
}
// Set correct Drop-items for Drag-item
$this->Dragndrop->setDropsForDrag(
$this->Auth->getUserId(),
$drag['id'],
array_key_exists('drops', $drag) ? array_keys($drag['drops']) : array()
);
}
else {
$this->Dragndrop->deleteDrag($drag['id']);
}
}
// Add new Drag-items
foreach($dragsNew as $drag)
{
if(array_key_exists('file', $drag) && array_key_exists('media_id', $drag['file']))
{
// Create Drag-item
$dragId = $this->Dragndrop->addDrag($dndField['quest_id'], $drag['file']['media_id']);
// Set Drop-items for Drag-item
$this->Dragndrop->setDropsForDrag(
$this->Auth->getUserId(),
$dragId,
array_key_exists('drops', $drag) ? array_keys($drag['drops']) : array()
);
}
}
// Reload Drag-items
$drags = $this->Dragndrop->getDrags($dndField['quest_id']);
foreach($drags as &$drag)
{
$drag['media'] = $this->Media->getSeminaryMediaById($drag['questmedia_id']);
$drag['drops'] = array_map(function($d) { return $d['id']; }, $this->Dragndrop->getDropsForDrag($drag['id']));
}
}
// Go to next/previous step
if($validation === true && $dragsValidation === true)
{
if(!is_null($this->request->getPostParam('prev'))) {
$step--;
}
else {
$step++;
}
// Redirect after last step
if($step > $steps) {
$this->redirect($this->linker->link(array('quest', $seminary['url'], $questgroup['url'], $quest['url']), 1));
}
}
}
// Pass data to view
$this->set('seminary', $seminary);
$this->set('zone', $dndField);
$this->set('drops', $drops);
$this->set('drags', $drags);
$this->set('mimetypes', $mimetypes);
$this->set('step', $step);
$this->set('validation', $validation);
$this->set('dragsValidation', $dragsValidation);
}
}
?>

View file

@ -0,0 +1,517 @@
<?php
/**
* The Legend of Z
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
* @copyright 2014 Heinrich-Heine-Universität Düsseldorf
* @license http://www.gnu.org/licenses/gpl.html
* @link https://bitbucket.org/coderkun/the-legend-of-z
*/
namespace hhu\z\questtypes;
/**
* Model of the DragndropQuesttypeAgent for Drag&Drop.
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
*/
class DragndropQuesttypeModel extends \hhu\z\models\QuesttypeModel
{
/**
* Required models
*
* @var array
*/
public $models = array('media');
/**
* Copy a Quest
*
* @param int $userId ID of creating user
* @param int $sourceQuestId ID of Quest to copy from
* @param int $targetQuestId ID of Quest to copy to
* @param int $seminaryMediaIds Mapping of SeminaryMedia-IDs from source Seminary to targetSeminary
*/
public function copyQuest($userId, $sourceQuestId, $targetQuestId, $seminaryMediaIds)
{
// Check Seminary media
if(is_null($seminaryMediaIds)) {
return;
}
// Get Dragndrop
$dragndrop = $this->getDragndrop($sourceQuestId);
// Copy media
$this->Media->copyQuestsmedia($userId, $seminaryMediaIds[$dragndrop['questmedia_id']]);
// Copy dran&drop
$this->db->query(
'INSERT INTO questtypes_dragndrop '.
'(quest_id, created_user_id, questmedia_id, width, height) '.
'SELECT ?, ?, ?, width, height '.
'FROM questtypes_dragndrop '.
'WHERE quest_id = ?',
'iiii',
$targetQuestId, $userId, $seminaryMediaIds[$dragndrop['questmedia_id']],
$sourceQuestId
);
// Copy drags
$dragIds = array();
$drags = $this->getDrags($sourceQuestId);
foreach($drags as &$drag)
{
// Copy media
$this->Media->copyQuestsmedia($userId, $seminaryMediaIds[$drag['questmedia_id']]);
// Copy drag
$this->db->query(
'INSERT INTO questtypes_dragndrop_drags '.
'(questtypes_dragndrop_id, questmedia_id) '.
'SELECT ?, ? '.
'FROM questtypes_dragndrop_drags '.
'WHERE id = ?',
'iii',
$targetQuestId, $seminaryMediaIds[$drag['questmedia_id']],
$drag['id']
);
$dragIds[$drag['id']] = $this->db->getInsertId();
}
// Copy drops
$dropIds = array();
$drops = $this->getDrops($sourceQuestId);
foreach($drops as &$drop)
{
// Copy drop
$this->db->query(
'INSERT INTO questtypes_dragndrop_drops '.
'(questtypes_dragndrop_id, top, `left`, width, height) '.
'SELECT ?, top, `left`, width, height '.
'FROM questtypes_dragndrop_drops '.
'WHERE id = ?',
'ii',
$targetQuestId,
$drop['id']
);
$dropIds[$drop['id']] = $this->db->getInsertId();
// Link drags and drops
$links = $this->db->query(
'SELECT questtypes_dragndrop_drag_id '.
'FROM questtypes_dragndrop_drops_drags '.
'WHERE questtypes_dragndrop_drop_id = ?',
'i',
$drop['id']
);
foreach($links as $link)
{
$this->db->query(
'INSERT INTO questtypes_dragndrop_drops_drags '.
'(questtypes_dragndrop_drop_id, questtypes_dragndrop_drag_id, created_user_id) '.
'VALUES '.
'(?, ?, ?)',
'iii',
$dropIds[$drop['id']],
$dragIds[$link['questtypes_dragndrop_drag_id']],
$userId
);
}
}
}
/**
* Delete a Quest.
*
* @param int $questId ID of Quest to delete
*/
public function deleteQuest($questId)
{
$this->db->query('DELETE FROM questtypes_dragndrop WHERE quest_id = ?', 'i', $questId);
}
/**
* Create a new Drag&Drop field for a Quest.
*
* @param int $userId ID of creating user
* @param int $questId ID of Quest to create Drag&Drop field for
* @param int $questmediaId ID of Questmedia to use for the field
*/
public function createDragndrop($userId, $questId, $questmediaId)
{
// Get image measurements
$infos = $this->Media->getSeminarymediaInfos($questmediaId);
// Create field
$this->db->query(
'INSERT INTO questtypes_dragndrop '.
'(quest_id, created_user_id, questmedia_id, width, height) '.
'VALUES '.
'(?, ?, ?, ?, ?) '.
'ON DUPLICATE KEY UPDATE '.
'questmedia_id = ?, width = ?, height = ?',
'iiiiiiii',
$questId, $userId, $questmediaId, $infos['width'], $infos['height'],
$questmediaId, $infos['width'], $infos['height']
);
}
/**
* Get Drag&Drop-field.
*
* @param int $questId ID of Quest
* @return array Drag&Drop-field
*/
public function getDragndrop($questId)
{
$data = $this->db->query(
'SELECT quest_id, questmedia_id, width, height '.
'FROM questtypes_dragndrop '.
'WHERE quest_id = ?',
'i',
$questId
);
if(!empty($data)) {
return $data[0];
}
return null;
}
/**
* Get Drop-items.
*
* @param int $dragndropId ID of Drag&Drop-field
* @return array Drop-items
*/
public function getDrops($dragndropId)
{
return $this->db->query(
'SELECT id, top, `left`, width, height '.
'FROM questtypes_dragndrop_drops '.
'WHERE questtypes_dragndrop_id = ?',
'i',
$dragndropId
);
}
/**
* Get Drop-items for a Drag-item
*
* @param int $dragId ID of Drag-item to get Drop-items for
* @return array List of Drop-items
*/
public function getDropsForDrag($dragId)
{
return $this->db->query(
'SELECT drops.id, top, `left`, width, height '.
'FROM questtypes_dragndrop_drops_drags AS drops_drags '.
'INNER JOIN questtypes_dragndrop_drops AS drops ON drops.id = drops_drags.questtypes_dragndrop_drop_id '.
'WHERE drops_drags.questtypes_dragndrop_drag_id = ?',
'i',
$dragId
);
}
/**
* Set correct Drop-items for a Drag-item.
*
* @param int $userId ID of creating user
* @param int $dragId ID of Drag-item to set Drop-items for
* @param array $dropIds List of Drop-items to set for Drag-item
*/
public function setDropsForDrag($userId, $dragId, $dropIds)
{
// Set new Drop-items
if(!empty($dropIds))
{
$this->db->query(
sprintf(
'INSERT INTO questtypes_dragndrop_drops_drags '.
'(questtypes_dragndrop_drop_id, questtypes_dragndrop_drag_id, created_user_id) '.
'SELECT questtypes_dragndrop_drops.id, ?, ? '.
'FROM questtypes_dragndrop_drops '.
'WHERE questtypes_dragndrop_drops.questtypes_dragndrop_id = ('.
'SELECT questtypes_dragndrop_drags.questtypes_dragndrop_id '.
'FROM questtypes_dragndrop_drags '.
'WHERE questtypes_dragndrop_drags.id = ?'.
') AND questtypes_dragndrop_drops.id IN (%s) '.
'ON DUPLICATE KEY UPDATE '.
'questtypes_dragndrop_drops_drags.created = questtypes_dragndrop_drops_drags.created',
implode(',', array_map(function($id) { return intval($id); }, $dropIds))
),
'iii',
$dragId, $userId,
$dragId
);
// Remove old Drop-items
$this->db->query(
sprintf(
'DELETE FROM questtypes_dragndrop_drops_drags '.
'WHERE questtypes_dragndrop_drag_id = ? AND questtypes_dragndrop_drop_id NOT IN (%s)',
implode(',', array_map(function($id) { return intval($id); }, $dropIds))
),
'i',
$dragId
);
}
else
{
// Remove all Drop-items
$this->db->query(
'DELETE FROM questtypes_dragndrop_drops_drags '.
'WHERE questtypes_dragndrop_drag_id = ?',
'i',
$dragId
);
}
}
/**
* Create a new Drop-item for a Drag&Drop-field.
*
* @param int $dragndropId ID of Drag&Drop-field to create Drop-item for
* @param int $width Width of Drop-item
* @param int $height Height of Drop-item
* @param int $x X-coordinate of Drop-item
* @param int $y Y-coordinate of Drop-item
* @return int ID of newly created Drop-item
*/
public function addDrop($dragndropId, $width, $height, $x, $y)
{
$this->db->query(
'INSERT INTO questtypes_dragndrop_drops '.
'(questtypes_dragndrop_id, top, `left`, width, height) '.
'VALUES '.
'(?, ?, ?, ?, ?)',
'iiiii',
$dragndropId, $y, $x, $width, $height
);
return $this->db->getInsertId();
}
/**
* Edit Drop-item.
*
* @param int $dropId ID of Drop-item to edit
* @param int $width New width of Drop-item
* @param int $height New height of Drop-item
* @param int $x New X-coordinate of Drop-item
* @param int $y New Y-coordinate of Drop-item
*/
public function editDrop($dropId, $width, $height, $x, $y)
{
$this->db->query(
'UPDATE questtypes_dragndrop_drops '.
'SET top = ?, `left` = ?, width = ?, height = ? '.
'WHERE id = ?',
'iiiii',
$y, $x, $width, $height,
$dropId
);
}
/**
* Delete a Drop-item.
*
* @param int $dropId ID of Drop-item to delete
*/
public function deleteDrop($dropId)
{
$this->db->query(
'DELETE FROM questtypes_dragndrop_drops '.
'WHERE id = ?',
'i',
$dropId
);
}
/**
* Get Drag-items.
*
* @param int $dragndropId ID of Drag&Drop-field
* @param boolean $onlyUsed Only Drag-items that are used for a Drop-item
* @return array Drag-items
*/
public function getDrags($dragndropId, $onlyUsed=false)
{
return $this->db->query(
'SELECT id, questmedia_id '.
'FROM questtypes_dragndrop_drags '.
'WHERE questtypes_dragndrop_id = ?'.
($onlyUsed
? ' AND EXISTS ('.
'SELECT questtypes_dragndrop_drag_id '.
'FROM questtypes_dragndrop_drops_drags '.
'WHERE questtypes_dragndrop_drag_id = questtypes_dragndrop_drags.id'.
')'
: null
),
'i',
$dragndropId
);
}
/**
* Create a new Drag-item.
*
* @param int $dragndropId ID of Drag&Drop-field to add Drag-item for
* @param int $questmediaId ID of Questmedia to use for this Drag-item
* @return int ID of newly created Drag-item
*/
public function addDrag($dragndropId, $questmediaId)
{
$this->db->query(
'INSERT INTO questtypes_dragndrop_drags '.
'(questtypes_dragndrop_id, questmedia_id) '.
'VALUES '.
'(?, ?) ',
'ii',
$dragndropId, $questmediaId
);
return $this->db->getInsertId();
}
/**
* Edit Drag-item.
*
* @param int $dragId ID of Drag-item to edit
* @param int $questmediaId ID of new Questmedia to use for this Drag-item
*/
public function editDrag($dragId, $questmediaId)
{
$this->db->query(
'UPDATE questtypes_dragndrop_drags '.
'SET questmedia_id = ? '.
'WHERE id = ?',
'ii',
$questmediaId,
$dragId
);
}
/**
* Delete a Drag-item.
*
* @param int $dragId ID of Drag-item to delete
*/
public function deleteDrag($dragId)
{
$this->db->query(
'DELETE FROM questtypes_dragndrop_drags '.
'WHERE id = ?',
'i',
$dragId
);
}
/**
* Check if a Drag-item mathes a Drop-item.
*
* @param int $dragId ID of Drag-field
* @param int $dropId ID of Drop-field
* @return boolean Drag-item is valid for Drop-item
*/
public function dragMatchesDrop($dragId, $dropId)
{
$data = $this->db->query(
'SELECT count(*) AS c '.
'FROM questtypes_dragndrop_drops_drags '.
'WHERE questtypes_dragndrop_drop_id = ? AND questtypes_dragndrop_drag_id = ?',
'ii',
$dropId, $dragId
);
if(!empty($data)) {
return ($data[0]['c'] > 0);
}
return false;
}
/**
* Save Characters submitted answer for one Drop-field.
*
* @param int $dropId ID of Drop-field
* @param int $characterId ID of Character
* @param string $answer Submitted Drag-field-ID for this field
*/
public function setCharacterSubmission($dropId, $characterId, $answer)
{
if(is_null($answer))
{
$this->db->query(
'DELETE FROM questtypes_dragndrop_drops_characters '.
'WHERE questtypes_dragndrop_drop_id = ? AND character_id = ?',
'ii',
$dropId, $characterId
);
}
else
{
$this->db->query(
'INSERT INTO questtypes_dragndrop_drops_characters '.
'(questtypes_dragndrop_drop_id, character_id, questtypes_dragndrop_drag_id) '.
'VALUES '.
'(?, ?, ?) '.
'ON DUPLICATE KEY UPDATE '.
'questtypes_dragndrop_drag_id = ?',
'iiii',
$dropId, $characterId, $answer, $answer
);
}
}
/**
* Get Characters saved answer for one Drop-field.
*
* @param int $dropId ID of Drop-field
* @param int $characterId ID of Character
* @return int ID of Drag-field or null
*/
public function getCharacterSubmission($dropId, $characterId)
{
$data = $this->db->query(
'SELECT questtypes_dragndrop_drag_id '.
'FROM questtypes_dragndrop_drops_characters '.
'WHERE questtypes_dragndrop_drop_id = ? AND character_id = ?',
'ii',
$dropId, $characterId
);
if(!empty($data)) {
return $data[0]['questtypes_dragndrop_drag_id'];
}
return null;
}
}
?>

View file

@ -0,0 +1,253 @@
<?php if($validation !== true && !empty($validation)) : ?>
<ul class="validation">
<?php foreach($validation as $field => &$settings) : ?>
<li>
<ul>
<?php foreach($settings as $setting => $value) : ?>
<li>
<?php switch($field) {
case 'zone':
switch($setting) {
case 'error': printf(_('Error during file upload: %s'), $value);
break;
case 'mimetype': printf(_('File has wrong type “%s”'), $value);
break;
case 'size': echo _('File exceeds size maximum');
break;
default: echo _('File invalid');
}
break;
} ?>
</li>
<?php endforeach ?>
</ul>
</li>
<?php endforeach ?>
</ul>
<?php endif ?>
<form method="post" enctype="multipart/form-data">
<?php if($step == 0) : ?>
<fieldset>
<legend><?=sprintf(_('Step %d'), 1)?>: <?=_('Field')?>:</legend>
<?php if(!is_null($zone)) : ?>
<div id="dropZone" style="width:<?=$zone['width']?>px; height:<?=$zone['height']?>px; background-image:url('<?=$linker->link(array('media','seminary',$seminary['url'],$zone['media']['url']))?>')">
</div>
<?php endif ?>
<label for="zone"><?=_('Upload background image')?>:</label>
<input type="file" id="zone" name="zone" />
<p><?=_('Allowed file types')?>:</p>
<ul>
<?php foreach($mimetypes as &$mimetype) : ?>
<li><?=sprintf(_('%s-files'), strtoupper(explode('/',$mimetype['mimetype'])[1]))?> <?php if($mimetype['size'] > 0) : ?>(<?=_('max.')?> <?=round($mimetype['size']/(1024*1024),2)?>MiB)<?php endif ?></li>
<?php endforeach ?>
</ul>
</fieldset>
<input type="submit" name="next" value="<?=_('next step')?>" />
<?php elseif($step == 1) : ?>
<fieldset>
<legend><?=sprintf(_('Step %d'), 2)?>: <?=_('Drop-items')?></legend>
<div id="dropZone" class="dev" style="position:relative; width:<?=$zone['width']?>px; height:<?=$zone['height']?>px; background-image:url('<?=$linker->link(array('media','seminary',$seminary['url'],$zone['media']['url']))?>')">
<?php foreach($drops as $index => &$drop) : ?>
<div id="drop<?=$index?>" ondragenter="onDragEnter(event)" ondragover="onDragOver(event)" ondragleave="onDragLeave(event)" ondrop="onDrop(event)" style="position:absolute; width:<?=$drop['width']?>px; height:<?=$drop['height']?>px; top:<?=$drop['top']?>px; left:<?=$drop['left']?>px;">
<?=$index+1?>
<i class="fa fa-arrows move"></i>
<i class="fa fa-expand resize"></i>
</div>
<?php endforeach ?>
</div>
<ol id="drops">
<?php foreach($drops as $index => &$drop) : ?>
<li id="drop<?=$index?>-p">
<span class="lstidx"><?=$index+1?></span>
<input type="hidden" name="drops[<?=$index?>][id]" value="<?=$drop['id']?>" />
<label><?=_('Size')?>:</label>
<input type="number" id="drop<?=$index?>-w" name="drops[<?=$index?>][width]" value="<?=$drop['width']?>" min="45" max="<?=$zone['width']?>" /> x
<input type="number" id="drop<?=$index?>-h" name="drops[<?=$index?>][height]" value="<?=$drop['height']?>" min="25" max="<?=$zone['height']?>" /> px
<br />
<label><?=_('Position')?>:</label>
<input type="number" id="drop<?=$index?>-x" name="drops[<?=$index?>][x]" value="<?=$drop['left']?>" min="0" max="<?=$zone['width']?>" /> x
<input type="number" id="drop<?=$index?>-y" name="drops[<?=$index?>][y]" value="<?=$drop['top']?>" min="0" max="<?=$zone['height']?>" /> px
<br />
<input type="button" class="remove-drop" value="" />
</li>
<?php endforeach ?>
<li>
<input type="button" class="add-drop" value="+" />
</li>
</ol>
</fieldset>
<input type="submit" name="prev" value="<?=_('previous step')?>" />
<input type="submit" name="next" value="<?=_('next step')?>" />
<?php elseif($step == 2) : ?>
<fieldset>
<legend><?=sprintf(_('Step %d'), 3)?>: <?=_('Drag-items')?></legend>
<div id="dropZone" class="dev" style="position:relative; width:<?=$zone['width']?>px; height:<?=$zone['height']?>px; background-image:url('<?=$linker->link(array('media','seminary',$seminary['url'],$zone['media']['url']))?>')">
<?php foreach($drops as $index => &$drop) : ?>
<div id="drop<?=$index?>" ondragenter="onDragEnter(event)" ondragover="onDragOver(event)" ondragleave="onDragLeave(event)" ondrop="onDrop(event)" style="position:absolute; width:<?=$drop['width']?>px; height:<?=$drop['height']?>px; top:<?=$drop['top']?>px; left:<?=$drop['left']?>px;">
<?=$index+1?>
</div>
<?php endforeach ?>
</div>
<ul id="drags">
<?php foreach($drags as $dragIndex => &$drag) : ?>
<li id="drag<?=$dragIndex?>">
<?php if($dragsValidation !== true && array_key_exists($dragIndex, $dragsValidation) && $dragsValidation[$dragIndex] !== true) : ?>
<ul class="validation">
<?php foreach($dragsValidation[$dragIndex] as $field => &$settings) : ?>
<li>
<ul>
<?php foreach($settings as $setting => $value) : ?>
<li>
<?php switch($field) {
case 'file':
switch($setting) {
case 'error': printf(_('Error during file upload: %s'), $value);
break;
case 'mimetype': printf(_('File has wrong type “%s”'), $value);
break;
case 'size': echo _('File exceeds size maximum');
break;
default: echo _('File invalid');
}
break;
} ?>
</li>
<?php endforeach ?>
</ul>
</li>
<?php endforeach ?>
</ul>
<?php endif ?>
<input type="hidden" name="drags[<?=$dragIndex?>][id]" value="<?=$drag['id']?>" />
<img id="drag<?=$dragIndex?>" src="<?=$linker->link(array('media','seminary',$seminary['url'],$drag['media']['url']))?>" />
<input type="file" name="drags[<?=$dragIndex?>]" />
<?php foreach($drops as $dropIndex => &$drop) : ?>
<input type="checkbox" id="drag<?=$dragIndex?>-drop<?=$dropIndex?>" name="drags[<?=$dragIndex?>][drops][<?=$drop['id']?>]" <?php if(in_array($drop['id'], $drag['drops'])) : ?>checked="checked"<?php endif ?> />
<label for="drag<?=$dragIndex?>-drop<?=$dropIndex?>"><?=$dropIndex+1?></label>
<?php endforeach ?>
<br />
<input type="button" class="remove-drag" value="" />
</li>
<?php endforeach?>
<li>
<input type="button" class="add-drag" value="+" />
</li>
</ul>
<p><?=_('Allowed file types')?>:</p>
<ul>
<?php foreach($mimetypes as &$mimetype) : ?>
<li><?=sprintf(_('%s-files'), strtoupper(explode('/',$mimetype['mimetype'])[1]))?> <?php if($mimetype['size'] > 0) : ?>(<?=_('max.')?> <?=round($mimetype['size']/(1024*1024),2)?>MiB)<?php endif ?></li>
<?php endforeach ?>
</ul>
</fieldset>
<input type="submit" name="prev" value="<?=_('previous step')?>" />
<input type="submit" name="next" value="<?=_('save')?>" />
<?php endif ?>
<input type="hidden" name="step" value="<?=$step?>" />
</form>
<script>
var dropIndex = <?=count($drops)?>;
var dragIndex = <?=count($drags)?>;
var cssProps = {w: "width", h: "height", x: "left", y: "top"};
var draggable = {
containment: "parent",
handle: 'i.move',
drag: function(event, ui) {
var id = ui.helper.prop('id').substr(4);
$('#drop' + id + '-x').prop('value', ui.position.left);
$('#drop' + id + '-y').prop('value', ui.position.top);
}
};
var resizable = {
minWidth: 45,
minHeight: 25,
handles: {
se: 'i.resize'
},
resize: function(event, ui) {
var id = ui.helper.prop('id').substr(4);
$('#drop' + id + '-w').prop('value', ui.size.width);
$('#drop' + id + '-h').prop('value', ui.size.height);
}
};
var dropElement =
'<div id="dropDROPINDEX" style="position:absolute; width:75px; height:50px; top:0; left:0;">' +
'DROPINDEX1' +
'<i class="fa fa-arrows move"></i>' +
'<i class="fa fa-expand resize"></i>' +
'</div>';
var dropPropElement =
'<li id="dropDROPINDEX-p">' +
'<span class="lstidx">DROPINDEX1</span>' +
"<label><?=_('Size')?>:</label>" +
'<input type="number" id="dropDROPINDEX-w" name="drops[DROPINDEX][width]" value="45" min="45" max="<?=$zone['width']?>" /> x' +
'<input type="number" id="dropDROPINDEX-h" name="drops[DROPINDEX][height]" value="25" min="25" max="<?=$zone['height']?>" /> px' +
'<br />' +
"<label><?=_('Position')?>:</label>" +
'<input type="number" id="dropDROPINDEX-x" name="drops[DROPINDEX][x]" value="0" min="0" max="<?=$zone['width']?>" /> x' +
'<input type="number" id="dropDROPINDEX-y" name="drops[DROPINDEX][y]" value="0" min="0" max="<?=$zone['height']?>" /> px' +
'<br /><input type="button" class="remove-drop" value="" />' +
'</li>';
var dragElement =
'<li id="dragDRAGINDEX">' +
'<input type="file" name="drags[DRAGINDEX]" />' +
<?php foreach($drops as $dropIndex => &$drop) : ?>
'<input type="checkbox" id="dragDRAGINDEX-drop<?=$dropIndex?>" name="drags[DRAGINDEX][drops][<?=$drop['id']?>]" />\n' +
'<label for="dragDRAGINDEX-drop<?=$dropIndex?>"><?=$dropIndex+1?></label>\n' +
<?php endforeach ?>
'<br /><input type="button" class="remove-drag" value="" /></li>';
function addDrop(event) {
var element = dropElement.replace(/DROPINDEX1/g, dropIndex+1).replace(/DROPINDEX/g, dropIndex);
$("#dropZone").append(element);
var propElement = dropPropElement.replace(/DROPINDEX1/g, dropIndex+1).replace(/DROPINDEX/g, dropIndex);
$(event.target).parent().before(propElement);
$("#drop"+dropIndex).draggable(draggable);
$("#drop"+dropIndex).resizable(resizable);
$("#drop"+dropIndex+"-p").change(changeDrop);
$("#drop"+dropIndex+"-p .remove-drop").click(removeDrop);
event.preventDefault();
dropIndex++;
}
function changeDrop(event) {
var id = event.target.id.substring(4, event.target.id.length-2);
var type = event.target.id.substr(event.target.id.length-1);
$("#drop" + id).css(cssProps[type], $(event.target).val()+'px');
}
function removeDrop(event) {
var element = $(event.target).parent();
var id = element.attr('id').substring(4, element.attr('id').length-2);
$("#drop" + id).remove();
element.remove();
event.preventDefault();
}
function addDrag(event) {
var element = dragElement.replace(/DRAGINDEX/g, dragIndex);
$(event.target).parent().before(element);
$("#drag"+dragIndex+" .remove-drag").click(removeDrag);
event.preventDefault();
dragIndex++;
}
function removeDrag(event) {
var element = $(event.target).parent();
element.remove();
event.preventDefault();
}
$(function() {
$("#dropZone.dev div").draggable(draggable);
$("#dropZone.dev div").resizable(resizable);
$("#drops li").change(changeDrop);
$(".add-drop").click(addDrop);
$(".remove-drop").click(removeDrop);
$(".add-drag").click(addDrag);
$(".remove-drag").click(removeDrag);
});
</script>

View file

@ -0,0 +1,17 @@
<form method="post">
<div id="dropZone" style="width:<?=$field['width']?>px; height:<?=$field['height']?>px; background-image:url('<?=$linker->link(array('media','seminary',$seminary['url'],$field['media']['url']))?>')">
<?php foreach($drops as &$drop) : ?>
<div id="drop<?=$drop['id']?>" ondragenter="onDragEnter(event)" ondragover="onDragOver(event)" ondragleave="onDragLeave(event)" ondrop="onDrop(event)" style="position:absolute; width:<?=$drop['width']?>px; height:<?=$drop['height']?>px; margin:<?=$drop['top']?>px 0 0 <?=$drop['left']?>px;"><?php if(array_key_exists('answer', $drop) && !is_null($drop['answer'])) : ?><img id="drag<?=$drop['answer']['id']?>" draggable="true" ondragstart="onDragStart(event)" ondragend="onDragEnd(event)" src="<?=$linker->link(array('media','seminary',$seminary['url'],$drop['answer']['media']['url']))?>" /><?php endif ?></div>
<input type="hidden" id="dnd_drop<?=$drop['id']?>" name="answers[<?=$drop['id']?>]" value="<?=(array_key_exists('answer', $drop)) ? 'drag'.$drop['answer']['id'] : null ?>" />
<?php endforeach ?>
</div>
<div id="dragZone" ondragenter="onDragEnter(event)" ondragover="onDragOver(event)" ondragleave="onDragLeave(event)" ondrop="onDrop(event, false)" style="width:100%; min-height:5em;">
<?php foreach($drags as &$drag) : ?>
<img id="drag<?=$drag['id']?>" draggable="true" ondragstart="onDragStart(event)" ondragend="onDragEnd(event)" src="<?=$linker->link(array('media','seminary',$seminary['url'],$drag['media']['url']))?>" />
<?php endforeach ?>
</div>
<br />
<input type="submit" name="submit" value="<?=_('solve')?>" />
</form>

View file

@ -0,0 +1,15 @@
<div style="width:<?=$field['width']?>px; height:<?=$field['height']?>px; background-image:url('<?=$linker->link(array('media','seminary',$seminary['url'],$field['media']['url']))?>')">
<?php foreach($drops as &$drop) : ?>
<div id="drop<?=$drop['id']?>" style="position:absolute; width:<?=$drop['width']?>px; height:<?=$drop['height']?>px; margin:<?=$drop['top']?>px 0 0 <?=$drop['left']?>px;">
<?php if(!is_null($drop['answer'])) : ?>
<img id="drag<?=$drop['answer']['id']?>" src="<?=$linker->link(array('media','seminary',$seminary['url'],$drop['answer']['media']['url']))?>" />
<?php endif ?>
</div>
<?php endforeach ?>
</div>
<div style="width:100%; min-height:5em;">
<?php foreach($drags as &$drag) : ?>
<img id="drag<?=$drag['id']?>" src="<?=$linker->link(array('media','seminary',$seminary['url'],$drag['media']['url']))?>" />
<?php endforeach ?>
</div>

View file

@ -0,0 +1,24 @@
<?php
/**
* The Legend of Z
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
* @copyright 2014 Heinrich-Heine-Universität Düsseldorf
* @license http://www.gnu.org/licenses/gpl.html
* @link https://bitbucket.org/coderkun/the-legend-of-z
*/
namespace hhu\z\questtypes;
/**
* QuesttypeAgent for multiple choice.
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
*/
class MultiplechoiceQuesttypeAgent extends \hhu\z\agents\QuesttypeAgent
{
}
?>

View file

@ -0,0 +1,386 @@
<?php
/**
* The Legend of Z
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
* @copyright 2014 Heinrich-Heine-Universität Düsseldorf
* @license http://www.gnu.org/licenses/gpl.html
* @link https://bitbucket.org/coderkun/the-legend-of-z
*/
namespace hhu\z\questtypes;
/**
* Controller of the MultiplechoiceQuesttypeAgent multiple choice.
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
*/
class MultiplechoiceQuesttypeController extends \hhu\z\controllers\QuesttypeController
{
/**
* Required components
*
* @var array
*/
public $components = array('validation');
/**
* Save the answers of a Character for a Quest.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
* @param array $character Current Character data
* @param array $answers Character answers for the Quest
*/
public function saveAnswersOfCharacter($seminary, $questgroup, $quest, $character, $answers)
{
// Save temporary user answer of last question
$answers = (!is_array($answers)) ? array() : $answers;
$pos = $this->Multiplechoice->getQuestionsCountOfQuest($quest['id']);
$question = $this->Multiplechoice->getQuestionOfQuest($quest['id'], $pos);
$this->saveUserAnswers($quest['id'], $question['id'], $answers);
// Save answers
$questions = $this->Multiplechoice->getQuestionsOfQuest($quest['id']);
foreach($questions as &$question)
{
$userAnswers = $this->getUserAnswers($quest['id'], $question['id']);
$answers = $this->Multiplechoice->getAnswersOfQuestion($question['id']);
foreach($answers as &$answer)
{
$userAnswer = (array_key_exists($answer['pos']-1, $userAnswers)) ? true : false;
$this->Multiplechoice->setCharacterSubmission($answer['id'], $character['id'], $userAnswer);
}
}
}
/**
* Save additional data for the answers of a Character for a Quest.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
* @param array $character Current Character data
* @param array $data Additional (POST-) data
*/
public function saveDataForCharacterAnswers($seminary, $questgroup, $quest, $character, $data)
{
}
/**
* Check if answers of a Character for a Quest match the correct ones.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
* @param array $character Current Character data
* @param array $answers Character answers for the Quest
* @return boolean True/false for a right/wrong answer or null for moderator evaluation
*/
public function matchAnswersOfCharacter($seminary, $questgroup, $quest, $character, $answers)
{
// Save temporary user answer of last question
$answers = (!is_array($answers)) ? array() : $answers;
$pos = $this->Multiplechoice->getQuestionsCountOfQuest($quest['id']);
$question = $this->Multiplechoice->getQuestionOfQuest($quest['id'], $pos);
$this->saveUserAnswers($quest['id'], $question['id'], $answers);
// Get questions
$questions = $this->Multiplechoice->getQuestionsOfQuest($quest['id']);
// Iterate questions
foreach($questions as &$question)
{
// Get answers
$userAnswers = $this->getUserAnswers($quest['id'], $question['id']);
$answers = $this->Multiplechoice->getAnswersOfQuestion($question['id']);
// Match answers with user answers
foreach($answers as &$answer)
{
if(is_null($answer['tick'])) {
continue;
}
if($answer['tick']) {
if(!array_key_exists($answer['pos']-1, $userAnswers)) {
return false;
}
}
else {
if(array_key_exists($answer['pos']-1, $userAnswers)) {
return false;
}
}
}
}
// All questions correct answerd
return true;
}
/**
* Action: quest.
*
* Display questions with a checkbox to let the user choose the
* right ones.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
* @param array $character Current Character data
* @param \Exception $exception Character submission exception
*/
public function quest($seminary, $questgroup, $quest, $character, $exception)
{
// Get count of questions
$count = $this->Multiplechoice->getQuestionsCountOfQuest($quest['id']);
// Get position
$pos = 1;
if($this->request->getRequestMethod() == 'POST' && !is_null($this->request->getPostParam('submit-answer')))
{
if(!is_null($this->request->getPostParam('question')))
{
// Get current position
$pos = intval($this->request->getPostParam('question'));
if($pos < 0 || $pos > $count) {
throw new \nre\exceptions\ParamsNotValidException($pos);
}
// Save temporary answer of user
$question = $this->Multiplechoice->getQuestionOfQuest($quest['id'], $pos);
$answers = ($this->request->getRequestMethod() == 'POST' && !is_null($this->request->getPostParam('answers'))) ? $this->request->getPostParam('answers') : array();
$this->saveUserAnswers($quest['id'], $question['id'], $answers);
// Go to next position
$pos++;
}
else {
throw new \nre\exceptions\ParamsNotValidException('pos');
}
}
// Get current question
$question = $this->Multiplechoice->getQuestionOfQuest($quest['id'], $pos);
if(!is_null($question))
{
// Get answers
$question['answers'] = $this->Multiplechoice->getAnswersOfQuestion($question['id']);
// Get previous user answers
if($this->request->getGetParam('show-answer') == 'true' || !$this->Quests->hasCharacterSolvedQuest($quest['id'], $character['id']) || $this->request->getGetParam('status') == 'solved')
{
foreach($question['answers'] as &$answer) {
$answer['useranswer'] = $this->Multiplechoice->getCharacterSubmission($answer['id'], $character['id']);
}
}
}
// Pass data to view
$this->set('question', $question);
$this->set('pos', $pos);
$this->set('count', $count);
}
/**
* Action: submission.
*
* Show the submission of a Character for a Quest.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
* @param array $character Current Character data
*/
public function submission($seminary, $questgroup, $quest, $character)
{
// Get questions
$questions = $this->Multiplechoice->getQuestionsOfQuest($quest['id']);
// Get answers
foreach($questions as &$question)
{
$question['answers'] = $this->Multiplechoice->getAnswersOfQuestion($question['id']);
// Get user answers
foreach($question['answers'] as &$answer) {
$answer['useranswer'] = $this->Multiplechoice->getCharacterSubmission($answer['id'], $character['id']);
}
}
// Pass data to view
$this->set('questions', $questions);
}
/**
* Action: edittask.
*
* Edit the task of a Quest.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
*/
public function edittask($seminary, $questgroup, $quest)
{
// Get questions
$questions = $this->Multiplechoice->getQuestionsOfQuest($quest['id']);
foreach($questions as &$question) {
$question['answers'] = $this->Multiplechoice->getAnswersOfQuestion($question['id']);
}
// Values
$validations = array();
// Save data
if($this->request->getRequestMethod() == 'POST' && !is_null($this->request->getPostParam('save')))
{
// Get params and validate them
$questions = $this->request->getPostParam('questions');
if(is_null($questions)) {
$questions = array();
}
$questions = array_values($questions);
foreach($questions as $questionIndex => &$question)
{
// Validate answers
$question['answers'] = array_values($question['answers']);
foreach($question['answers'] as $answerIndex => &$answer)
{
$answerValidation = $this->Validation->validate($answer['answer'], \nre\configs\AppConfig::$validation['answer']);
if($answerValidation !== true)
{
if(!array_key_exists($questionIndex, $validations) || !is_array($validations[$questionIndex])) {
$validations[$questionIndex] = array();
}
if(!array_key_exists('answers', $validations[$questionIndex])) {
$validations[$questionIndex]['answers'] = array();
}
$validations[$questionIndex]['answers'][$answerIndex] = $answerValidation;
}
}
}
// Save and redirect
if(empty($validations))
{
// Save questions
foreach($questions as $questionIndex => &$question)
{
// Save question
$this->Multiplechoice->setQuestionForQuest(
$this->Auth->getUserId(),
$quest['id'],
$questionIndex + 1,
$question['question']
);
// Save answers
foreach($question['answers'] as $answerIndex => &$answer)
{
$this->Multiplechoice->setAnswerForQuestion(
$this->Auth->getUserId(),
$quest['id'],
$questionIndex + 1,
$answerIndex + 1,
$answer['answer'],
array_key_exists('tick', $answer)
);
}
// Delete deleted answers
$this->Multiplechoice->deleteAnswersOfQuestion(
$quest['id'],
$questionIndex + 1,
count($question['answers'])
);
}
// Delete deleted questions
$this->Multiplechoice->deleteQuestionsOfQuest(
$quest['id'],
count($questions)
);
// Redirect
$this->redirect($this->linker->link(array('quest', $seminary['url'], $questgroup['url'], $quest['url']), 1));
}
}
// Pass data to view
$this->set('questions', $questions);
$this->set('validations', $validations);
}
/**
* Save the answers of a user for a question temporary in the
* session.
*
* @param int $questId ID of Quest
* @param int $questionId ID of multiple choice question
* @param array $userAnswers Answers of user for the question
*/
private function saveUserAnswers($questId, $questionId, $userAnswers)
{
// Ensure session structure
if(!array_key_exists('answers', $_SESSION)) {
$_SESSION['answers'] = array();
}
if(!array_key_exists($questId, $_SESSION['answers'])) {
$_SESSION['answers'][$questId] = array();
}
$_SESSION['answers'][$questId][$questionId] = array();
// Save answres
foreach($userAnswers as $pos => &$answer) {
$_SESSION['answers'][$questId][$questionId][$pos] = $answer;
}
}
/**
* Get the temporary saved answers of a user for a question.
*
* @param int $questId ID of Quest
* @param int $questionId ID of multiple choice question
* @return array Answers of user for the question
*/
private function getUserAnswers($questId, $questionId)
{
// Ensure session structure
if(!array_key_exists('answers', $_SESSION)) {
$_SESSION['answers'] = array();
}
if(!array_key_exists($questId, $_SESSION['answers'])) {
$_SESSION['answers'][$questId] = array();
}
if(!array_key_exists($questionId, $_SESSION['answers'][$questId])) {
$_SESSION['answers'][$questId][$questionId] = array();
}
// Return answers
return $_SESSION['answers'][$questId][$questionId];
}
}
?>

View file

@ -0,0 +1,323 @@
<?php
/**
* The Legend of Z
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
* @copyright 2014 Heinrich-Heine-Universität Düsseldorf
* @license http://www.gnu.org/licenses/gpl.html
* @link https://bitbucket.org/coderkun/the-legend-of-z
*/
namespace hhu\z\questtypes;
/**
* Model of the MultiplechoiceQuesttypeAgent for multiple choice.
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
*/
class MultiplechoiceQuesttypeModel extends \hhu\z\models\QuesttypeModel
{
/**
* Copy a Quest
*
* @param int $userId ID of creating user
* @param int $sourceQuestId ID of Quest to copy from
* @param int $targetQuestId ID of Quest to copy to
* @param int $seminaryMediaIds Mapping of SeminaryMedia-IDs from source Seminary to targetSeminary
*/
public function copyQuest($userId, $sourceQuestId, $targetQuestId, $seminaryMediaIds)
{
// Get questions
$questions = $this->getQuestionsOfQuest($sourceQuestId);
// Copy each question
foreach($questions as &$question)
{
// Copy question
$this->db->query(
'INSERT INTO questtypes_multiplechoice '.
'(created_user_id, quest_id, pos, question) '.
'SELECT ?, ?, pos, question '.
'FROM questtypes_multiplechoice '.
'WHERE id = ?',
'iii',
$userId, $targetQuestId,
$question['id']
);
$targetQuestionId = $this->db->getInsertId();
// Copy answers
$this->db->query(
'INSERT INTO questtypes_multiplechoice_answers '.
'(created_user_id, questtypes_multiplechoice_id, pos, answer, tick) '.
'SELECT ?, ?, pos, answer, tick '.
'FROM questtypes_multiplechoice_answers '.
'WHERE questtypes_multiplechoice_id = ?',
'iii',
$userId, $targetQuestionId,
$question['id']
);
}
}
/**
* Delete a Quest.
*
* @param int $questId ID of Quest to delete
*/
public function deleteQuest($questId)
{
$this->db->query('DELETE FROM questtypes_multiplechoice WHERE quest_id = ?', 'i', $questId);
}
/**
* Get the count of multiple choice questions for a Quest.
*
* @param int $questId ID of Quest to get count for
* @return int Conut of questions
*/
public function getQuestionsCountOfQuest($questId)
{
$data = $this->db->query(
'SELECT count(id) AS c '.
'FROM questtypes_multiplechoice '.
'WHERE quest_id = ?',
'i',
$questId
);
if(!empty($data)) {
return $data[0]['c'];
}
return 0;
}
/**
* Get all multiple choice questions of a Quest.
*
* @param int $questId ID of Quest
* @return array Multiple choice questions
*/
public function getQuestionsOfQuest($questId)
{
return $this->db->query(
'SELECT id, pos, question '.
'FROM questtypes_multiplechoice '.
'WHERE quest_id = ?',
'i',
$questId
);
}
/**
* Get one multiple choice question of a Quest.
*
* @param int $questId ID of Quest
* @param int $pos Position of question
* @return array Question data
*/
public function getQuestionOfQuest($questId, $pos)
{
$data = $this->db->query(
'SELECT id, pos, question '.
'FROM questtypes_multiplechoice '.
'WHERE quest_id = ? AND pos = ?',
'ii',
$questId, $pos
);
if(!empty($data)) {
return $data[0];
}
return null;
}
/**
* Get all answers of a multiple choice question.
*
* @param int $questionId ID of multiple choice question
* @return array Answers of question
*/
public function getAnswersOfQuestion($questionId)
{
return $this->db->query(
'SELECT id, pos, answer, tick '.
'FROM questtypes_multiplechoice_answers '.
'WHERE questtypes_multiplechoice_id = ?',
'i',
$questionId
);
}
/**
* Save Characters submitted answer for one option.
*
* @param int $answerId ID of multiple choice answer
* @param int $characterId ID of Character
* @param boolean $answer Submitted answer for this option
*/
public function setCharacterSubmission($answerId, $characterId, $answer)
{
$this->db->query(
'INSERT INTO questtypes_multiplechoice_characters '.
'(questtypes_multiplechoice_answer_id, character_id, ticked) '.
'VALUES '.
'(?, ?, ?) '.
'ON DUPLICATE KEY UPDATE '.
'ticked = ?',
'iiii',
$answerId, $characterId, $answer, $answer
);
}
/**
* Get answer of one option submitted by Character.
*
* @param int $answerId ID of multiple choice answer
* @param int $characterId ID of Character
* @return boolean Submitted answer of Character or false
*/
public function getCharacterSubmission($answerId, $characterId)
{
$data = $this->db->query(
'SELECT ticked '.
'FROM questtypes_multiplechoice_characters '.
'WHERE questtypes_multiplechoice_answer_id = ? AND character_id = ? ',
'ii',
$answerId, $characterId
);
if(!empty($data)) {
return $data[0]['ticked'];
}
return false;
}
/**
* Set a question for a multiplechoice Quest.
*
* @param int $userId ID of user
* @param int $questId ID of Quest to set question for
* @param int $pos Position of question
* @param string $question Question text
*/
public function setQuestionForQuest($userId, $questId, $pos, $question)
{
$this->db->query(
'INSERT INTO questtypes_multiplechoice '.
'(created_user_id, quest_id, pos, question) '.
'VALUES '.
'(?, ?, ?, ?) '.
'ON DUPLICATE KEY UPDATE '.
'question = ?',
'iiiss',
$userId,
$questId,
$pos,
$question,
$question
);
}
/**
* Delete questions of a Quest.
*
* @param int $questId ID of Quest to delete question of
* @param int $offset Only delete questions after this position
*/
public function deleteQuestionsOfQuest($questId, $offset)
{
$this->db->query(
'DELETE FROM questtypes_multiplechoice '.
'WHERE quest_id = ? AND pos > ?',
'ii',
$questId,
$offset
);
}
/**
* Set an answer for a question.
*
* @param int $userId ID of user
* @param int $questId ID of Quest to set answer for
* @param int $questionPos Position of question
* @param int $answerPos Position of answer
* @param string $answer Answer text
* @param boolean $tick Whether answer is correct or not
*/
public function setAnswerForQuestion($userId, $questId, $questionPos, $answerPos, $answer, $tick)
{
// Get question
$question = $this->getQuestionOfQuest($questId, $questionPos);
if(is_null($question)) {
return;
}
// Add answer
$this->db->query(
'INSERT INTO questtypes_multiplechoice_answers '.
'(created_user_id, questtypes_multiplechoice_id, pos, answer, tick) '.
'VALUES '.
'(?, ?, ?, ?, ?) '.
'ON DUPLICATE KEY UPDATE '.
'answer = ?, tick = ?',
'iiisisi',
$userId,
$question['id'],
$answerPos,
$answer,
$tick,
$answer,
$tick
);
}
/**
* Delete answers of a question.
*
* @param int $questId ID of Quest to delete answers for
* @param int $questionPos Position of question
* @param int $offset Only delete answers after this position
*/
public function deleteAnswersOfQuestion($questId, $questionPos, $offset)
{
// Get question
$question = $this->getQuestionOfQuest($questId, $questionPos);
if(is_null($question)) {
return;
}
// Delete answer
$this->db->query(
'DELETE FROM questtypes_multiplechoice_answers '.
'WHERE questtypes_multiplechoice_id = ? AND pos > ?',
'ii',
$question['id'],
$offset
);
}
}
?>

View file

@ -0,0 +1,143 @@
<?php if(!empty($validations)) : ?>
<ul>
<?php foreach($validations as &$question) : ?>
<li>
<?php if(!empty($question['answers'])) : ?>
<?php foreach($question['answers'] as &$answer) : ?>
<ul>
<?php foreach($answer as $setting => $value) : ?>
<li>
<?php
switch($setting) {
case 'minlength': printf(_('Answer input is too short (min. %d chars)'), $value);
break;
case 'maxlength': printf(_('Answer input is too long (max. %d chars)'), $value);
break;
default: echo _('Answer input invalid');
}
?>
</li>
<?php endforeach ?>
</ul>
<?php endforeach ?>
<?php endif ?>
</li>
<?php endforeach ?>
</ul>
<?php endif ?>
<form method="post">
<fieldset>
<legend><?=_('Questions')?></legend>
<ol id="questions">
<?php foreach($questions as $questionIndex => &$question) : ?>
<li id="question-<?=$questionIndex?>">
<?=_('Question')?>:
<textarea id="question-<?=$questionIndex?>-question" name="questions[<?=$questionIndex?>][question]"><?=$question['question']?></textarea>
<script>
$(function() {
$("#question-<?=$questionIndex?>-question").markItUp(mySettings);
});
</script>
<?php if(!empty($validations) && array_key_exists($questionIndex, $validations) && !empty($validations[$questionIndex]) && $validations[$questionIndex]['answers'] !== true) : ?>
<ul>
<?php foreach($validations[$questionIndex]['answers'] as &$answer) : ?>
<?php foreach($answer as $setting => $value) : ?>
<li>
<?php
switch($setting) {
case 'minlength': printf(_('Answer input is too short (min. %d chars)'), $value);
break;
case 'maxlength': printf(_('Answer input is too long (max. %d chars)'), $value);
break;
default: echo _('Answer input invalid');
}
?>
</li>
<?php endforeach ?>
<?php endforeach ?>
</ul>
<?php endif ?>
<ul>
<?php foreach($question['answers'] as $answerIndex => &$answer) : ?>
<li>
<input id="question-<?=$questionIndex?>-answer-<?=$answerIndex?>-tick" type="checkbox" name="questions[<?=$questionIndex?>][answers][<?=$answerIndex?>][tick]" <?php if(array_key_exists('tick', $answer) && $answer['tick']) : ?>checked="checked"<?php endif ?> />
<label for="questions[<?=$questionIndex?>][answers][<?=$answerIndex?>][tick]">
<input id="question-<?=$questionIndex?>-answer-<?=$answerIndex?>" type="text" name="questions[<?=$questionIndex?>][answers][<?=$answerIndex?>][answer]" value="<?=$answer['answer']?>" <?php if(!empty($validations) && array_key_exists($questionIndex, $validations) && !empty($validations[$questionIndex]) && array_key_exists($answerIndex, $validations[$questionIndex]['answers']) && $validations[$questionIndex]['answers'][$answerIndex] !== true) : ?>class="invalid"<?php endif ?> />
</label>
<button class="remove-answer" type="button"></button>
</li>
<?php endforeach ?>
<li>
<button class="add-answer" type="button">+</button>
</li>
</ul>
<button class="remove-question" type="button"><?=_('Remove question')?></button>
</li>
<?php endforeach ?>
<li>
<button class="add-question" type="button"><?=_('Add question')?></button>
</li>
</ol>
</fieldset>
<input type="submit" name="save" value="<?=_('save')?>" />
</form>
<script>
var questionIndex = <?=count($questions)?>;
var answerIndices = new Array(<?=count($questions)?>);
<?php foreach($questions as $index => &$question) : ?>
answerIndices[<?=$index?>] = <?=count($question['answers'])?>;
<?php endforeach?>
var questionElement = '<?=_('Question')?>: <textarea id="questions-QUESTIONINDEX-question" name="questions[QUESTIONINDEX][question]"></textarea>' +
'<ul><li><button class="add-answer" type="button">+</button></li></ul>' +
'<button class="remove-question" type="button"><?=_('Remove question')?></button>';
var answerElement = '<input id="question-QUESTIONINDEX-answer-ANSWERINDEX-tick" type="checkbox" name="questions[QUESTIONINDEX][answers][ANSWERINDEX][tick]" />' +
'<label for="questions[QUESTIONINDEX][answers][ANSWERINDEX][tick]">' +
'<input id="question-QUESTIONINDEX-answer-ANSWERINDEX" type="text" name="questions[QUESTIONINDEX][answers][ANSWERINDEX][answer]" value="" />' +
'</label>' +
'<button class="remove-answer" type="button"></button>';
$(".add-question").click(addQuestion);
$(".remove-question").click(removeQuestion);
$(".add-answer").click(addAnswer);
$(".remove-answer").click(removeAnswer);
function addQuestion(event)
{
event.preventDefault();
answerIndices.push(0);
var element = '<li id="question-'+questionIndex+'">' + questionElement.replace(/QUESTIONINDEX/g, questionIndex) + '</li>';
$(event.target).parent().before(element);
$("#question-"+questionIndex+" .remove-question").click(removeQuestion);
$("#question-"+questionIndex+" .add-answer").click(addAnswer);
$("#question-"+questionIndex+" .remove-answer").click(removeAnswer);
$("#questions-"+questionIndex+"-question").markItUp(mySettings);
questionIndex++;
}
function removeQuestion(event)
{
event.preventDefault();
$(event.target).parent().remove();
}
function addAnswer(event)
{
event.preventDefault();
var parent = $(event.target).parent();
var index = parent.parent().parent().attr('id').substring(9);
var element = '<li>' + answerElement.replace(/QUESTIONINDEX/g, index).replace(/ANSWERINDEX/g, answerIndices[index]) + '</li>';
$(event.target).parent().before(element);
$(".remove-answer").click(removeAnswer);
answerIndices[index]++;
}
function removeAnswer(event)
{
event.preventDefault();
$(event.target).parent().remove();
}
</script>

View file

@ -0,0 +1,23 @@
<form method="post">
<fieldset>
<?php if(!is_null($question)) : ?>
<legend><?=sprintf(_('Question %d of %d'), $pos, $count)?>:</legend>
<p class="fwb"><?=$t->t($question['question'])?></p>
<ol class="mchoice">
<?php foreach($question['answers'] as $i => &$answer) : ?>
<li class="cf">
<input type="checkbox" id="answers[<?=$i?>]" name="answers[<?=$i?>]" value="true" <?=(array_key_exists('useranswer', $answer) && $answer['useranswer']) ? 'checked="checked"' : '' ?> />
<label for="answers[<?=$i?>]"><?=$t->t($answer['answer'])?></label>
</li>
<?php endforeach ?>
</ol>
<?php endif ?>
</fieldset>
<input type="hidden" name="question" value="<?=$pos?>" />
<?php if($pos < $count) : ?>
<input type="submit" name="submit-answer" value="<?=_('solve Question')?>" />
<?php else : ?>
<input type="submit" name="submit" value="<?=_('solve')?>" />
<?php endif ?>
</form>

View file

@ -0,0 +1,16 @@
<ol>
<?php foreach($questions as $pos => &$question) : ?>
<li>
<h1><?=$t->t($question['question'])?></h1>
<ol>
<?php foreach($question['answers'] as &$answer) : ?>
<li>
<?php if($answer['useranswer']) : ?>☑<?php else : ?>☐<?php endif ?>
<?php if($answer['useranswer'] == $answer['tick']) : ?>✓<?php else : ?>×<?php endif ?>
<?=$answer['answer']?>
</li>
<?php endforeach ?>
</ol>
</li>
<?php endforeach ?>
</ol>

View file

@ -0,0 +1,24 @@
<?php
/**
* The Legend of Z
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
* @copyright 2014 Heinrich-Heine-Universität Düsseldorf
* @license http://www.gnu.org/licenses/gpl.html
* @link https://bitbucket.org/coderkun/the-legend-of-z
*/
namespace hhu\z\questtypes;
/**
* QuesttypeAgent for submitting.
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
*/
class SubmitQuesttypeAgent extends \hhu\z\agents\QuesttypeAgent
{
}
?>

View file

@ -0,0 +1,241 @@
<?php
/**
* The Legend of Z
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
* @copyright 2014 Heinrich-Heine-Universität Düsseldorf
* @license http://www.gnu.org/licenses/gpl.html
* @link https://bitbucket.org/coderkun/the-legend-of-z
*/
namespace hhu\z\questtypes;
/**
* Controller of the SubmitQuesttypeAgent for a submit task.
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
*/
class SubmitQuesttypeController extends \hhu\z\controllers\QuesttypeController
{
/**
* Required models
*
* @var array
*/
public $models = array('quests', 'uploads', 'users');
/**
* Save the answers of a Character for a Quest.
*
* @throws \hhu\z\exceptions\SubmissionNotValidException
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
* @param array $character Current Character data
* @param array $answers Character answers for the Quest
*/
public function saveAnswersOfCharacter($seminary, $questgroup, $quest, $character, $answers)
{
// Save answer
if(array_key_exists('answers', $_FILES))
{
$answer = $_FILES['answers'];
// Check error
if($answer['error'] !== 0) {
throw new \hhu\z\exceptions\SubmissionNotValidException(
new \hhu\z\exceptions\FileUploadException($answer['error'])
);
}
// Check mimetype
$mimetypes = $this->Submit->getAllowedMimetypes($seminary['id']);
$answerMimetype = null;
$answer['mimetype'] = \hhu\z\Utils::getMimetype($answer['tmp_name'], $answer['type']);
foreach($mimetypes as &$mimetype) {
if($mimetype['mimetype'] == $answer['mimetype']) {
$answerMimetype = $mimetype;
break;
}
}
if(is_null($answerMimetype)) {
throw new \hhu\z\exceptions\SubmissionNotValidException(
new \hhu\z\exceptions\WrongFiletypeException($answer['mimetype'])
);
}
// Check file size
if($answer['size'] > $answerMimetype['size']) {
throw new \hhu\z\exceptions\SubmissionNotValidException(
new \hhu\z\exceptions\MaxFilesizeException()
);
}
// Create filename
$filename = sprintf(
'%s,%s,%s.%s',
$character['url'],
mb_substr($quest['url'], 0, 32),
date('Ymd-His'),
mb_substr(mb_substr($answer['name'], strrpos($answer['name'], '.')+1), 0, 4)
);
// Save file
if(!$this->Submit->setCharacterSubmission($seminary['id'], $quest['id'], $this->Auth->getUserId(), $character['id'], $answer, $filename)) {
throw new \hhu\z\exceptions\SubmissionNotValidException(
new \hhu\z\exceptions\FileUploadException(error_get_last()['message'])
);
}
}
}
/**
* Save additional data for the answers of a Character for a Quest.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
* @param array $character Current Character data
* @param array $data Additional (POST-) data
*/
public function saveDataForCharacterAnswers($seminary, $questgroup, $quest, $character, $data)
{
$this->Submit->addCommentForCharacterAnswer($this->Auth->getUserId(), $data['submission_id'], $data['comment']);
}
/**
* Check if answers of a Character for a Quest match the correct ones.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
* @param array $character Current Character data
* @param array $answers Character answers for the Quest
* @return boolean True/false for a right/wrong answer or null for moderator evaluation
*/
public function matchAnswersOfCharacter($seminary, $questgroup, $quest, $character, $answers)
{
// A moderator has to evaluate the answer
return null;
}
/**
* Action: quest.
*
* Display a big textbox to let the user enter a text that has
* to be evaluated by a moderator.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
* @param array $character Current Character data
* @param \Exception $exception Character submission exception
*/
public function quest($seminary, $questgroup, $quest, $character, $exception)
{
// Answers (Submissions)
$characterSubmissions = $this->Submit->getCharacterSubmissions($quest['id'], $character['id']);
foreach($characterSubmissions as &$submission)
{
$submission['upload'] = $this->Uploads->getSeminaryuploadById($submission['upload_id']);
$submission['comments'] = $this->Submit->getCharacterSubmissionComments($submission['id']);
foreach($submission['comments'] as &$comment)
{
try {
$comment['user'] = $this->Users->getUserById($comment['created_user_id']);
$comment['user']['character'] = $this->Characters->getCharacterForUserAndSeminary($comment['user']['id'], $seminary['id']);
}
catch(\nre\exceptions\IdNotFoundException $e) {
}
}
}
// Show answer of Character
if($this->request->getGetParam('show-answer') == 'true') {
$this->redirect($this->linker->link(array('uploads','seminary',$seminary['url'], $characterSubmissions[count($characterSubmissions)-1]['upload']['url'])));
}
// Has Character already solved Quest?
$solved = $this->Quests->hasCharacterSolvedQuest($quest['id'], $character['id']);
// Last Quest status for Character
$lastStatus = $this->Quests->getLastQuestStatus($quest['id'], $character['id']);
// Get allowed mimetypes
$mimetypes = $this->Submit->getAllowedMimetypes($seminary['id']);
// Pass data to view
$this->set('seminary', $seminary);
$this->set('submissions', $characterSubmissions);
$this->set('solved', $solved);
$this->set('lastStatus', $lastStatus);
$this->set('mimetypes', $mimetypes);
$this->set('exception', $exception);
}
/**
* Action: submission.
*
* Show the submission of a Character for a Quest.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
* @param array $character Current Character data
*/
public function submission($seminary, $questgroup, $quest, $character)
{
// Get Character submissions
$submissions = $this->Submit->getCharacterSubmissions($quest['id'], $character['id']);
foreach($submissions as &$submission)
{
$submission['upload'] = $this->Uploads->getSeminaryuploadById($submission['upload_id']);
$submission['comments'] = $this->Submit->getCharacterSubmissionComments($submission['id']);
foreach($submission['comments'] as &$comment)
{
try {
$comment['user'] = $this->Users->getUserById($comment['created_user_id']);
$comment['user']['character'] = $this->Characters->getCharacterForUserAndSeminary($comment['user']['id'], $seminary['id']);
}
catch(\nre\exceptions\IdNotFoundException $e) {
}
}
}
// Status
$solved = $this->Quests->hasCharacterSolvedQuest($quest['id'], $character['id']);
// Pass data to view
$this->set('seminary', $seminary);
$this->set('submissions', $submissions);
$this->set('solved', $solved);
}
/**
* TODO Action: edittask.
*
* Edit the task of a Quest.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
*/
public function edittask($seminary, $questgroup, $quest)
{
}
}
?>

View file

@ -0,0 +1,168 @@
<?php
/**
* The Legend of Z
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
* @copyright 2014 Heinrich-Heine-Universität Düsseldorf
* @license http://www.gnu.org/licenses/gpl.html
* @link https://bitbucket.org/coderkun/the-legend-of-z
*/
namespace hhu\z\questtypes;
/**
* Model of the SubmitQuesttypeAgent for a submit task.
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
*/
class SubmitQuesttypeModel extends \hhu\z\models\QuesttypeModel
{
/**
* Required models
*
* @var array
*/
public $models = array('uploads');
/**
* Copy a Quest
*
* @param int $userId ID of creating user
* @param int $sourceQuestId ID of Quest to copy from
* @param int $targetQuestId ID of Quest to copy to
* @param int $seminaryMediaIds Mapping of SeminaryMedia-IDs from source Seminary to targetSeminary
*/
public function copyQuest($userId, $sourceQuestId, $targetQuestId, $seminaryMediaIds)
{
}
/**
* Delete a Quest.
*
* @param int $questId ID of Quest to delete
*/
public function deleteQuest($questId)
{
$this->db->query('DELETE FROM questtypes_submit_characters WHERE quest_id = ?', 'i', $questId);
}
/**
* Save Characters submitted upload.
*
* @param int $seminaryId ID of Seminary
* @param int $questId ID of Quest
* @param int $userId ID of user
* @param int $characterId ID of Character
* @param array $file Submitted upload
* @param string $filename Name of submitted file
*/
public function setCharacterSubmission($seminaryId, $questId, $userId, $characterId, $file, $filename)
{
// Save file on harddrive
$uploadId = $this->Uploads->uploadSeminaryFile($userId, $seminaryId, $file['name'], $filename, $file['tmp_name'], $file['type']);
if($uploadId === false) {
return false;
}
// Create database record
$this->db->query(
'INSERT INTO questtypes_submit_characters '.
'(quest_id, character_id, upload_id) '.
'VALUES '.
'(?, ?, ?) ',
'iii',
$questId, $characterId, $uploadId
);
return true;
}
/**
* Add a comment for the answer of a Character.
*
* @param int $userId ID of user that comments
* @param int $submissionId ID of Character answer to comment
* @param string $comment Comment text
*/
public function addCommentForCharacterAnswer($userId, $submissionId, $comment)
{
$this->db->query(
'INSERT INTO questtypes_submit_characters_comments '.
'(created_user_id, questtypes_submit_character_id, comment) '.
'VALUES '.
'(?, ?, ?)',
'iis',
$userId,
$submissionId,
$comment
);
}
/**
* Get all uploads submitted by Character.
*
* @param int $questId ID of Quest
* @param int $characterId ID of Character
* @return array Text submitted by Character or NULL
*/
public function getCharacterSubmissions($questId, $characterId)
{
return $this->db->query(
'SELECT id, created, upload_id '.
'FROM questtypes_submit_characters '.
'WHERE quest_id = ? AND character_id = ? '.
'ORDER BY created ASC',
'ii',
$questId, $characterId
);
}
/**
* Get allowed mimetypes for uploading a file.
*
* @param int $seminaryId ID of Seminary
* @return array Allowed mimetypes
*/
public function getAllowedMimetypes($seminaryId)
{
return $this->db->query(
'SELECT id, mimetype, size '.
'FROM questtypes_submit_mimetypes '.
'WHERE seminary_id = ?',
'i',
$seminaryId
);
}
/**
* Get all comments for a Character submission.
*
* @param int $characterSubmissionId ID of Character submission
* @return array Comments for this submission
*/
public function getCharacterSubmissionComments($characterSubmissionId)
{
return $this->db->query(
'SELECT id, created, created_user_id, comment '.
'FROM questtypes_submit_characters_comments '.
'WHERE questtypes_submit_character_id = ?',
'i',
$characterSubmissionId
);
}
}
?>

View file

@ -0,0 +1 @@
<p>TODO</p>

View file

@ -0,0 +1,53 @@
<?php if(!is_null($exception)) : ?>
<p class="error">
<?php if($exception->getNestedException() instanceof \hhu\z\exceptions\WrongFiletypeException) : ?>
<?=sprintf(_('File has wrong type “%s”'), $exception->getNestedException()->getType())?>
<?php elseif($exception->getNestedException() instanceof \hhu\z\exceptions\WrongFiletypeException) : ?>
<?=_('File exceeds size maximum')?>
<?php elseif($exception->getNestedException() instanceof \hhu\z\exceptions\FileUploadException) : ?>
<?=sprintf(_('Error during file upload: %s'), $exception->getNestedException()->getNestedMessage())?>
<?php else : ?>
<?=$exception->getNestedException()->getMessage()?>
<?php endif ?>
</p>
<?php endif ?>
<?php if(!$solved && (is_null($lastStatus) || count($submissions) == 0 || $lastStatus['created'] > $submissions[count($submissions)-1]['created'])) : ?>
<form method="post" enctype="multipart/form-data" class="submit">
<input type="file" name="answers" required="required" accept="<?=implode(',', array_map(function($m) { return $m['mimetype']; }, $mimetypes))?>" />
<p><?=_('Allowed file types')?>:</p>
<ul>
<?php foreach($mimetypes as &$mimetype) : ?>
<li><?=sprintf(_('%s-files'), strtoupper(explode('/',$mimetype['mimetype'])[1]))?> <?php if($mimetype['size'] > 0) : ?>(<?=_('max.')?> <?=round($mimetype['size']/(1024*1024),2)?>MiB)<?php endif ?></li>
<?php endforeach ?>
</ul>
<input type="submit" name="submit" value="<?=_('solve')?>" />
</form>
<?php endif ?>
<?php if(count($submissions) > 0) : ?>
<h2><?=_('Your submissions')?></h2>
<ol class="admnql">
<?php foreach($submissions as $index => &$submission) : ?>
<li>
<a href="<?=$linker->link(array('uploads','seminary',$seminary['url'], $submission['upload']['url']))?>"><?=$submission['upload']['name']?></a><span><?=sprintf(_('submitted at %s on %sh'), $dateFormatter->format(new \DateTime($submission['created'])), $timeFormatter->format(new \DateTime($submission['created'])))?></span>
<?php if($lastStatus['status'] == 1 && ($index > 0 || count($submissions) == 1)) : ?>
<p><?=_('This submission is waiting for approval')?></p>
<?php endif ?>
<?php if(count($submission['comments']) > 0) : ?>
<ol>
<?php foreach($submission['comments'] as &$comment) : ?>
<li>
<?php if(array_key_exists('user', $comment) && array_key_exists('character', $comment['user'])) : ?>
<p class="fwb"><?=sprintf(_('Approved on %s at %s'), $dateFormatter->format(new \DateTime($comment['created'])), $timeFormatter->format(new \DateTime($comment['created'])))?></p>
<?php endif ?>
<?php if(!empty($comment['comment'])) : ?>
<p><?=\hhu\z\Utils::t($comment['comment'])?></p>
<?php endif ?>
</li>
<?php endforeach ?>
</ol>
<?php endif ?>
</li>
<?php endforeach ?>
</ol>
<?php endif ?>

View file

@ -0,0 +1,33 @@
<?php if(count($submissions) > 0) : ?>
<ol class="admnql">
<?php foreach($submissions as &$submission) : ?>
<li>
<p><a href="<?=$linker->link(array('uploads','seminary',$seminary['url'], $submission['upload']['url']))?>"><?=$submission['upload']['name']?></a></p>
<p><small><?=sprintf(_('submitted at %s on %sh'), $dateFormatter->format(new \DateTime($submission['created'])), $timeFormatter->format(new \DateTime($submission['created'])))?></small></p>
<?php if(count($submission['comments']) > 0) : ?>
<ol>
<?php foreach($submission['comments'] as &$comment) : ?>
<li>
<?php if(array_key_exists('user', $comment) && array_key_exists('character', $comment['user'])) : ?>
<p class="fwb"><?=sprintf(_('Approved by %s on %s at %s'), $comment['user']['character']['name'], $dateFormatter->format(new \DateTime($comment['created'])), $timeFormatter->format(new \DateTime($comment['created'])))?></p>
<?php endif ?>
<p><?=\hhu\z\Utils::t($comment['comment'])?></p>
</li>
<?php endforeach ?>
</ol>
<?php endif ?>
</li>
<?php endforeach ?>
</ol>
<?php endif ?>
<form method="post" class="logreg">
<?php $submission = array_pop($submissions); ?>
<?php if(!$solved) : ?>
<?=_('Comment')?><br />
<textarea name="characterdata[comment]"></textarea><br />
<input type="hidden" name="characterdata[submission_id]" value="<?=$submission['id']?>" />
<input type="submit" name="submit" value="<?=_('solved')?>" />
<input type="submit" name="submit" value="<?=_('unsolved')?>" />
<?php endif ?>
</form>

View file

@ -0,0 +1,24 @@
<?php
/**
* The Legend of Z
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
* @copyright 2014 Heinrich-Heine-Universität Düsseldorf
* @license http://www.gnu.org/licenses/gpl.html
* @link https://bitbucket.org/coderkun/the-legend-of-z
*/
namespace hhu\z\questtypes;
/**
* QuesttypeAgent for inserting text.
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
*/
class TextinputQuesttypeAgent extends \hhu\z\agents\QuesttypeAgent
{
}
?>

View file

@ -0,0 +1,334 @@
<?php
/**
* The Legend of Z
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
* @copyright 2014 Heinrich-Heine-Universität Düsseldorf
* @license http://www.gnu.org/licenses/gpl.html
* @link https://bitbucket.org/coderkun/the-legend-of-z
*/
namespace hhu\z\questtypes;
/**
* Controller of the TextinputQuesttypeAgent for for inserting text.
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
*/
class TextinputQuesttypeController extends \hhu\z\controllers\QuesttypeController
{
/**
* Required components
*
* @var array
*/
public $components = array('validation', 'questtypedata');
/**
* Count of correct answers
*
* @var int
*/
const KEY_QUESTTYPEDATA_N_CORRECT_ANSWRES = 'nCorrectAnswers';
private $nCorrectAnswers = null;
/**
* Save the answers of a Character for a Quest.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
* @param array $character Current Character data
* @param array $answers Character answers for the Quest
*/
public function saveAnswersOfCharacter($seminary, $questgroup, $quest, $character, $answers)
{
// Get fields
$fields = $this->Textinput->getTextinputFields($quest['id']);
// Save answers
foreach($fields as &$field)
{
$pos = intval($field['number']) - 1;
$answer = (array_key_exists($pos, $answers)) ? $answers[$pos] : '';
$this->Textinput->setCharacterSubmission($field['id'], $character['id'], $answer);
}
}
/**
* Save additional data for the answers of a Character for a Quest.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
* @param array $character Current Character data
* @param array $data Additional (POST-) data
*/
public function saveDataForCharacterAnswers($seminary, $questgroup, $quest, $character, $data)
{
}
/**
* Check if answers of a Character for a Quest match the correct ones.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
* @param array $character Current Character data
* @param array $answers Character answers for the Quest
* @return boolean True/false for a right/wrong answer or null for moderator evaluation
*/
public function matchAnswersOfCharacter($seminary, $questgroup, $quest, $character, $answers)
{
// Get right answers
$fields = $this->Textinput->getTextinputFields($quest['id']);
// Match regexs with user answers
$nCorrectAnswers = 0;
foreach($fields as &$field)
{
$pos = intval($field['number']) - 1;
if(!array_key_exists($pos, $answers)) {
continue;
}
if(!$this->isMatching($field['regex'], $answers[$pos])) {
continue;
}
$nCorrectAnswers++;
}
// Save count of correct answers
$this->Questtypedata->set(
$quest['id'],
self::KEY_QUESTTYPEDATA_N_CORRECT_ANSWRES,
$nCorrectAnswers
);
// All answers right
return ($nCorrectAnswers == count($fields));
}
/**
* Action: quest.
*
* Display a text with input fields and evaluate if user input
* matches with stored regular expressions.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
* @param array $character Current Character data
* @param \Exception $exception Character submission exception
*/
public function quest($seminary, $questgroup, $quest, $character, $exception)
{
// Get Task
$task = $this->Textinput->getTextinputQuest($quest['id']);
// Get fields
$fields = $this->Textinput->getTextinputFields($quest['id']);
// Has Character already solved Quest?
$solved = $this->Quests->hasCharacterSolvedQuest($quest['id'], $character['id']);
// Get Character answers
if(!$solved || $this->request->getGetParam('show-answer') == 'true' || $this->request->getGetParam('status') == 'solved')
{
foreach($fields as &$field) {
$field['answer'] = $this->Textinput->getCharacterSubmission($field['id'], $character['id']);
}
}
// Get count of last correct answers
$nCorrectAnswers = $this->Questtypedata->get($quest['id'], self::KEY_QUESTTYPEDATA_N_CORRECT_ANSWRES);
$this->Questtypedata->set(
$quest['id'],
self::KEY_QUESTTYPEDATA_N_CORRECT_ANSWRES,
null
);
// Pass data to view
$this->set('task', $task);
$this->set('fields', $fields);
$this->set('nCorrectAnswers', $nCorrectAnswers);
}
/**
* Action: submission.
*
* Show the submission of a Character for a Quest.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
* @param array $character Current Character data
*/
public function submission($seminary, $questgroup, $quest, $character)
{
// Get Task
$task = $this->Textinput->getTextinputQuest($quest['id']);
// Process text
$textParts = preg_split('/(\$\$)/', ' '.$task['text'].' ');
// Get fields
$fields = $this->Textinput->getTextinputFields($quest['id']);
// Get Character answers
foreach($fields as &$field)
{
$field['answer'] = $this->Textinput->getCharacterSubmission($field['id'], $character['id']);
$field['right'] = $this->isMatching($field['regex'], $field['answer']);
}
// Pass data to view
$this->set('task', $task);
$this->set('fields', $fields);
}
/**
* Action: edittask.
*
* Edit the task of a Quest.
*
* @param array $seminary Current Seminary data
* @param array $questgroup Current Questgroup data
* @param array $quest Current Quest data
*/
public function edittask($seminary, $questgroup, $quest)
{
// Get Task
$task = $this->Textinput->getTextinputQuest($quest['id']);
$text = $task['text'];
// Get fields
$fields = $this->Textinput->getTextinputFields($quest['id']);
// Get field sizes
$fieldSizes = $this->Textinput->getFieldSizes();
// Values
$validations = array();
// Save data
if($this->request->getRequestMethod() == 'POST')
{
if(!is_null($this->request->getPostParam('preview')) || !is_null($this->request->getPostParam('save')))
{
// Get params and validate them
if(is_null($this->request->getPostParam('text'))) {
throw new \nre\exceptions\ParamsNotValidException('text');
}
$text = $this->request->getPostParam('text');
$fields = $this->request->getPostParam('fields');
if(is_null($fields) && !is_array($fields)) {
$fields = array();
}
$fields = array_values($fields);
$fieldIndex = 0;
foreach($fields as &$field)
{
// Validate regex
$regex = $field['regex'];
$fieldValidation = @preg_match($regex, '') !== false;
if($fieldValidation !== true)
{
if(!array_key_exists($fieldIndex, $validations) || !is_array($validations[$fieldIndex])) {
$validations[$fieldIndex] = array();
}
$validations[$fieldIndex] = $this->Validation->addValidationResults($validations[$fieldIndex], 'regex', $fieldValidation);
}
// Validate size
foreach($fieldSizes as $sizeIndex => &$size)
{
if($size['size'] == $field['size'])
{
$field['sizeIndex'] = $sizeIndex;
break;
}
}
if(!array_key_exists('sizeIndex', $field)) {
throw new \nre\exceptions\ParamsNotValidException($fieldIndex);
}
$fieldIndex++;
}
// Save and redirect
if(!is_null($this->request->getPostParam('save')) && empty($validations))
{
// Save text
$this->Textinput->setTextForQuest(
$this->Auth->getUserId(),
$quest['id'],
$text
);
// Save field
foreach($fields as $index => &$field)
{
// Add regex modifiers
$modifiers = substr($field['regex'], strrpos($field['regex'], $field['regex'][0]) + 1);
if(strpos($modifiers, 'u') === false) {
$field['regex'] .= 'u';
}
// Save field
$this->Textinput->setFieldForText(
$quest['id'],
$index + 1,
$fieldSizes[$field['sizeIndex']]['id'],
$field['regex']
);
}
// Redirect
$this->redirect($this->linker->link(array('quest', $seminary['url'], $questgroup['url'], $quest['url']), 1));
}
}
}
// Pass data to view
$this->set('task', $task);
$this->set('text', $text);
$this->set('fields', $fields);
$this->set('fieldSizes', $fieldSizes);
$this->set('validations', $validations);
}
/**
* Check if an Character answer matches a Regex.
*
* @param string $regex Regex to match against
* @param string $answer Character answer to match
* @return boolean Whether answer matches Regex or not
*/
private function isMatching($regex, $answer)
{
$score = preg_match($regex, trim($answer));
return ($score !== false && $score > 0);
}
}
?>

View file

@ -0,0 +1,268 @@
<?php
/**
* The Legend of Z
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
* @copyright 2014 Heinrich-Heine-Universität Düsseldorf
* @license http://www.gnu.org/licenses/gpl.html
* @link https://bitbucket.org/coderkun/the-legend-of-z
*/
namespace hhu\z\questtypes;
/**
* Model of the TextinputQuesttypeAgent for inserting text.
*
* @author Oliver Hanraths <oliver.hanraths@uni-duesseldorf.de>
*/
class TextinputQuesttypeModel extends \hhu\z\models\QuesttypeModel
{
/**
* Copy a Quest
*
* @param int $userId ID of creating user
* @param int $sourceQuestId ID of Quest to copy from
* @param int $targetQuestId ID of Quest to copy to
* @param int $seminaryMediaIds Mapping of SeminaryMedia-IDs from source Seminary to targetSeminary
*/
public function copyQuest($userId, $sourceQuestId, $targetQuestId, $seminaryMediaIds)
{
// Copy textinput
$this->db->query(
'INSERT INTO questtypes_textinput '.
'(quest_id, created_user_id, text) '.
'SELECT ?, ?, text '.
'FROM questtypes_textinput '.
'WHERE quest_id = ?',
'iii',
$targetQuestId, $userId,
$sourceQuestId
);
// Copy fields
$this->db->query(
'INSERT INTO questtypes_textinput_fields '.
'(questtypes_textinput_quest_id, number, questtypes_textinput_fieldsize_id, regex) '.
'SELECT ?, number, questtypes_textinput_fieldsize_id, regex '.
'FROM questtypes_textinput_fields '.
'WHERE questtypes_textinput_quest_id = ?',
'ii',
$targetQuestId,
$sourceQuestId
);
}
/**
* Delete a Quest.
*
* @param int $questId ID of Quest to delete
*/
public function deleteQuest($questId)
{
$this->db->query('DELETE FROM questtypes_textinput WHERE quest_id = ?', 'i', $questId);
}
/**
* Get textinput-text for a Quest.
*
* @param int $questId ID of Quest
* @return array Textinput-text
*/
public function getTextinputQuest($questId)
{
$data = $this->db->query(
'SELECT text '.
'FROM questtypes_textinput '.
'WHERE quest_id = ?',
'i',
$questId
);
if(!empty($data)) {
return $data[0];
}
return null;
}
/**
* Get fields for a textinput-text.
*
* @param int $questId ID of Quest
* @return array Fields
*/
public function getTextinputFields($questId)
{
return $this->db->query(
'SELECT fields.id, fields.number, fields.regex, fieldsizes.id AS fieldsize_id, fieldsizes.size '.
'FROM questtypes_textinput_fields AS fields '.
'LEFT JOIN questtypes_textinput_fieldsizes AS fieldsizes ON fieldsizes.id = fields.questtypes_textinput_fieldsize_id '.
'WHERE fields.questtypes_textinput_quest_id = ? '.
'ORDER BY fields.number ASC',
'i',
$questId
);
}
/**
* Save Characters submitted answer for one textinput field.
*
* @param int $fieldId ID of field
* @param int $characterId ID of Character
* @param string $answer Submitted answer for this field
*/
public function setCharacterSubmission($fieldId, $characterId, $answer)
{
$this->db->query(
'INSERT INTO questtypes_textinput_fields_characters '.
'(questtypes_textinput_field_id, character_id, value) '.
'VALUES '.
'(?, ?, ?) '.
'ON DUPLICATE KEY UPDATE '.
'value = ?',
'iiss',
$fieldId, $characterId, $answer, $answer
);
}
/**
* Get answer of one input field submitted by Character.
*
* @param int $fieldId ID of field
* @param int $characterId ID of Character
* @return string Submitted answer for this field or empty string
*/
public function getCharacterSubmission($fieldId, $characterId)
{
$data = $this->db->query(
'SELECT value '.
'FROM questtypes_textinput_fields_characters '.
'WHERE questtypes_textinput_field_id = ? AND character_id = ? ',
'ii',
$fieldId, $characterId
);
if(!empty($data)) {
return $data[0]['value'];
}
return '';
}
/**
* Set the text for a Quest and correct fields count.
*
* @param int $userId ID of user setting text
* @param int $questId ID of Quest to set text for
* @param string $text Text for Quest
*/
public function setTextForQuest($userId, $questId, $text)
{
$this->db->setAutocommit(false);
try {
// Set text
$this->db->query(
'INSERT INTO questtypes_textinput '.
'(quest_id, created_user_id, text) '.
'VALUES '.
'(?, ?, ?) '.
'ON DUPLICATE KEY UPDATE '.
'text = ?',
'iiss',
$questId,
$userId,
$text,
$text
);
// Count fields
$fieldCount = substr_count($text, '[textinput]');
// Remove fields
$this->db->query(
'DELETE FROM questtypes_textinput_fields '.
'WHERE questtypes_textinput_quest_id = ? AND number > ?',
'ii',
$questId,
$fieldCount
);
// Add fields
for($i=1; $i<=$fieldCount; $i++)
{
$this->db->query(
'INSERT IGNORE INTO questtypes_textinput_fields '.
'(questtypes_textinput_quest_id, number, regex) '.
'VALUES '.
'(?, ?, ?) ',
'iis',
$questId,
$i,
''
);
}
$this->db->commit();
}
catch(\Exception $e) {
$this->db->rollback();
$this->db->setAutocommit(true);
throw $e;
}
$this->db->setAutocommit(true);
}
/**
* Set values for a field of a text.
*
* @param int $questId ID of Quest to set field for
* @param int $number Field number
* @param int $sizeId ID of field size
* @param string $regex RegEx for field
*/
public function setFieldForText($questId, $number, $sizeId, $regex)
{
$this->db->query(
'UPDATE questtypes_textinput_fields '.
'SET questtypes_textinput_fieldsize_id = ?, regex = ? '.
'WHERE questtypes_textinput_quest_id = ? AND number = ?',
'isii',
$sizeId,
$regex,
$questId,
$number
);
}
/**
* Get all registered field sizes.
*
* @return List of field sizes
*/
public function getFieldSizes()
{
return $this->db->query(
'SELECT id, size '.
'FROM questtypes_textinput_fieldsizes '.
'ORDER BY size'
);
}
}
?>

View file

@ -0,0 +1,114 @@
<?php if(!empty($validations)) : ?>
<ul>
<?php foreach($validations as $field => &$settings) : ?>
<li>
<ul>
<?php foreach($settings as $setting => $value) : ?>
<li>
<?php
switch($setting) {
case 'regex': echo _('Regex invalid');
break;
default: echo _('Regex invalid');
}
?>
</li>
<?php endforeach ?>
</ul>
</li>
<?php endforeach ?>
</ul>
<?php endif ?>
<form method="post">
<fieldset>
<legend><?=_('Text')?></legend>
<button id="add-field" type="button"><?=_('Add field')?></button><br />
<textarea id="text" name="text"><?=$text?></textarea>
</fieldset>
<fieldset>
<legend><?=_('Fields')?></legend>
<ul id="fields">
<?php foreach($fields as $index => &$field) : ?>
<li>
<select name="fields[<?=$index?>][size]">
<?php foreach($fieldSizes as &$size) : ?>
<option value="<?=$size['size']?>" <?php if($fields[$index]['size'] == $size['size']) : ?>selected="selected"<?php endif ?>><?=$size['size']?></option>
<?php endforeach ?>
</select>
<input type="text" name="fields[<?=$index?>][regex]" required="required" placeholder="/regex/i" value="<?=$field['regex']?>" <?php if(!empty($validations) && array_key_exists($index, $validations)) : ?>class="invalid"<?php endif ?> />
</li>
<?php endforeach ?>
</ul>
</fieldset>
<input type="submit" name="preview" value="<?=_('Preview')?>" />
<input type="submit" name="save" value="<?=_('save')?>" />
</form>
<h2><?=_('Preview')?></h2>
<p>
<?php $posStart = 0; ?>
<?php foreach($fields as &$field) : ?>
<?php $posEnd = mb_strpos($text, '[textinput]', $posStart, 'UTF-8'); ?>
<?=$t->t(mb_substr($text, $posStart, $posEnd-$posStart, 'UTF-8'))?>
<input type="text" name="answers[]" value="<?=(array_key_exists('answer', $field)) ? $field['answer'] : ''?>" <?php if($field['size'] != 'default') : ?>class="<?=$field['size']?>"<?php endif ?> />
<?php $posStart = $posEnd + mb_strlen('[textinput]', 'UTF-8'); ?>
<?php endforeach ?>
<?=$t->t(mb_substr($text, $posStart, mb_strlen($text, 'UTF-8')-$posStart, 'UTF-8'))?>
</p>
<script>
$(function() {
$("#text").markItUp(mySettings);
});
var index = <?=count($fields)?>;
var selectElement = '<select name="fields[INDEX][size]">' +
<?php foreach($fieldSizes as &$size) : ?>
'<option value="<?=$size['size']?>"><?=$size['size']?></option>' +
<?php endforeach ?>
'</select>';
var inputElement = '<input type="text" name="fields[INDEX][regex]" required="required" placeholder="/regex/i" />';
$("#add-field").click(function(event) {
event.preventDefault();
var caret = getCaret("text");
insertAtCaret("text", caret, "[textinput]");
updateFields();
});
$("#text").on('change keyup paste', function(event) {
updateFields();
});
function updateFields()
{
var newCount = $("#text").val().split("[textinput]").length - 1;
var oldCount = $("#fields > li").length;
var caret = getCaret("text");
var pos = $("#text").val().substring(0, caret).split("[textinput]").length - 1;
if(newCount > oldCount)
{
// Add fields
for(var i=oldCount; i<newCount; i++)
{
index++;
var element = '<li>' + selectElement.replace('INDEX', index) + inputElement.replace('INDEX', index) + '</li>';
if($("#fields > li").length > 0)
{
if($("#fields > li").length > pos-1) {
$($("#fields > li")[pos-1]).before(element);
}
else {
$($("#fields > li")[pos-2]).after(element);
}
}
else {
$("#fields").append(element);
}
}
}
else if(newCount < oldCount)
{
// Remove fields
for(var i=oldCount; i>newCount; i--) {
$($("#fields > li")[pos]).remove();
}
}
}
</script>

View file

@ -0,0 +1,16 @@
<form method="post" class="textinput">
<?php $text = $t->t($task['text']); ?>
<?php $posStart = 0; ?>
<?php foreach($fields as &$field) : ?>
<?php $posEnd = mb_strpos($text, '[textinput]', $posStart, 'UTF-8'); ?>
<?=mb_substr($text, $posStart, $posEnd-$posStart, 'UTF-8')?>
<input type="text" name="answers[]" value="<?=(array_key_exists('answer', $field)) ? $field['answer'] : ''?>" <?php if($field['size'] != 'default') : ?>class="<?=$field['size']?>"<?php endif ?> />
<?php $posStart = $posEnd + mb_strlen('[textinput]', 'UTF-8'); ?>
<?php endforeach ?>
<?=mb_substr($text, $posStart, mb_strlen($text, 'UTF-8')-$posStart, 'UTF-8')?>
<?php if(!is_null($nCorrectAnswers)) : ?>
<p><?=sprintf(_('You filled %d of %d fields correctly'), $nCorrectAnswers, count($fields))?>.</p>
<?php endif ?>
<input type="submit" name="submit" value="<?=_('solve')?>" />
</form>

View file

@ -0,0 +1,10 @@
<p>
<?php $posStart = 0; ?>
<?php foreach($fields as &$field) : ?>
<?php $posEnd = mb_strpos($task['text'], '[textinput]', $posStart, 'UTF-8'); ?>
<?=$t->t(mb_substr($task['text'], $posStart, $posEnd-$posStart, 'UTF-8'))?>
<span style="background-color:grey"><?=$field['answer']?></span><?=($field['right']) ? '✓' : '✕'?>
<?php $posStart = $posEnd + mb_strlen('[textinput]', 'UTF-8'); ?>
<?php endforeach ?>
<?=$t->t(mb_substr($task['text'], $posStart, mb_strlen($task['text'], 'UTF-8')-$posStart, 'UTF-8'))?>
</p>