download json quiz.

@EXT\Route("/{id}/export", name="exercise_export")
@EXT\Method("GET")
@EXT\ParamConverter("exercise", class="UJMExoBundle:Exercise", options={"mapping": {"id": "uuid"}})

@param Exercise $exercise

@return Response
340593
public function exportAction(Exercise $exercise)
    {
        $this->assertHasPermission('ADMINISTRATE', $exercise);

        $file = $this->exerciseManager->export($exercise);

        $response = new StreamedResponse();
        $response->setCallBack(
            function () use ($file) {
                readfile($file);
            }
        );

        $name = $exercise->getResourceNode()->getName().'.json';
        $response->headers->set('Content-Transfer-Encoding', 'octet-stream');
        $response->headers->set('Content-Type', 'application/force-download');
        $response->headers->set('Content-Disposition', 'attachment; filename='.urlencode($name));
        $response->headers->set('Content-Type', 'application/json');
        $response->headers->set('Connection', 'close');
        $response->send();

        return new Response();
    }
649377
public function save($object, array $options = []) {
		$returnobject = [];
		$returnobject['result'] = false;
		$returnobject['msg'] = '';

		if (empty($object)) {
			return $returnobject;
		}

		//Create filename based on timestamp and random number (to prevent collisions)
		$object['filename'] = $this->generateFilename($object);

		if ($this->saveFile($object, $options['location'])) {
			$msg = __d('feedback', 'Thank you. Your feedback was saved.');

			if (!empty($options['returnlink'])) {
				$msg .= ' ';
				$msg .= __d('feedback', 'View your feedback on: ');

				$url = Router::url(['plugin' => 'Feedback', 'controller' => 'Feedback', 'action' => 'index'], true);

				$msg .= '<a target="_blank" href="' . $url . '">' . $url . '</a>';
			}

			$returnobject['result'] = true;
			$returnobject['msg'] = $msg;
		}

		return $returnobject;
	}
1206878
public function canPass(Exercise $exercise, User $user = null)
    {
        // TODO : max attempts by day

        $canPass = true;
        if ($user) {
            $max = $exercise->getMaxAttempts();
            if ($max > 0) {
                $nbFinishedPapers = $this->paperManager->countUserFinishedPapers($exercise, $user);
                if ($nbFinishedPapers >= $max) {
                    $canPass = false;
                }
            }
        }

        return $canPass;
    }
995344
private function serializeParameters(Exercise $exercise)
    {
        $parameters = [
            'type' => $exercise->getType(),
            'maxAttempts' => $exercise->getMaxAttempts(),
            'maxAttemptsPerDay' => $exercise->getMaxAttemptsPerDay(),
            'maxPapers' => $exercise->getMaxPapers(),
            'showFeedback' => $exercise->getShowFeedback(),
            'progressionDisplayed' => $exercise->isProgressionDisplayed(),
            'timeLimited' => $exercise->isTimeLimited(), // todo : remove me
            'duration' => $exercise->getDuration(),
            'anonymizeAttempts' => $exercise->getAnonymizeAttempts(),
            'interruptible' => $exercise->isInterruptible(),
            'numbering' => $exercise->getNumbering(),
            'mandatoryQuestions' => $exercise->getMandatoryQuestions(),
            'answersEditable' => $exercise->isAnswersEditable(),
            'showOverview' => $exercise->getShowOverview(),
            'showEndConfirm' => $exercise->getShowEndConfirm(),
            'showEndPage' => $exercise->getShowEndPage(),
            'endNavigation' => $exercise->hasEndNavigation(),
            'showMetadata' => $exercise->isMetadataVisible(),
            'showStatistics' => $exercise->hasStatistics(),
            'allPapersStatistics' => $exercise->isAllPapersStatistics(),
            'showFullCorrection' => !$exercise->isMinimalCorrection(),
            'showScoreAt' => $exercise->getMarkMode(),
            'showCorrectionAt' => $exercise->getCorrectionMode(),
            'successMessage' => $exercise->getSuccessMessage(),
            'failureMessage' => $exercise->getFailureMessage(),
            'totalScoreOn' => $exercise->getTotalScoreOn(),
            'successScore' => $exercise->getSuccessScore(),
            'correctionDate' => $exercise->getDateCorrection() ? DateNormalizer::normalize($exercise->getDateCorrection()) : null,
        ];

        if (!empty($exercise->getEndMessage())) {
            $parameters['endMessage'] = $exercise->getEndMessage();
        }

        return $parameters;
    }
