question.class.php 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Class Question
  5. *
  6. * This class allows to instantiate an object of type Question
  7. *
  8. * @author Olivier Brouckaert, original author
  9. * @author Patrick Cool, LaTeX support
  10. * @author Julio Montoya <gugli100@gmail.com> lot of bug fixes
  11. * @author hubert.borderiou@grenet.fr - add question categories
  12. * @package chamilo.exercise
  13. */
  14. abstract class Question
  15. {
  16. public $id;
  17. public $question;
  18. public $description;
  19. public $weighting;
  20. public $position;
  21. public $type;
  22. public $level;
  23. public $picture;
  24. public $exerciseList; // array with the list of exercises which this question is in
  25. public $category_list;
  26. public $parent_id;
  27. public $category;
  28. public $isContent;
  29. public $course;
  30. public static $typePicture = 'new_question.png';
  31. public static $explanationLangVar = '';
  32. public $question_table_class = 'table table-striped';
  33. public static $questionTypes = array(
  34. UNIQUE_ANSWER => array('unique_answer.class.php' , 'UniqueAnswer'),
  35. MULTIPLE_ANSWER => array('multiple_answer.class.php' , 'MultipleAnswer'),
  36. FILL_IN_BLANKS => array('fill_blanks.class.php' , 'FillBlanks'),
  37. MATCHING => array('matching.class.php' , 'Matching'),
  38. FREE_ANSWER => array('freeanswer.class.php' , 'FreeAnswer'),
  39. ORAL_EXPRESSION => array('oral_expression.class.php' , 'OralExpression'),
  40. HOT_SPOT => array('hotspot.class.php' , 'HotSpot'),
  41. HOT_SPOT_DELINEATION => array('hotspot.class.php' , 'HotspotDelineation'),
  42. MULTIPLE_ANSWER_COMBINATION => array('multiple_answer_combination.class.php', 'MultipleAnswerCombination'),
  43. UNIQUE_ANSWER_NO_OPTION => array('unique_answer_no_option.class.php', 'UniqueAnswerNoOption'),
  44. MULTIPLE_ANSWER_TRUE_FALSE => array('multiple_answer_true_false.class.php', 'MultipleAnswerTrueFalse'),
  45. MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE => array('multiple_answer_combination_true_false.class.php', 'MultipleAnswerCombinationTrueFalse'),
  46. GLOBAL_MULTIPLE_ANSWER => array('global_multiple_answer.class.php' , 'GlobalMultipleAnswer'),
  47. CALCULATED_ANSWER => array('calculated_answer.class.php' , 'CalculatedAnswer')
  48. //MEDIA_QUESTION => array('media_question.class.php' , 'MediaQuestion')
  49. );
  50. /**
  51. * constructor of the class
  52. *
  53. * @author Olivier Brouckaert
  54. */
  55. public function Question()
  56. {
  57. $this->id=0;
  58. $this->question='';
  59. $this->description='';
  60. $this->weighting=0;
  61. $this->position=1;
  62. $this->picture='';
  63. $this->level = 1;
  64. $this->category=0;
  65. // This variable is used when loading an exercise like an scenario with
  66. // an special hotspot: final_overlap, final_missing, final_excess
  67. $this->extra='';
  68. $this->exerciseList=array();
  69. $this->course = api_get_course_info();
  70. $this->category_list = array();
  71. $this->parent_id = 0;
  72. }
  73. public function getIsContent()
  74. {
  75. $isContent = null;
  76. if (isset($_REQUEST['isContent'])) {
  77. $isContent = intval($_REQUEST['isContent']);
  78. }
  79. return $this->isContent = $isContent;
  80. }
  81. /**
  82. * Reads question information from the data base
  83. *
  84. * @author Olivier Brouckaert
  85. * @param integer $id - question ID
  86. *
  87. * @return Question
  88. */
  89. static function read($id, $course_id = null)
  90. {
  91. $id = intval($id);
  92. if (!empty($course_id)) {
  93. $course_info = api_get_course_info_by_id($course_id);
  94. } else {
  95. $course_info = api_get_course_info();
  96. }
  97. $course_id = $course_info['real_id'];
  98. if (empty($course_id) || $course_id == -1 ) {
  99. return false;
  100. }
  101. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  102. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  103. $sql = "SELECT question,description,ponderation,position,type,picture,level,extra
  104. FROM $TBL_QUESTIONS WHERE c_id = $course_id AND id = $id ";
  105. $result = Database::query($sql);
  106. // if the question has been found
  107. if ($object = Database::fetch_object($result)) {
  108. $objQuestion = Question::getInstance($object->type);
  109. if (!empty($objQuestion)) {
  110. $objQuestion->id = $id;
  111. $objQuestion->question = $object->question;
  112. $objQuestion->description = $object->description;
  113. $objQuestion->weighting = $object->ponderation;
  114. $objQuestion->position = $object->position;
  115. $objQuestion->type = $object->type;
  116. $objQuestion->picture = $object->picture;
  117. $objQuestion->level = (int) $object->level;
  118. $objQuestion->extra = $object->extra;
  119. $objQuestion->course = $course_info;
  120. $objQuestion->category = Testcategory::getCategoryForQuestion($id);
  121. $sql = "SELECT exercice_id FROM $TBL_EXERCICE_QUESTION
  122. WHERE c_id = $course_id AND question_id = $id";
  123. $result_exercise_list = Database::query($sql);
  124. // fills the array with the exercises which this question is in
  125. if ($result_exercise_list) {
  126. while ($obj = Database::fetch_object($result_exercise_list)) {
  127. $objQuestion->exerciseList[] = $obj->exercice_id;
  128. }
  129. }
  130. return $objQuestion;
  131. }
  132. }
  133. // question not found
  134. return false;
  135. }
  136. /**
  137. * returns the question ID
  138. *
  139. * @author Olivier Brouckaert
  140. * @return - integer - question ID
  141. */
  142. public function selectId()
  143. {
  144. return $this->id;
  145. }
  146. /**
  147. * returns the question title
  148. *
  149. * @author Olivier Brouckaert
  150. * @return string - question title
  151. */
  152. public function selectTitle()
  153. {
  154. return $this->question;
  155. }
  156. /**
  157. * returns the question description
  158. *
  159. * @author Olivier Brouckaert
  160. * @return string - question description
  161. */
  162. public function selectDescription()
  163. {
  164. $this->description = text_filter($this->description);
  165. return $this->description;
  166. }
  167. /**
  168. * returns the question weighting
  169. *
  170. * @author Olivier Brouckaert
  171. * @return integer - question weighting
  172. */
  173. public function selectWeighting()
  174. {
  175. return $this->weighting;
  176. }
  177. /**
  178. * returns the question position
  179. *
  180. * @author Olivier Brouckaert
  181. * @return integer - question position
  182. */
  183. public function selectPosition()
  184. {
  185. return $this->position;
  186. }
  187. /**
  188. * returns the answer type
  189. *
  190. * @author Olivier Brouckaert
  191. * @return integer - answer type
  192. */
  193. public function selectType()
  194. {
  195. return $this->type;
  196. }
  197. /**
  198. * returns the level of the question
  199. *
  200. * @author Nicolas Raynaud
  201. * @return integer - level of the question, 0 by default.
  202. */
  203. function selectLevel()
  204. {
  205. return $this->level;
  206. }
  207. /**
  208. * returns the picture name
  209. *
  210. * @author Olivier Brouckaert
  211. * @return string - picture name
  212. */
  213. public function selectPicture()
  214. {
  215. return $this->picture;
  216. }
  217. /**
  218. * @return bool|string
  219. */
  220. public function selectPicturePath()
  221. {
  222. if (!empty($this->picture)) {
  223. return api_get_path(WEB_COURSE_PATH).$this->course['path'].'/document/images/'.$this->picture;
  224. }
  225. return false;
  226. }
  227. /**
  228. * returns the array with the exercise ID list
  229. *
  230. * @author Olivier Brouckaert
  231. * @return array - list of exercise ID which the question is in
  232. */
  233. public function selectExerciseList()
  234. {
  235. return $this->exerciseList;
  236. }
  237. /**
  238. * returns the number of exercises which this question is in
  239. *
  240. * @author Olivier Brouckaert
  241. * @return integer - number of exercises
  242. */
  243. public function selectNbrExercises() {
  244. return sizeof($this->exerciseList);
  245. }
  246. /**
  247. * changes the question title
  248. *
  249. * @author Olivier Brouckaert
  250. * @param string $title - question title
  251. */
  252. public function updateTitle($title)
  253. {
  254. $this->question=$title;
  255. }
  256. /**
  257. * @param int $id
  258. */
  259. public function updateParentId($id)
  260. {
  261. $this->parent_id = intval($id);
  262. }
  263. /**
  264. * changes the question description
  265. *
  266. * @author Olivier Brouckaert
  267. * @param string $description - question description
  268. */
  269. public function updateDescription($description)
  270. {
  271. $this->description=$description;
  272. }
  273. /**
  274. * changes the question weighting
  275. *
  276. * @author Olivier Brouckaert
  277. * @param integer $weighting - question weighting
  278. */
  279. public function updateWeighting($weighting)
  280. {
  281. $this->weighting=$weighting;
  282. }
  283. /**
  284. * @author Hubert Borderiou 12-10-2011
  285. * @param array of category $in_category
  286. */
  287. public function updateCategory($in_category)
  288. {
  289. $this->category=$in_category;
  290. }
  291. /**
  292. * @author Hubert Borderiou 12-10-2011
  293. * @param int $in_positive
  294. */
  295. public function updateScoreAlwaysPositive($in_positive)
  296. {
  297. $this->scoreAlwaysPositive=$in_positive;
  298. }
  299. /**
  300. * @author Hubert Borderiou 12-10-2011
  301. * @param int $in_positive
  302. */
  303. public function updateUncheckedMayScore($in_positive)
  304. {
  305. $this->uncheckedMayScore=$in_positive;
  306. }
  307. /**
  308. * Save category of a question
  309. *
  310. * A question can have n categories
  311. * if category is empty, then question has no category then delete the category entry
  312. *
  313. * @param - int $in_positive
  314. * @author Julio Montoya - Adding multiple cat support
  315. */
  316. public function saveCategories($category_list)
  317. {
  318. if (!empty($category_list)) {
  319. $this->deleteCategory();
  320. $TBL_QUESTION_REL_CATEGORY = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
  321. // update or add category for a question
  322. foreach ($category_list as $category_id) {
  323. $category_id = intval($category_id);
  324. $question_id = intval($this->id);
  325. $sql = "SELECT count(*) AS nb FROM $TBL_QUESTION_REL_CATEGORY
  326. WHERE category_id = $category_id AND question_id = $question_id AND c_id=".api_get_course_int_id();
  327. $res = Database::query($sql);
  328. $row = Database::fetch_array($res);
  329. if ($row['nb'] > 0) {
  330. //DO nothing
  331. //$sql = "UPDATE $TBL_QUESTION_REL_CATEGORY SET category_id = $category_id WHERE question_id=$question_id AND c_id=".api_get_course_int_id();
  332. //$res = Database::query($sql);
  333. } else {
  334. $sql = "INSERT INTO $TBL_QUESTION_REL_CATEGORY (c_id, question_id, category_id) VALUES (".api_get_course_int_id().", $question_id, $category_id)";
  335. Database::query($sql);
  336. }
  337. }
  338. }
  339. }
  340. /**
  341. * @author Hubert Borderiou 12-10-2011
  342. * @param int $in_category
  343. * in this version, a question can only have 1 category
  344. * if category is 0, then question has no category then delete the category entry
  345. */
  346. public function saveCategory($in_category)
  347. {
  348. if ($in_category <= 0) {
  349. $this->deleteCategory();
  350. } else {
  351. // update or add category for a question
  352. $TBL_QUESTION_REL_CATEGORY = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
  353. $category_id = intval($in_category);
  354. $question_id = intval($this->id);
  355. $sql = "SELECT count(*) AS nb FROM $TBL_QUESTION_REL_CATEGORY
  356. WHERE question_id=$question_id AND c_id=".api_get_course_int_id();
  357. $res = Database::query($sql);
  358. $row = Database::fetch_array($res);
  359. if ($row['nb'] > 0){
  360. $sql = "UPDATE $TBL_QUESTION_REL_CATEGORY SET category_id=$category_id WHERE question_id=$question_id AND c_id=".api_get_course_int_id();
  361. Database::query($sql);
  362. } else {
  363. $sql = "INSERT INTO $TBL_QUESTION_REL_CATEGORY VALUES (".api_get_course_int_id().", $question_id, $category_id)";
  364. Database::query($sql);
  365. }
  366. }
  367. }
  368. /**
  369. * @author hubert borderiou 12-10-2011
  370. * delete any category entry for question id
  371. * @param : none
  372. * delete the category for question
  373. */
  374. public function deleteCategory()
  375. {
  376. $TBL_QUESTION_REL_CATEGORY = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
  377. $question_id = intval($this->id);
  378. $sql = "DELETE FROM $TBL_QUESTION_REL_CATEGORY
  379. WHERE question_id=$question_id AND c_id=".api_get_course_int_id();
  380. Database::query($sql);
  381. }
  382. /**
  383. * changes the question position
  384. *
  385. * @author Olivier Brouckaert
  386. * @param integer $position - question position
  387. */
  388. public function updatePosition($position)
  389. {
  390. $this->position=$position;
  391. }
  392. /**
  393. * changes the question level
  394. *
  395. * @author Nicolas Raynaud
  396. * @param integer $level - question level
  397. */
  398. public function updateLevel($level)
  399. {
  400. $this->level=$level;
  401. }
  402. /**
  403. * changes the answer type. If the user changes the type from "unique answer" to "multiple answers"
  404. * (or conversely) answers are not deleted, otherwise yes
  405. *
  406. * @author Olivier Brouckaert
  407. * @param integer $type - answer type
  408. */
  409. public function updateType($type)
  410. {
  411. $TBL_REPONSES = Database::get_course_table(TABLE_QUIZ_ANSWER);
  412. $course_id = $this->course['real_id'];
  413. if (empty($course_id)) {
  414. $course_id = api_get_course_int_id();
  415. }
  416. // if we really change the type
  417. if ($type != $this->type) {
  418. // if we don't change from "unique answer" to "multiple answers" (or conversely)
  419. if (!in_array($this->type, array(UNIQUE_ANSWER,MULTIPLE_ANSWER)) || !in_array($type,array(UNIQUE_ANSWER,MULTIPLE_ANSWER))) {
  420. // removes old answers
  421. $sql = "DELETE FROM $TBL_REPONSES
  422. WHERE c_id = $course_id AND question_id = ".intval($this->id)."";
  423. Database::query($sql);
  424. }
  425. $this->type=$type;
  426. }
  427. }
  428. /**
  429. * adds a picture to the question
  430. *
  431. * @author Olivier Brouckaert
  432. * @param string $Picture - temporary path of the picture to upload
  433. * @param string $PictureName - Name of the picture
  434. * @return boolean - true if uploaded, otherwise false
  435. */
  436. public function uploadPicture($Picture, $PictureName, $picturePath = null)
  437. {
  438. if (empty($picturePath)) {
  439. global $picturePath;
  440. }
  441. if (!file_exists($picturePath)) {
  442. if (mkdir($picturePath, api_get_permissions_for_new_directories())) {
  443. // document path
  444. $documentPath = api_get_path(SYS_COURSE_PATH) . $this->course['path'] . "/document";
  445. $path = str_replace($documentPath,'',$picturePath);
  446. $title_path = basename($picturePath);
  447. $doc_id = add_document($this->course, $path, 'folder', 0,$title_path);
  448. api_item_property_update($this->course, TOOL_DOCUMENT, $doc_id, 'FolderCreated', api_get_user_id());
  449. }
  450. }
  451. // if the question has got an ID
  452. if ($this->id) {
  453. $extension = pathinfo($PictureName, PATHINFO_EXTENSION);
  454. $this->picture = 'quiz-'.$this->id.'.jpg';
  455. $o_img = new Image($Picture);
  456. $o_img->send_image($picturePath.'/'.$this->picture, -1, 'jpg');
  457. $document_id = add_document(
  458. $this->course,
  459. '/images/' . $this->picture, 'file',
  460. filesize($picturePath . '/' . $this->picture),
  461. $this->picture
  462. );
  463. if ($document_id) {
  464. return api_item_property_update($this->course, TOOL_DOCUMENT,
  465. $document_id, 'DocumentAdded', api_get_user_id());
  466. }
  467. }
  468. return false;
  469. }
  470. /**
  471. * Resizes a picture || Warning!: can only be called after uploadPicture, or if picture is already available in object.
  472. *
  473. * @author Toon Keppens
  474. * @param string $Dimension - Resizing happens proportional according to given dimension: height|width|any
  475. * @param integer $Max - Maximum size
  476. * @return boolean - true if success, false if failed
  477. */
  478. public function resizePicture($Dimension, $Max)
  479. {
  480. global $picturePath;
  481. // if the question has an ID
  482. if ($this->id) {
  483. // Get dimensions from current image.
  484. $my_image = new Image($picturePath.'/'.$this->picture);
  485. $current_image_size = $my_image->get_image_size();
  486. $current_width = $current_image_size['width'];
  487. $current_height = $current_image_size['height'];
  488. if($current_width < $Max && $current_height <$Max)
  489. return true;
  490. elseif($current_height == "")
  491. return false;
  492. // Resize according to height.
  493. if ($Dimension == "height") {
  494. $resize_scale = $current_height / $Max;
  495. $new_height = $Max;
  496. $new_width = ceil($current_width / $resize_scale);
  497. }
  498. // Resize according to width
  499. if ($Dimension == "width") {
  500. $resize_scale = $current_width / $Max;
  501. $new_width = $Max;
  502. $new_height = ceil($current_height / $resize_scale);
  503. }
  504. // Resize according to height or width, both should not be larger than $Max after resizing.
  505. if ($Dimension == "any") {
  506. if ($current_height > $current_width || $current_height == $current_width)
  507. {
  508. $resize_scale = $current_height / $Max;
  509. $new_height = $Max;
  510. $new_width = ceil($current_width / $resize_scale);
  511. }
  512. if ($current_height < $current_width)
  513. {
  514. $resize_scale = $current_width / $Max;
  515. $new_width = $Max;
  516. $new_height = ceil($current_height / $resize_scale);
  517. }
  518. }
  519. $my_image->resize($new_width, $new_height);
  520. $result = $my_image->send_image($picturePath.'/'.$this->picture);
  521. if ($result) {
  522. return true;
  523. } else {
  524. return false;
  525. }
  526. }
  527. }
  528. /**
  529. * deletes the picture
  530. *
  531. * @author Olivier Brouckaert
  532. * @return boolean - true if removed, otherwise false
  533. */
  534. public function removePicture()
  535. {
  536. global $picturePath;
  537. // if the question has got an ID and if the picture exists
  538. if($this->id) {
  539. $picture=$this->picture;
  540. $this->picture='';
  541. return @unlink($picturePath.'/'.$picture)?true:false;
  542. }
  543. return false;
  544. }
  545. /**
  546. * Exports a picture to another question
  547. *
  548. * @author Olivier Brouckaert
  549. * @param integer $questionId - ID of the target question
  550. * @return boolean - true if copied, otherwise false
  551. */
  552. public function exportPicture($questionId, $course_info)
  553. {
  554. $course_id = $course_info['real_id'];
  555. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  556. $destination_path = api_get_path(SYS_COURSE_PATH).$course_info['path'].'/document/images';
  557. $source_path = api_get_path(SYS_COURSE_PATH).$this->course['path'].'/document/images';
  558. // if the question has got an ID and if the picture exists
  559. if ($this->id && !empty($this->picture)) {
  560. $picture=explode('.',$this->picture);
  561. $extension = $picture[sizeof($picture)-1];
  562. $picture = 'quiz-'.$questionId.'.'.$extension;
  563. $result = @copy($source_path.'/'.$this->picture, $destination_path.'/'.$picture) ? true : false;
  564. //If copy was correct then add to the database
  565. if ($result) {
  566. $sql = "UPDATE $TBL_QUESTIONS SET picture='".Database::escape_string($picture)."'
  567. WHERE c_id = $course_id AND id='".intval($questionId)."'";
  568. Database::query($sql);
  569. $document_id = add_document($course_info, '/images/'.$picture, 'file', filesize($destination_path.'/'.$picture), $picture);
  570. if ($document_id) {
  571. return api_item_property_update($course_info, TOOL_DOCUMENT, $document_id, 'DocumentAdded', api_get_user_id());
  572. }
  573. }
  574. return $result;
  575. }
  576. return false;
  577. }
  578. /**
  579. * Saves the picture coming from POST into a temporary file
  580. * Temporary pictures are used when we don't want to save a picture right after a form submission.
  581. * For example, if we first show a confirmation box.
  582. *
  583. * @author Olivier Brouckaert
  584. * @param string $Picture - temporary path of the picture to move
  585. * @param string $PictureName - Name of the picture
  586. */
  587. public function setTmpPicture($Picture,$PictureName)
  588. {
  589. global $picturePath;
  590. $PictureName = explode('.',$PictureName);
  591. $Extension = $PictureName[sizeof($PictureName)-1];
  592. // saves the picture into a temporary file
  593. @move_uploaded_file($Picture,$picturePath.'/tmp.'.$Extension);
  594. }
  595. /**
  596. * Sets the title
  597. */
  598. public function setTitle($title)
  599. {
  600. $this->question = $title;
  601. }
  602. /**
  603. * Sets extra info
  604. */
  605. public function setExtra($extra)
  606. {
  607. $this->extra = $extra;
  608. }
  609. /**
  610. * Moves the temporary question "tmp" to "quiz-$questionId"
  611. * Temporary pictures are used when we don't want to save a picture right after a form submission.
  612. * For example, if we first show a confirmation box.
  613. *
  614. * @author Olivier Brouckaert
  615. * @return boolean - true if moved, otherwise false
  616. */
  617. function getTmpPicture() {
  618. global $picturePath;
  619. // if the question has got an ID and if the picture exists
  620. if ($this->id) {
  621. if (file_exists($picturePath.'/tmp.jpg')) {
  622. $Extension='jpg';
  623. } elseif(file_exists($picturePath.'/tmp.gif')) {
  624. $Extension='gif';
  625. } elseif(file_exists($picturePath.'/tmp.png')) {
  626. $Extension='png';
  627. }
  628. $this->picture='quiz-'.$this->id.'.'.$Extension;
  629. return @rename($picturePath.'/tmp.'.$Extension,$picturePath.'/'.$this->picture)?true:false;
  630. }
  631. return false;
  632. }
  633. /**
  634. * updates the question in the data base
  635. * if an exercise ID is provided, we add that exercise ID into the exercise list
  636. *
  637. * @author Olivier Brouckaert
  638. * @param integer $exerciseId - exercise ID if saving in an exercise
  639. */
  640. public function save($exerciseId = 0)
  641. {
  642. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  643. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  644. $id = $this->id;
  645. $question = $this->question;
  646. $description = $this->description;
  647. $weighting = $this->weighting;
  648. $position = $this->position;
  649. $type = $this->type;
  650. $picture = $this->picture;
  651. $level = $this->level;
  652. $extra = $this->extra;
  653. $c_id = $this->course['real_id'];
  654. $category = $this->category;
  655. // question already exists
  656. if(!empty($id)) {
  657. $sql="UPDATE $TBL_QUESTIONS SET
  658. question ='".Database::escape_string($question)."',
  659. description ='".Database::escape_string($description)."',
  660. ponderation ='".Database::escape_string($weighting)."',
  661. position ='".Database::escape_string($position)."',
  662. type ='".Database::escape_string($type)."',
  663. picture ='".Database::escape_string($picture)."',
  664. extra ='".Database::escape_string($extra)."',
  665. level ='".Database::escape_string($level)."'
  666. WHERE c_id = $c_id AND id = ".intval($id)."";
  667. Database::query($sql);
  668. $this->saveCategory($category);
  669. if (!empty($exerciseId)) {
  670. api_item_property_update($this->course, TOOL_QUIZ, $id,'QuizQuestionUpdated',api_get_user_id());
  671. }
  672. if (api_get_setting('search_enabled')=='true') {
  673. if ($exerciseId != 0) {
  674. $this -> search_engine_edit($exerciseId);
  675. } else {
  676. /**
  677. * actually there is *not* an user interface for
  678. * creating questions without a relation with an exercise
  679. */
  680. }
  681. }
  682. } else {
  683. // creates a new question
  684. $sql = "SELECT max(position) FROM $TBL_QUESTIONS as question, $TBL_EXERCICE_QUESTION as test_question
  685. WHERE question.id = test_question.question_id AND
  686. test_question.exercice_id = ".intval($exerciseId)." AND
  687. question.c_id = $c_id AND
  688. test_question.c_id = $c_id ";
  689. $result = Database::query($sql);
  690. $current_position = Database::result($result,0,0);
  691. $this->updatePosition($current_position+1);
  692. $position = $this->position;
  693. $sql = "INSERT INTO $TBL_QUESTIONS (c_id, question, description, ponderation, position, type, picture, extra, level) VALUES (
  694. $c_id,
  695. '".Database::escape_string($question)."',
  696. '".Database::escape_string($description)."',
  697. '".Database::escape_string($weighting)."',
  698. '".Database::escape_string($position)."',
  699. '".Database::escape_string($type)."',
  700. '".Database::escape_string($picture)."',
  701. '".Database::escape_string($extra)."',
  702. '".Database::escape_string($level)."'
  703. )";
  704. Database::query($sql);
  705. $this->id = Database::insert_id();
  706. api_item_property_update($this->course, TOOL_QUIZ, $this->id,'QuizQuestionAdded',api_get_user_id());
  707. // If hotspot, create first answer
  708. if ($type == HOT_SPOT || $type == HOT_SPOT_ORDER) {
  709. $TBL_ANSWERS = Database::get_course_table(TABLE_QUIZ_ANSWER);
  710. $sql = "INSERT INTO $TBL_ANSWERS (c_id, id, question_id , answer , correct , comment , ponderation , position , hotspot_coordinates , hotspot_type )
  711. VALUES (".$c_id.", '1', ".intval($this->id).", '', NULL , '', '10' , '1', '0;0|0|0', 'square')";
  712. Database::query($sql);
  713. }
  714. if ($type == HOT_SPOT_DELINEATION ) {
  715. $TBL_ANSWERS = Database::get_course_table(TABLE_QUIZ_ANSWER);
  716. $sql="INSERT INTO $TBL_ANSWERS (c_id, id, question_id , answer , correct , comment , ponderation , position , hotspot_coordinates , hotspot_type )
  717. VALUES (".$c_id.", '1', ".intval($this->id).", '', NULL , '', '10' , '1', '0;0|0|0', 'delineation')";
  718. Database::query($sql);
  719. }
  720. if (api_get_setting('search_enabled')=='true') {
  721. if ($exerciseId != 0) {
  722. $this -> search_engine_edit($exerciseId, TRUE);
  723. } else {
  724. /**
  725. * actually there is *not* an user interface for
  726. * creating questions without a relation with an exercise
  727. */
  728. }
  729. }
  730. }
  731. // if the question is created in an exercise
  732. if ($exerciseId) {
  733. /*
  734. $sql = 'UPDATE '.Database::get_course_table(TABLE_LP_ITEM).'
  735. SET max_score = '.intval($weighting).'
  736. WHERE item_type = "'.TOOL_QUIZ.'"
  737. AND path='.intval($exerciseId);
  738. Database::query($sql);
  739. */
  740. // adds the exercise into the exercise list of this question
  741. $this->addToList($exerciseId, TRUE);
  742. }
  743. }
  744. public function search_engine_edit($exerciseId, $addQs=false, $rmQs=false)
  745. {
  746. // update search engine and its values table if enabled
  747. if (api_get_setting('search_enabled')=='true' && extension_loaded('xapian')) {
  748. $course_id = api_get_course_id();
  749. // get search_did
  750. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  751. if ($addQs || $rmQs) {
  752. //there's only one row per question on normal db and one document per question on search engine db
  753. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_second_level=%s LIMIT 1';
  754. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  755. } else {
  756. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level=%s LIMIT 1';
  757. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $exerciseId, $this->id);
  758. }
  759. $res = Database::query($sql);
  760. if (Database::num_rows($res) > 0 || $addQs) {
  761. require_once(api_get_path(LIBRARY_PATH) . 'search/ChamiloIndexer.class.php');
  762. require_once(api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php');
  763. $di = new ChamiloIndexer();
  764. if ($addQs) {
  765. $question_exercises = array((int)$exerciseId);
  766. } else {
  767. $question_exercises = array();
  768. }
  769. isset($_POST['language'])? $lang=Database::escape_string($_POST['language']): $lang = 'english';
  770. $di->connectDb(NULL, NULL, $lang);
  771. // retrieve others exercise ids
  772. $se_ref = Database::fetch_array($res);
  773. $se_doc = $di->get_document((int)$se_ref['search_did']);
  774. if ($se_doc !== FALSE) {
  775. if ( ($se_doc_data=$di->get_document_data($se_doc)) !== FALSE ) {
  776. $se_doc_data = unserialize($se_doc_data);
  777. if (isset($se_doc_data[SE_DATA]['type']) && $se_doc_data[SE_DATA]['type'] == SE_DOCTYPE_EXERCISE_QUESTION) {
  778. if (isset($se_doc_data[SE_DATA]['exercise_ids']) && is_array($se_doc_data[SE_DATA]['exercise_ids'])) {
  779. foreach ($se_doc_data[SE_DATA]['exercise_ids'] as $old_value) {
  780. if (!in_array($old_value, $question_exercises)) {
  781. $question_exercises[] = $old_value;
  782. }
  783. }
  784. }
  785. }
  786. }
  787. }
  788. if ($rmQs) {
  789. while ( ($key=array_search($exerciseId, $question_exercises)) !== FALSE) {
  790. unset($question_exercises[$key]);
  791. }
  792. }
  793. // build the chunk to index
  794. $ic_slide = new IndexableChunk();
  795. $ic_slide->addValue("title", $this->question);
  796. $ic_slide->addCourseId($course_id);
  797. $ic_slide->addToolId(TOOL_QUIZ);
  798. $xapian_data = array(
  799. SE_COURSE_ID => $course_id,
  800. SE_TOOL_ID => TOOL_QUIZ,
  801. SE_DATA => array('type' => SE_DOCTYPE_EXERCISE_QUESTION, 'exercise_ids' => $question_exercises, 'question_id' => (int)$this->id),
  802. SE_USER => (int)api_get_user_id(),
  803. );
  804. $ic_slide->xapian_data = serialize($xapian_data);
  805. $ic_slide->addValue("content", $this->description);
  806. //TODO: index answers, see also form validation on question_admin.inc.php
  807. $di->remove_document((int)$se_ref['search_did']);
  808. $di->addChunk($ic_slide);
  809. //index and return search engine document id
  810. if (!empty($question_exercises)) { // if empty there is nothing to index
  811. $did = $di->index();
  812. unset($di);
  813. }
  814. if ($did || $rmQs) {
  815. // save it to db
  816. if ($addQs || $rmQs) {
  817. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_second_level=\'%s\'';
  818. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  819. } else {
  820. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=\'%s\' AND ref_id_second_level=\'%s\'';
  821. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $exerciseId, $this->id);
  822. }
  823. Database::query($sql);
  824. if ($rmQs) {
  825. if (!empty($question_exercises)) {
  826. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did)
  827. VALUES (NULL , \'%s\', \'%s\', %s, %s, %s)';
  828. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, array_shift($question_exercises), $this->id, $did);
  829. Database::query($sql);
  830. }
  831. } else {
  832. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, ref_id_second_level, search_did)
  833. VALUES (NULL , \'%s\', \'%s\', %s, %s, %s)';
  834. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $exerciseId, $this->id, $did);
  835. Database::query($sql);
  836. }
  837. }
  838. }
  839. }
  840. }
  841. /**
  842. * adds an exercise into the exercise list
  843. *
  844. * @author Olivier Brouckaert
  845. * @param integer $exerciseId - exercise ID
  846. * @param boolean $fromSave - comming from $this->save() or not
  847. */
  848. function addToList($exerciseId, $fromSave = false)
  849. {
  850. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  851. $id = $this->id;
  852. // checks if the exercise ID is not in the list
  853. if (!in_array($exerciseId,$this->exerciseList)) {
  854. $this->exerciseList[]=$exerciseId;
  855. $new_exercise = new Exercise();
  856. $new_exercise->read($exerciseId);
  857. $count = $new_exercise->selectNbrQuestions();
  858. $count++;
  859. $sql="INSERT INTO $TBL_EXERCICE_QUESTION (c_id, question_id, exercice_id, question_order) VALUES
  860. ({$this->course['real_id']}, ".intval($id).", ".intval($exerciseId).", '$count' )";
  861. Database::query($sql);
  862. // we do not want to reindex if we had just saved adnd indexed the question
  863. if (!$fromSave) {
  864. $this->search_engine_edit($exerciseId, TRUE);
  865. }
  866. }
  867. }
  868. /**
  869. * removes an exercise from the exercise list
  870. *
  871. * @author Olivier Brouckaert
  872. * @param integer $exerciseId - exercise ID
  873. * @return boolean - true if removed, otherwise false
  874. */
  875. function removeFromList($exerciseId)
  876. {
  877. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  878. $id = $this->id;
  879. // searches the position of the exercise ID in the list
  880. $pos=array_search($exerciseId,$this->exerciseList);
  881. $course_id = api_get_course_int_id();
  882. // exercise not found
  883. if($pos === false) {
  884. return false;
  885. } else {
  886. // deletes the position in the array containing the wanted exercise ID
  887. unset($this->exerciseList[$pos]);
  888. //update order of other elements
  889. $sql = "SELECT question_order FROM $TBL_EXERCICE_QUESTION
  890. WHERE c_id = $course_id AND question_id = ".intval($id)." AND exercice_id = ".intval($exerciseId)."";
  891. $res = Database::query($sql);
  892. if (Database::num_rows($res)>0) {
  893. $row = Database::fetch_array($res);
  894. if (!empty($row['question_order'])) {
  895. $sql = "UPDATE $TBL_EXERCICE_QUESTION SET question_order = question_order-1
  896. WHERE c_id = $course_id AND exercice_id = ".intval($exerciseId)." AND question_order > ".$row['question_order'];
  897. $res = Database::query($sql);
  898. }
  899. }
  900. $sql = "DELETE FROM $TBL_EXERCICE_QUESTION
  901. WHERE c_id = $course_id AND question_id = ".intval($id)." AND exercice_id = ".intval($exerciseId)."";
  902. Database::query($sql);
  903. return true;
  904. }
  905. }
  906. /**
  907. * Deletes a question from the database
  908. * the parameter tells if the question is removed from all exercises (value = 0),
  909. * or just from one exercise (value = exercise ID)
  910. *
  911. * @author Olivier Brouckaert
  912. * @param integer $deleteFromEx - exercise ID if the question is only removed from one exercise
  913. */
  914. function delete($deleteFromEx = 0)
  915. {
  916. $course_id = api_get_course_int_id();
  917. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  918. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  919. $TBL_REPONSES = Database::get_course_table(TABLE_QUIZ_ANSWER);
  920. $TBL_QUIZ_QUESTION_REL_CATEGORY = Database::get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
  921. $id = $this->id;
  922. // if the question must be removed from all exercises
  923. if (!$deleteFromEx) {
  924. //update the question_order of each question to avoid inconsistencies
  925. $sql = "SELECT exercice_id, question_order FROM $TBL_EXERCICE_QUESTION
  926. WHERE c_id = $course_id AND question_id = ".intval($id)."";
  927. $res = Database::query($sql);
  928. if (Database::num_rows($res) > 0) {
  929. while ($row = Database::fetch_array($res)) {
  930. if (!empty($row['question_order'])) {
  931. $sql = "UPDATE $TBL_EXERCICE_QUESTION
  932. SET question_order = question_order-1
  933. WHERE c_id = $course_id AND exercice_id = ".intval($row['exercice_id'])." AND question_order > ".$row['question_order'];
  934. Database::query($sql);
  935. }
  936. }
  937. }
  938. $sql = "DELETE FROM $TBL_EXERCICE_QUESTION WHERE c_id = $course_id AND question_id = ".intval($id)."";
  939. Database::query($sql);
  940. $sql = "DELETE FROM $TBL_QUESTIONS WHERE c_id = $course_id AND id = ".intval($id)."";
  941. Database::query($sql);
  942. $sql = "DELETE FROM $TBL_REPONSES WHERE c_id = $course_id AND question_id = ".intval($id)."";
  943. Database::query($sql);
  944. // remove the category of this question in the question_rel_category table
  945. $sql = "DELETE FROM $TBL_QUIZ_QUESTION_REL_CATEGORY
  946. WHERE c_id = $course_id AND question_id = ".intval($id)." AND c_id=".api_get_course_int_id();
  947. Database::query($sql);
  948. api_item_property_update($this->course, TOOL_QUIZ, $id,'QuizQuestionDeleted',api_get_user_id());
  949. $this->removePicture();
  950. // resets the object
  951. $this->Question();
  952. } else {
  953. // just removes the exercise from the list
  954. $this->removeFromList($deleteFromEx);
  955. if (api_get_setting('search_enabled')=='true' && extension_loaded('xapian')) {
  956. // disassociate question with this exercise
  957. $this -> search_engine_edit($deleteFromEx, FALSE, TRUE);
  958. }
  959. api_item_property_update($this->course, TOOL_QUIZ, $id,'QuizQuestionDeleted',api_get_user_id());
  960. }
  961. }
  962. /**
  963. * Duplicates the question
  964. *
  965. * @author Olivier Brouckaert
  966. * @param array Course info of the destination course
  967. * @return int ID of the new question
  968. */
  969. public function duplicate($course_info = null)
  970. {
  971. if (empty($course_info)) {
  972. $course_info = $this->course;
  973. } else {
  974. $course_info = $course_info;
  975. }
  976. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  977. $TBL_QUESTION_OPTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
  978. $question = $this->question;
  979. $description = $this->description;
  980. $weighting = $this->weighting;
  981. $position = $this->position;
  982. $type = $this->type;
  983. $level = intval($this->level);
  984. $extra = $this->extra;
  985. //Using the same method used in the course copy to transform URLs
  986. if ($this->course['id'] != $course_info['id']) {
  987. $description = DocumentManager::replace_urls_inside_content_html_from_copy_course($description, $this->course['id'], $course_info['id']);
  988. $question = DocumentManager::replace_urls_inside_content_html_from_copy_course($question, $this->course['id'], $course_info['id']);
  989. }
  990. $course_id = $course_info['real_id'];
  991. //Read the source options
  992. $options = self::readQuestionOption($this->id, $this->course['real_id']);
  993. //Inserting in the new course db / or the same course db
  994. $sql = "INSERT INTO $TBL_QUESTIONS (c_id, question, description, ponderation, position, type, level, extra )
  995. VALUES('$course_id', '".Database::escape_string($question)."','".Database::escape_string($description)."','".Database::escape_string($weighting)."','".Database::escape_string($position)."','".Database::escape_string($type)."' ,'".Database::escape_string($level)."' ,'".Database::escape_string($extra)."' )";
  996. Database::query($sql);
  997. $new_question_id = Database::insert_id();
  998. if (!empty($options)) {
  999. //Saving the quiz_options
  1000. foreach ($options as $item) {
  1001. $item['question_id'] = $new_question_id;
  1002. $item['c_id'] = $course_id;
  1003. unset($item['id']);
  1004. Database::insert($TBL_QUESTION_OPTIONS, $item);
  1005. }
  1006. }
  1007. // Duplicates the picture of the hotspot
  1008. $this->exportPicture($new_question_id, $course_info);
  1009. return $new_question_id;
  1010. }
  1011. public function get_question_type_name()
  1012. {
  1013. $key = self::$questionTypes[$this->type];
  1014. return get_lang($key[1]);
  1015. }
  1016. public static function get_question_type($type)
  1017. {
  1018. if ($type == ORAL_EXPRESSION && api_get_setting('enable_nanogong') != 'true') {
  1019. return null;
  1020. }
  1021. return self::$questionTypes[$type];
  1022. }
  1023. public static function get_question_type_list()
  1024. {
  1025. if (api_get_setting('enable_nanogong') != 'true') {
  1026. self::$questionTypes[ORAL_EXPRESSION] = null;
  1027. unset(self::$questionTypes[ORAL_EXPRESSION]);
  1028. }
  1029. return self::$questionTypes;
  1030. }
  1031. /**
  1032. * Returns an instance of the class corresponding to the type
  1033. * @param integer $type the type of the question
  1034. * @return an instance of a Question subclass (or of Questionc class by default)
  1035. */
  1036. public static function getInstance($type)
  1037. {
  1038. if (!is_null($type)) {
  1039. list($file_name, $class_name) = self::get_question_type($type);
  1040. if (!empty($file_name)) {
  1041. include_once $file_name;
  1042. if (class_exists($class_name)) {
  1043. return new $class_name();
  1044. } else {
  1045. echo 'Can\'t instanciate class '.$class_name.' of type '.$type;
  1046. }
  1047. }
  1048. }
  1049. return null;
  1050. }
  1051. /**
  1052. * Creates the form to create / edit a question
  1053. * A subclass can redefine this function to add fields...
  1054. * @param FormValidator $form
  1055. */
  1056. public function createForm(&$form, $fck_config=0)
  1057. {
  1058. echo '<style>
  1059. .media { display:none;}
  1060. </style>';
  1061. echo '<script>
  1062. // hack to hide http://cksource.com/forums/viewtopic.php?f=6&t=8700
  1063. function FCKeditor_OnComplete( editorInstance ) {
  1064. if (document.getElementById ( \'HiddenFCK\' + editorInstance.Name )) {
  1065. HideFCKEditorByInstanceName (editorInstance.Name);
  1066. }
  1067. }
  1068. function HideFCKEditorByInstanceName ( editorInstanceName ) {
  1069. if (document.getElementById ( \'HiddenFCK\' + editorInstanceName ).className == "HideFCKEditor" ) {
  1070. document.getElementById ( \'HiddenFCK\' + editorInstanceName ).className = "media";
  1071. }
  1072. }
  1073. function show_media(){
  1074. var my_display = document.getElementById(\'HiddenFCKquestionDescription\').style.display;
  1075. if(my_display== \'none\' || my_display == \'\') {
  1076. document.getElementById(\'HiddenFCKquestionDescription\').style.display = \'block\';
  1077. document.getElementById(\'media_icon\').innerHTML=\'&nbsp;<img style="vertical-align: middle;" src="../img/looknfeelna.png" alt="" />&nbsp;'.get_lang('EnrichQuestion').'\';
  1078. } else {
  1079. document.getElementById(\'HiddenFCKquestionDescription\').style.display = \'none\';
  1080. document.getElementById(\'media_icon\').innerHTML=\'&nbsp;<img style="vertical-align: middle;" src="../img/looknfeel.png" alt="" />&nbsp;'.get_lang('EnrichQuestion').'\';
  1081. }
  1082. }
  1083. // hub 13-12-2010
  1084. function visiblerDevisibler(in_id) {
  1085. if (document.getElementById(in_id)) {
  1086. if (document.getElementById(in_id).style.display == "none") {
  1087. document.getElementById(in_id).style.display = "block";
  1088. if (document.getElementById(in_id+"Img")) {
  1089. document.getElementById(in_id+"Img").src = "../img/div_hide.gif";
  1090. }
  1091. }
  1092. else {
  1093. document.getElementById(in_id).style.display = "none";
  1094. if (document.getElementById(in_id+"Img")) {
  1095. document.getElementById(in_id+"Img").src = "../img/div_show.gif";
  1096. }
  1097. }
  1098. }
  1099. }
  1100. </script>';
  1101. // question name
  1102. $form->addElement('text', 'questionName', get_lang('Question'), array('class' => 'span6'));
  1103. $form->addRule('questionName', get_lang('GiveQuestion'), 'required');
  1104. // default content
  1105. $isContent = isset($_REQUEST['isContent']) ? intval($_REQUEST['isContent']) : null;
  1106. // Question type
  1107. $answerType = isset($_REQUEST['answerType']) ? intval($_REQUEST['answerType']) : null;
  1108. $form->addElement('hidden','answerType', $answerType);
  1109. // html editor
  1110. $editor_config = array('ToolbarSet' => 'TestQuestionDescription', 'Width' => '100%', 'Height' => '150');
  1111. if (is_array($fck_config)){
  1112. $editor_config = array_merge($editor_config, $fck_config);
  1113. }
  1114. if (!api_is_allowed_to_edit(null,true)) {
  1115. $editor_config['UserStatus'] = 'student';
  1116. }
  1117. $form->addElement('advanced_settings','
  1118. <a href="javascript://" onclick=" return show_media()"><span id="media_icon"><img style="vertical-align: middle;" src="../img/looknfeel.png" alt="" />&nbsp;'.get_lang('EnrichQuestion').'</span></a>
  1119. ');
  1120. $form->addElement ('html','<div class="HideFCKEditor" id="HiddenFCKquestionDescription" >');
  1121. $form->addHtmlEditor('questionDescription', get_lang('QuestionDescription'), false, false, $editor_config);
  1122. $form->addElement ('html','</div>');
  1123. // hidden values
  1124. $my_id = isset($_REQUEST['myid']) ? intval($_REQUEST['myid']) : null;
  1125. $form->addElement('hidden', 'myid', $my_id);
  1126. if ($this->type != MEDIA_QUESTION) {
  1127. // Advanced parameters
  1128. $form->addElement('advanced_settings','<a href="javascript:void(0)" onclick="visiblerDevisibler(\'id_advancedOption\')"><img id="id_advancedOptionImg" style="vertical-align:middle;" src="../img/div_show.gif" alt="" />&nbsp;'.get_lang("AdvancedParameters").'</a>');
  1129. $form->addElement('html','<div id="id_advancedOption" style="display:none;">');
  1130. $select_level = Question::get_default_levels();
  1131. $form->addElement('select', 'questionLevel', get_lang('Difficulty'), $select_level);
  1132. // Categories
  1133. //$category_list = Testcategory::getCategoriesIdAndName();
  1134. //$form->addElement('select', 'questionCategory', get_lang('Category'), $category_list, array('multiple' => 'multiple'));
  1135. // Categories
  1136. $tabCat = Testcategory::getCategoriesIdAndName();
  1137. $form->addElement('select', 'questionCategory', get_lang('Category'), $tabCat);
  1138. if (in_array($this->type, array(UNIQUE_ANSWER, MULTIPLE_ANSWER))) {
  1139. $buttonValue = $this->type == UNIQUE_ANSWER ? 'ConvertToMultipleAnswer' : 'ConvertToUniqueAnswer';
  1140. $form->addElement('button', 'convertAnswer', get_lang($buttonValue));
  1141. }
  1142. //Medias
  1143. //$course_medias = Question::prepare_course_media_select(api_get_course_int_id());
  1144. //$form->addElement('select', 'parent_id', get_lang('AttachToMedia'), $course_medias);
  1145. $form->addElement('html','</div>');
  1146. }
  1147. if (!isset($_GET['fromExercise'])) {
  1148. switch ($answerType) {
  1149. case 1:
  1150. $this->question = get_lang('DefaultUniqueQuestion');
  1151. break;
  1152. case 2:
  1153. $this->question = get_lang('DefaultMultipleQuestion');
  1154. break;
  1155. case 3:
  1156. $this->question = get_lang('DefaultFillBlankQuestion');
  1157. break;
  1158. case 4:
  1159. $this->question = get_lang('DefaultMathingQuestion');
  1160. break;
  1161. case 5:
  1162. $this->question = get_lang('DefaultOpenQuestion');
  1163. break;
  1164. case 9:
  1165. $this->question = get_lang('DefaultMultipleQuestion');
  1166. break;
  1167. }
  1168. }
  1169. // default values
  1170. $defaults = array();
  1171. $defaults['questionName'] = $this -> question;
  1172. $defaults['questionDescription'] = $this -> description;
  1173. $defaults['questionLevel'] = $this -> level;
  1174. $defaults['questionCategory'] = $this->category;
  1175. //$defaults['questionCategory'] = $this->category_list;
  1176. //$defaults['parent_id'] = $this->parent_id;
  1177. //Came from he question pool
  1178. if (isset($_GET['fromExercise'])) {
  1179. $form->setDefaults($defaults);
  1180. }
  1181. if (!empty($_REQUEST['myid'])) {
  1182. $form->setDefaults($defaults);
  1183. } else {
  1184. if ($isContent == 1) {
  1185. $form->setDefaults($defaults);
  1186. }
  1187. }
  1188. }
  1189. /**
  1190. * function which process the creation of questions
  1191. * @param FormValidator $form
  1192. * @param Exercise $objExercise
  1193. */
  1194. public function processCreation ($form, $objExercise = null)
  1195. {
  1196. //$this->updateParentId($form->getSubmitValue('parent_id'));
  1197. $this->updateTitle($form->getSubmitValue('questionName'));
  1198. $this->updateDescription($form->getSubmitValue('questionDescription'));
  1199. $this->updateLevel($form->getSubmitValue('questionLevel'));
  1200. $this->updateCategory($form->getSubmitValue('questionCategory'));
  1201. //Save normal question if NOT media
  1202. if ($this->type != MEDIA_QUESTION) {
  1203. $this->save($objExercise->id);
  1204. // modify the exercise
  1205. $objExercise->addToList($this->id);
  1206. $objExercise->update_question_positions();
  1207. }
  1208. }
  1209. /**
  1210. * abstract function which creates the form to create / edit the answers of the question
  1211. * @param the formvalidator instance
  1212. */
  1213. abstract function createAnswersForm ($form);
  1214. /**
  1215. * abstract function which process the creation of answers
  1216. * @param the formvalidator instance
  1217. */
  1218. abstract function processAnswersCreation ($form);
  1219. /**
  1220. * Displays the menu of question types
  1221. */
  1222. public static function display_type_menu($objExercise)
  1223. {
  1224. $feedback_type = $objExercise->feedback_type;
  1225. $exerciseId = $objExercise->id;
  1226. // 1. by default we show all the question types
  1227. $question_type_custom_list = self::get_question_type_list();
  1228. if (!isset($feedback_type)) {
  1229. $feedback_type = 0;
  1230. }
  1231. if ($feedback_type == 1) {
  1232. //2. but if it is a feedback DIRECT we only show the UNIQUE_ANSWER type that is currently available
  1233. $question_type_custom_list = array (
  1234. UNIQUE_ANSWER => self::$questionTypes[UNIQUE_ANSWER],
  1235. HOT_SPOT_DELINEATION => self::$questionTypes[HOT_SPOT_DELINEATION]
  1236. );
  1237. } else {
  1238. unset($question_type_custom_list[HOT_SPOT_DELINEATION]);
  1239. }
  1240. echo '<div class="actionsbig">';
  1241. echo '<ul class="question_menu">';
  1242. foreach ($question_type_custom_list as $i => $a_type) {
  1243. // include the class of the type
  1244. require_once $a_type[0];
  1245. // get the picture of the type and the langvar which describes it
  1246. $img = $explanation = '';
  1247. eval('$img = '.$a_type[1].'::$typePicture;');
  1248. eval('$explanation = get_lang('.$a_type[1].'::$explanationLangVar);');
  1249. echo '<li>';
  1250. echo '<div class="icon_image_content">';
  1251. if ($objExercise->exercise_was_added_in_lp == true) {
  1252. $img = pathinfo($img);
  1253. $img = $img['filename'].'_na.'.$img['extension'];
  1254. echo Display::return_icon($img, $explanation, null, ICON_SIZE_BIG);
  1255. } else {
  1256. echo '<a href="admin.php?'.api_get_cidreq().'&newQuestion=yes&answerType='.$i.'">'.Display::return_icon($img, $explanation, null, ICON_SIZE_BIG).'</a>';
  1257. }
  1258. echo '</div>';
  1259. echo '</li>';
  1260. }
  1261. echo '<li>';
  1262. echo '<div class="icon_image_content">';
  1263. if ($objExercise->exercise_was_added_in_lp == true) {
  1264. echo Display::return_icon('database_na.png', get_lang('GetExistingQuestion'), null, ICON_SIZE_BIG);
  1265. } else {
  1266. if ($feedback_type==1) {
  1267. echo $url = '<a href="question_pool.php?'.api_get_cidreq().'&type=1&fromExercise='.$exerciseId.'">';
  1268. } else {
  1269. echo $url = '<a href="question_pool.php?'.api_get_cidreq().'&fromExercise='.$exerciseId.'">';
  1270. }
  1271. echo Display::return_icon('database.png', get_lang('GetExistingQuestion'), null, ICON_SIZE_BIG);
  1272. }
  1273. echo '</a>';
  1274. echo '</div></li>';
  1275. echo '</ul>';
  1276. echo '</div>';
  1277. }
  1278. static function saveQuestionOption($question_id, $name, $course_id, $position = 0) {
  1279. $TBL_EXERCICE_QUESTION_OPTION = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
  1280. $params['question_id'] = intval($question_id);
  1281. $params['name'] = $name;
  1282. $params['position'] = $position;
  1283. $params['c_id'] = $course_id;
  1284. $result = self::readQuestionOption($question_id, $course_id);
  1285. $last_id = Database::insert($TBL_EXERCICE_QUESTION_OPTION, $params);
  1286. return $last_id;
  1287. }
  1288. static function deleteAllQuestionOptions($question_id, $course_id) {
  1289. $TBL_EXERCICE_QUESTION_OPTION = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
  1290. Database::delete($TBL_EXERCICE_QUESTION_OPTION, array('c_id = ? AND question_id = ?'=> array($course_id, $question_id)));
  1291. }
  1292. static function updateQuestionOption($id, $params, $course_id) {
  1293. $TBL_EXERCICE_QUESTION_OPTION = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
  1294. $result = Database::update($TBL_EXERCICE_QUESTION_OPTION, $params, array('c_id = ? AND id = ?'=>array($course_id, $id)));
  1295. return $result;
  1296. }
  1297. static function readQuestionOption($question_id, $course_id) {
  1298. $TBL_EXERCICE_QUESTION_OPTION = Database::get_course_table(TABLE_QUIZ_QUESTION_OPTION);
  1299. $result = Database::select('*', $TBL_EXERCICE_QUESTION_OPTION, array('where'=>array('c_id = ? AND question_id = ?' =>array($course_id, $question_id)), 'order'=>'id ASC'));
  1300. return $result;
  1301. }
  1302. /**
  1303. * Shows question title an description
  1304. *
  1305. * @param string $feedback_type
  1306. * @param int $counter
  1307. * @param float $score
  1308. */
  1309. function return_header($feedback_type = null, $counter = null, $score = null)
  1310. {
  1311. $counter_label = '';
  1312. if (!empty($counter)) {
  1313. $counter_label = intval($counter);
  1314. }
  1315. $score_label = get_lang('Wrong');
  1316. $class = 'error';
  1317. if ($score['pass'] == true) {
  1318. $score_label = get_lang('Correct');
  1319. $class = 'success';
  1320. }
  1321. if ($this->type == FREE_ANSWER || $this->type == ORAL_EXPRESSION) {
  1322. $score['revised'] = isset($score['revised']) ? $score['revised'] : false;
  1323. if ($score['revised'] == true) {
  1324. $score_label = get_lang('Revised');
  1325. $class = '';
  1326. } else {
  1327. $score_label = get_lang('NotRevised');
  1328. $class = 'error';
  1329. }
  1330. }
  1331. $question_title = $this->question;
  1332. // display question category, if any
  1333. $header = Testcategory::returnCategoryAndTitle($this->id);
  1334. $show_media = null;
  1335. if ($show_media) {
  1336. $header .= $this->show_media_content();
  1337. }
  1338. $header .= Display::page_subheader2($counter_label.". ".$question_title);
  1339. $header .= Display::div('<div class="rib rib-'.$class.'"><h3>'.$score_label.'</h3></div> <h4>'.$score['result'].' </h4>', array('class'=>'ribbon'));
  1340. $header .= Display::div($this->description, array('id'=>'question_description'));
  1341. return $header;
  1342. }
  1343. /**
  1344. * Create a question from a set of parameters
  1345. * @param int Quiz ID
  1346. * @param string Question name
  1347. * @param int Maximum result for the question
  1348. * @param int Type of question (see constants at beginning of question.class.php)
  1349. * @param int Question level/category
  1350. */
  1351. public function create_question(
  1352. $quiz_id,
  1353. $question_name,
  1354. $question_description = "" ,
  1355. $max_score = 0,
  1356. $type = 1,
  1357. $level = 1
  1358. ) {
  1359. $course_id = api_get_course_int_id();
  1360. $tbl_quiz_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1361. $tbl_quiz_rel_question = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  1362. $quiz_id = intval($quiz_id);
  1363. $max_score = (float) $max_score;
  1364. $type = intval($type);
  1365. $level = intval($level);
  1366. // Get the max position
  1367. $sql = "SELECT max(position) as max_position"
  1368. ." FROM $tbl_quiz_question q INNER JOIN $tbl_quiz_rel_question r"
  1369. ." ON q.id = r.question_id"
  1370. ." AND exercice_id = $quiz_id AND q.c_id = $course_id AND r.c_id = $course_id";
  1371. $rs_max = Database::query($sql);
  1372. $row_max = Database::fetch_object($rs_max);
  1373. $max_position = $row_max->max_position +1;
  1374. // Insert the new question
  1375. $sql = "INSERT INTO $tbl_quiz_question (c_id, question, description, ponderation, position, type, level)
  1376. VALUES ($course_id, '".Database::escape_string($question_name)."', '".Database::escape_string($question_description)."', '$max_score', $max_position, $type, $level)";
  1377. Database::query($sql);
  1378. // Get the question ID
  1379. $question_id = Database::get_last_insert_id();
  1380. // Get the max question_order
  1381. $sql = "SELECT max(question_order) as max_order "
  1382. ."FROM $tbl_quiz_rel_question WHERE c_id = $course_id AND exercice_id = $quiz_id ";
  1383. $rs_max_order = Database::query($sql);
  1384. $row_max_order = Database::fetch_object($rs_max_order);
  1385. $max_order = $row_max_order->max_order + 1;
  1386. // Attach questions to quiz
  1387. $sql = "INSERT INTO $tbl_quiz_rel_question "
  1388. ."(c_id, question_id,exercice_id,question_order)"
  1389. ." VALUES($course_id, $question_id, $quiz_id, $max_order)";
  1390. Database::query($sql);
  1391. return $question_id;
  1392. }
  1393. /**
  1394. * @return array the image filename of the question type
  1395. */
  1396. public function get_type_icon_html()
  1397. {
  1398. $type = $this->selectType();
  1399. $tabQuestionList = Question::get_question_type_list(); // [0]=file to include [1]=type name
  1400. require_once $tabQuestionList[$type][0];
  1401. eval('$img = '.$tabQuestionList[$type][1].'::$typePicture;');
  1402. eval('$explanation = get_lang('.$tabQuestionList[$type][1].'::$explanationLangVar);');
  1403. return array($img, $explanation);
  1404. }
  1405. /**
  1406. * Get course medias
  1407. * @param int course id
  1408. */
  1409. static function get_course_medias($course_id, $start = 0, $limit = 100, $sidx = "question", $sord = "ASC", $where_condition = array())
  1410. {
  1411. $table_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1412. $default_where = array('c_id = ? AND parent_id = 0 AND type = ?' => array($course_id, MEDIA_QUESTION));
  1413. $result = Database::select('*', $table_question,
  1414. array(
  1415. 'limit' => " $start, $limit",
  1416. 'where' => $default_where,
  1417. 'order' => "$sidx $sord")
  1418. );
  1419. return $result;
  1420. }
  1421. /**
  1422. * Get count course medias
  1423. * @param int course id
  1424. *
  1425. * @return int
  1426. */
  1427. static function get_count_course_medias($course_id)
  1428. {
  1429. $table_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1430. $result = Database::select(
  1431. 'count(*) as count',
  1432. $table_question,
  1433. array('where'=>array('c_id = ? AND parent_id = 0 AND type = ?' => array($course_id, MEDIA_QUESTION))),
  1434. 'first'
  1435. );
  1436. if ($result && isset($result['count'])) {
  1437. return $result['count'];
  1438. }
  1439. return 0;
  1440. }
  1441. /**
  1442. * @param int $course_id
  1443. * @return array
  1444. */
  1445. public static function prepare_course_media_select($course_id)
  1446. {
  1447. $medias = self::get_course_medias($course_id);
  1448. $media_list = array();
  1449. $media_list[0] = get_lang('NoMedia');
  1450. if (!empty($medias)) {
  1451. foreach($medias as $media) {
  1452. $media_list[$media['id']] = empty($media['question']) ? get_lang('Untitled') : $media['question'];
  1453. }
  1454. }
  1455. return $media_list;
  1456. }
  1457. /**
  1458. * @return array
  1459. */
  1460. public static function get_default_levels()
  1461. {
  1462. $select_level = array(
  1463. 1 => 1,
  1464. 2 => 2,
  1465. 3 => 3,
  1466. 4 => 4,
  1467. 5 => 5
  1468. );
  1469. return $select_level;
  1470. }
  1471. /**
  1472. * @return null|string
  1473. */
  1474. public function show_media_content()
  1475. {
  1476. $html = null;
  1477. if ($this->parent_id != 0) {
  1478. $parent_question = Question::read($this->parent_id);
  1479. $html = $parent_question->show_media_content();
  1480. } else {
  1481. $html .= Display::page_subheader($this->selectTitle());
  1482. $html .= $this->selectDescription();
  1483. }
  1484. return $html;
  1485. }
  1486. /**
  1487. * Swap between unique and multiple type answers
  1488. * @return object
  1489. */
  1490. public function swapSimpleAnswerTypes()
  1491. {
  1492. $oppositeAnswers = array(
  1493. UNIQUE_ANSWER => MULTIPLE_ANSWER,
  1494. MULTIPLE_ANSWER => UNIQUE_ANSWER
  1495. );
  1496. $this->type = $oppositeAnswers[$this->type];
  1497. Database::update(
  1498. Database::get_course_table(TABLE_QUIZ_QUESTION),
  1499. array('type' => $this->type),
  1500. array('c_id = ? AND id = ?' => array($this->course['real_id'], $this->id))
  1501. );
  1502. $answerClasses = array(
  1503. UNIQUE_ANSWER => 'UniqueAnswer',
  1504. MULTIPLE_ANSWER => 'MultipleAnswer'
  1505. );
  1506. $swappedAnswer = new $answerClasses[$this->type];
  1507. foreach ($this as $key => $value) {
  1508. $swappedAnswer->$key = $value;
  1509. }
  1510. return $swappedAnswer;
  1511. }
  1512. }