Remove SurveyTree class, use repository to get survey list.

Add migrations, remove c_survey.author use resourceNode.author instead.
pull/3844/head
Julio Montoya 5 years ago
parent 307ff058e8
commit 7b6b244b4f
  1. 125
      public/main/inc/lib/SurveyTree.php
  2. 38
      public/main/survey/create_new_survey.php
  3. 32
      public/main/survey/survey.lib.php
  4. 53
      public/main/survey/surveyUtil.class.php
  5. 18
      src/CoreBundle/Migrations/Schema/V200/Version20180319145700.php
  6. 19
      src/CoreBundle/Repository/ResourceRepository.php
  7. 143
      src/CourseBundle/Entity/CSurvey.php
  8. 57
      src/CourseBundle/Repository/CSurveyRepository.php

@ -1,125 +0,0 @@
<?php
/* For licensing terms, see /license.txt */
/**
* Manage the "versioning" of a conditional survey.
*/
class SurveyTree
{
public $surveylist;
public $plainsurveylist;
public $numbersurveys;
/**
* Sets the surveylist and the plainsurveylist.
*/
public function __construct()
{
// Database table definitions
$table_survey = Database::get_course_table(TABLE_SURVEY);
$table_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
$table_user = Database::get_main_table(TABLE_MAIN_USER);
// searching
$search_restriction = SurveyUtil::survey_search_restriction();
if ($search_restriction) {
$search_restriction = ' AND '.$search_restriction;
}
$course_id = api_get_course_int_id();
$sql = "SELECT
survey.iid survey_id,
survey.parent_id,
survey_version,
survey.code as name
FROM $table_survey survey
LEFT JOIN $table_survey_question survey_question
ON survey.iid = survey_question.survey_id , $table_user user
WHERE
survey.c_id = $course_id AND
survey_question.c_id = $course_id AND
survey.author = user.id
GROUP BY survey.iid";
$res = Database::query($sql);
$refs = [];
$list = [];
$plain_array = [];
while ($survey = Database::fetch_array($res, 'ASSOC')) {
$plain_array[$survey['survey_id']] = $survey;
$surveys_parents[] = $survey['survey_version'];
$thisref = &$refs[$survey['survey_id']];
$thisref['parent_id'] = $survey['parent_id'];
$thisref['name'] = $survey['name'];
$thisref['id'] = $survey['survey_id'];
$thisref['survey_version'] = $survey['survey_version'];
if (0 == $survey['parent_id']) {
$list[$survey['survey_id']] = &$thisref;
} else {
$refs[$survey['parent_id']]['children'][$survey['survey_id']] = &$thisref;
}
}
$this->surveylist = $list;
$this->plainsurveylist = $plain_array;
}
/**
* This function gets the parent id of a survey.
*
* @param int $id survey id
*
* @return int survey parent id
*
* @author Julio Montoya <gugli100@gmail.com>, Dokeos
*
* @version September 2008
*/
public function getParentId($id)
{
$node = $this->plainsurveylist[$id];
if (is_array($node) && !empty($node['parent_id'])) {
return $node['parent_id'];
}
return -1;
}
/**
* This function creates a list of all surveys id.
*
* @param array $list of nodes
*
* @return array with the structure survey_id => survey_name
*
* @author Julio Montoya <gugli100@gmail.com>
*
* @version September 2008
*/
public function createList($list)
{
$result = [];
if (is_array($list)) {
foreach ($list as $key => $node) {
if (isset($node['children']) && is_array($node['children'])) {
$result[$key] = $node['name'];
$re = self::createList($node['children']);
if (!empty($re)) {
if (is_array($re)) {
foreach ($re as $key => $r) {
$result[$key] = ''.$r;
}
} else {
$result[] = $re;
}
}
} else {
$result[$key] = $node['name'];
}
}
}
return $result;
}
}