1264314
public function exportAction()
  {
    $this->setNoRender();

    /* grab user parameters from $_REQUEST array */
    $sid = TeamSpeak3_Helper_Uri::getUserParam("id", 0);

    try
    {
      /* create snapshot and return data as base64 encoded string */
      $data = $this->ts3->serverGetById($sid)->snapshotCreate(TeamSpeak3::SNAPSHOT_BASE64);
    }
    catch(Exception $e)
    {
      /* save catched error mesage */
      $this->setLastEvent($e->getMessage(), TRUE);

      /* goto indexAction() */
      $this->redirect("server");
    }

    /* stream snapshot data to browser */
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=" . $this->ts3->getAdapterHost() . "_" . $this->ts3->getAdapterPort() . "-virtualserver_" . $sid . ".snapshot");
    header("Content-Transfer-Encoding: binary");

    /* send output */
    echo chunk_split($data);
  }
530809
function jsonSerialize(): \stdClass {
    $map = new \stdClass;
    $map->name = $this->getName();
    $map->source_digest = $this->getSourceDigest();
    $map->coverage = $this->getCoverage()->getArrayCopy();
    if (mb_strlen($source = $this->getSource())) $map->source = $source;
    return $map;
  }
560680
public function export() {
        
        try {
            if ($this->getRequestMethod()!=Request::HTTP_GET) {
                    throw new \common_exception_NotImplemented('Only GET method is accepted to export QIT Item.');
            }
            
            if(!$this->hasRequestParameter('id')) {
                $this->returnFailure(new \common_exception_MissingParameter('required parameter `id` is missing'));
            } 
            
            $id = $this->getRequestParameter('id');
            
            $item = new \core_kernel_classes_Resource($id); 

            $itemService = \taoItems_models_classes_ItemsService::singleton();

            if($itemService->hasItemModel($item, array(ItemModel::MODEL_URI))){
                
                $path = \tao_helpers_Export::getExportFile();
                $tmpZip = new \ZipArchive();
                $tmpZip->open($path , \ZipArchive::CREATE);
                
                $exporter = new QTIPackedItemExporter( $item , $tmpZip);
                $exporter->export(array('apip' => false));

                $exporter->getZip()->close();

                header('Content-Type: application/zip');
                \tao_helpers_Http::returnFile($path, false);

                return;
            } else {

                $this->returnFailure(new \common_exception_NotFound('item can\'t be found'));

            }
        } catch (\Exception $e) {
      
            $this->returnFailure($e);
        }
    }
495669
public function loadJSONObject($jsonObject)
    {
        if (isset($jsonObject->type)) {
            $this->setType($jsonObject->type);
        }
        if (isset($jsonObject->url)) {
            $this->setUrl($jsonObject->url);
        }
        if (isset($jsonObject->options)) {
            $this->setOptions($jsonObject->options);
        }
        if (isset($jsonObject->package)) {
            $package = new Package();
            $package->setName($jsonObject->package->name)
                ->setVersion($jsonObject->package->version)
                ->setDist($jsonObject->package->dist)
                ->setSource($jsonObject->package->source);

            $this->setPackage($package);
        }

        return $this;
    }
26236
public function update(Exercise $exercise, array $data)
    {
        // Validate received data
        $errors = $this->validator->validate($data, [Validation::REQUIRE_SOLUTIONS]);

        if (count($errors) > 0) {
            throw new InvalidDataException('Exercise is not valid', $errors);
        }
        // Start flush suite to avoid persisting and flushing tags before quiz
        $this->om->startFlushSuite();
        // Update Exercise with new data
        $this->serializer->deserialize($data, $exercise, [Transfer::PERSIST_TAG]);

        // Save to DB
        $this->om->persist($exercise);
        $this->om->endFlushSuite();

        // Invalidate unfinished papers
        $this->repository->invalidatePapers($exercise);

        // Log exercise update
        $event = new LogExerciseUpdateEvent($exercise, (array) $this->serializer->serialize($exercise));
        $this->eventDispatcher->dispatch('log', $event);

        return $exercise;
    }
577618
private function generateStructure(Exercise $exercise, Paper $previousPaper = null)
    {
        // The structure of the previous paper if any
        $previousStructure = !empty($previousPaper) ? json_decode($previousPaper->getStructure(), true) : null;

        // Get JSON representation of the full exercise
        $structure = $this->exerciseSerializer->serialize($exercise);
        // Pick questions for each steps and generate structure
        $structure['steps'] = $this->pickSteps($exercise, $previousStructure);

        return $structure;
    }
728754
public function performToJson($exportMode) {
    	$result = array();
    	$result['name'] = $this->getName();
    
    	$result['exportmode'] = $exportMode;
    
    	// The filename is relative to the ROOT_PATH.
    	// It is "null" if the class is not part of the ROOT_PATH.
    	$fileName = $this->getFileName();
    	if (strpos($fileName, ROOT_PATH) === 0) {
    		$result['filename'] = substr($fileName, strlen(ROOT_PATH));
    	} else {
    		$result['filename'] = null;
    	}
    	$result['startline'] = $this->getStartLine();
    	$result['isinstantiable'] = $this->isInstantiable();
    
    	$result['comment'] = $this->getMoufDocComment()->getJsonArray();
    	$result['implements'] = array();

    	$interfaces = $this->getInterfaces();
    	foreach ($interfaces as $interface) {
    		/* @var $interface MoufReflectionClass */
    		$result['implements'][] = $interface->getName();
    	}
    
    	/*$extends = array();
    		$currentClass = $this;
    	while ($currentClass->getExtension()) {
    	$currentClass = $currentClass->getExtension();
    	$extends[] = $currentClass->getName();
    	}
    	$result['extends'] = $extends;*/
    	if ($this->getParentClass()) {
    		$result['extend'] = $this->getParentClass()->getName();
    	}
    
    	if ($exportMode != MoufReflectionClass::EXPORT_TINY) {
    
    		$result['properties'] = array();
    		foreach ($this->getProperties() as $property) {
    			if ($property->isPublic() && !$property->isStatic()) {
    				$result['properties'][] = $property->toJson();
    			}
    		}
    			
    		$result['methods'] = array();
    		foreach ($this->getMethods() as $method) {
    			$doExport = false;
    			if ($exportMode == MoufReflectionClass::EXPORT_PROPERTIES) {
    				$doExport = $method->isSetter();
    			} else {
    				$doExport = true;
    			}
    			if ($doExport) {
    				$result['methods'][] = $method->toJson();
    			}
    		}
    
    	}
    		
    	return $result;
    }
518443
public function export_to_client() {
        if(!Permission::check('CODE_BANK_ACCESS')) {
            return Security::permissionFailure($this);
        }
        
        
        //Bump up time limit we may need it
        set_time_limit(480);
        
        
        //Dump Data
        $languages=$this->queryToArray(DB::query('SELECT "ID", "Name", "FileExtension", "HighlightCode", "UserLanguage" FROM "SnippetLanguage"'));
        $snippets=$this->queryToArray(DB::query('SELECT "ID", "Title", "Description", "Tags", "LanguageID", "PackageID", "FolderID" FROM "Snippet"'));
        $versions=$this->queryToArray(DB::query('SELECT "ID", "Created", "Text", "ParentID" FROM "SnippetVersion"'));
        $packages=$this->queryToArray(DB::query('SELECT "ID", "Title" FROM "SnippetPackage"'));
        $folders=$this->queryToArray(DB::query('SELECT "ID", "Name", "ParentID", "LanguageID" FROM "SnippetFolder"'));
        
        
        //Build final response array
        $response=array(
                        'format'=>'ToClient',
                        'data'=>array(
                                    'languages'=>$languages,
                                    'snippets'=>$snippets,
                                    'versions'=>$versions,
                                    'packages'=>$packages,
                                    'folders'=>$folders
                                )
                    );
        
        
        //Send File
        SS_HTTPRequest::send_file(json_encode($response), date('Y-m-d_hi').'.cbexport', 'application/json')->output();
        
        
        //Save session and exit
        Session::save();
        exit;
    }
1108581
public function findByQuestion(Item $question, Exercise $exercise = null, $finishedPapersOnly = false)
    {
        $qb = $this->createQueryBuilder('a')
            ->join('a.paper', 'p', 'WITH', 'p.exercise = :exercise')
            ->where('a.questionId = :question')
            ->setParameters([
                'exercise' => $exercise,
                'question' => $question->getUuid(),
            ]);

        if ($finishedPapersOnly) {
            $qb->andWhere('p.end IS NOT NULL');
        }

        return $qb->getQuery()->getResult();
    }
148335
function renew_url() {
		$license_data = get_option( $this->product->get_key() . '_license_data', '' );
		if ( '' === $license_data ) {
			return $this->get_api_url();
		}
		if ( ! isset( $license_data->download_id ) || ! isset( $license_data->key ) ) {
			return $this->get_api_url();
		}

		return $this->get_api_url() . '/checkout/?edd_license_key=' . $license_data->key . '&download_id=' . $license_data->download_id;
	}