@ -2,6 +2,8 @@
/* For licensing terms, see /license.txt */
use Chamilo\CoreBundle\Framework\Container;
/**
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University: cleanup,
* refactoring and rewriting large parts (if not all) of the code
@ -11,8 +13,11 @@
* @todo only the available platform languages should be used => need an
* api get_languages and and api_get_available_languages (or a parameter)
*/
require_once __DIR__.'/../inc/global.inc.php';
$repo = Container::getSurveyRepository();
$_course = api_get_course_info();
$this_section = SECTION_COURSES;
$table_gradebook_link = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
@ -40,14 +45,14 @@ $gradebook_link_type = 8;
$urlname = isset($survey_data['title']) ? strip_tags($survey_data['title']) : null;
// Breadcrumbs
if ('add' == $action) {
if ('add' === $action) {
$interbreadcrumb[] = [
'url' => api_get_path(WEB_CODE_PATH).'survey/survey_list.php?'.api_get_cidreq(),
'name' => get_lang('Survey list'),
];
$tool_name = get_lang('Create survey');
}
if ('edit' == $action && is_numeric($survey_id)) {
if ('edit' === $action && is_numeric($survey_id)) {
$interbreadcrumb[] = [
'url' => api_get_path(WEB_CODE_PATH).'survey/survey_list.php?'.api_get_cidreq(),
'name' => get_lang('Survey list'),
@ -106,7 +111,7 @@ $form = new FormValidator(
$form->addElement('header', $tool_name);
// Setting the form elements
if ('edit' == $action && isset($survey_id) && is_numeric($survey_id)) {
if ('edit' === $action && isset($survey_id) && is_numeric($survey_id)) {
$form->addElement('hidden', 'survey_id');
}
@ -117,7 +122,7 @@ $survey_code = $form->addElement(
['size' => '20', 'maxlength' => '20', 'autofocus' => 'autofocus']
);
if ('edit' == $action) {
if ('edit' === $action) {
$survey_code->freeze();
$form->applyFilter('survey_code', 'api_strtoupper');
}
@ -215,10 +220,7 @@ if (Gradebook::is_active()) {
get_lang('Grade in the assessment tool'),
'onclick="javascript: if (this.checked) { document.getElementById(\'gradebook_options\').style.display = \'block\'; } else { document.getElementById(\'gradebook_options\').style.display = \'none\'; }"'
);
$form->addElement(
'html',
'<div id="gradebook_options"'.($gradebook_link_id ? '' : ' style="display:none"').'>'
);
$form->addHtml('<div id="gradebook_options"'.($gradebook_link_id ? '' : ' style="display:none"').'>');
$form->addElement(
'text',
'survey_weight',
@ -229,7 +231,7 @@ if (Gradebook::is_active()) {
// Loading Gradebook select
GradebookUtils::load_gradebook_select_in_tool($form);
if ('edit' == $action) {
if ('edit' === $action) {
$element = $form->getElement('category_id');
$element->freeze();
}
@ -240,12 +242,15 @@ if (Gradebook::is_active()) {
$surveytypes[0] = get_lang('Normal');
$surveytypes[1] = get_lang('Conditional');
if ('add' == $action) {
$form->addElement('hidden', 'survey_type', 0);
$survey_tree = new SurveyTree();
$list_surveys = $survey_tree->createList($survey_tree->surveylist);
$list_surveys[0] = '';
$form->addElement('select', 'parent_id', get_lang('Parent Survey'), $list_surveys);
if ('add' === $action) {
$form->addHidden('survey_type', 0);
$qb = $repo->findAllByCourse(api_get_course_entity(), api_get_session_entity());
$surveys = $qb->getQuery()->getResult();
$surveyOptions[0] = '';
foreach ($surveys as $survey) {
$surveyOptions[$survey->getIid()] = implode(' > ', $repo->getPath($survey));
}
$form->addSelect('parent_id', get_lang('Parent Survey'), $surveyOptions);
$defaults['parent_id'] = 0;
}
@ -254,7 +259,7 @@ $form->addElement('checkbox', 'shuffle', null, get_lang('Enable shuffle mode'));
$input_name_list = null;
if ('edit' == $action && !empty($survey_id)) {
if ('edit' === $action && !empty($survey_id)) {
if (0 == $survey_data['anonymous']) {
$form->addElement(
'checkbox',
@ -300,7 +305,6 @@ if ('edit' == $action && !empty($survey_id)) {
}
$skillList = Skill::addSkillsToForm($form, ITEM_TYPE_SURVEY, $survey_id);
$form->addElement('html', '</div><br />');
if (isset($_GET['survey_id']) && 'edit' === $action) {

@ -220,7 +220,6 @@ class SurveyManager
*/
public static function store_survey($values)
{
$_user = api_get_user_info();
$course_id = api_get_course_int_id();
$session_id = api_get_session_id();
$courseCode = api_get_course_id();
@ -232,7 +231,6 @@ class SurveyManager
// Check if the code doesn't soon exists in this language
$sql = 'SELECT 1 FROM '.$table_survey.'
WHERE
c_id = '.$course_id.' AND
code = "'.Database::escape_string($values['survey_code']).'" AND
lang = "'.Database::escape_string($values['survey_language']).'"';
$rs = Database::query($sql);
@ -363,6 +361,11 @@ class SurveyManager
->addCourseLink($course, $session)
;
if (isset($values['parent_id']) && !empty($values['parent_id'])) {
$parent = $repo->find($values['parent_id']);
$survey->setSurveyParent($parent);
}
$repo->create($survey);
$survey_id = $survey->getIid();
@ -402,7 +405,6 @@ class SurveyManager
// Check whether the code doesn't soon exists in this language
$sql = 'SELECT 1 FROM '.$table_survey.'
WHERE
c_id = '.$course_id.' AND
code = "'.Database::escape_string($values['survey_code']).'" AND
lang = "'.Database::escape_string($values['survey_language']).'" AND
iid !='.intval($values['survey_id']);
@ -1223,7 +1225,7 @@ class SurveyManager
WHERE iid = $question_id";
Database::query($sql);*/
$form_content['question_id'] = $question_id;
$message = 'QuestionAdded';
$message = 'The question has been added.';
}
} else {
$repo = $em->getRepository(CSurveyQuestion::class);
@ -1270,30 +1272,8 @@ class SurveyManager
$em->persist($question);
$em->flush();
/*Database::update(
$tbl_survey_question,
$params,
[
'c_id = ? AND iid = ?' => [
$course_id,
$form_content['question_id'],
],
]
);*/
$message = 'QuestionUpdated';
}
if (!empty($form_content['survey_id'])) {
//Updating survey
/*api_item_property_update(
api_get_course_info(),
TOOL_SURVEY,
$form_content['survey_id'],
'SurveyUpdated',
api_get_user_id()
);*/
}
// Storing the options of the question
self::saveQuestionOptions($survey, $question, $form_content, $dataFromDatabase);
} else {

@ -3250,20 +3250,11 @@ class SurveyUtil
{
if (1 == $anonymous) {
return get_lang('Yes');
} else {
return get_lang('No');
}
return get_lang('No');
}
/**
* This function handles the search restriction for the SQL statements.
*
* @return string Part of a SQL statement or false on error
*
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
*
* @version January 2007
*/
public static function survey_search_restriction()
{
if (isset($_GET['do_search'])) {
@ -3316,9 +3307,15 @@ class SurveyUtil
*/
public static function get_number_of_surveys_for_coach()
{
$survey_tree = new SurveyTree();
$repo = Container::getSurveyRepository();
$course = api_get_course_entity();
$session = api_get_session_entity();
$qb = $repo->findAllByCourse($course, $session);
return count($survey_tree->surveylist);
return $repo->getCount($qb);
/*$survey_tree = new SurveyTree();
return count($survey_tree->surveylist);*/
}
/**
@ -3344,7 +3341,6 @@ class SurveyUtil
$direction,
$isDrh = false
) {
$repo = Container::getSurveyRepository();
$course = api_get_course_entity();
$session = api_get_session_entity();
@ -3352,12 +3348,10 @@ class SurveyUtil
/** @var CSurvey[] $surveys */
$surveys = $qb->getQuery()->getResult();
$table_survey = Database::get_course_table(TABLE_SURVEY);
$table_user = Database::get_main_table(TABLE_MAIN_USER);
$table_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
$mandatoryAllowed = api_get_configuration_value('allow_mandatory_survey');
$_user = api_get_user_info();
$allowSurveyAvailabilityDatetime = api_get_configuration_value('allow_survey_availability_datetime');
// Searching
@ -3445,14 +3439,14 @@ class SurveyUtil
// Dates
$array[5] = '';
$from = $survey->getAvailFrom() ?? $survey->getAvailFrom()->format('Y-m-d H:i:s');
$from = $survey->getAvailFrom() ? $survey->getAvailFrom()->format('Y-m-d H:i:s') : null;
if (null !== $from) {
$array[5] = api_convert_and_format_date(
$from,
$allowSurveyAvailabilityDatetime ? DATE_TIME_FORMAT_LONG : DATE_FORMAT_LONG
);
}
$till = $survey->getAvailTill() ?? $survey->getAvailTill()->format('Y-m-d H:i:s');
$till = $survey->getAvailTill() ? $survey->getAvailTill()->format('Y-m-d H:i:s') : null;
$array[6] = '';
if (null !== $till) {
$array[6] = api_convert_and_format_date(
@ -3511,18 +3505,25 @@ class SurveyUtil
{
$mandatoryAllowed = api_get_configuration_value('allow_mandatory_survey');
$allowSurveyAvailabilityDatetime = api_get_configuration_value('allow_survey_availability_datetime');
$survey_tree = new SurveyTree();
$last_version_surveys = $survey_tree->surveylist;
$repo = Container::getSurveyRepository();
$qb = $repo->findAllByCourse(
api_get_course_entity(),
api_get_session_entity(),
null,
null,
api_get_user_entity()
);
/** @var CSurvey[] $surveys */
$surveys = $qb->getQuery()->getResult();
$list = [];
foreach ($last_version_surveys as &$survey) {
$list[] = $survey['id'];
foreach ($surveys as $survey) {
$list[] = $survey->getIid();
}
$list_condition = '';
if (count($list) > 0) {
$list_condition = " AND survey.iid IN (".implode(',', $list).") ";
} else {
$list_condition = '';
}
$from = (int) $from;
$number_of_items = (int) $number_of_items;
$column = (int) $column;
@ -3554,7 +3555,7 @@ class SurveyUtil
survey.iid AS col9
FROM $table_survey survey
LEFT JOIN $table_survey_question survey_question
ON (survey.iid = survey_question.survey_id AND survey.c_id = survey_question.c_id),
ON (survey.iid = survey_question.survey_id),
$table_user user
WHERE survey.author = user.id AND survey.c_id = $course_id $list_condition
";

@ -34,6 +34,24 @@ class Version20180319145700 extends AbstractMigrationChamilo
$this->addSql('ALTER TABLE c_survey ADD COLUMN is_mandatory TINYINT(1) DEFAULT "0" NOT NULL');
}
$this->addSql('UPDATE c_survey SET parent_id = NULL WHERE parent_id = 0');
$this->addSql('ALTER TABLE c_survey CHANGE parent_id parent_id INT DEFAULT NULL');
if (!$survey->hasColumn('lft')) {
$this->addSql(
'ALTER TABLE c_survey ADD lft INT DEFAULT NULL, ADD rgt INT DEFAULT NULL, ADD lvl INT DEFAULT NULL'
);
}
if (!$survey->hasForeignKey('FK_F246DB30727ACA70')) {
$this->addSql(
'ALTER TABLE c_survey ADD CONSTRAINT FK_F246DB30727ACA70 FOREIGN KEY (parent_id) REFERENCES c_survey (iid) ON DELETE CASCADE '
);
}
if (!$survey->hasIndex('IDX_F246DB30727ACA70')) {
$this->addSql('CREATE INDEX IDX_F246DB30727ACA70 ON c_survey (parent_id)');
}
if (false === $survey->hasColumn('resource_node_id')) {
$this->addSql('ALTER TABLE c_survey ADD resource_node_id INT DEFAULT NULL');
$this->addSql('ALTER TABLE c_survey ADD CONSTRAINT FK_F246DB301BAD783F FOREIGN KEY (resource_node_id) REFERENCES resource_node (id) ON DELETE CASCADE');

@ -68,7 +68,6 @@ abstract class ResourceRepository extends ServiceEntityRepository
* The entity class FQN.
*/
protected string $className;
protected Settings $settings;
protected Template $templates;
protected ?ResourceType $resourceType = null;
@ -535,8 +534,7 @@ abstract class ResourceRepository extends ServiceEntityRepository
$qb->setParameter('parentNode', $parentNode);
}
$qb->andWhere('node.creator = :creator');
$qb->setParameter('creator', $user);
$this->addCreatorQueryBuilder($user, $qb);
return $qb;
}
@ -942,6 +940,21 @@ abstract class ResourceRepository extends ServiceEntityRepository
return $qb;
}
protected function addCreatorQueryBuilder(?User $user, QueryBuilder $qb = null): QueryBuilder
{
$qb = $this->getOrCreateQueryBuilder($qb);
if (null === $user) {
return $qb;
}
$qb
->andWhere('node.creator = :creator')
->setParameter('creator', $user)
;
return $qb;
}
private function setLinkVisibility(AbstractResource $resource, int $visibility, bool $recursive = true): bool
{
$resourceNode = $resource->getResourceNode();

@ -12,11 +12,13 @@ use DateTime;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Validator\Constraints as Assert;
/**
* CSurvey.
*
* @Gedmo\Tree(type="nested")
* @ORM\Table(
* name="c_survey",
* indexes={
@ -50,11 +52,6 @@ class CSurvey extends AbstractResource implements ResourceInterface
*/
protected ?string $subtitle;
/**
* @ORM\Column(name="author", type="string", length=20, nullable=true)
*/
protected ?string $author;
/**
* @ORM\Column(name="lang", type="string", length=20, nullable=true)
*/
@ -146,9 +143,36 @@ class CSurvey extends AbstractResource implements ResourceInterface
protected string $surveyVersion;
/**
* @ORM\Column(name="parent_id", type="integer", nullable=false)
* @Gedmo\TreeLeft
* @ORM\Column(name="lft", type="integer", nullable=true, unique=false)
*/
protected ?int $lft = null;
/**
* @Gedmo\TreeRight
* @ORM\Column(name="rgt", type="integer", nullable=true, unique=false)
*/
protected ?int $rgt = null;
/**
* @Gedmo\TreeLevel
* @ORM\Column(name="lvl", type="integer", nullable=true, unique=false)
*/
protected ?int $lvl = null;
/**
* @Gedmo\TreeParent
* @ORM\ManyToOne(targetEntity="Chamilo\CourseBundle\Entity\CSurvey")
* @ORM\JoinColumn(name="parent_id", referencedColumnName="iid", onDelete="CASCADE")
*/
protected ?CSurvey $surveyParent = null;
/**
* @var Collection|CSurvey[]
*
* @ORM\OneToMany(targetEntity="CSurvey", mappedBy="surveyParent")
*/
protected int $parentId;
protected Collection $children;
/**
* @ORM\Column(name="survey_type", type="integer", nullable=false)
@ -188,7 +212,6 @@ class CSurvey extends AbstractResource implements ResourceInterface
$this->invited = 0;
$this->answered = 0;
$this->subtitle = '';
$this->author = '';
$this->inviteMail = '';
$this->lang = '';
$this->reminderMail = '';
@ -196,9 +219,9 @@ class CSurvey extends AbstractResource implements ResourceInterface
$this->shuffle = false;
$this->oneQuestionPerPage = false;
$this->surveyVersion = '';
$this->parentId = 0;
$this->surveyType = 0;
$this->questions = new ArrayCollection();
$this->children = new ArrayCollection();
}
public function __toString(): string
@ -257,23 +280,6 @@ class CSurvey extends AbstractResource implements ResourceInterface
return $this->subtitle;
}
public function setAuthor(string $author): self
{
$this->author = $author;
return $this;
}
/**
* Get author.
*
* @return string
*/
public function getAuthor()
{
return $this->author;
}
public function setLang(string $lang): self
{
$this->lang = $lang;
@ -570,23 +576,6 @@ class CSurvey extends AbstractResource implements ResourceInterface
return $this->surveyVersion;
}
public function setParentId(int $parentId): self
{
$this->parentId = $parentId;
return $this;
}
/**
* Get parentId.
*
* @return int
*/
public function getParentId()
{
return $this->parentId;
}
public function setSurveyType(int $surveyType): self
{
$this->surveyType = $surveyType;
@ -679,6 +668,74 @@ class CSurvey extends AbstractResource implements ResourceInterface
return $this;
}
public function getSurveyParent(): ?self
{
return $this->surveyParent;
}
public function setSurveyParent(?self $surveyParent): self
{
$this->surveyParent = $surveyParent;
return $this;
}
public function getLft(): ?int
{
return $this->lft;
}
public function setLft(?int $lft): self
{
$this->lft = $lft;
return $this;
}
public function getRgt(): ?int
{
return $this->rgt;
}
public function setRgt(?int $rgt): self
{
$this->rgt = $rgt;
return $this;
}
public function getLvl(): ?int
{
return $this->lvl;
}
public function setLvl(?int $lvl): self
{
$this->lvl = $lvl;
return $this;
}
/**
* @return CSurvey[]|Collection
*/
public function getChildren()
{
return $this->children;
}
/**
* @param CSurvey[]|Collection $children
*
* @return CSurvey
*/
public function setChildren(Collection $children): self
{
$this->children = $children;
return $this;
}
public function getResourceIdentifier(): int
{
return $this->getIid();

@ -8,26 +8,81 @@ namespace Chamilo\CourseBundle\Repository;
use Chamilo\CoreBundle\Entity\Course;
use Chamilo\CoreBundle\Entity\Session;
use Chamilo\CoreBundle\Entity\User;
use Chamilo\CoreBundle\Repository\ResourceRepository;
use Chamilo\CoreBundle\Traits\Repository\ORM\NestedTreeRepositoryTrait;
use Chamilo\CourseBundle\Entity\CSurvey;
use Doctrine\ORM\QueryBuilder;
use Doctrine\Persistence\ManagerRegistry;
final class CSurveyRepository extends ResourceRepository
{
use NestedTreeRepositoryTrait;
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, CSurvey::class);
$this->initializeTreeRepository($this->getEntityManager(), $this->getClassMetadata());
}
public function findAllByCourse(
Course $course,
Session $session = null,
?string $title = null
?string $title = null,
?string $language = null,
?User $author = null
): QueryBuilder {
$qb = $this->getResourcesByCourse($course, $session);
$this->addTitleQueryBuilder($title, $qb);
$this->addLanguageQueryBuilder($language, $qb);
$this->addCreatorQueryBuilder($author, $qb);
return $qb;
}
public function getTreeByCourse(Course $course, Session $session = null): void
{
/*$qb = $this->getResourcesByCourse($course, $session);
$this->getEntityManager()->getConfiguration()->addCustomHydrationMode(
'tree',
TreeObjectHydrator::class
);
/*$options = ['decorate' => true, 'html' => false];
$tree = $this->buildTree($qb->getQuery()->getArrayResult(), $options);*/
//return $qb->getQuery()->setHint(Query::HINT_INCLUDE_META_COLUMNS, true)->getResult('tree');
}
protected function addTitleQueryBuilder(?string $title, QueryBuilder $qb = null): QueryBuilder
{
$qb = $this->getOrCreateQueryBuilder($qb);
if (null === $title) {
return $qb;
}
$qb
->andWhere('resource.code = :title')
->andWhere('node.title = :title')
->setParameter('title', $title)
;
return $qb;
}
private function addLanguageQueryBuilder(?string $language = null, QueryBuilder $qb = null): QueryBuilder
{
$qb = $this->getOrCreateQueryBuilder($qb);
if (null !== $language) {
$qb
->andWhere('resource.lang = :lang')
->setParameter('lang', $language)
;
}
return $qb;
}

Loading…
Cancel
Save