331299
private function migrateExerciseQuestionData()
    {
        $exoId = -1;
        $orderStep = 1;

        $exoQuestion = $this->checkExoQuestion();
        $stepStmt = $this->connection->prepare("
            INSERT INTO ujm_step
            (exercise_id, value, nbQuestion, keepSameQuestion, shuffle, duration, max_attempts, ordre)
            VALUES (:exoId, '', 0, FALSE, FALSE, 0, 0, :orderStep)
        ");

        foreach ($exoQuestion as $eq) {
            if ($eq['exercise_id'] !== $exoId) {
                $exoId = $eq['exercise_id'];
            }

            $this->log('Create step ...');

            $stepStmt->bindValue('exoId', $exoId);
            $stepStmt->bindValue('orderStep', $orderStep);
            $stepStmt->execute();

            $stepId = $this->connection->lastInsertId();
            $this->addQuestionStep($stepId, $eq['question_id'], 1);
            ++$orderStep;
        }
    }
1053854
private function getDiscriminationCoefficient(Exercise $exercise)
    {
        // get all scores for the exercise
        $papers = $this->paperRepository->findBy([
            'exercise' => $exercise,
        ]);

        $itemRepository = $this->om->getRepository('UJMExoBundle:Item\Item');
        $reportScoreOn = 100;
        // all scores obtained for an exercise
        $exerciseScores = $this->getPapersScores($papers, $reportScoreOn);
        // exercise standard deviation
        $standardDeviationE = $this->getStandardDeviation($exerciseScores);
        // get average score per exercise
        $exerciseAverageScore = $this->getMinMaxAverageScores($exercise, $reportScoreOn)['avg'];
        // all scores obtained per question
        $questionsScores = [];
        // all average scores per question
        $questionsAvgScores = [];
        // all margin marks per question
        $questionsMarginMark = [];
        // computed result to return
        $discriminationCoef = [];

        /** @var Paper $paper */
        foreach ($papers as $paper) {
            // base success compution on paper structure
            $structure = json_decode($paper->getStructure(), true);

            foreach ($structure['steps'] as $step) {
                foreach (array_filter($step['items'], function ($item) {
                    return ItemType::isSupported($item['type']);
                }) as $item) {
                    // since the compution is based on the structure the same item can come several times
                    if (!array_key_exists($item['id'], $discriminationCoef)) {
                        $itemEntity = $itemRepository->findOneBy(['uuid' => $item['id']]);
                        // set questions scores
                        $questionsScores[$item['id']] = $this->itemManager->getItemScores($exercise, $itemEntity);
                        // get average score for the item
                        $questionsAvgScores[$item['id']] = array_sum($questionsScores[$item['id']]) / count($questionsScores[$item['id']]);
                        $i = 0;

                        foreach ($questionsScores[$item['id']] as $score) {
                            $questionsMarginMark[$item['id']][] = ($score - $questionsAvgScores[$item['id']]) * ($exerciseScores[$i] - $exerciseAverageScore);
                            ++$i;
                        }

                        $questionProductMarginMark = $questionsMarginMark[$item['id']];
                        $sumPenq = array_sum($questionProductMarginMark);
                        $sumPenq = round($sumPenq, 3);
                        $standardDeviationQ = $this->getStandardDeviation($questionsScores[$item['id']]);
                        $n = count($questionProductMarginMark);
                        $nSxSy = $n * $standardDeviationQ * $standardDeviationE;
                        $coef = $nSxSy === floatval(0) ? 0 : round($sumPenq / ($nSxSy), 3);

                        $discriminationCoef[$item['id']] = [
                            'xData' => $itemEntity->getTitle() ? strip_tags($itemEntity->getTitle()) : strip_tags($itemEntity->getContent()),
                            'yData' => $coef,
                        ];
                    }
                }
            }
        }

        return $discriminationCoef;
    }
140043
public function deSerialize()
    {
        $legacySaveFile = sprintf('%s/%s', $this->path, static::LEGACY_SAVE_FILE);
        if (file_exists($legacySaveFile)) {
            $userState = $this->migrateData($legacySaveFile);

            if ($userState instanceof UserState) {
                return $userState;
            }
        }

        $json = $this->readJson(sprintf('%s/%s', $this->path, static::SAVE_FILE));
        if (null === $json) {
            $this->wipeFile();
            return new UserState();
        }

        if (!isset($json[$this->workshopName])) {
            return new UserState();
        }

        $json = $json[$this->workshopName];
        if (!array_key_exists('completed_exercises', $json)) {
            return new UserState();
        }

        if (!array_key_exists('current_exercise', $json)) {
            return new UserState();
        }

        if (!is_array($json['completed_exercises'])) {
            $json['completed_exercises'] = [];
        }

        foreach ($json['completed_exercises'] as $i => $exercise) {
            if (!is_string($exercise)) {
                unset($json['completed_exercises'][$i]);
            }
        }

        if (null !== $json['current_exercise'] && !is_string($json['current_exercise'])) {
            $json['current_exercise'] = null;
        }

        return new UserState(
            $json['completed_exercises'],
            $json['current_exercise']
        );
    }