exercise.class.php 149 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Exercise class: This class allows to instantiate an object of type Exercise
  5. * @package chamilo.exercise
  6. * @author Olivier Brouckaert
  7. * @author Julio Montoya Cleaning exercises
  8. * @version $Id: exercise.class.php 22046 2009-07-14 01:45:19Z ivantcholakov $
  9. */
  10. define('ALL_ON_ONE_PAGE', 1);
  11. define('ONE_PER_PAGE', 2);
  12. //0=>Feedback , 1=>DirectFeedback, 2=>NoFeedback
  13. define('EXERCISE_FEEDBACK_TYPE_END', 0);
  14. define('EXERCISE_FEEDBACK_TYPE_DIRECT', 1);
  15. define('EXERCISE_FEEDBACK_TYPE_EXAM', 2);
  16. define('EXERCISE_MAX_NAME_BREADCRUMB', 60);
  17. $debug = 0; //All exercise scripts should depend in this debug variable
  18. require_once dirname(__FILE__).'/../inc/lib/exercise_show_functions.lib.php';
  19. if(!class_exists('Exercise')):
  20. class Exercise {
  21. public $id;
  22. public $exercise;
  23. public $description;
  24. public $sound;
  25. public $type; //ALL_ON_ONE_PAGE or ONE_PER_PAGE
  26. public $random;
  27. public $random_answers;
  28. public $active;
  29. public $timeLimit;
  30. public $attempts;
  31. public $feedbacktype;
  32. public $end_time;
  33. public $start_time;
  34. public $questionList; // array with the list of this exercise's questions
  35. public $results_disabled;
  36. public $expired_time;
  37. public $course;
  38. public $propagate_neg;
  39. /**
  40. * Constructor of the class
  41. *
  42. * @author - Olivier Brouckaert
  43. */
  44. function Exercise($course_id = null) {
  45. $this->id = 0;
  46. $this->exercise = '';
  47. $this->description = '';
  48. $this->sound = '';
  49. $this->type = ALL_ON_ONE_PAGE;
  50. $this->random = 0;
  51. $this->random_answers = 0;
  52. $this->active = 1;
  53. $this->questionList = array();
  54. $this->timeLimit = 0;
  55. $this->end_time = '0000-00-00 00:00:00';
  56. $this->start_time = '0000-00-00 00:00:00';
  57. $this->results_disabled = 1;
  58. $this->expired_time = '0000-00-00 00:00:00';
  59. $this->propagate_neg = 0;
  60. if (!empty($course_id)) {
  61. $this->course_id = intval($course_id);
  62. $course_info = api_get_course_info_by_id($this->course_id);
  63. } else {
  64. $course_info = api_get_course_info();
  65. }
  66. $this->course = $course_info;
  67. }
  68. /**
  69. * reads exercise informations from the data base
  70. *
  71. * @author - Olivier Brouckaert
  72. * @param - integer $id - exercise ID
  73. * @return - boolean - true if exercise exists, otherwise false
  74. */
  75. function read($id) {
  76. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION,$this->course['db_name']);
  77. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST,$this->course['db_name']);
  78. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION,$this->course['db_name']);
  79. #$TBL_REPONSES = Database::get_course_table(TABLE_QUIZ_ANSWER);
  80. $id = intval($id);
  81. $sql = "SELECT * FROM $TBL_EXERCICES WHERE id = ".$id;
  82. $result = Database::query($sql);
  83. // if the exercise has been found
  84. if ($object=Database::fetch_object($result)) {
  85. $this->id = $id;
  86. $this->exercise = $object->title;
  87. $this->description = $object->description;
  88. $this->sound = $object->sound;
  89. $this->type = $object->type;
  90. $this->random = $object->random;
  91. $this->random_answers = $object->random_answers;
  92. $this->active = $object->active;
  93. $this->results_disabled = $object->results_disabled;
  94. $this->attempts = $object->max_attempt;
  95. $this->feedbacktype = $object->feedback_type;
  96. $this->propagate_neg = $object->propagate_neg;
  97. if ($object->end_time != '0000-00-00 00:00:00') {
  98. $this->end_time = api_get_local_time($object->end_time);
  99. }
  100. if ($object->start_time != '0000-00-00 00:00:00') {
  101. $this->start_time = api_get_local_time($object->start_time);
  102. }
  103. $this->expired_time = $object->expired_time; //control time
  104. $sql="SELECT question_id, question_order FROM $TBL_EXERCICE_QUESTION, $TBL_QUESTIONS WHERE question_id=id AND exercice_id='".Database::escape_string($id)."' ORDER BY question_order";
  105. $result = Database::query($sql);
  106. // fills the array with the question ID for this exercise
  107. // the key of the array is the question position
  108. while ($new_object = Database::fetch_object($result)) {
  109. $this->questionList[$new_object->question_order]= $new_object->question_id;
  110. }
  111. //overload questions list with recorded questions list
  112. //load questions only for exercises of type 'one question per page'
  113. //this is needed only is there is no questions
  114. //
  115. // @todo not sure were in the code this is used somebody mess with the exercise tool
  116. global $_configuration, $questionList;
  117. if ($this->type == ONE_PER_PAGE && $_configuration['live_exercise_tracking'] && $_SERVER['REQUEST_METHOD'] != 'POST' && defined('QUESTION_LIST_ALREADY_LOGGED')) {
  118. //if(empty($_SESSION['questionList']))
  119. $this->questionList = $questionList;
  120. }
  121. return true;
  122. }
  123. // exercise not found
  124. return false;
  125. }
  126. /**
  127. * returns the exercise ID
  128. *
  129. * @author - Olivier Brouckaert
  130. * @return - integer - exercise ID
  131. */
  132. function selectId() {
  133. return $this->id;
  134. }
  135. /**
  136. * returns the exercise title
  137. *
  138. * @author - Olivier Brouckaert
  139. * @return - string - exercise title
  140. */
  141. function selectTitle() {
  142. return $this->exercise;
  143. }
  144. /**
  145. * returns the number of attempts setted
  146. *
  147. * @return - numeric - exercise attempts
  148. */
  149. function selectAttempts() {
  150. return $this->attempts;
  151. }
  152. /** returns the number of FeedbackType *
  153. * 0=>Feedback , 1=>DirectFeedback, 2=>NoFeedback
  154. * @return - numeric - exercise attempts
  155. */
  156. function selectFeedbackType() {
  157. return $this->feedbacktype;
  158. }
  159. /**
  160. * returns the time limit
  161. */
  162. function selectTimeLimit() {
  163. return $this->timeLimit;
  164. }
  165. /**
  166. * returns the exercise description
  167. *
  168. * @author - Olivier Brouckaert
  169. * @return - string - exercise description
  170. */
  171. function selectDescription() {
  172. return $this->description;
  173. }
  174. /**
  175. * returns the exercise sound file
  176. *
  177. * @author - Olivier Brouckaert
  178. * @return - string - exercise description
  179. */
  180. function selectSound() {
  181. return $this->sound;
  182. }
  183. /**
  184. * returns the exercise type
  185. *
  186. * @author - Olivier Brouckaert
  187. * @return - integer - exercise type
  188. */
  189. function selectType() {
  190. return $this->type;
  191. }
  192. /**
  193. * tells if questions are selected randomly, and if so returns the draws
  194. *
  195. * @author - Carlos Vargas
  196. * @return - integer - results disabled exercise
  197. */
  198. function selectResultsDisabled() {
  199. return $this->results_disabled;
  200. }
  201. /**
  202. * tells if questions are selected randomly, and if so returns the draws
  203. *
  204. * @author - Olivier Brouckaert
  205. * @return - integer - 0 if not random, otherwise the draws
  206. */
  207. function isRandom() {
  208. if($this->random > 0){
  209. return true;
  210. } else {
  211. return false;
  212. }
  213. }
  214. /**
  215. * returns random answers status.
  216. *
  217. * @author - Juan Carlos Ra�a
  218. */
  219. function selectRandomAnswers() {
  220. $this->random_answers;
  221. return $this->random_answers;
  222. }
  223. /**
  224. * Same as isRandom() but has a name applied to values different than 0 or 1
  225. */
  226. function getShuffle() {
  227. return $this->random;
  228. }
  229. /**
  230. * returns the exercise status (1 = enabled ; 0 = disabled)
  231. *
  232. * @author - Olivier Brouckaert
  233. * @return - boolean - true if enabled, otherwise false
  234. */
  235. function selectStatus() {
  236. return $this->active;
  237. }
  238. /**
  239. * returns the array with the question ID list
  240. *
  241. * @author - Olivier Brouckaert
  242. * @return - array - question ID list
  243. */
  244. function selectQuestionList($from_db = false) {
  245. if ($from_db && !empty($this->id)) {
  246. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION, $this->course['db_name']);
  247. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION, $this->course['db_name']);
  248. $sql="SELECT question_id, question_order FROM $TBL_EXERCICE_QUESTION, $TBL_QUESTIONS WHERE question_id = id AND exercice_id='".$this->id."' ORDER BY question_order";
  249. $result = Database::query($sql);
  250. $question_list = array();
  251. while ($new_object = Database::fetch_object($result)) {
  252. $question_list[$new_object->question_order]= $new_object->question_id;
  253. }
  254. return $question_list;
  255. }
  256. return $this->questionList;
  257. }
  258. /**
  259. * returns the number of questions in this exercise
  260. *
  261. * @author - Olivier Brouckaert
  262. * @return - integer - number of questions
  263. */
  264. function selectNbrQuestions() {
  265. return sizeof($this->questionList);
  266. }
  267. function selectPropagateNeg() {
  268. return $this->propagate_neg;
  269. }
  270. /**
  271. * Selects questions randomly in the question list
  272. *
  273. * @author - Olivier Brouckaert
  274. * @return - array - if the exercise is not set to take questions randomly, returns the question list
  275. * without randomizing, otherwise, returns the list with questions selected randomly
  276. */
  277. function selectRandomList() {
  278. $nbQuestions = $this->selectNbrQuestions();
  279. $temp_list = $this->questionList;
  280. //Not a random exercise, or if there are not at least 2 questions
  281. if($this->random == 0 || $nbQuestions < 2) {
  282. return $this->questionList;
  283. }
  284. if ($nbQuestions != 0) {
  285. shuffle($temp_list);
  286. $my_random_list = array_combine(range(1,$nbQuestions),$temp_list);
  287. $my_question_list = array();
  288. $i = 0;
  289. foreach ($my_random_list as $item) {
  290. if ($i < $this->random) {
  291. $my_question_list[$i] = $item;
  292. } else {
  293. break;
  294. }
  295. $i++;
  296. }
  297. return $my_question_list;
  298. }
  299. }
  300. /**
  301. * returns 'true' if the question ID is in the question list
  302. *
  303. * @author - Olivier Brouckaert
  304. * @param - integer $questionId - question ID
  305. * @return - boolean - true if in the list, otherwise false
  306. */
  307. function isInList($questionId) {
  308. if (is_array($this->questionList))
  309. return in_array($questionId,$this->questionList);
  310. else
  311. return false;
  312. }
  313. /**
  314. * changes the exercise title
  315. *
  316. * @author - Olivier Brouckaert
  317. * @param - string $title - exercise title
  318. */
  319. function updateTitle($title) {
  320. $this->exercise=$title;
  321. }
  322. /**
  323. * changes the exercise max attempts
  324. *
  325. * @param - numeric $attempts - exercise max attempts
  326. */
  327. function updateAttempts($attempts) {
  328. $this->attempts=$attempts;
  329. }
  330. /**
  331. * changes the exercise feedback type
  332. *
  333. * @param - numeric $attempts - exercise max attempts
  334. */
  335. function updateFeedbackType($feedback_type) {
  336. $this->feedbacktype=$feedback_type;
  337. }
  338. /**
  339. * changes the exercise description
  340. *
  341. * @author - Olivier Brouckaert
  342. * @param - string $description - exercise description
  343. */
  344. function updateDescription($description) {
  345. $this->description=$description;
  346. }
  347. /**
  348. * changes the exercise expired_time
  349. *
  350. * @author - Isaac flores
  351. * @param - int The expired time of the quiz
  352. */
  353. function updateExpiredTime($expired_time) {
  354. $this->expired_time = $expired_time;
  355. }
  356. function updatePropagateNegative($value) {
  357. $this->propagate_neg = $value;
  358. }
  359. /**
  360. * changes the exercise sound file
  361. *
  362. * @author - Olivier Brouckaert
  363. * @param - string $sound - exercise sound file
  364. * @param - string $delete - ask to delete the file
  365. */
  366. function updateSound($sound,$delete) {
  367. global $audioPath, $documentPath;
  368. $TBL_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT, $this->course['db_name']);
  369. $TBL_ITEM_PROPERTY = Database::get_course_table(TABLE_ITEM_PROPERTY,$this->course['db_name']);
  370. if ($sound['size'] && (strstr($sound['type'],'audio') || strstr($sound['type'],'video'))) {
  371. $this->sound=$sound['name'];
  372. if (@move_uploaded_file($sound['tmp_name'],$audioPath.'/'.$this->sound)) {
  373. $query="SELECT 1 FROM $TBL_DOCUMENT WHERE path='".str_replace($documentPath,'',$audioPath).'/'.$this->sound."'";
  374. $result=Database::query($query);
  375. if(!Database::num_rows($result)) {
  376. /*$query="INSERT INTO $TBL_DOCUMENT(path,filetype) VALUES "
  377. ." ('".str_replace($documentPath,'',$audioPath).'/'.$this->sound."','file')";
  378. Database::query($query);*/
  379. $id = add_document($this->course,str_replace($documentPath,'',$audioPath).'/'.$this->sound,'file',$sound['size'],$sound['name']);
  380. //$id = Database::insert_id();
  381. //$time = time();
  382. //$time = date("Y-m-d H:i:s", $time);
  383. // insert into the item_property table, using default visibility of "visible"
  384. /*$query = "INSERT INTO $TBL_ITEM_PROPERTY "
  385. ."(tool, ref, insert_user_id,to_group_id, insert_date, lastedit_date, lastedit_type) "
  386. ." VALUES "
  387. ."('".TOOL_DOCUMENT."', $id, $_user['user_id'], 0, '$time', '$time', 'DocumentAdded' )";
  388. Database::query($query);*/
  389. api_item_property_update($this->course, TOOL_DOCUMENT, $id, 'DocumentAdded',api_get_user_id());
  390. item_property_update_on_folder($this->course,str_replace($documentPath,'',$audioPath),api_get_user_id());
  391. }
  392. }
  393. } elseif($delete && is_file($audioPath.'/'.$this->sound)) {
  394. $this->sound='';
  395. }
  396. }
  397. /**
  398. * changes the exercise type
  399. *
  400. * @author - Olivier Brouckaert
  401. * @param - integer $type - exercise type
  402. */
  403. function updateType($type) {
  404. $this->type=$type;
  405. }
  406. /**
  407. * sets to 0 if questions are not selected randomly
  408. * if questions are selected randomly, sets the draws
  409. *
  410. * @author - Olivier Brouckaert
  411. * @param - integer $random - 0 if not random, otherwise the draws
  412. */
  413. function setRandom($random) {
  414. $this->random=$random;
  415. }
  416. /**
  417. * sets to 0 if answers are not selected randomly
  418. * if answers are selected randomly
  419. * @author - Juan Carlos Ra�a
  420. * @param - integer $random_answers - random answers
  421. */
  422. function updateRandomAnswers($random_answers) {
  423. $this->$random_answers = $random_answers;
  424. }
  425. /**
  426. * enables the exercise
  427. *
  428. * @author - Olivier Brouckaert
  429. */
  430. function enable() {
  431. $this->active=1;
  432. }
  433. /**
  434. * disables the exercise
  435. *
  436. * @author - Olivier Brouckaert
  437. */
  438. function disable() {
  439. $this->active=0;
  440. }
  441. function disable_results() {
  442. $this->results_disabled = true;
  443. }
  444. function enable_results()
  445. {
  446. $this->results_disabled = false;
  447. }
  448. function updateResultsDisabled($results_disabled) {
  449. $this->results_disabled = intval($results_disabled);
  450. }
  451. /**
  452. * updates the exercise in the data base
  453. *
  454. * @author - Olivier Brouckaert
  455. */
  456. function save($type_e='') {
  457. global $_course;
  458. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  459. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  460. $TBL_QUIZ_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  461. $id = $this->id;
  462. $exercise = $this->exercise;
  463. $description = $this->description;
  464. $sound = $this->sound;
  465. $type = $this->type;
  466. $attempts = $this->attempts;
  467. $feedbacktype = $this->feedbacktype;
  468. $random = $this->random;
  469. $random_answers = $this->random_answers;
  470. $active = $this->active;
  471. $propagate_neg = $this->propagate_neg;
  472. $session_id = api_get_session_id();
  473. //If direct we do not show results
  474. if ($feedbacktype == EXERCISE_FEEDBACK_TYPE_DIRECT) {
  475. $results_disabled = 0;
  476. } else {
  477. $results_disabled = intval($this->results_disabled);
  478. }
  479. $expired_time = intval($this->expired_time);
  480. $start_time = Database::escape_string(api_get_utc_datetime($this->start_time));
  481. $end_time = Database::escape_string(api_get_utc_datetime($this->end_time));
  482. // Exercise already exists
  483. if ($id) {
  484. $sql="UPDATE $TBL_EXERCICES SET
  485. title='".Database::escape_string($exercise)."',
  486. description='".Database::escape_string($description)."'";
  487. if ($type_e != 'simple') {
  488. $sql .= ",sound='".Database::escape_string($sound)."',
  489. type ='".Database::escape_string($type)."',
  490. random ='".Database::escape_string($random)."',
  491. random_answers ='".Database::escape_string($random_answers)."',
  492. active ='".Database::escape_string($active)."',
  493. feedback_type ='".Database::escape_string($feedbacktype)."',
  494. start_time = '$start_time',
  495. end_time = '$end_time',
  496. max_attempt ='".Database::escape_string($attempts)."',
  497. expired_time ='".Database::escape_string($expired_time)."',
  498. propagate_neg ='".Database::escape_string($propagate_neg)."',
  499. results_disabled='".Database::escape_string($results_disabled)."'";
  500. }
  501. $sql .= " WHERE id='".Database::escape_string($id)."'";
  502. Database::query($sql);
  503. // update into the item_property table
  504. api_item_property_update($_course, TOOL_QUIZ, $id,'QuizUpdated',api_get_user_id());
  505. if (api_get_setting('search_enabled')=='true') {
  506. $this->search_engine_edit();
  507. }
  508. } else {
  509. // creates a new exercise
  510. $sql="INSERT INTO $TBL_EXERCICES (start_time, end_time, title, description, sound, type, random, random_answers,active, results_disabled, max_attempt, feedback_type, expired_time, session_id)
  511. VALUES(
  512. '$start_time','$end_time',
  513. '".Database::escape_string($exercise)."',
  514. '".Database::escape_string($description)."',
  515. '".Database::escape_string($sound)."',
  516. '".Database::escape_string($type)."',
  517. '".Database::escape_string($random)."',
  518. '".Database::escape_string($random_answers)."',
  519. '".Database::escape_string($active)."',
  520. '".Database::escape_string($results_disabled)."',
  521. '".Database::escape_string($attempts)."',
  522. '".Database::escape_string($feedbacktype)."',
  523. '".Database::escape_string($expired_time)."',
  524. '".Database::escape_string($session_id)."'
  525. )";
  526. Database::query($sql);
  527. $this->id=Database::insert_id();
  528. // insert into the item_property table
  529. api_item_property_update($_course, TOOL_QUIZ, $this->id,'QuizAdded',api_get_user_id());
  530. if (api_get_setting('search_enabled')=='true' && extension_loaded('xapian')) {
  531. $this->search_engine_save();
  532. }
  533. }
  534. // updates the question position
  535. $this->update_question_positions();
  536. }
  537. /* Updates question position */
  538. function update_question_positions() {
  539. $quiz_question_table = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  540. //Fixes #3483 when updating order
  541. $question_list = $this->selectQuestionList(true);
  542. if (!empty($question_list)) {
  543. foreach ($question_list as $position => $questionId) {
  544. $sql="UPDATE $quiz_question_table SET question_order ='".intval($position)."'".
  545. "WHERE question_id = ".intval($questionId)." AND exercice_id=".intval($this->id);
  546. Database::query($sql);
  547. }
  548. }
  549. }
  550. /**
  551. * moves a question up in the list
  552. *
  553. * @author - Olivier Brouckaert
  554. * @author - Julio Montoya (rewrote the code)
  555. * @param - integer $id - question ID to move up
  556. */
  557. function moveUp($id) {
  558. // there is a bug with some version of PHP with the key and prev functions
  559. // the script commented was tested in dev.dokeos.com with no success
  560. // Instead of using prev and next this was change with arrays.
  561. /*
  562. foreach($this->questionList as $position=>$questionId)
  563. {
  564. // if question ID found
  565. if($questionId == $id)
  566. {
  567. // position of question in the array
  568. echo $pos1=$position; //1
  569. echo "<br>";
  570. prev($this->questionList);
  571. prev($this->questionList);
  572. // position of previous question in the array
  573. $pos2=key($this->questionList);
  574. //if the cursor of the array hit the end
  575. // then we must reset the array to get the previous key
  576. if($pos2===null)
  577. {
  578. end($this->questionList);
  579. prev($this->questionList);
  580. $pos2=key($this->questionList);
  581. }
  582. // error, can't move question
  583. if(!$pos2)
  584. {
  585. //echo 'cant move!';
  586. $pos2=key($this->questionList);
  587. reset($this->questionList);
  588. }
  589. $id2=$this->questionList[$pos2];
  590. // exits foreach()
  591. break;
  592. }
  593. $i++;
  594. }
  595. */
  596. $question_list =array();
  597. foreach($this->questionList as $position=>$questionId)
  598. {
  599. $question_list[]= $questionId;
  600. }
  601. $len=count($question_list);
  602. $orderlist=array_keys($this->questionList);
  603. for($i=0;$i<$len;$i++)
  604. {
  605. $questionId = $question_list[$i];
  606. if($questionId == $id)
  607. {
  608. // position of question in the array
  609. $pos1=$orderlist[$i];
  610. $pos2=$orderlist[$i-1];
  611. if($pos2===null)
  612. {
  613. $pos2 = $orderlist[$len-1];
  614. }
  615. // error, can't move question
  616. if(!$pos2)
  617. {
  618. $pos2=$orderlist[0];
  619. $i=0;
  620. }
  621. break;
  622. }
  623. }
  624. // permutes questions in the array
  625. $temp=$this->questionList[$pos2];
  626. $this->questionList[$pos2]=$this->questionList[$pos1];
  627. $this->questionList[$pos1]=$temp;
  628. }
  629. /**
  630. * moves a question down in the list
  631. *
  632. * @author - Olivier Brouckaert
  633. * @param - integer $id - question ID to move down
  634. */
  635. function moveDown($id) {
  636. // there is a bug with some version of PHP with the key and prev functions
  637. // the script commented was tested in dev.dokeos.com with no success
  638. // Instead of using prev and next this was change with arrays.
  639. /*
  640. foreach($this->questionList as $position=>$questionId)
  641. {
  642. // if question ID found
  643. if($questionId == $id)
  644. {
  645. // position of question in the array
  646. $pos1=$position;
  647. //next($this->questionList);
  648. // position of next question in the array
  649. $pos2=key($this->questionList);
  650. // error, can't move question
  651. if(!$pos2)
  652. {
  653. //echo 'cant move!';
  654. return;
  655. }
  656. $id2=$this->questionList[$pos2];
  657. // exits foreach()
  658. break;
  659. }
  660. }
  661. */
  662. $question_list =array();
  663. foreach($this->questionList as $position=>$questionId) {
  664. $question_list[]= $questionId;
  665. }
  666. $len=count($question_list);
  667. $orderlist=array_keys($this->questionList);
  668. for($i=0;$i<$len;$i++) {
  669. $questionId = $question_list[$i];
  670. if($questionId == $id) {
  671. $pos1=$orderlist[$i+1];
  672. $pos2 =$orderlist[$i];
  673. if(!$pos2) {
  674. //echo 'cant move!';
  675. }
  676. break;
  677. }
  678. }
  679. // permutes questions in the array
  680. $temp=$this->questionList[$pos2];
  681. $this->questionList[$pos2]=$this->questionList[$pos1];
  682. $this->questionList[$pos1]=$temp;
  683. }
  684. /**
  685. * adds a question into the question list
  686. *
  687. * @author - Olivier Brouckaert
  688. * @param - integer $questionId - question ID
  689. * @return - boolean - true if the question has been added, otherwise false
  690. */
  691. function addToList($questionId) {
  692. // checks if the question ID is not in the list
  693. if(!$this->isInList($questionId)) {
  694. // selects the max position
  695. if(!$this->selectNbrQuestions()) {
  696. $pos=1;
  697. } else {
  698. if (is_array($this->questionList))
  699. $pos=max(array_keys($this->questionList))+1;
  700. }
  701. $this->questionList[$pos]=$questionId;
  702. return true;
  703. }
  704. return false;
  705. }
  706. /**
  707. * removes a question from the question list
  708. *
  709. * @author - Olivier Brouckaert
  710. * @param - integer $questionId - question ID
  711. * @return - boolean - true if the question has been removed, otherwise false
  712. */
  713. function removeFromList($questionId) {
  714. // searches the position of the question ID in the list
  715. $pos=array_search($questionId,$this->questionList);
  716. // question not found
  717. if($pos === false) {
  718. return false;
  719. } else {
  720. // deletes the position from the array containing the wanted question ID
  721. unset($this->questionList[$pos]);
  722. return true;
  723. }
  724. }
  725. /**
  726. * deletes the exercise from the database
  727. * Notice : leaves the question in the data base
  728. *
  729. * @author - Olivier Brouckaert
  730. */
  731. function delete() {
  732. global $_course;
  733. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  734. $sql="UPDATE $TBL_EXERCICES SET active='-1' WHERE id='".Database::escape_string($this->id)."'";
  735. Database::query($sql);
  736. api_item_property_update($_course, TOOL_QUIZ, $this->id,'QuizDeleted',api_get_user_id());
  737. if (api_get_setting('search_enabled')=='true' && extension_loaded('xapian') ) {
  738. $this->search_engine_delete();
  739. }
  740. }
  741. /**
  742. * Creates the form to create / edit an exercise
  743. * @param FormValidator $form the formvalidator instance (by reference)
  744. */
  745. function createForm ($form, $type='full') {
  746. global $id;
  747. if (empty($type)){
  748. $type='full';
  749. }
  750. // form title
  751. if (!empty($_GET['exerciseId'])) {
  752. $form_title = get_lang('ModifyExercise');
  753. } else {
  754. $form_title = get_lang('NewEx');
  755. }
  756. $form->addElement('header', '', $form_title);
  757. // title
  758. $form->addElement('text', 'exerciseTitle', get_lang('ExerciseName'), ' size="60" id="exercise_title"');
  759. //$form->applyFilter('exerciseTitle','html_filter');
  760. $form->addElement('html','<div class="row">
  761. <div class="label"></div>
  762. <div class="formw" style="height:50px">
  763. <a href="javascript://" onclick=" return show_media()"> <span id="media_icon"> <img style="vertical-align: middle;" src="../img/looknfeel.png" alt="" />&nbsp;'.get_lang('ExerciseDescription').'</span></a>
  764. </div>
  765. </div>');
  766. $editor_config = array('ToolbarSet' => 'TestQuestionDescription', 'Width' => '100%', 'Height' => '150');
  767. if(is_array($type)){
  768. $editor_config = array_merge($editor_config, $type);
  769. }
  770. $form->addElement ('html','<div class="HideFCKEditor" id="HiddenFCKexerciseDescription" >');
  771. $form->add_html_editor('exerciseDescription', get_lang('langExerciseDescription'), false, false, $editor_config);
  772. $form->addElement ('html','</div>');
  773. $form->addElement('html','<div class="row">
  774. <div class="label">&nbsp;</div>
  775. <div class="formw">
  776. <a href="javascript://" onclick=" return advanced_parameters()"><span id="img_plus_and_minus"><div style="vertical-align:top;" ><img style="vertical-align:middle;" src="../img/div_show.gif" alt="" />&nbsp;'.get_lang('AdvancedParameters').'</div></span></a>
  777. </div>
  778. </div>');
  779. // Random questions
  780. $form->addElement('html','<div id="options" style="display:none">');
  781. if ($type=='full') {
  782. /*$feedback_option[0]=get_lang('ExerciseAtTheEndOfTheTest');
  783. $feedback_option[1]=get_lang('DirectFeedback');
  784. $feedback_option[2]=get_lang('NoFeedback');
  785. */
  786. //Can't modify a DirectFeedback question
  787. if ($this->selectFeedbackType() != EXERCISE_FEEDBACK_TYPE_DIRECT ) {
  788. // feedback type
  789. $radios_feedback = array();
  790. $radios_feedback[] = FormValidator :: createElement ('radio', 'exerciseFeedbackType', null, get_lang('ExerciseAtTheEndOfTheTest'),'0',array('id' =>'exerciseType_0', 'onclick' => 'check_feedback()'));
  791. if (api_get_setting('enable_quiz_scenario') == 'true') {
  792. //Can't convert a question from one feedback to another if there is more than 1 question already added
  793. if ($this->selectNbrQuestions() == 0) {
  794. $radios_feedback[] = FormValidator :: createElement ('radio', 'exerciseFeedbackType', null, get_lang('DirectFeedback'),'1',array('id' =>'exerciseType_1' , 'onclick' => 'check_direct_feedback()'));
  795. }
  796. }
  797. $radios_feedback[] = FormValidator :: createElement ('radio', 'exerciseFeedbackType', null, get_lang('NoFeedback'),'2',array('id' =>'exerciseType_2'));
  798. $form->addGroup($radios_feedback, null, get_lang('FeedbackType'));
  799. //$form->addElement('select', 'exerciseFeedbackType',get_lang('FeedbackType'),$feedback_option,'onchange="javascript:feedbackselection()"');
  800. // test type
  801. $radios = array();
  802. $radios[] = FormValidator :: createElement ('radio', 'exerciseType', null, get_lang('SimpleExercise'), '1', array('onclick' => 'check_per_page_all()', 'id'=>'option_page_all'));
  803. $radios[] = FormValidator :: createElement ('radio', 'exerciseType', null, get_lang('SequentialExercise'),'2', array('onclick' => 'check_per_page_one()', 'id'=>'option_page_one'));
  804. $form->addGroup($radios, null, get_lang('QuestionsPerPage'));
  805. $radios_results_disabled = array();
  806. $radios_results_disabled[] = FormValidator :: createElement ('radio', 'results_disabled', null, get_lang('ShowScoreAndRightAnswer'), '0', array('id'=>'result_disabled_0'));
  807. $radios_results_disabled[] = FormValidator :: createElement ('radio', 'results_disabled', null, get_lang('DoNotShowScoreNorRightAnswer'), '1',array('id'=>'result_disabled_1','onclick' => 'check_results_disabled()'));
  808. $radios_results_disabled[] = FormValidator :: createElement ('radio', 'results_disabled', null, get_lang('OnlyShowScore'), '2',array('id'=>'result_disabled_2','onclick' => 'check_results_disabled()'));
  809. $form->addGroup($radios_results_disabled, null, get_lang('ShowResultsToStudents'),'<br />');
  810. } else {
  811. // if is Directfeedback but has not questions we can allow to modify the question type
  812. if ($this->selectNbrQuestions() == 0) {
  813. // feedback type
  814. $radios_feedback = array();
  815. $radios_feedback[] = FormValidator :: createElement ('radio', 'exerciseFeedbackType', null, get_lang('ExerciseAtTheEndOfTheTest'),'0',array('id' =>'exerciseType_0', 'onclick' => 'check_feedback()'));
  816. if (api_get_setting('enable_quiz_scenario') == 'true') {
  817. $radios_feedback[] = FormValidator :: createElement ('radio', 'exerciseFeedbackType', null, get_lang('DirectFeedback'), '1', array('id' =>'exerciseType_1' , 'onclick' => 'check_direct_feedback()'));
  818. }
  819. $radios_feedback[] = FormValidator :: createElement ('radio', 'exerciseFeedbackType', null, get_lang('NoFeedback'),'2',array('id' =>'exerciseType_2'));
  820. $form->addGroup($radios_feedback, null, get_lang('FeedbackType'));
  821. //$form->addElement('select', 'exerciseFeedbackType',get_lang('FeedbackType'),$feedback_option,'onchange="javascript:feedbackselection()"');
  822. // test type
  823. $radios = array();
  824. $radios[] = FormValidator :: createElement ('radio', 'exerciseType', null, get_lang('SimpleExercise'), '1');
  825. $radios[] = FormValidator :: createElement ('radio', 'exerciseType', null, get_lang('SequentialExercise'),'2');
  826. $form->addGroup($radios, null, get_lang('ExerciseType'));
  827. $radios_results_disabled = array();
  828. $radios_results_disabled[] = FormValidator :: createElement ('radio', 'results_disabled', null, get_lang('ShowScoreAndRightAnswer'), '0', array('id'=>'result_disabled_0'));
  829. $radios_results_disabled[] = FormValidator :: createElement ('radio', 'results_disabled', null, get_lang('DoNotShowScoreNorRightAnswer'), '1',array('id'=>'result_disabled_1','onclick' => 'check_results_disabled()'));
  830. $radios_results_disabled[] = FormValidator :: createElement ('radio', 'results_disabled', null, get_lang('OnlyShowScore'), '2',array('id'=>'result_disabled_2','onclick' => 'check_results_disabled()'));
  831. $form->addGroup($radios_results_disabled, null, get_lang('ShowResultsToStudents'),'<br />');
  832. } else {
  833. //Show options freeze
  834. $radios_results_disabled[] = FormValidator :: createElement ('radio', 'results_disabled', null, get_lang('ShowScoreAndRightAnswer'), '0', array('id'=>'result_disabled_0'));
  835. $radios_results_disabled[] = FormValidator :: createElement ('radio', 'results_disabled', null, get_lang('DoNotShowScoreNorRightAnswer'), '1',array('id'=>'result_disabled_1','onclick' => 'check_results_disabled()'));
  836. $radios_results_disabled[] = FormValidator :: createElement ('radio', 'results_disabled', null, get_lang('OnlyShowScore'), '2',array('id'=>'result_disabled_2','onclick' => 'check_results_disabled()'));
  837. $result_disable_group = $form->addGroup($radios_results_disabled, null, get_lang('ShowResultsToStudents'),'<br />');
  838. $result_disable_group->freeze();
  839. $radios[] = FormValidator :: createElement ('radio', 'exerciseType', null, get_lang('SimpleExercise'), '1', array('onclick' => 'check_per_page_all()', 'id'=>'option_page_all'));
  840. $radios[] = FormValidator :: createElement ('radio', 'exerciseType', null, get_lang('SequentialExercise'),'2', array('onclick' => 'check_per_page_one()', 'id'=>'option_page_one'));
  841. $type_group = $form->addGroup($radios, null, get_lang('QuestionsPerPage'));
  842. $type_group->freeze();
  843. //we force the options to the DirectFeedback exercisetype
  844. $form->addElement('hidden', 'exerciseFeedbackType', EXERCISE_FEEDBACK_TYPE_DIRECT);
  845. $form->addElement('hidden', 'exerciseType', ONE_PER_PAGE);
  846. }
  847. }
  848. $random = array();
  849. $option=array();
  850. $max = ($this->id > 0) ? $this->selectNbrQuestions() : 10 ;
  851. $option = range(0,$max);
  852. $option[0]=get_lang('No');
  853. $random[] = FormValidator :: createElement ('select', 'randomQuestions',null,$option);
  854. $random[] = FormValidator :: createElement ('static', 'help','help','<span style="font-style: italic;">'.get_lang('RandomQuestionsHelp').'</span>');
  855. //$random[] = FormValidator :: createElement ('text', 'randomQuestions', null,null,'0');
  856. $form->addGroup($random,null,get_lang('RandomQuestions'),'<br />');
  857. //random answers
  858. $radios_random_answers = array();
  859. $radios_random_answers[] = FormValidator :: createElement ('radio', 'randomAnswers', null, get_lang('Yes'),'1');
  860. $radios_random_answers[] = FormValidator :: createElement ('radio', 'randomAnswers', null, get_lang('No'),'0');
  861. $form->addGroup($radios_random_answers, null, get_lang('RandomAnswers'));
  862. //Attempts
  863. $attempt_option=range(0,10);
  864. $attempt_option[0]=get_lang('Infinite');
  865. $form->addElement('select', 'exerciseAttempts',get_lang('ExerciseAttempts'),$attempt_option);
  866. $form->addElement('checkbox', 'activate_start_date_check',get_lang('EnableStartTime'),null, array('onclick' => 'activate_start_date()'));
  867. $var = Exercise::selectTimeLimit();
  868. if (($this->start_time!='0000-00-00 00:00:00'))
  869. $form->addElement('html','<div id="start_date_div" style="display:block;">');
  870. else
  871. $form->addElement('html','<div id="start_date_div" style="display:none;">');
  872. $form->addElement('datepicker', 'start_time', '', array('form_name'=>'exercise_admin'), 5);
  873. $form->addElement('html','</div>');
  874. $form->addElement('checkbox', 'activate_end_date_check', get_lang('EnableEndTime'), null,array('onclick' => 'activate_end_date()'));
  875. if (($this->end_time!='0000-00-00 00:00:00'))
  876. $form->addElement('html','<div id="end_date_div" style="display:block;">');
  877. else
  878. $form->addElement('html','<div id="end_date_div" style="display:none;">');
  879. $form->addElement('datepicker', 'end_time', '', array('form_name'=>'exercise_admin'), 5);
  880. //$form->addElement('select', 'enabletimercontroltotalminutes',get_lang('ExerciseTimerControlMinutes'),$time_minutes_option);
  881. $form->addElement('html','</div>');
  882. $check_option=$this->selectType();
  883. if ($check_option==1 && isset($_GET['exerciseId'])) {
  884. $diplay = 'none';
  885. } else {
  886. $diplay = 'block';
  887. }
  888. $form->addElement('checkbox', 'propagate_neg',get_lang('PropagateNegativeResults'),null);
  889. $form->addElement('html','<div id="divtimecontrol" style="display:'.$diplay.';">');
  890. //Timer control
  891. $time_hours_option = range(0,12);
  892. $time_minutes_option = range(0,59);
  893. $form->addElement('checkbox', 'enabletimercontrol',get_lang('EnableTimerControl'),null,array('onclick' =>'option_time_expired()','id'=>'enabletimercontrol','onload'=>'check_load_time()'));
  894. $expired_date = (int)$this->selectExpiredTime();
  895. if(($expired_date!='0')) {
  896. $form->addElement('html','<div id="timercontrol" style="display:block;">');
  897. } else {
  898. $form->addElement('html','<div id="timercontrol" style="display:none;">');
  899. }
  900. $form->addElement('text', 'enabletimercontroltotalminutes',get_lang('ExerciseTotalDurationInMinutes'),array('style' => 'width : 35px','id' => 'enabletimercontroltotalminutes'));
  901. $form->addElement('html','</div>');
  902. //$form->addElement('text', 'exerciseAttempts', get_lang('ExerciseAttempts').' : ',array('size'=>'2'));
  903. $defaults = array();
  904. if (api_get_setting('search_enabled') === 'true') {
  905. require_once(api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php');
  906. $form->addElement ('checkbox', 'index_document','', get_lang('SearchFeatureDoIndexDocument'));
  907. $form->addElement ('html','<br /><div class="row">');
  908. $form->addElement ('html', '<div class="label">'. get_lang('SearchFeatureDocumentLanguage') .'</div>');
  909. $form->addElement ('html', '<div class="formw">'. api_get_languages_combo() .'</div>');
  910. $form->addElement ('html','</div><div class="sub-form">');
  911. $specific_fields = get_specific_field_list();
  912. foreach ($specific_fields as $specific_field) {
  913. $form->addElement ('text', $specific_field['code'], $specific_field['name']);
  914. $filter = array('course_code'=> "'". api_get_course_id() ."'", 'field_id' => $specific_field['id'], 'ref_id' => $this->id, 'tool_id' => '\''. TOOL_QUIZ .'\'');
  915. $values = get_specific_field_values_list($filter, array('value'));
  916. if ( !empty($values) ) {
  917. $arr_str_values = array();
  918. foreach ($values as $value) {
  919. $arr_str_values[] = $value['value'];
  920. }
  921. $defaults[$specific_field['code']] = implode(', ', $arr_str_values);
  922. }
  923. }
  924. $form->addElement ('html','</div>');
  925. }
  926. $form->addElement('html','</div>'); //End advanced setting
  927. $form->addElement('html','</div>');
  928. }
  929. // submit
  930. isset($_GET['exerciseId'])?$text=get_lang('ModifyExercise'):$text=get_lang('ProcedToQuestions');
  931. $form->addElement('html', '<br /><br />');
  932. $form->addElement('style_submit_button', 'submitExercise', $text, 'class="save"');
  933. $form->addRule('exerciseTitle', get_lang('GiveExerciseName'), 'required');
  934. if($type=='full') {
  935. // rules
  936. $form->addRule('exerciseAttempts', get_lang('Numeric'), 'numeric');
  937. $form->addRule('start_time', get_lang('InvalidDate'), 'date');
  938. $form->addRule('end_time', get_lang('InvalidDate'), 'date');
  939. //$form->addRule(array ('start_time', 'end_time'), get_lang('StartDateShouldBeBeforeEndDate'), 'date_compare', 'lte');
  940. }
  941. // defaults
  942. if ($type=='full') {
  943. if($this->id > 0) {
  944. if ($this->random > $this->selectNbrQuestions()) {
  945. $defaults['randomQuestions'] = $this->selectNbrQuestions();
  946. } else {
  947. $defaults['randomQuestions'] = $this->random;
  948. }
  949. $defaults['randomAnswers'] = $this ->selectRandomAnswers();
  950. $defaults['exerciseType'] = $this->selectType();
  951. $defaults['exerciseTitle'] = $this->selectTitle();
  952. $defaults['exerciseDescription'] = $this->selectDescription();
  953. $defaults['exerciseAttempts'] = $this->selectAttempts();
  954. $defaults['exerciseFeedbackType'] = $this->selectFeedbackType();
  955. $defaults['results_disabled'] = $this->selectResultsDisabled();
  956. $defaults['propagate_neg'] = $this->selectPropagateNeg();
  957. if (($this->start_time!='0000-00-00 00:00:00'))
  958. $defaults['activate_start_date_check'] = 1;
  959. if ($this->end_time!='0000-00-00 00:00:00')
  960. $defaults['activate_end_date_check'] = 1;
  961. $defaults['start_time'] = ($this->start_time!='0000-00-00 00:00:00')? $this->start_time : date('Y-m-d 12:00:00');
  962. $defaults['end_time'] = ($this->end_time!='0000-00-00 00:00:00')?$this->end_time : date('Y-m-d 12:00:00',time()+84600);
  963. //Get expired time
  964. if($this->expired_time != '0') {
  965. $defaults['enabletimercontrol'] = 1;
  966. $defaults['enabletimercontroltotalminutes'] = $this->expired_time;
  967. } else {
  968. $defaults['enabletimercontroltotalminutes'] = 0;
  969. }
  970. } else {
  971. $defaults['exerciseType'] = 2;
  972. $defaults['exerciseAttempts'] = 0;
  973. $defaults['randomQuestions'] = 0;
  974. $defaults['randomAnswers'] = 0;
  975. $defaults['exerciseDescription'] = '';
  976. $defaults['exerciseFeedbackType'] = 0;
  977. $defaults['results_disabled'] = 0;
  978. $defaults['start_time'] = date('Y-m-d 12:00:00');
  979. $defaults['end_time'] = date('Y-m-d 12:00:00',time()+84600);
  980. }
  981. } else {
  982. $defaults['exerciseTitle'] = $this->selectTitle();
  983. $defaults['exerciseDescription'] = $this->selectDescription();
  984. }
  985. if (api_get_setting('search_enabled') === 'true') {
  986. $defaults['index_document'] = 'checked="checked"';
  987. }
  988. $form->setDefaults($defaults);
  989. }
  990. /**
  991. * function which process the creation of exercises
  992. * @param FormValidator $form the formvalidator instance
  993. */
  994. function processCreation($form, $type='') {
  995. $this->updateTitle($form->getSubmitValue('exerciseTitle'));
  996. $this->updateDescription($form->getSubmitValue('exerciseDescription'));
  997. $this->updateAttempts($form->getSubmitValue('exerciseAttempts'));
  998. $this->updateFeedbackType($form->getSubmitValue('exerciseFeedbackType'));
  999. $this->updateType($form->getSubmitValue('exerciseType'));
  1000. $this->setRandom($form->getSubmitValue('randomQuestions'));
  1001. $this->updateRandomAnswers($form->getSubmitValue('randomAnswers'));
  1002. $this->updateResultsDisabled($form->getSubmitValue('results_disabled'));
  1003. $this->updateExpiredTime($form->getSubmitValue('enabletimercontroltotalminutes'));
  1004. $this->updatePropagateNegative($form->getSubmitValue('propagate_neg'));
  1005. if ($form->getSubmitValue('activate_start_date_check') == 1) {
  1006. $start_time = $form->getSubmitValue('start_time');
  1007. $this->start_time = $start_time['Y'].'-'.$start_time['F'].'-'.$start_time['d'].' '.$start_time['H'].':'.$start_time['i'].':00';
  1008. } else {
  1009. $this->start_time = '0000-00-00 00:00:00';
  1010. }
  1011. if ($form->getSubmitValue('activate_end_date_check') == 1) {
  1012. $end_time = $form->getSubmitValue('end_time');
  1013. $this->end_time = $end_time['Y'].'-'.$end_time['F'].'-'.$end_time['d'].' '.$end_time['H'].':'.$end_time['i'].':00';
  1014. } else {
  1015. $this->end_time = '0000-00-00 00:00:00';
  1016. }
  1017. if ($form->getSubmitValue('enabletimercontrol') == 1) {
  1018. $expired_total_time = $form->getSubmitValue('enabletimercontroltotalminutes');
  1019. if ($this->expired_time == 0) {
  1020. $this->expired_time = $expired_total_time;
  1021. }
  1022. } else {
  1023. $this->expired_time = 0;
  1024. }
  1025. if ($form->getSubmitValue('randomAnswers') == 1) {
  1026. $this->random_answers=1;
  1027. } else {
  1028. $this->random_answers=0;
  1029. }
  1030. $this->save($type);
  1031. }
  1032. function search_engine_save() {
  1033. if ($_POST['index_document'] != 1) {
  1034. return;
  1035. }
  1036. $course_id = api_get_course_id();
  1037. require_once api_get_path(LIBRARY_PATH) . 'search/DokeosIndexer.class.php';
  1038. require_once api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php';
  1039. require_once api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php';
  1040. $specific_fields = get_specific_field_list();
  1041. $ic_slide = new IndexableChunk();
  1042. $all_specific_terms = '';
  1043. foreach ($specific_fields as $specific_field) {
  1044. if (isset($_REQUEST[$specific_field['code']])) {
  1045. $sterms = trim($_REQUEST[$specific_field['code']]);
  1046. if (!empty($sterms)) {
  1047. $all_specific_terms .= ' '. $sterms;
  1048. $sterms = explode(',', $sterms);
  1049. foreach ($sterms as $sterm) {
  1050. $ic_slide->addTerm(trim($sterm), $specific_field['code']);
  1051. add_specific_field_value($specific_field['id'], $course_id, TOOL_QUIZ, $this->id, $sterm);
  1052. }
  1053. }
  1054. }
  1055. }
  1056. // build the chunk to index
  1057. $ic_slide->addValue("title", $this->exercise);
  1058. $ic_slide->addCourseId($course_id);
  1059. $ic_slide->addToolId(TOOL_QUIZ);
  1060. $xapian_data = array(
  1061. SE_COURSE_ID => $course_id,
  1062. SE_TOOL_ID => TOOL_QUIZ,
  1063. SE_DATA => array('type' => SE_DOCTYPE_EXERCISE_EXERCISE, 'exercise_id' => (int)$this->id),
  1064. SE_USER => (int)api_get_user_id(),
  1065. );
  1066. $ic_slide->xapian_data = serialize($xapian_data);
  1067. $exercise_description = $all_specific_terms .' '. $this->description;
  1068. $ic_slide->addValue("content", $exercise_description);
  1069. $di = new DokeosIndexer();
  1070. isset($_POST['language'])? $lang=Database::escape_string($_POST['language']): $lang = 'english';
  1071. $di->connectDb(NULL, NULL, $lang);
  1072. $di->addChunk($ic_slide);
  1073. //index and return search engine document id
  1074. $did = $di->index();
  1075. if ($did) {
  1076. // save it to db
  1077. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  1078. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
  1079. VALUES (NULL , \'%s\', \'%s\', %s, %s)';
  1080. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id, $did);
  1081. Database::query($sql);
  1082. }
  1083. }
  1084. function search_engine_edit() {
  1085. // update search enchine and its values table if enabled
  1086. if (api_get_setting('search_enabled')=='true' && extension_loaded('xapian')) {
  1087. $course_id = api_get_course_id();
  1088. // actually, it consists on delete terms from db, insert new ones, create a new search engine document, and remove the old one
  1089. // get search_did
  1090. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  1091. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s LIMIT 1';
  1092. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  1093. $res = Database::query($sql);
  1094. if (Database::num_rows($res) > 0) {
  1095. require_once(api_get_path(LIBRARY_PATH) . 'search/DokeosIndexer.class.php');
  1096. require_once(api_get_path(LIBRARY_PATH) . 'search/IndexableChunk.class.php');
  1097. require_once(api_get_path(LIBRARY_PATH) . 'specific_fields_manager.lib.php');
  1098. $se_ref = Database::fetch_array($res);
  1099. $specific_fields = get_specific_field_list();
  1100. $ic_slide = new IndexableChunk();
  1101. $all_specific_terms = '';
  1102. foreach ($specific_fields as $specific_field) {
  1103. delete_all_specific_field_value($course_id, $specific_field['id'], TOOL_QUIZ, $this->id);
  1104. if (isset($_REQUEST[$specific_field['code']])) {
  1105. $sterms = trim($_REQUEST[$specific_field['code']]);
  1106. $all_specific_terms .= ' '. $sterms;
  1107. $sterms = explode(',', $sterms);
  1108. foreach ($sterms as $sterm) {
  1109. $ic_slide->addTerm(trim($sterm), $specific_field['code']);
  1110. add_specific_field_value($specific_field['id'], $course_id, TOOL_QUIZ, $this->id, $sterm);
  1111. }
  1112. }
  1113. }
  1114. // build the chunk to index
  1115. $ic_slide->addValue("title", $this->exercise);
  1116. $ic_slide->addCourseId($course_id);
  1117. $ic_slide->addToolId(TOOL_QUIZ);
  1118. $xapian_data = array(
  1119. SE_COURSE_ID => $course_id,
  1120. SE_TOOL_ID => TOOL_QUIZ,
  1121. SE_DATA => array('type' => SE_DOCTYPE_EXERCISE_EXERCISE, 'exercise_id' => (int)$this->id),
  1122. SE_USER => (int)api_get_user_id(),
  1123. );
  1124. $ic_slide->xapian_data = serialize($xapian_data);
  1125. $exercise_description = $all_specific_terms .' '. $this->description;
  1126. $ic_slide->addValue("content", $exercise_description);
  1127. $di = new DokeosIndexer();
  1128. isset($_POST['language'])? $lang=Database::escape_string($_POST['language']): $lang = 'english';
  1129. $di->connectDb(NULL, NULL, $lang);
  1130. $di->remove_document((int)$se_ref['search_did']);
  1131. $di->addChunk($ic_slide);
  1132. //index and return search engine document id
  1133. $did = $di->index();
  1134. if ($did) {
  1135. // save it to db
  1136. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=\'%s\'';
  1137. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  1138. Database::query($sql);
  1139. $sql = 'INSERT INTO %s (id, course_code, tool_id, ref_id_high_level, search_did)
  1140. VALUES (NULL , \'%s\', \'%s\', %s, %s)';
  1141. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id, $did);
  1142. Database::query($sql);
  1143. }
  1144. } else {
  1145. $this->search_engine_save();
  1146. }
  1147. }
  1148. }
  1149. function search_engine_delete() {
  1150. // remove from search engine if enabled
  1151. if (api_get_setting('search_enabled') == 'true' && extension_loaded('xapian') ) {
  1152. $course_id = api_get_course_id();
  1153. $tbl_se_ref = Database::get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
  1154. $sql = 'SELECT * FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level IS NULL LIMIT 1';
  1155. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  1156. $res = Database::query($sql);
  1157. if (Database::num_rows($res) > 0) {
  1158. $row = Database::fetch_array($res);
  1159. require_once(api_get_path(LIBRARY_PATH) .'search/DokeosIndexer.class.php');
  1160. $di = new DokeosIndexer();
  1161. $di->remove_document((int)$row['search_did']);
  1162. unset($di);
  1163. $tbl_quiz_question = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1164. foreach ( $this->questionList as $question_i) {
  1165. $sql = 'SELECT type FROM %s WHERE id=%s';
  1166. $sql = sprintf($sql, $tbl_quiz_question, $question_i);
  1167. $qres = Database::query($sql);
  1168. if (Database::num_rows($qres) > 0) {
  1169. $qrow = Database::fetch_array($qres);
  1170. $objQuestion = Question::getInstance($qrow['type']);
  1171. $objQuestion = Question::read((int)$question_i);
  1172. $objQuestion->search_engine_edit($this->id, FALSE, TRUE);
  1173. unset($objQuestion);
  1174. }
  1175. }
  1176. }
  1177. $sql = 'DELETE FROM %s WHERE course_code=\'%s\' AND tool_id=\'%s\' AND ref_id_high_level=%s AND ref_id_second_level IS NULL LIMIT 1';
  1178. $sql = sprintf($sql, $tbl_se_ref, $course_id, TOOL_QUIZ, $this->id);
  1179. Database::query($sql);
  1180. // remove terms from db
  1181. require_once(api_get_path(LIBRARY_PATH) .'specific_fields_manager.lib.php');
  1182. delete_all_values_for_item($course_id, TOOL_QUIZ, $this->id);
  1183. }
  1184. }
  1185. function selectExpiredTime() {
  1186. return $this->expired_time;
  1187. }
  1188. /**
  1189. * Cleans the student's results only for the Exercise tool (Not from the LP)
  1190. * The LP results are NOT deleted
  1191. * Works with exercises in sessions
  1192. * @return int quantity of user's exercises deleted
  1193. */
  1194. function clean_results() {
  1195. $table_track_e_exercises = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  1196. $table_track_e_attempt = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  1197. $sql_select = "SELECT exe_id FROM $table_track_e_exercises
  1198. WHERE exe_cours_id = '".api_get_course_id()."' AND exe_exo_id = ".$this->id." AND orig_lp_id = 0 AND orig_lp_item_id = 0 AND session_id = ".api_get_session_id()."";
  1199. $result = Database::query($sql_select);
  1200. $exe_list = Database::store_result($result);
  1201. //deleting TRACK_E_ATTEMPT table
  1202. $i = 0;
  1203. if (is_array($exe_list) && count($exe_list) > 0) {
  1204. foreach($exe_list as $item) {
  1205. $sql = "DELETE FROM $table_track_e_attempt WHERE exe_id = '".$item['exe_id']."'";
  1206. Database::query($sql);
  1207. $i++;
  1208. }
  1209. }
  1210. //delete TRACK_E_EXERCICES table
  1211. $sql = "DELETE FROM $table_track_e_exercises
  1212. WHERE exe_cours_id = '".api_get_course_id()."' AND exe_exo_id = ".$this->id." AND orig_lp_id = 0 AND orig_lp_item_id = 0 AND session_id = ".api_get_session_id()."";
  1213. Database::query($sql);
  1214. return $i;
  1215. }
  1216. /**
  1217. * Copies an exercise (duplicate all questions and answers)
  1218. */
  1219. public function copy_exercise() {
  1220. $exercise_obj= new Exercise();
  1221. $exercise_obj = $this;
  1222. $TBL_EXERCICE_QUESTION = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
  1223. $TBL_EXERCICES = Database::get_course_table(TABLE_QUIZ_TEST);
  1224. $TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
  1225. // force the creation of a new exercise
  1226. $exercise_obj->updateTitle($exercise_obj->selectTitle().' - '.get_lang('Copy'));
  1227. //Hides the new exercise
  1228. $exercise_obj->updateStatus(false);
  1229. $exercise_obj->updateId(0);
  1230. $exercise_obj->save();
  1231. $new_exercise_id = $exercise_obj->selectId();
  1232. $question_list = $exercise_obj->selectQuestionList();
  1233. //Question creation
  1234. foreach ($question_list as $old_question_id) {
  1235. $old_question_obj = Question::read($old_question_id);
  1236. $new_id = $old_question_obj->duplicate();
  1237. $new_question_obj = Question::read($new_id);
  1238. $new_question_obj->addToList($new_exercise_id);
  1239. // This should be moved to the duplicate function
  1240. $new_answer_obj = new Answer($old_question_id);
  1241. $new_answer_obj->read();
  1242. $new_answer_obj->duplicate($new_id);
  1243. }
  1244. }
  1245. /**
  1246. * Changes the exercise id
  1247. *
  1248. * @param - in $id - exercise id
  1249. */
  1250. private function updateId($id) {
  1251. $this->id = $id;
  1252. }
  1253. /**
  1254. * Changes the exercise status
  1255. *
  1256. * @param - string $status - exercise status
  1257. */
  1258. function updateStatus($status) {
  1259. $this->active = $status;
  1260. }
  1261. public function get_stat_track_exercise_info($lp_id = 0, $lp_item_id = 0, $lp_item_view_id = 0, $status = 'incomplete') {
  1262. $track_exercises = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  1263. if (empty($lp_id)) {
  1264. $lp_id = 0;
  1265. }
  1266. if (empty($lp_item_id)) {
  1267. $lp_item_id = 0;
  1268. }
  1269. if (empty($lp_item_view_id)) {
  1270. $lp_item_view_id = 0;
  1271. }
  1272. $condition = ' WHERE exe_exo_id = ' . "'" . $this->id . "'" .' AND
  1273. exe_user_id = ' . "'" . api_get_user_id() . "'" . ' AND
  1274. exe_cours_id = ' . "'" . api_get_course_id() . "'" . ' AND
  1275. status = ' . "'" . Database::escape_string($status). "'" . ' AND
  1276. orig_lp_id = ' . "'" . $lp_id . "'" . ' AND
  1277. orig_lp_item_id = ' . "'" . $lp_item_id . "'" . ' AND
  1278. orig_lp_item_view_id = ' . "'" . $lp_item_view_id . "'" . ' AND
  1279. session_id = ' . "'" . api_get_session_id() . "' LIMIT 1"; //Adding limit 1 just in case
  1280. $sql_track = 'SELECT * FROM '.$track_exercises.$condition;
  1281. $result = Database::query($sql_track);
  1282. $new_array = array();
  1283. if (Database::num_rows($result) > 0 ) {
  1284. $new_array = Database::fetch_array($result, 'ASSOC');
  1285. }
  1286. return $new_array;
  1287. }
  1288. /**
  1289. * Saves a test attempt
  1290. *
  1291. * @param int clock_expired_time
  1292. * @param int lp id
  1293. * @param int lp item id
  1294. * @param int lp item_view id
  1295. * @param array question list
  1296. */
  1297. public function save_stat_track_exercise_info($clock_expired_time = 0, $safe_lp_id = 0, $safe_lp_item_id = 0, $safe_lp_item_view_id = 0, $questionList = array(), $weight) {
  1298. $track_exercises = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  1299. if (empty($safe_lp_id)) {
  1300. $safe_lp_id = 0;
  1301. }
  1302. if (empty($safe_lp_item_id)) {
  1303. $safe_lp_item_id = 0;
  1304. }
  1305. if (empty($clock_expired_time)) {
  1306. $clock_expired_time = 0;
  1307. }
  1308. if ($this->expired_time != 0) {
  1309. $sql_fields = "expired_time_control, ";
  1310. $sql_fields_values = "'"."$clock_expired_time"."',";
  1311. } else {
  1312. $sql_fields = "";
  1313. $sql_fields_values = "";
  1314. }
  1315. if ($this->type == ONE_PER_PAGE) {
  1316. $sql = "INSERT INTO $track_exercises ($sql_fields exe_exo_id, exe_user_id, exe_cours_id, status,session_id, data_tracking, start_date, orig_lp_id, orig_lp_item_id, exe_weighting)
  1317. VALUES($sql_fields_values '".$this->id."','" . api_get_user_id() . "','" . api_get_course_id() . "','incomplete','" . api_get_session_id() . "','" . implode(',', $questionList) . "', '" . api_get_utc_datetime() . "', '$safe_lp_id', '$safe_lp_item_id', '$weight' )";
  1318. } else {
  1319. $sql = "INSERT INTO $track_exercises ($sql_fields exe_exo_id,exe_user_id,exe_cours_id,status,session_id,start_date,orig_lp_id,orig_lp_item_id)
  1320. VALUES($sql_fields_values '".$this->id."','" . api_get_user_id() . "','" . api_get_course_id() . "','incomplete','" . api_get_session_id() . "','" . api_get_utc_datetime() . "', '$safe_lp_id', '$safe_lp_item_id' , '$weight' )";
  1321. }
  1322. Database::query($sql);
  1323. }
  1324. public function show_button($nbrQuestions, $questionNum, $exerciseId) {
  1325. global $origin, $learnpath_id,$learnpath_item_id;
  1326. $nbrQuestions = intval($nbrQuestions);
  1327. $exerciseId = intval($exerciseId);
  1328. $html = '';
  1329. $html = '<div style="margin-top:-10px;">';
  1330. $confirmation_alert = $this->type == 1? " onclick=\"javascript:if(!confirm('".get_lang("ConfirmYourChoice")."')) return false;\" ":"";
  1331. $submit_btn = '<button class="next" type="submit" name="submit" name="submit_save" id="submit_save" '.$confirmation_alert.' >';
  1332. $hotspot_get = $_POST['hotspot'];
  1333. if ($this->selectFeedbackType() == EXERCISE_FEEDBACK_TYPE_DIRECT && $this->type == ONE_PER_PAGE) {
  1334. $submit_btn = '';
  1335. $html .='<script src="' . api_get_path(WEB_LIBRARY_PATH) . 'javascript/thickbox.js" type="text/javascript"></script>';
  1336. $html .='<style type="text/css" media="all">@import "' . api_get_path(WEB_LIBRARY_PATH) . 'javascript/thickbox.css";</style>';
  1337. $html .='<style type="text/css" media="all">@import "' . api_get_path(WEB_LIBRARY_PATH) . 'javascript/thickbox.css";</style>';
  1338. $html .= api_get_jquery_ui_js();
  1339. $html .='
  1340. <script>
  1341. $(function() {
  1342. $(".button").button();
  1343. });
  1344. </script>';
  1345. //$html .='<br /><a href="exercise_submit_modal.php?learnpath_id='.$learnpath_id.'&learnpath_item_id='.$learnpath_item_id.'&origin='.$origin.'&hotspot='.$hotspot_get.'&nbrQuestions='.$nbrQuestions.'&questionnum='.$questionNum.'&exerciseType='.$exerciseType.'&exerciseId='.$exerciseId.'&placeValuesBeforeTB_=savedValues&TB_iframe=true&height=480&width=640&modal=true" title="" class="thickbox button" id="validationButton">';
  1346. $html .='<a href="exercise_submit_modal.php?learnpath_id='.$learnpath_id.'&learnpath_item_id='.$learnpath_item_id.'&origin='.$origin.'&hotspot='.$hotspot_get.'&nbrQuestions='.$nbrQuestions.'&questionnum='.$questionNum.'&exerciseType='.$this->type.'&exerciseId='.$exerciseId.'&placeValuesBeforeTB_=savedValues&TB_iframe=true&height=480&width=640&modal=true" title="" class="thickbox button" id="validationButton">';
  1347. $html .= get_lang('ValidateAnswer').'</a>';
  1348. $html .='<br />';
  1349. } else {
  1350. if (api_is_allowed_to_session_edit() ) {
  1351. if ($this->type == ALL_ON_ONE_PAGE || $nbrQuestions == $questionNum) {
  1352. $submit_btn .= get_lang('ValidateAnswer');
  1353. $name_btn = get_lang('ValidateAnswer');
  1354. } else {
  1355. $submit_btn .= get_lang('NextQuestion');
  1356. $name_btn = get_lang('NextQuestion');
  1357. }
  1358. $submit_btn .= '</button>';
  1359. if ($this->expired_time != 0) {
  1360. $html .= $submit_btn ='<button class="next" type="submit" id="submit_save" value="'.$name_btn.'" name="submit_save"/>'.$name_btn.'</button>';
  1361. } else {
  1362. $html .= $submit_btn;
  1363. }
  1364. }
  1365. }
  1366. $html .= '</div>'; //margin top -10
  1367. return $html;
  1368. }
  1369. /**
  1370. * So the time control will work
  1371. */
  1372. public function show_time_control_js($time_left) {
  1373. $time_left = intval($time_left);
  1374. return "<script type=\"text/javascript\">
  1375. $(document).ready(function(){
  1376. function get_expired_date_string(expired_time) {
  1377. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  1378. var day, month, year, hours, minutes, seconds, date_string;
  1379. var obj_date = new Date(expired_time);
  1380. day = obj_date.getDate();
  1381. if (day < 10) day = '0' + day;
  1382. month = obj_date.getMonth();
  1383. year = obj_date.getFullYear();
  1384. hours = obj_date.getHours();
  1385. if (hours < 10) hours = '0' + hours;
  1386. minutes = obj_date.getMinutes();
  1387. if (minutes < 10) minutes = '0' + minutes;
  1388. seconds = obj_date.getSeconds();
  1389. if (seconds < 10) seconds = '0' + seconds;
  1390. date_string = months[month] +' ' + day + ', ' + year + ' ' + hours + ':' + minutes + ':' + seconds;
  1391. return date_string;
  1392. }
  1393. function onExpiredTimeExercise() {
  1394. $('#wrapper-clock').hide(); $('#exercise_form').hide();
  1395. $('#expired-message-id').show();
  1396. $('#exercise_form').submit();
  1397. }
  1398. var current_time = new Date().getTime();
  1399. var time_left = parseInt(".$time_left.");
  1400. var expired_time = current_time + (time_left*1000);
  1401. var expired_date = get_expired_date_string(expired_time);
  1402. $('#text-content').epiclock({
  1403. mode: EC_COUNTDOWN,
  1404. format: 'x{ : } i{ : } s{}',
  1405. target: expired_date,
  1406. onTimer: function(){ onExpiredTimeExercise(); }
  1407. }).clocks(EC_RUN);
  1408. $('#submit_save').click(function () {});
  1409. });
  1410. </script>";
  1411. }
  1412. /**
  1413. * Lp javascript for hotspots
  1414. */
  1415. public function show_lp_javascript() {
  1416. return "<script type=\"text/javascript\" src=\"../plugin/hotspot/JavaScriptFlashGateway.js\"></script>
  1417. <script src=\"../plugin/hotspot/hotspot.js\" type=\"text/javascript\"></script>
  1418. <script language=\"JavaScript\" type=\"text/javascript\">
  1419. <!--
  1420. // -----------------------------------------------------------------------------
  1421. // Globals
  1422. // Major version of Flash required
  1423. var requiredMajorVersion = 7;
  1424. // Minor version of Flash required
  1425. var requiredMinorVersion = 0;
  1426. // Minor version of Flash required
  1427. var requiredRevision = 0;
  1428. // the version of javascript supported
  1429. var jsVersion = 1.0;
  1430. // -----------------------------------------------------------------------------
  1431. // -->
  1432. </script>
  1433. <script language=\"VBScript\" type=\"text/vbscript\">
  1434. <!-- // Visual basic helper required to detect Flash Player ActiveX control version information
  1435. Function VBGetSwfVer(i)
  1436. on error resume next
  1437. Dim swControl, swVersion
  1438. swVersion = 0
  1439. set swControl = CreateObject(\"ShockwaveFlash.ShockwaveFlash.\" + CStr(i))
  1440. if (IsObject(swControl)) then
  1441. swVersion = swControl.GetVariable(\"\$version\")
  1442. end if
  1443. VBGetSwfVer = swVersion
  1444. End Function
  1445. // -->
  1446. </script>
  1447. <script language=\"JavaScript1.1\" type=\"text/javascript\">
  1448. <!-- // Detect Client Browser type
  1449. var isIE = (navigator.appVersion.indexOf(\"MSIE\") != -1) ? true : false;
  1450. var isWin = (navigator.appVersion.toLowerCase().indexOf(\"win\") != -1) ? true : false;
  1451. var isOpera = (navigator.userAgent.indexOf(\"Opera\") != -1) ? true : false;
  1452. jsVersion = 1.1;
  1453. // JavaScript helper required to detect Flash Player PlugIn version information
  1454. function JSGetSwfVer(i){
  1455. // NS/Opera version >= 3 check for Flash plugin in plugin array
  1456. if (navigator.plugins != null && navigator.plugins.length > 0) {
  1457. if (navigator.plugins[\"Shockwave Flash 2.0\"] || navigator.plugins[\"Shockwave Flash\"]) {
  1458. var swVer2 = navigator.plugins[\"Shockwave Flash 2.0\"] ? \" 2.0\" : \"\";
  1459. var flashDescription = navigator.plugins[\"Shockwave Flash\" + swVer2].description;
  1460. descArray = flashDescription.split(\" \");
  1461. tempArrayMajor = descArray[2].split(\".\");
  1462. versionMajor = tempArrayMajor[0];
  1463. versionMinor = tempArrayMajor[1];
  1464. if ( descArray[3] != \"\" ) {
  1465. tempArrayMinor = descArray[3].split(\"r\");
  1466. } else {
  1467. tempArrayMinor = descArray[4].split(\"r\");
  1468. }
  1469. versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
  1470. flashVer = versionMajor + \".\" + versionMinor + \".\" + versionRevision;
  1471. } else {
  1472. flashVer = -1;
  1473. }
  1474. }
  1475. // MSN/WebTV 2.6 supports Flash 4
  1476. else if (navigator.userAgent.toLowerCase().indexOf(\"webtv/2.6\") != -1) flashVer = 4;
  1477. // WebTV 2.5 supports Flash 3
  1478. else if (navigator.userAgent.toLowerCase().indexOf(\"webtv/2.5\") != -1) flashVer = 3;
  1479. // older WebTV supports Flash 2
  1480. else if (navigator.userAgent.toLowerCase().indexOf(\"webtv\") != -1) flashVer = 2;
  1481. // Can't detect in all other cases
  1482. else {
  1483. flashVer = -1;
  1484. }
  1485. return flashVer;
  1486. }
  1487. // When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
  1488. function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
  1489. {
  1490. reqVer = parseFloat(reqMajorVer + \".\" + reqRevision);
  1491. // loop backwards through the versions until we find the newest version
  1492. for (i=25;i>0;i--) {
  1493. if (isIE && isWin && !isOpera) {
  1494. versionStr = VBGetSwfVer(i);
  1495. } else {
  1496. versionStr = JSGetSwfVer(i);
  1497. }
  1498. if (versionStr == -1 ) {
  1499. return false;
  1500. } else if (versionStr != 0) {
  1501. if(isIE && isWin && !isOpera) {
  1502. tempArray = versionStr.split(\" \");
  1503. tempString = tempArray[1];
  1504. versionArray = tempString .split(\",\");
  1505. } else {
  1506. versionArray = versionStr.split(\".\");
  1507. }
  1508. versionMajor = versionArray[0];
  1509. versionMinor = versionArray[1];
  1510. versionRevision = versionArray[2];
  1511. versionString = versionMajor + \".\" + versionRevision; // 7.0r24 == 7.24
  1512. versionNum = parseFloat(versionString);
  1513. // is the major.revision >= requested major.revision AND the minor version >= requested minor
  1514. if ( (versionMajor > reqMajorVer) && (versionNum >= reqVer) ) {
  1515. return true;
  1516. } else {
  1517. return ((versionNum >= reqVer && versionMinor >= reqMinorVer) ? true : false );
  1518. }
  1519. }
  1520. }
  1521. }
  1522. // -->
  1523. </script>";
  1524. }
  1525. /**
  1526. * This function was originally found in the exercise_show.php
  1527. * @param int exe id
  1528. * @param int question id
  1529. * @param int the choice the user selected
  1530. * @param array the hotspot coordinates $hotspot[$question_id] = coordinates
  1531. * @param string function is called from 'exercise_show' or 'exercise_result'
  1532. * @param bool save results in the DB or just show the reponse
  1533. * @param bool gets information from DB or from the current selection
  1534. * @param bool show results or not
  1535. * @todo reduce parameters of this function
  1536. * @return string html code
  1537. */
  1538. function manage_answer($exeId, $questionId, $choice, $from = 'exercise_show', $exerciseResultCoordinates = array(), $saved_results = true, $from_database = false, $show_result = true, $propagate_neg = 0, $hotspot_delineation_result = array()) {
  1539. global $_configuration, $feedback_type, $debug;
  1540. require_once api_get_path(LIBRARY_PATH).'geometry.lib.php';
  1541. if ($debug) error_log('manage_answer called exe_id '.$exeId);
  1542. if ($debug) error_log('manage_answer $from '.$from);
  1543. if ($debug) error_log('manage_answer $saved_results '.$saved_results);
  1544. if ($debug) error_log('manage_answer $from_database '.$from_database);
  1545. if ($debug) error_log('manage_answer $show_result '.$show_result);
  1546. if ($debug) error_log('manage_answer $propagate_neg '.$propagate_neg);
  1547. if ($debug) error_log('manage_answer $$hotspot_delineation_result '.print_r($hotspot_delineation_result, 1));
  1548. $extra_data = array();
  1549. $html = '';
  1550. $questionId = intval($questionId);
  1551. $exeId = intval($exeId);
  1552. $TBL_TRACK_ATTEMPT = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
  1553. $table_ans = Database::get_course_table(TABLE_QUIZ_ANSWER);
  1554. // Creates a temporary Question object
  1555. $objQuestionTmp = Question :: read($questionId);
  1556. $questionName = $objQuestionTmp->selectTitle();
  1557. $questionDescription = $objQuestionTmp->selectDescription();
  1558. $questionWeighting = $objQuestionTmp->selectWeighting();
  1559. $answerType = $objQuestionTmp->selectType();
  1560. $quesId = $objQuestionTmp->selectId();
  1561. $extra = $objQuestionTmp->extra;
  1562. $next = 1; //not for now
  1563. //Extra information of the question
  1564. if (!empty($extra)){
  1565. $extra = explode(':', $extra);
  1566. $true_score = $extra[0];
  1567. $false_score = $extra[1];
  1568. $doubt_score = $extra[2];
  1569. }
  1570. $totalWeighting = 0;
  1571. $totalScore = 0;
  1572. // Destruction of the Question object
  1573. unset ($objQuestionTmp);
  1574. // Construction of the Answer object
  1575. $objAnswerTmp = new Answer($questionId);
  1576. $nbrAnswers = $objAnswerTmp->selectNbrAnswers();
  1577. if ($debug) error_log('Count of answers :'.$nbrAnswers);
  1578. if ($debug) error_log('$answerType : '.$answerType);
  1579. $questionScore = 0;
  1580. if ($answerType == FREE_ANSWER) {
  1581. $nbrAnswers = 1;
  1582. }
  1583. $user_answer = '';
  1584. // Get answer list for matching
  1585. $sql_answer = 'SELECT id, answer FROM '.$table_ans.' WHERE question_id = "'.$questionId.'" ';
  1586. $res_answer = Database::query($sql_answer);
  1587. $answer_matching =array();
  1588. while ($real_answer = Database::fetch_array($res_answer)) {
  1589. $answer_matching[$real_answer['id']]= $real_answer['answer'];
  1590. }
  1591. $real_answers = array();
  1592. $quiz_question_options = Question::readQuestionOption($questionId);
  1593. $organs_at_risk_hit = 0;
  1594. for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
  1595. $answer = $objAnswerTmp->selectAnswer($answerId);
  1596. $answerComment = $objAnswerTmp->selectComment($answerId);
  1597. $answerCorrect = $objAnswerTmp->isCorrect($answerId);
  1598. $answerWeighting = $objAnswerTmp->selectWeighting($answerId);
  1599. $numAnswer = $objAnswerTmp->selectAutoId($answerId);
  1600. //delineation
  1601. $delineation_cord = $objAnswerTmp->selectHotspotCoordinates(1);
  1602. $answer_delineation_destination=$objAnswerTmp->selectDestination(1);
  1603. switch ($answerType) {
  1604. // for unique answer
  1605. case UNIQUE_ANSWER :
  1606. case UNIQUE_ANSWER_NO_OPTION :
  1607. if ($from_database) {
  1608. $queryans = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." where exe_id = '".$exeId."' and question_id= '".$questionId."'";
  1609. $resultans = Database::query($queryans);
  1610. $choice = Database::result($resultans,0,"answer");
  1611. $numAnswer=$objAnswerTmp->selectAutoId($answerId);
  1612. $studentChoice=($choice == $numAnswer)?1:0;
  1613. if ($studentChoice) {
  1614. $questionScore+=$answerWeighting;
  1615. $totalScore+=$answerWeighting;
  1616. }
  1617. } else {
  1618. $studentChoice=($choice == $numAnswer)?1:0;
  1619. if ($studentChoice) {
  1620. $questionScore+=$answerWeighting;
  1621. $totalScore+=$answerWeighting;
  1622. }
  1623. }
  1624. break;
  1625. // for multiple answers
  1626. case MULTIPLE_ANSWER_TRUE_FALSE :
  1627. if ($from_database) {
  1628. $choice=array();
  1629. $queryans = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." where exe_id = '".$exeId."' and question_id= '".$questionId."'";
  1630. $resultans = Database::query($queryans);
  1631. while ($row = Database::fetch_array($resultans)) {
  1632. $ind = $row['answer'];
  1633. $result = explode(':',$ind);
  1634. $my_answer_id = $result[0];
  1635. $option = $result[1];
  1636. $choice[$my_answer_id] = $option;
  1637. }
  1638. $numAnswer=$objAnswerTmp->selectAutoId($answerId);
  1639. $studentChoice =$choice[$numAnswer];
  1640. } else {
  1641. $studentChoice =$choice[$numAnswer];
  1642. }
  1643. if ($studentChoice == $answerCorrect ) {
  1644. $questionScore +=$true_score;
  1645. } else {
  1646. if ($quiz_question_options[$studentChoice]['name'] != 'DoubtScore') {
  1647. $questionScore += $false_score;
  1648. } else {
  1649. $questionScore += $doubt_score;
  1650. }
  1651. }
  1652. $totalScore +=$true_score;
  1653. break;
  1654. case MULTIPLE_ANSWER :
  1655. if ($from_database) {
  1656. $choice=array();
  1657. $queryans = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." where exe_id = '".$exeId."' and question_id= '".$questionId."'";
  1658. $resultans = Database::query($queryans);
  1659. while ($row = Database::fetch_array($resultans)) {
  1660. $ind = $row['answer'];
  1661. $choice[$ind] = 1;
  1662. }
  1663. $numAnswer=$objAnswerTmp->selectAutoId($answerId);
  1664. $studentChoice=$choice[$numAnswer];
  1665. if ($studentChoice) {
  1666. $questionScore +=$answerWeighting;
  1667. $totalScore +=$answerWeighting;
  1668. }
  1669. } else {
  1670. $studentChoice=$choice[$numAnswer];
  1671. if ($studentChoice) {
  1672. $questionScore +=$answerWeighting;
  1673. $totalScore +=$answerWeighting;
  1674. }
  1675. }
  1676. break;
  1677. case MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE:
  1678. if ($from_database) {
  1679. $queryans = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." where exe_id = '".$exeId."' and question_id= '".$questionId."'";
  1680. $resultans = Database::query($queryans);
  1681. while ($row = Database::fetch_array($resultans)) {
  1682. $ind = $row['answer'];
  1683. $result = explode(':',$ind);
  1684. $my_answer_id = $result[0];
  1685. $option = $result[1];
  1686. $choice[$my_answer_id] = $option;
  1687. }
  1688. $numAnswer=$objAnswerTmp->selectAutoId($answerId);
  1689. $studentChoice=$choice[$numAnswer];
  1690. if ($answerCorrect == 1) {
  1691. if ($studentChoice == 1) { //true value see MultipleAnswerCombinationTrueFalse class
  1692. $real_answers[$answerId] = true;
  1693. } elseif ($studentChoice == 2) { //false value
  1694. $real_answers[$answerId] = false;
  1695. } else {
  1696. $real_answers[$answerId] = false;
  1697. }
  1698. } else {
  1699. if ($studentChoice == 1) { //true value
  1700. $real_answers[$answerId] = false;
  1701. } elseif ($studentChoice == 2) { //false value see MultipleAnswerCombinationTrueFalse class
  1702. $real_answers[$answerId] = true;
  1703. } else {
  1704. $real_answers[$answerId] = true;
  1705. }
  1706. }
  1707. } else {
  1708. $studentChoice=$choice[$numAnswer];
  1709. if ($answerCorrect == 1) {
  1710. if ($studentChoice == 1) { //true value see MultipleAnswerCombinationTrueFalse class
  1711. $real_answers[$answerId] = true;
  1712. } elseif ($studentChoice == 2) { //false value
  1713. $real_answers[$answerId] = false;
  1714. } else {
  1715. $real_answers[$answerId] = false;
  1716. }
  1717. } else {
  1718. if ($studentChoice == 1) { //true value
  1719. $real_answers[$answerId] = false;
  1720. } elseif ($studentChoice == 2) { //false value see MultipleAnswerCombinationTrueFalse class
  1721. $real_answers[$answerId] = true;
  1722. } else {
  1723. $real_answers[$answerId] = true;
  1724. }
  1725. }
  1726. $final_answer = true;
  1727. foreach($real_answers as $my_answer) {
  1728. if (!$my_answer) {
  1729. $final_answer = false;
  1730. }
  1731. }
  1732. }
  1733. break;
  1734. case MULTIPLE_ANSWER_COMBINATION:
  1735. if ($from_database) {
  1736. $queryans = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." where exe_id = '".$exeId."' and question_id= '".$questionId."'";
  1737. $resultans = Database::query($queryans);
  1738. while ($row = Database::fetch_array($resultans)) {
  1739. $ind = $row['answer'];
  1740. $choice[$ind] = 1;
  1741. }
  1742. $numAnswer=$objAnswerTmp->selectAutoId($answerId);
  1743. $studentChoice=$choice[$numAnswer];
  1744. if ($answerCorrect == 1) {
  1745. if ($studentChoice) {
  1746. $real_answers[$answerId] = true;
  1747. } else {
  1748. $real_answers[$answerId] = false;
  1749. }
  1750. } else {
  1751. if ($studentChoice) {
  1752. $real_answers[$answerId] = false;
  1753. } else {
  1754. $real_answers[$answerId] = true;
  1755. }
  1756. }
  1757. } else {
  1758. $studentChoice=$choice[$numAnswer];
  1759. if ($answerCorrect == 1) {
  1760. if ($studentChoice) {
  1761. $real_answers[$answerId] = true;
  1762. } else {
  1763. $real_answers[$answerId] = false;
  1764. }
  1765. } else {
  1766. if ($studentChoice) {
  1767. $real_answers[$answerId] = false;
  1768. } else {
  1769. $real_answers[$answerId] = true;
  1770. }
  1771. }
  1772. $final_answer = true;
  1773. foreach($real_answers as $my_answer) {
  1774. if (!$my_answer) {
  1775. $final_answer = false;
  1776. }
  1777. }
  1778. }
  1779. break;
  1780. // for fill in the blanks
  1781. case FILL_IN_BLANKS :
  1782. // the question is encoded like this
  1783. // [A] B [C] D [E] F::10,10,10@1
  1784. // number 1 before the "@" means that is a switchable fill in blank question
  1785. // [A] B [C] D [E] F::10,10,10@ or [A] B [C] D [E] F::10,10,10
  1786. // means that is a normal fill blank question
  1787. // first we explode the "::"
  1788. $pre_array = explode('::', $answer);
  1789. // is switchable fill blank or not
  1790. $last = count($pre_array) - 1;
  1791. $is_set_switchable = explode('@', $pre_array[$last]);
  1792. $switchable_answer_set = false;
  1793. if (isset ($is_set_switchable[1]) && $is_set_switchable[1] == 1) {
  1794. $switchable_answer_set = true;
  1795. }
  1796. $answer = '';
  1797. for ($k = 0; $k < $last; $k++) {
  1798. $answer .= $pre_array[$k];
  1799. }
  1800. // splits weightings that are joined with a comma
  1801. $answerWeighting = explode(',', $is_set_switchable[0]);
  1802. // we save the answer because it will be modified
  1803. //$temp = $answer;
  1804. $temp = text_filter($answer);
  1805. $answer = '';
  1806. $j = 0;
  1807. //initialise answer tags
  1808. $user_tags = $correct_tags = $real_text = array ();
  1809. // the loop will stop at the end of the text
  1810. while (1) {
  1811. // quits the loop if there are no more blanks (detect '[')
  1812. if (($pos = api_strpos($temp, '[')) === false) {
  1813. // adds the end of the text
  1814. $answer = $temp;
  1815. /* // Deprecated code
  1816. // TeX parsing - replacement of texcode tags
  1817. $texstring = api_parse_tex($texstring);
  1818. $answer = str_replace("{texcode}", $texstring, $answer);
  1819. */
  1820. $real_text[] = $answer;
  1821. break; //no more "blanks", quit the loop
  1822. }
  1823. // adds the piece of text that is before the blank
  1824. //and ends with '[' into a general storage array
  1825. $real_text[] = api_substr($temp, 0, $pos +1);
  1826. $answer .= api_substr($temp, 0, $pos +1);
  1827. //take the string remaining (after the last "[" we found)
  1828. $temp = api_substr($temp, $pos +1);
  1829. // quit the loop if there are no more blanks, and update $pos to the position of next ']'
  1830. if (($pos = api_strpos($temp, ']')) === false) {
  1831. // adds the end of the text
  1832. $answer .= $temp;
  1833. break;
  1834. }
  1835. if ($from_database) {
  1836. $queryfill = "SELECT answer FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = '".$exeId."' AND question_id= '".Database::escape_string($questionId)."'";
  1837. $resfill = Database::query($queryfill);
  1838. $str = Database::result($resfill,0,'answer');
  1839. preg_match_all('#\[([^[]*)\]#', $str, $arr);
  1840. $str = str_replace('\r\n', '', $str);
  1841. $choice = $arr[1];
  1842. $tmp = api_strrpos($choice[$j],' / ');
  1843. $choice[$j] = api_substr($choice[$j],0,$tmp);
  1844. $choice[$j] = trim($choice[$j]);
  1845. //Needed to let characters ' and " to work as part of an answer
  1846. $choice[$j] = stripslashes($choice[$j]);
  1847. } else {
  1848. $choice[$j] = trim($choice[$j]);
  1849. }
  1850. $user_tags[] = api_strtolower($choice[$j]);
  1851. //put the contents of the [] answer tag into correct_tags[]
  1852. $correct_tags[] = api_strtolower(api_substr($temp, 0, $pos));
  1853. $j++;
  1854. $temp = api_substr($temp, $pos +1);
  1855. }
  1856. $answer = '';
  1857. $real_correct_tags = $correct_tags;
  1858. $chosen_list = array ();
  1859. for ($i = 0; $i < count($real_correct_tags); $i++) {
  1860. if ($i == 0) {
  1861. $answer .= $real_text[0];
  1862. }
  1863. if (!$switchable_answer_set) {
  1864. //needed to parse ' and " characters
  1865. $user_tags[$i] = stripslashes($user_tags[$i]);
  1866. if ($correct_tags[$i] == $user_tags[$i]) {
  1867. // gives the related weighting to the student
  1868. $questionScore += $answerWeighting[$i];
  1869. // increments total score
  1870. $totalScore += $answerWeighting[$i];
  1871. // adds the word in green at the end of the string
  1872. $answer .= $correct_tags[$i];
  1873. }
  1874. // else if the word entered by the student IS NOT the same as the one defined by the professor
  1875. elseif (!empty ($user_tags[$i])) {
  1876. // adds the word in red at the end of the string, and strikes it
  1877. $answer .= '<font color="red"><s>' . $user_tags[$i] . '</s></font>';
  1878. } else {
  1879. // adds a tabulation if no word has been typed by the student
  1880. $answer .= '&nbsp;&nbsp;&nbsp;';
  1881. }
  1882. } else {
  1883. // switchable fill in the blanks
  1884. if (in_array($user_tags[$i], $correct_tags)) {
  1885. $chosen_list[] = $user_tags[$i];
  1886. $correct_tags = array_diff($correct_tags, $chosen_list);
  1887. // gives the related weighting to the student
  1888. $questionScore += $answerWeighting[$i];
  1889. // increments total score
  1890. $totalScore += $answerWeighting[$i];
  1891. // adds the word in green at the end of the string
  1892. $answer .= $user_tags[$i];
  1893. }
  1894. elseif (!empty ($user_tags[$i])) {
  1895. // else if the word entered by the student IS NOT the same as the one defined by the professor
  1896. // adds the word in red at the end of the string, and strikes it
  1897. $answer .= '<font color="red"><s>' . $user_tags[$i] . '</s></font>';
  1898. } else {
  1899. // adds a tabulation if no word has been typed by the student
  1900. $answer .= '&nbsp;&nbsp;&nbsp;';
  1901. }
  1902. }
  1903. // adds the correct word, followed by ] to close the blank
  1904. $answer .= ' / <font color="green"><b>' . $real_correct_tags[$i] . '</b></font>]';
  1905. if (isset ($real_text[$i +1])) {
  1906. $answer .= $real_text[$i +1];
  1907. }
  1908. }
  1909. break;
  1910. // for free answer
  1911. case FREE_ANSWER :
  1912. if ($from_database) {
  1913. $query = "SELECT answer, marks FROM ".$TBL_TRACK_ATTEMPT." WHERE exe_id = '".$exeId."' AND question_id= '".$questionId."'";
  1914. $resq = Database::query($query);
  1915. $choice = Database::result($resq,0,'answer');
  1916. $choice = str_replace('\r\n', '', $choice);
  1917. $choice = stripslashes($choice);
  1918. $questionScore = Database::result($resq,0,"marks");
  1919. if ($questionScore==-1) {
  1920. $totalScore+=0;
  1921. } else {
  1922. $totalScore+=$questionScore;
  1923. }
  1924. $arrques[] = $questionName;
  1925. $arrans[] = $choice;
  1926. } else {
  1927. $studentChoice = $choice;
  1928. if ($studentChoice) {
  1929. //Fixing negative puntation see #2193
  1930. $questionScore = 0;
  1931. $totalScore += 0;
  1932. }
  1933. }
  1934. break;
  1935. // for matching
  1936. case MATCHING :
  1937. if ($from_database) {
  1938. $sql_answer = 'SELECT id, answer FROM '.$table_ans.' WHERE question_id="'.$questionId.'" AND correct=0';
  1939. $res_answer = Database::query($sql_answer);
  1940. // getting the real answer
  1941. $real_list =array();
  1942. while ($real_answer = Database::fetch_array($res_answer)) {
  1943. $real_list[$real_answer['id']]= $real_answer['answer'];
  1944. }
  1945. $sql_select_answer = 'SELECT id, answer, correct, id_auto FROM '.$table_ans.'
  1946. WHERE question_id="'.$questionId.'" AND correct <> 0 ORDER BY id_auto';
  1947. $res_answers = Database::query($sql_select_answer);
  1948. $questionScore = 0;
  1949. while ($a_answers = Database::fetch_array($res_answers)) {
  1950. $i_answer_id = $a_answers['id']; //3
  1951. $s_answer_label = $a_answers['answer']; // your daddy - your mother
  1952. $i_answer_correct_answer = $a_answers['correct']; //1 - 2
  1953. $i_answer_id_auto = $a_answers['id_auto']; // 3 - 4
  1954. $sql_user_answer = "SELECT answer FROM $TBL_TRACK_ATTEMPT
  1955. WHERE exe_id = '$exeId' AND question_id = '$questionId' AND position='$i_answer_id_auto'";
  1956. $res_user_answer = Database::query($sql_user_answer);
  1957. if (Database::num_rows($res_user_answer)>0 ) {
  1958. $s_user_answer = Database::result($res_user_answer,0,0); // rich - good looking
  1959. } else {
  1960. $s_user_answer = 0;
  1961. }
  1962. $i_answerWeighting=$objAnswerTmp->selectWeighting($i_answer_id);
  1963. $user_answer = '';
  1964. if (!empty($s_user_answer)) {
  1965. if ($s_user_answer == $i_answer_correct_answer) {
  1966. $questionScore += $i_answerWeighting;
  1967. $totalScore += $i_answerWeighting;
  1968. $user_answer = '<span>'.$real_list[$i_answer_correct_answer].'</span>';
  1969. } else {
  1970. $user_answer = '<span style="color: #FF0000; text-decoration: line-through;">'.$real_list[$s_user_answer].'</span>';
  1971. }
  1972. }
  1973. if ($show_result) {
  1974. echo '<tr>';
  1975. echo '<td>'.$s_answer_label.'</td><td>'.$user_answer.' / <b><span style="color: #008000;">'.$real_list[$i_answer_correct_answer].'</span></b></td>';
  1976. echo '</tr>';
  1977. }
  1978. }
  1979. break(2); //break the switch and the "for" condition
  1980. } else {
  1981. $numAnswer=$objAnswerTmp->selectAutoId($answerId);
  1982. if ($answerCorrect) {
  1983. if ($answerCorrect == $choice[$numAnswer]) {
  1984. $questionScore += $answerWeighting;
  1985. $totalScore += $answerWeighting;
  1986. $user_answer = '<span>'.$answer_matching[$choice[$numAnswer]].'</span>';
  1987. } else {
  1988. $user_answer = '<span style="color: #FF0000; text-decoration: line-through;">'.$answer_matching[$choice[$numAnswer]].'</span>';
  1989. }
  1990. $matching[$numAnswer] = $choice[$numAnswer];
  1991. }
  1992. break;
  1993. }
  1994. // for hotspot with no order
  1995. case HOT_SPOT :
  1996. if ($from_database) {
  1997. if ($show_result) {
  1998. $TBL_TRACK_HOTSPOT = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
  1999. $query = "SELECT hotspot_correct FROM ".$TBL_TRACK_HOTSPOT." where hotspot_exe_id = '".$exeId."' and hotspot_question_id= '".$questionId."' AND hotspot_answer_id='".Database::escape_string($answerId)."'";
  2000. $resq=Database::query($query);
  2001. $studentChoice = Database::result($resq,0,"hotspot_correct");
  2002. }
  2003. } else {
  2004. $studentChoice = $choice[$answerId];
  2005. if ($studentChoice) {
  2006. $questionScore += $answerWeighting;
  2007. $totalScore += $answerWeighting;
  2008. }
  2009. }
  2010. break;
  2011. // @todo never added to chamilo
  2012. //for hotspot with fixed order
  2013. case HOT_SPOT_ORDER :
  2014. $studentChoice = $choice['order'][$answerId];
  2015. if ($studentChoice == $answerId) {
  2016. $questionScore += $answerWeighting;
  2017. $totalScore += $answerWeighting;
  2018. $studentChoice = true;
  2019. } else {
  2020. $studentChoice = false;
  2021. }
  2022. break;
  2023. // for hotspot with delineation
  2024. case HOT_SPOT_DELINEATION :
  2025. if ($from_database) {
  2026. // getting the user answer
  2027. $TBL_TRACK_HOTSPOT = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
  2028. $query = "SELECT hotspot_correct, hotspot_coordinate from ".$TBL_TRACK_HOTSPOT." where hotspot_exe_id = '".$exeId."' and hotspot_question_id= '".$questionId."' AND hotspot_answer_id='1'"; //by default we take 1 because it's a delineation
  2029. $resq = Database::query($query);
  2030. $row = Database::fetch_array($resq,'ASSOC');
  2031. $choice = $row['hotspot_correct'];
  2032. $user_answer = $row['hotspot_coordinate'];
  2033. // THIS is very important otherwise the poly_compile will throw an error!!
  2034. // round-up the coordinates
  2035. $coords = explode('/',$user_answer);
  2036. $user_array = '';
  2037. foreach ($coords as $coord) {
  2038. list($x,$y) = explode(';',$coord);
  2039. $user_array .= round($x).';'.round($y).'/';
  2040. }
  2041. $user_array = substr($user_array,0,-1);
  2042. } else {
  2043. if ($studentChoice) {
  2044. $newquestionList[]=$questionId;
  2045. }
  2046. if ($answerId===1) {
  2047. $studentChoice =$choice[$answerId];
  2048. $questionScore +=$answerWeighting;
  2049. if ($hotspot_delineation_result[1]==1) {
  2050. $totalScore +=$answerWeighting; //adding the total
  2051. }
  2052. //$totalScore +=$answerWeighting; we do not if the hotspot is right or not
  2053. }
  2054. }
  2055. $_SESSION['hotspot_coord'][1] = $delineation_cord;
  2056. $_SESSION['hotspot_dest'][1] = $answer_delineation_destination;
  2057. break;
  2058. } // end switch Answertype
  2059. global $origin, $debug;
  2060. if ($show_result) {
  2061. if ($from == 'exercise_result') {
  2062. if ($debug) error_log('Showing questions $from '.$from);
  2063. //display answers (if not matching type, or if the answer is correct)
  2064. if ($answerType != MATCHING || $answerCorrect) {
  2065. if (in_array($answerType, array(UNIQUE_ANSWER, UNIQUE_ANSWER_NO_OPTION, MULTIPLE_ANSWER, MULTIPLE_ANSWER_COMBINATION))) {
  2066. if ($origin!='learnpath') {
  2067. ExerciseShowFunctions::display_unique_or_multiple_answer($answerType, $studentChoice, $answer, $answerComment, $answerCorrect,0,0,0);
  2068. }
  2069. } elseif($answerType == MULTIPLE_ANSWER_TRUE_FALSE) {
  2070. if ($origin!='learnpath') {
  2071. ExerciseShowFunctions::display_multiple_answer_true_false($answerType, $studentChoice, $answer, $answerComment, $answerCorrect,0,$questionId,0);
  2072. }
  2073. } elseif($answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE ) {
  2074. if ($origin!='learnpath') {
  2075. ExerciseShowFunctions::display_multiple_answer_combination_true_false($answerType, $studentChoice, $answer, $answerComment, $answerCorrect,0,0,0);
  2076. }
  2077. } elseif($answerType == FILL_IN_BLANKS) {
  2078. if ($origin!='learnpath') {
  2079. ExerciseShowFunctions::display_fill_in_blanks_answer($answer,0,0);
  2080. }
  2081. } elseif($answerType == FREE_ANSWER) {
  2082. // to store the details of open questions in an array to be used in mail
  2083. $arrques[] = $questionName;
  2084. $arrans[] = $choice;
  2085. if($origin != 'learnpath') {
  2086. ExerciseShowFunctions::display_free_answer($choice,0,0);
  2087. }
  2088. } elseif($answerType == HOT_SPOT) {
  2089. if ($origin != 'learnpath') {
  2090. ExerciseShowFunctions::display_hotspot_answer($answerId, $answer, $studentChoice, $answerComment);
  2091. }
  2092. } elseif($answerType == HOT_SPOT_ORDER) {
  2093. if ($origin != 'learnpath') {
  2094. ExerciseShowFunctions::display_hotspot_order_answer($answerId, $answer, $studentChoice, $answerComment);
  2095. }
  2096. } elseif ($answerType == HOT_SPOT_DELINEATION) {
  2097. $user_answer = $_SESSION['exerciseResultCoordinates'][$questionId];
  2098. //$_SESSION['exerciseResultCoordinates']=str_replace('/','|',$user_answer);
  2099. //if (!$comes_from_popup) {
  2100. //round-up the coordinates
  2101. $coords = explode('/',$user_answer);
  2102. $user_array = '';
  2103. foreach ($coords as $coord) {
  2104. list($x,$y) = explode(';',$coord);
  2105. $user_array .= round($x).';'.round($y).'/';
  2106. }
  2107. $user_array = substr($user_array,0,-1);
  2108. if ($next) {
  2109. //$tbl_track_e_hotspot = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
  2110. // Save into db
  2111. /* $sql = "INSERT INTO $tbl_track_e_hotspot (hotspot_user_id, hotspot_course_code, hotspot_exe_id, hotspot_question_id, hotspot_answer_id, hotspot_correct, hotspot_coordinate )
  2112. VALUES ('".Database::escape_string($_user['user_id'])."', '".Database::escape_string($_course['id'])."', '".Database::escape_string($exeId)."', '".Database::escape_string($questionId)."', '".Database::escape_string($answerId)."', '".Database::escape_string($studentChoice)."', '".Database::escape_string($user_array)."')";
  2113. $result = api_sql_query($sql,__FILE__,__LINE__);*/
  2114. $user_answer = $user_array;
  2115. // we compare only the delineation not the other points
  2116. $answer_question = $_SESSION['hotspot_coord'][1];
  2117. $answerDestination = $_SESSION['hotspot_dest'][1];
  2118. //calculating the area
  2119. $poly_user = convert_coordinates($user_answer,'/');
  2120. $poly_answer = convert_coordinates($answer_question,'|');
  2121. $max_coord = poly_get_max($poly_user,$poly_answer);
  2122. $poly_user_compiled = poly_compile($poly_user,$max_coord);
  2123. $poly_answer_compiled = poly_compile($poly_answer,$max_coord);
  2124. $poly_results = poly_result($poly_answer_compiled,$poly_user_compiled,$max_coord);
  2125. $overlap = $poly_results['both'];
  2126. $poly_answer_area = $poly_results['s1'];
  2127. $poly_user_area = $poly_results['s2'];
  2128. $missing = $poly_results['s1Only'];
  2129. $excess = $poly_results['s2Only'];
  2130. //$overlap = round(polygons_overlap($poly_answer,$poly_user)); //this is an area in pixels
  2131. if ($debug>0) { error_log(__LINE__.' - Polygons results are '.print_r($poly_results,1),0);}
  2132. if ($overlap < 1) {
  2133. //shortcut to avoid complicated calculations
  2134. $final_overlap = 0;
  2135. $final_missing = 100;
  2136. $final_excess = 100;
  2137. } else {
  2138. // the final overlap is the percentage of the initial polygon that is overlapped by the user's polygon
  2139. $final_overlap = round(((float)$overlap / (float)$poly_answer_area)*100);
  2140. if ($debug>1) { error_log(__LINE__.' - Final overlap is '.$final_overlap,0);}
  2141. // the final missing area is the percentage of the initial polygon that is not overlapped by the user's polygon
  2142. $final_missing = 100 - $final_overlap;
  2143. if ($debug>1) { error_log(__LINE__.' - Final missing is '.$final_missing,0);}
  2144. // the final excess area is the percentage of the initial polygon's size that is covered by the user's polygon outside of the initial polygon
  2145. $final_excess = round((((float)$poly_user_area-(float)$overlap)/(float)$poly_answer_area)*100);
  2146. if ($debug>1) { error_log(__LINE__.' - Final excess is '.$final_excess,0);}
  2147. }
  2148. //checking the destination parameters parsing the "@@"
  2149. $destination_items= explode('@@', $answerDestination);
  2150. $threadhold_total = $destination_items[0];
  2151. $threadhold_items=explode(';',$threadhold_total);
  2152. $threadhold1 = $threadhold_items[0]; // overlap
  2153. $threadhold2 = $threadhold_items[1]; // excess
  2154. $threadhold3 = $threadhold_items[2]; //missing
  2155. // if is delineation
  2156. if ($answerId===1) {
  2157. //setting colors
  2158. if ($final_overlap>=$threadhold1) {
  2159. $overlap_color=true; //echo 'a';
  2160. }
  2161. //echo $excess.'-'.$threadhold2;
  2162. if ($final_excess<=$threadhold2) {
  2163. $excess_color=true; //echo 'b';
  2164. }
  2165. //echo '--------'.$missing.'-'.$threadhold3;
  2166. if ($final_missing<=$threadhold3) {
  2167. $missing_color=true; //echo 'c';
  2168. }
  2169. // if pass
  2170. if ($final_overlap>=$threadhold1 && $final_missing<=$threadhold3 && $final_excess<=$threadhold2) {
  2171. $next=1; //go to the oars
  2172. $result_comment=get_lang('Acceptable');
  2173. $final_answer = 1; // do not update with update_exercise_attempt
  2174. } else {
  2175. $next=0;
  2176. $result_comment=get_lang('Unacceptable');
  2177. $comment=$answerDestination=$objAnswerTmp->selectComment(1);
  2178. $answerDestination=$objAnswerTmp->selectDestination(1);
  2179. //checking the destination parameters parsing the "@@"
  2180. $destination_items= explode('@@', $answerDestination);
  2181. }
  2182. } elseif($answerId>1) {
  2183. if ($objAnswerTmp->selectHotspotType($answerId) == 'noerror') {
  2184. if ($debug>0) { error_log(__LINE__.' - answerId is of type noerror',0);}
  2185. //type no error shouldn't be treated
  2186. $next = 1;
  2187. continue;
  2188. }
  2189. if ($debug>0) { error_log(__LINE__.' - answerId is >1 so we\'re probably in OAR',0);}
  2190. //check the intersection between the oar and the user
  2191. //echo 'user'; print_r($x_user_list); print_r($y_user_list);
  2192. //echo 'official';print_r($x_list);print_r($y_list);
  2193. //$result = get_intersection_data($x_list,$y_list,$x_user_list,$y_user_list);
  2194. $inter= $result['success'];
  2195. //$delineation_cord=$objAnswerTmp->selectHotspotCoordinates($answerId);
  2196. $delineation_cord=$objAnswerTmp->selectHotspotCoordinates($answerId);
  2197. $poly_answer = convert_coordinates($delineation_cord,'|');
  2198. $max_coord = poly_get_max($poly_user,$poly_answer);
  2199. $poly_answer_compiled = poly_compile($poly_answer,$max_coord);
  2200. $overlap = poly_touch($poly_user_compiled, $poly_answer_compiled,$max_coord);
  2201. if ($overlap == false) {
  2202. //all good, no overlap
  2203. $next = 1;
  2204. continue;
  2205. } else {
  2206. if ($debug>0) { error_log(__LINE__.' - Overlap is '.$overlap.': OAR hit',0);}
  2207. $organs_at_risk_hit++;
  2208. //show the feedback
  2209. $next=0;
  2210. $comment=$answerDestination=$objAnswerTmp->selectComment($answerId);
  2211. $answerDestination=$objAnswerTmp->selectDestination($answerId);
  2212. $destination_items= explode('@@', $answerDestination);
  2213. $try_hotspot=$destination_items[1];
  2214. $lp_hotspot=$destination_items[2];
  2215. $select_question_hotspot=$destination_items[3];
  2216. $url_hotspot=$destination_items[4];
  2217. }
  2218. }
  2219. } else { // the first delineation feedback
  2220. if ($debug>0) { error_log(__LINE__.' first',0);}
  2221. }
  2222. } elseif($answerType==MATCHING) {
  2223. if ($origin != 'learnpath') {
  2224. echo '<tr>';
  2225. echo '<td>'.text_filter($answer_matching[$answerId]).'</td><td>'.text_filter($user_answer).' / <b><span style="color: #008000;">'.text_filter($answer_matching[$answerCorrect]).'</span></b></td>';
  2226. echo '</tr>';
  2227. }
  2228. }
  2229. }
  2230. } else {
  2231. if ($debug) error_log('Showing questions $from '.$from);
  2232. switch($answerType) {
  2233. case UNIQUE_ANSWER :
  2234. case UNIQUE_ANSWER_NO_OPTION:
  2235. case MULTIPLE_ANSWER :
  2236. case MULTIPLE_ANSWER_COMBINATION :
  2237. if ($answerId==1) {
  2238. ExerciseShowFunctions::display_unique_or_multiple_answer($answerType, $studentChoice, $answer, $answerComment, $answerCorrect,$exeId,$questionId,$answerId);
  2239. } else {
  2240. ExerciseShowFunctions::display_unique_or_multiple_answer($answerType, $studentChoice, $answer, $answerComment, $answerCorrect,$exeId,$questionId,"");
  2241. }
  2242. break;
  2243. case MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE:
  2244. if ($answerId==1) {
  2245. ExerciseShowFunctions::display_multiple_answer_combination_true_false($answerType, $studentChoice, $answer, $answerComment, $answerCorrect,$exeId,$questionId,$answerId);
  2246. } else {
  2247. ExerciseShowFunctions::display_multiple_answer_combination_true_false($answerType, $studentChoice, $answer, $answerComment, $answerCorrect,$exeId,$questionId,"");
  2248. }
  2249. break;
  2250. case MULTIPLE_ANSWER_TRUE_FALSE :
  2251. if ($answerId==1) {
  2252. ExerciseShowFunctions::display_multiple_answer_true_false($answerType, $studentChoice, $answer, $answerComment, $answerCorrect,$exeId,$questionId,$answerId);
  2253. } else {
  2254. ExerciseShowFunctions::display_multiple_answer_true_false($answerType, $studentChoice, $answer, $answerComment, $answerCorrect,$exeId,$questionId,"");
  2255. }
  2256. break;
  2257. case FILL_IN_BLANKS:
  2258. echo '<tr><td>';
  2259. ExerciseShowFunctions::display_fill_in_blanks_answer($answer,$exeId,$questionId);
  2260. echo '</td></tr>';
  2261. break;
  2262. case FREE_ANSWER:
  2263. echo '<tr>
  2264. <td valign="top">'.ExerciseShowFunctions::display_free_answer($choice, $exeId, $questionId).'</td>
  2265. </tr>
  2266. </table>';
  2267. break;
  2268. case HOT_SPOT:
  2269. ExerciseShowFunctions::display_hotspot_answer($answerId, $answer, $studentChoice, $answerComment);
  2270. break;
  2271. case HOT_SPOT_DELINEATION:
  2272. $user_answer = $user_array;
  2273. if ($next) {
  2274. //$tbl_track_e_hotspot = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
  2275. // Save into db
  2276. /* $sql = "INSERT INTO $tbl_track_e_hotspot (hotspot_user_id, hotspot_course_code, hotspot_exe_id, hotspot_question_id, hotspot_answer_id, hotspot_correct, hotspot_coordinate )
  2277. VALUES ('".Database::escape_string($_user['user_id'])."', '".Database::escape_string($_course['id'])."', '".Database::escape_string($exeId)."', '".Database::escape_string($questionId)."', '".Database::escape_string($answerId)."', '".Database::escape_string($studentChoice)."', '".Database::escape_string($user_array)."')";
  2278. $result = api_sql_query($sql,__FILE__,__LINE__);*/
  2279. $user_answer = $user_array;
  2280. // we compare only the delineation not the other points
  2281. $answer_question = $_SESSION['hotspot_coord'][1];
  2282. $answerDestination = $_SESSION['hotspot_dest'][1];
  2283. //calculating the area
  2284. $poly_user = convert_coordinates($user_answer,'/');
  2285. $poly_answer = convert_coordinates($answer_question,'|');
  2286. $max_coord = poly_get_max($poly_user,$poly_answer);
  2287. $poly_user_compiled = poly_compile($poly_user,$max_coord);
  2288. $poly_answer_compiled = poly_compile($poly_answer,$max_coord);
  2289. $poly_results = poly_result($poly_answer_compiled,$poly_user_compiled,$max_coord);
  2290. $overlap = $poly_results['both'];
  2291. $poly_answer_area = $poly_results['s1'];
  2292. $poly_user_area = $poly_results['s2'];
  2293. $missing = $poly_results['s1Only'];
  2294. $excess = $poly_results['s2Only'];
  2295. //$overlap = round(polygons_overlap($poly_answer,$poly_user)); //this is an area in pixels
  2296. if ($debug>0) { error_log(__LINE__.' - Polygons results are '.print_r($poly_results,1),0);}
  2297. if ($overlap < 1) {
  2298. //shortcut to avoid complicated calculations
  2299. $final_overlap = 0;
  2300. $final_missing = 100;
  2301. $final_excess = 100;
  2302. } else {
  2303. // the final overlap is the percentage of the initial polygon that is overlapped by the user's polygon
  2304. $final_overlap = round(((float)$overlap / (float)$poly_answer_area)*100);
  2305. if ($debug>1) { error_log(__LINE__.' - Final overlap is '.$final_overlap,0);}
  2306. // the final missing area is the percentage of the initial polygon that is not overlapped by the user's polygon
  2307. $final_missing = 100 - $final_overlap;
  2308. if ($debug>1) { error_log(__LINE__.' - Final missing is '.$final_missing,0);}
  2309. // the final excess area is the percentage of the initial polygon's size that is covered by the user's polygon outside of the initial polygon
  2310. $final_excess = round((((float)$poly_user_area-(float)$overlap)/(float)$poly_answer_area)*100);
  2311. if ($debug>1) { error_log(__LINE__.' - Final excess is '.$final_excess,0);}
  2312. }
  2313. //checking the destination parameters parsing the "@@"
  2314. $destination_items= explode('@@', $answerDestination);
  2315. $threadhold_total = $destination_items[0];
  2316. $threadhold_items=explode(';',$threadhold_total);
  2317. $threadhold1 = $threadhold_items[0]; // overlap
  2318. $threadhold2 = $threadhold_items[1]; // excess
  2319. $threadhold3 = $threadhold_items[2]; //missing
  2320. // if is delineation
  2321. if ($answerId===1) {
  2322. //setting colors
  2323. if ($final_overlap>=$threadhold1) {
  2324. $overlap_color=true; //echo 'a';
  2325. }
  2326. //echo $excess.'-'.$threadhold2;
  2327. if ($final_excess<=$threadhold2) {
  2328. $excess_color=true; //echo 'b';
  2329. }
  2330. //echo '--------'.$missing.'-'.$threadhold3;
  2331. if ($final_missing<=$threadhold3) {
  2332. $missing_color=true; //echo 'c';
  2333. }
  2334. // if pass
  2335. if ($final_overlap>=$threadhold1 && $final_missing<=$threadhold3 && $final_excess<=$threadhold2) {
  2336. $next=1; //go to the oars
  2337. $result_comment=get_lang('Acceptable');
  2338. $final_answer = 1; // do not update with update_exercise_attempt
  2339. } else {
  2340. $next=0;
  2341. $result_comment=get_lang('Unacceptable');
  2342. $comment=$answerDestination=$objAnswerTmp->selectComment(1);
  2343. $answerDestination=$objAnswerTmp->selectDestination(1);
  2344. //checking the destination parameters parsing the "@@"
  2345. $destination_items= explode('@@', $answerDestination);
  2346. }
  2347. } elseif($answerId>1) {
  2348. if ($objAnswerTmp->selectHotspotType($answerId) == 'noerror') {
  2349. if ($debug>0) { error_log(__LINE__.' - answerId is of type noerror',0);}
  2350. //type no error shouldn't be treated
  2351. $next = 1;
  2352. continue;
  2353. }
  2354. if ($debug>0) { error_log(__LINE__.' - answerId is >1 so we\'re probably in OAR',0);}
  2355. //check the intersection between the oar and the user
  2356. //echo 'user'; print_r($x_user_list); print_r($y_user_list);
  2357. //echo 'official';print_r($x_list);print_r($y_list);
  2358. //$result = get_intersection_data($x_list,$y_list,$x_user_list,$y_user_list);
  2359. $inter= $result['success'];
  2360. //$delineation_cord=$objAnswerTmp->selectHotspotCoordinates($answerId);
  2361. $delineation_cord=$objAnswerTmp->selectHotspotCoordinates($answerId);
  2362. $poly_answer = convert_coordinates($delineation_cord,'|');
  2363. $max_coord = poly_get_max($poly_user,$poly_answer);
  2364. $poly_answer_compiled = poly_compile($poly_answer,$max_coord);
  2365. $overlap = poly_touch($poly_user_compiled, $poly_answer_compiled,$max_coord);
  2366. if ($overlap == false) {
  2367. //all good, no overlap
  2368. $next = 1;
  2369. continue;
  2370. } else {
  2371. if ($debug>0) { error_log(__LINE__.' - Overlap is '.$overlap.': OAR hit',0);}
  2372. $organs_at_risk_hit++;
  2373. //show the feedback
  2374. $next=0;
  2375. $comment=$answerDestination=$objAnswerTmp->selectComment($answerId);
  2376. $answerDestination=$objAnswerTmp->selectDestination($answerId);
  2377. $destination_items= explode('@@', $answerDestination);
  2378. $try_hotspot=$destination_items[1];
  2379. $lp_hotspot=$destination_items[2];
  2380. $select_question_hotspot=$destination_items[3];
  2381. $url_hotspot=$destination_items[4];
  2382. }
  2383. }
  2384. } else { // the first delineation feedback
  2385. if ($debug>0) { error_log(__LINE__.' first',0);}
  2386. }
  2387. break;
  2388. case HOT_SPOT_ORDER:
  2389. ExerciseShowFunctions::display_hotspot_order_answer($answerId, $answer, $studentChoice, $answerComment);
  2390. break;
  2391. case MATCHING:
  2392. if ($origin != 'learnpath') {
  2393. echo '<tr>';
  2394. echo '<td>'.text_filter($answer_matching[$answerId]).'</td><td>'.text_filter($user_answer).' / <b><span style="color: #008000;">'.text_filter($answer_matching[$answerCorrect]).'</span></b></td>';
  2395. echo '</tr>';
  2396. }
  2397. break;
  2398. }
  2399. }
  2400. }
  2401. } // end for that loops over all answers of the current question
  2402. // destruction of Answer
  2403. if (!$saved_results && $answerType == HOT_SPOT) {
  2404. $queryfree = "SELECT marks FROM ".$TBL_TRACK_ATTEMPT." where exe_id = '".Database::escape_string($exeId)."' and question_id= '".Database::escape_string($questionId)."'";
  2405. $resfree = Database::query($queryfree);
  2406. $questionScore = Database::result($resfree,0,"marks");
  2407. }
  2408. $final_answer = true;
  2409. foreach($real_answers as $my_answer) {
  2410. if (!$my_answer) {
  2411. $final_answer = false;
  2412. }
  2413. }
  2414. //we add the total score after dealing with the answers
  2415. if ($answerType == MULTIPLE_ANSWER_COMBINATION || $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE ) {
  2416. if ($final_answer) {
  2417. //getting only the first score where we save the weight of all the question
  2418. $answerWeighting = $objAnswerTmp->selectWeighting(1);
  2419. $questionScore += $answerWeighting;
  2420. $totalScore += $answerWeighting;
  2421. }
  2422. }
  2423. $extra_data = array('final_overlap' => $final_overlap, 'final_missing'=>$final_missing, 'final_excess'=> $final_excess,
  2424. 'overlap_color' => $overlap_color, 'missing_color'=>$missing_color, 'excess_color'=> $excess_color,
  2425. 'threadhold1' => $threadhold1, 'threadhold2'=>$threadhold2, 'threadhold3'=> $threadhold3,
  2426. );
  2427. if ($from == 'exercise_result') {
  2428. // if answer is hotspot. To the difference of exercise_show.php, we use the results from the session (from_db=0)
  2429. // TODO Change this, because it is wrong to show the user some results that haven't been stored in the database yet
  2430. if ($answerType == HOT_SPOT || $answerType == HOT_SPOT_ORDER || $answerType == HOT_SPOT_DELINEATION ) {
  2431. if ($debug) error_log('$from AND this is a hotspot kind of question ');
  2432. $my_exe_id = 0;
  2433. $from_database = 0;
  2434. if ($answerType == HOT_SPOT_DELINEATION) {
  2435. if (0) {
  2436. if ($overlap_color) {
  2437. $overlap_color='green';
  2438. } else {
  2439. $overlap_color='red';
  2440. }
  2441. if ($missing_color) {
  2442. $missing_color='green';
  2443. } else {
  2444. $missing_color='red';
  2445. }
  2446. if ($excess_color) {
  2447. $excess_color='green';
  2448. } else {
  2449. $excess_color='red';
  2450. }
  2451. if (!is_numeric($final_overlap)) {
  2452. $final_overlap = 0;
  2453. }
  2454. if (!is_numeric($final_missing)) {
  2455. $final_missing = 0;
  2456. }
  2457. if (!is_numeric($final_excess)) {
  2458. $final_excess = 0;
  2459. }
  2460. if ($final_overlap>100) {
  2461. $final_overlap = 100;
  2462. }
  2463. $table_resume='<table class="data_table">
  2464. <tr class="row_odd" >
  2465. <td></td>
  2466. <td ><b>'.get_lang('Requirements').'</b></td>
  2467. <td><b>'.get_lang('YourAnswer').'</b></td>
  2468. </tr>
  2469. <tr class="row_even">
  2470. <td><b>'.get_lang('Overlap').'</b></td>
  2471. <td>'.get_lang('Min').' '.$threadhold1.'</td>
  2472. <td><div style="color:'.$overlap_color.'">'.(($final_overlap < 0)?0:intval($final_overlap)).'</div></td>
  2473. </tr>
  2474. <tr>
  2475. <td><b>'.get_lang('Excess').'</b></td>
  2476. <td>'.get_lang('Max').' '.$threadhold2.'</td>
  2477. <td><div style="color:'.$excess_color.'">'.(($final_excess < 0)?0:intval($final_excess)).'</div></td>
  2478. </tr>
  2479. <tr class="row_even">
  2480. <td><b>'.get_lang('Missing').'</b></td>
  2481. <td>'.get_lang('Max').' '.$threadhold3.'</td>
  2482. <td><div style="color:'.$missing_color.'">'.(($final_missing < 0)?0:intval($final_missing)).'</div></td>
  2483. </tr>
  2484. </table>';
  2485. if ($next==0) {
  2486. $try = $try_hotspot;
  2487. $lp = $lp_hotspot;
  2488. $destinationid= $select_question_hotspot;
  2489. $url=$url_hotspot;
  2490. } else {
  2491. //show if no error
  2492. //echo 'no error';
  2493. $comment=$answerComment=$objAnswerTmp->selectComment($nbrAnswers);
  2494. $answerDestination=$objAnswerTmp->selectDestination($nbrAnswers);
  2495. }
  2496. echo '<h1><div style="color:#333;">'.get_lang('Feedback').'</div></h1>
  2497. <p style="text-align:center">';
  2498. $message='<p>'.get_lang('YourDelineation').'</p>';
  2499. $message.=$table_resume;
  2500. $message.='<br />'.get_lang('ResultIs').' '.$result_comment.'<br />';
  2501. if ($organs_at_risk_hit>0) {
  2502. $message.='<p><b>'.get_lang('OARHit').'</b></p>';
  2503. }
  2504. $message.='<p>'.$comment.'</p>';
  2505. echo $message;
  2506. } else {
  2507. echo $hotspot_delineation_result[0]; //prints message
  2508. $from_database = 1; // the hotspot_solution.swf needs this variable
  2509. }
  2510. //save the score attempts
  2511. if (1 ) {
  2512. $final_answer = $hotspot_delineation_result[1]; //getting the answer 1 or 0 comes from exercise_submit_modal.php
  2513. if ($final_answer == 0) {
  2514. $questionScore = 0;
  2515. }
  2516. exercise_attempt($questionScore, 1, $quesId, $exeId, 0); // we always insert the answer_id 1 = delineation
  2517. //we will only save one item - @TODO $my_hotspot_answer seems unefined. Find where it should come from
  2518. exercise_attempt_hotspot($exeId,$quesId,1, $my_hotspot_answer, $exerciseResultCoordinates[$quesId]);
  2519. } else {
  2520. if ($final_answer==0) {
  2521. $questionScore = 0;
  2522. $answer=0;
  2523. exercise_attempt($questionScore, $answer, $quesId, $exeId, 0);
  2524. if (is_array($exerciseResultCoordinates[$quesId])) {
  2525. foreach($exerciseResultCoordinates[$quesId] as $idx => $val) {
  2526. exercise_attempt_hotspot($exeId,$quesId,$idx,0,$val);
  2527. }
  2528. }
  2529. } else {
  2530. exercise_attempt($questionScore, $answer, $quesId, $exeId, 0);
  2531. if (is_array($exerciseResultCoordinates[$quesId])) {
  2532. foreach($exerciseResultCoordinates[$quesId] as $idx => $val) {
  2533. exercise_attempt_hotspot($exeId,$quesId,$idx,$choice[$idx],$val);
  2534. }
  2535. }
  2536. }
  2537. }
  2538. $my_exe_id = $exeId;
  2539. }
  2540. // We made an extra table for the answers
  2541. if($origin != 'learnpath') {
  2542. echo "</table></td></tr>"; //echo Security::remove_XSS($questionId);
  2543. ?>
  2544. <tr>
  2545. <td colspan="2">
  2546. <i><?php echo get_lang('Hotspot'); ?></i><br /><br />
  2547. <object type="application/x-shockwave-flash" data="../plugin/hotspot/hotspot_solution.swf?modifyAnswers=<?php echo Security::remove_XSS($questionId); ?>&exe_id=<?php echo $my_exe_id; ?>&from_db=<?php echo $from_database; ?>" width="552" height="352">
  2548. <param name="movie" value="../plugin/hotspot/hotspot_solution.swf?modifyAnswers=<?php echo Security::remove_XSS($questionId); ?>&exe_id=<?php echo $my_exe_id; ?>&from_db=<?php echo $from_database; ?>" />
  2549. </object>
  2550. </td>
  2551. </tr>
  2552. <?php
  2553. }
  2554. }
  2555. if ($answerType == HOT_SPOT || $answerType == HOT_SPOT_ORDER) {
  2556. // We made an extra table for the answers
  2557. if ($show_result) {
  2558. if ($origin != 'learnpath') {
  2559. echo '</table></td></tr>';
  2560. echo '<tr>
  2561. <td colspan="2">';
  2562. echo '<i>'.get_lang('HotSpot').'</i><br /><br />';
  2563. echo '<object type="application/x-shockwave-flash" data="'.api_get_path(WEB_CODE_PATH).'plugin/hotspot/hotspot_solution.swf?modifyAnswers='.Security::remove_XSS($questionId).'&exe_id=&from_db=0" width="552" height="352">';
  2564. echo '<param name="movie" value="'.api_get_path(WEB_PLUGIN_PATH).'plugin/hotspot/hotspot_solution.swf?modifyAnswers='.Security::remove_XSS($questionId).'&exe_id=&from_db=0" />
  2565. </object>
  2566. </td>
  2567. </tr>';
  2568. }
  2569. }
  2570. }
  2571. if ($origin != 'learnpath') {
  2572. if ($show_result) {
  2573. echo '</table>';
  2574. if ($this->type == ALL_ON_ONE_PAGE) {
  2575. echo '<div id="question_score">';
  2576. if ($propagate_neg == 0 && $questionScore < 0) {
  2577. $questionScore = 0;
  2578. }
  2579. echo get_lang('Score').": ".show_score($questionScore, $questionWeighting, false, false);
  2580. echo '</div>';
  2581. }
  2582. echo '<br />';
  2583. }
  2584. }
  2585. }
  2586. unset ($objAnswerTmp);
  2587. $i++;
  2588. $totalWeighting += $questionWeighting;
  2589. // Store results directly in the database
  2590. // For all in one page exercises, the results will be
  2591. // stored by exercise_results.php (using the session)
  2592. if ($saved_results) {
  2593. if (empty ($choice)) {
  2594. $choice = 0;
  2595. }
  2596. if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE || $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE ) {
  2597. if ($choice != 0) {
  2598. $reply = array_keys($choice);
  2599. for ($i = 0; $i < sizeof($reply); $i++) {
  2600. $ans = $reply[$i];
  2601. exercise_attempt($questionScore, $ans.':'.$choice[$ans], $quesId, $exeId, $i, $this->id);
  2602. }
  2603. } else {
  2604. exercise_attempt($questionScore, 0, $quesId, $exeId, 0, $this->id);
  2605. }
  2606. } elseif ($answerType == MULTIPLE_ANSWER) {
  2607. if ($choice != 0) {
  2608. $reply = array_keys($choice);
  2609. for ($i = 0; $i < sizeof($reply); $i++) {
  2610. $ans = $reply[$i];
  2611. exercise_attempt($questionScore, $ans, $quesId, $exeId, $i, $this->id);
  2612. }
  2613. } else {
  2614. exercise_attempt($questionScore, 0, $quesId, $exeId, 0, $this->id);
  2615. }
  2616. } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION) {
  2617. if ($choice != 0) {
  2618. $reply = array_keys($choice);
  2619. for ($i = 0; $i < sizeof($reply); $i++) {
  2620. $ans = $reply[$i];
  2621. exercise_attempt($questionScore, $ans, $quesId, $exeId, $i, $this->id);
  2622. }
  2623. } else {
  2624. exercise_attempt($questionScore, 0, $quesId, $exeId, 0, $this->id);
  2625. }
  2626. } elseif ($answerType == MATCHING) {
  2627. foreach ($matching as $j => $val) {
  2628. exercise_attempt($questionScore, $val, $quesId, $exeId, $j, $this->id);
  2629. }
  2630. } elseif ($answerType == FREE_ANSWER) {
  2631. $answer = $choice;
  2632. exercise_attempt($questionScore, $answer, $quesId, $exeId, 0, $this->id);
  2633. } elseif ($answerType == UNIQUE_ANSWER || $answerType == UNIQUE_ANSWER_NO_OPTION) {
  2634. $answer = $choice;
  2635. exercise_attempt($questionScore, $answer, $quesId, $exeId, 0, $this->id);
  2636. // } elseif ($answerType == HOT_SPOT || $answerType == HOT_SPOT_DELINEATION) {
  2637. } elseif ($answerType == HOT_SPOT) {
  2638. exercise_attempt($questionScore, $answer, $quesId, $exeId, 0, $this->id);
  2639. if (isset($exerciseResultCoordinates[$questionId]) && !empty($exerciseResultCoordinates[$questionId])) {
  2640. foreach($exerciseResultCoordinates[$questionId] as $idx => $val) {
  2641. exercise_attempt_hotspot($exeId,$quesId,$idx,$choice[$idx],$val,$this->id);
  2642. }
  2643. }
  2644. } else {
  2645. exercise_attempt($questionScore, $answer, $quesId, $exeId, 0,$this->id);
  2646. }
  2647. }
  2648. if ($saved_results) {
  2649. $stat_table = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
  2650. $sql_update = 'UPDATE ' . $stat_table . ' SET exe_result = exe_result + ' . floatval($totalScore) . ' WHERE exe_id = ' . $exeId;
  2651. Database::query($sql_update);
  2652. }
  2653. if ($propagate_neg == 0 && $questionScore < 0) {
  2654. $questionScore = 0;
  2655. }
  2656. $return_array = array('score'=>$questionScore, 'weight'=>$questionWeighting,'extra'=>$extra_data);
  2657. return $return_array;
  2658. } //End function
  2659. function send_notification($arrques, $arrans) {
  2660. // Email configuration settings
  2661. $coursecode = api_get_course_id();
  2662. $course_info = api_get_course_info(api_get_course_id());
  2663. $to = '';
  2664. $teachers = array();
  2665. if (api_get_session_id()) {
  2666. $teachers = CourseManager::get_coach_list_from_course_code($coursecode, api_get_session_id());
  2667. } else {
  2668. $teachers = CourseManager::get_teacher_list_from_course_code($coursecode);
  2669. }
  2670. $num = count($teachers);
  2671. if($num>1) {
  2672. $to = array();
  2673. foreach($teachers as $teacher) {
  2674. $to[] = $teacher['email'];
  2675. }
  2676. } elseif ($num>0){
  2677. foreach($teachers as $teacher) {
  2678. $to = $teacher['email'];
  2679. }
  2680. } else {
  2681. //this is a problem (it means that there is no admin for this course)
  2682. }
  2683. global $courseName, $exerciseTitle, $url_email;
  2684. require_once api_get_path(LIBRARY_PATH).'usermanager.lib.php';
  2685. $user_info = UserManager::get_user_info_by_id(api_get_user_id());
  2686. if (api_get_course_setting('email_alert_manager_on_new_quiz') != 1 ) {
  2687. return '';
  2688. }
  2689. $mycharset = api_get_system_encoding();
  2690. $msg = '<html><head>
  2691. <link rel="stylesheet" href="'.api_get_path(WEB_CODE_PATH).'css/'.api_get_setting('stylesheets').'/default.css" type="text/css">
  2692. <meta content="text/html; charset='.$mycharset.'" http-equiv="content-type"></head>';
  2693. if(count($arrques)>0) {
  2694. $msg .= '<body>
  2695. <p>'.get_lang('OpenQuestionsAttempted').' :
  2696. </p>
  2697. <p>'.get_lang('AttemptDetails').' : <br />
  2698. </p>
  2699. <table width="730" height="136" border="0" cellpadding="3" cellspacing="3">
  2700. <tr>
  2701. <td width="229" valign="top"><h2>&nbsp;&nbsp;'.get_lang('CourseName').'</h2></td>
  2702. <td width="469" valign="top"><h2>#course#</h2></td>
  2703. </tr>
  2704. <tr>
  2705. <td width="229" valign="top" class="outerframe">&nbsp;&nbsp;'.get_lang('TestAttempted').'</span></td>
  2706. <td width="469" valign="top" class="outerframe">#exercise#</td>
  2707. </tr>
  2708. <tr>
  2709. <td valign="top">&nbsp;&nbsp;<span class="style10">'.get_lang('StudentName').'</span></td>
  2710. <td valign="top" >#firstName# #lastName#</td>
  2711. </tr>
  2712. <tr>
  2713. <td valign="top" >&nbsp;&nbsp;'.get_lang('StudentEmail').' </td>
  2714. <td valign="top"> #mail#</td>
  2715. </tr></table>
  2716. <p><br />'.get_lang('OpenQuestionsAttemptedAre').' :</p>
  2717. <table width="730" height="136" border="0" cellpadding="3" cellspacing="3">';
  2718. for($i=0;$i<sizeof($arrques);$i++) {
  2719. $msg.='
  2720. <tr>
  2721. <td width="220" valign="top" bgcolor="#E5EDF8">&nbsp;&nbsp;<span class="style10">'.get_lang('Question').'</span></td>
  2722. <td width="473" valign="top" bgcolor="#F3F3F3"><span class="style16"> #questionName#</span></td>
  2723. </tr>
  2724. <tr>
  2725. <td width="220" valign="top" bgcolor="#E5EDF8">&nbsp;&nbsp;<span class="style10">'.get_lang('Answer').' </span></td>
  2726. <td valign="top" bgcolor="#F3F3F3"><span class="style16"> #answer#</span></td>
  2727. </tr>';
  2728. $msg1= str_replace("#exercise#",$exerciseTitle,$msg);
  2729. $msg= str_replace("#firstName#",$user_info['firstname'],$msg1);
  2730. $msg1= str_replace("#lastName#",$user_info['lastname'],$msg);
  2731. $msg= str_replace("#mail#",$user_info['email'],$msg1);
  2732. $msg1= str_replace("#questionName#",$arrques[$i],$msg);
  2733. $msg= str_replace("#answer#",$arrans[$i],$msg1);
  2734. $msg1= str_replace("#i#",$i,$msg);
  2735. $msg= str_replace("#course#",$courseName,$msg1);
  2736. }
  2737. $msg.='</table><br>
  2738. <span class="style16">'.get_lang('ClickToCommentAndGiveFeedback').',<br />
  2739. <a href="#url#">#url#</a></span></body></html>';
  2740. $msg1= str_replace("#url#",$url_email,$msg);
  2741. $mail_content = $msg1;
  2742. $subject = get_lang('OpenQuestionsAttempted');
  2743. $sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
  2744. $email_admin = api_get_setting('emailAdministrator');
  2745. $result = @api_mail_html('', $to, $subject, $mail_content, $sender_name, $email_admin, array('charset'=>$mycharset));
  2746. } else {
  2747. $msg .= '<body>
  2748. <p>'.get_lang('ExerciseAttempted').' <br />
  2749. </p>
  2750. <table width="730" height="136" border="0" cellpadding="3" cellspacing="3">
  2751. <tr>
  2752. <td width="229" valign="top"><h2>&nbsp;&nbsp;'.get_lang('CourseName').'</h2></td>
  2753. <td width="469" valign="top"><h2>#course#</h2></td>
  2754. </tr>
  2755. <tr>
  2756. <td width="229" valign="top" class="outerframe">&nbsp;&nbsp;'.get_lang('TestAttempted').'</span></td>
  2757. <td width="469" valign="top" class="outerframe">#exercise#</td>
  2758. </tr>
  2759. <tr>
  2760. <td valign="top">&nbsp;&nbsp;<span class="style10">'.get_lang('StudentName').'</span></td>
  2761. '.(api_is_western_name_order() ? '<td valign="top" >#firstName# #lastName#</td>' : '<td valign="top" >#lastName# #firstName#</td>').'
  2762. </tr>
  2763. <tr>
  2764. <td valign="top" >&nbsp;&nbsp;'.get_lang('StudentEmail').' </td>
  2765. <td valign="top"> #mail#</td>
  2766. </tr></table>';
  2767. $msg= str_replace("#exercise#",$exerciseTitle,$msg);
  2768. $msg= str_replace("#firstName#",$user_info['firstname'],$msg);
  2769. $msg= str_replace("#lastName#",$user_info['lastname'],$msg);
  2770. $msg= str_replace("#mail#",$user_info['email'],$msg);
  2771. $msg= str_replace("#course#",$courseName,$msg);
  2772. $msg.='<br />
  2773. <span class="style16">'.get_lang('ClickToCommentAndGiveFeedback').',<br />
  2774. <a href="#url#">#url#</a></span></body></html>';
  2775. $msg= str_replace("#url#",$url_email,$msg);
  2776. $mail_content = $msg;
  2777. $sender_name = api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname'), null, PERSON_NAME_EMAIL_ADDRESS);
  2778. $email_admin = api_get_setting('emailAdministrator');
  2779. $subject = get_lang('ExerciseAttempted');
  2780. $result = @api_mail_html('', $to, $subject, $mail_content, $sender_name, $email_admin, array('charset'=>$mycharset));
  2781. }
  2782. }
  2783. function show_exercise_result_header($user_data, $date = null) {
  2784. $description = '';
  2785. if (!empty($this->description)) {
  2786. $description = '<tr>
  2787. <td style="font-weight:bold" width="10%">
  2788. &nbsp;'.get_lang("Description").' :
  2789. </td>
  2790. <td width="90%">
  2791. '.$this->description.'
  2792. </td>
  2793. </tr>';
  2794. }
  2795. $date_data = '';
  2796. if (!empty($date)) {
  2797. $date_data = '<tr>
  2798. <td style="font-weight:bold" width="10%">
  2799. &nbsp;'.get_lang("Date").' :
  2800. </td>
  2801. <td width="90%">
  2802. '.$date.'
  2803. </td>
  2804. </tr>';
  2805. }
  2806. $html = '<table width="100%">
  2807. <tr>
  2808. <td colspan="2">
  2809. <h2>'.Display::return_icon('quiz_big.png', get_lang('Result')).' '.$this->exercise.' : '.get_lang('Result').'</h2>
  2810. </td>
  2811. </tr>
  2812. <tr>
  2813. <td style="font-weight:bold" width="90px">&nbsp;'.get_lang('User').' : </td>
  2814. <td>
  2815. '.$user_data.'
  2816. </td>
  2817. </tr>
  2818. '.$date_data.'
  2819. '.$description.'
  2820. </table>
  2821. <br />';
  2822. return $html;
  2823. }
  2824. /**
  2825. * Create a quiz from quiz data
  2826. * @param string Title
  2827. * @param int Time before it expires (in minutes)
  2828. * @param int Type of exercise
  2829. * @param int Whether it's randomly picked questions (1) or not (0)
  2830. * @param int Whether the exercise is visible to the user (1) or not (0)
  2831. * @param int Whether the results are show to the user (0) or not (1)
  2832. * @param int Maximum number of attempts (0 if no limit)
  2833. * @param int Feedback type
  2834. * @return int New exercise ID
  2835. */
  2836. function create_quiz ($title, $expired_time = 0, $type = 2, $random = 0, $active = 1, $results_disabled = 0, $max_attempt = 0, $feedback = 3) {
  2837. $tbl_quiz = Database::get_course_table(TABLE_QUIZ_TEST);
  2838. $expired_time = filter_var($expired_time,FILTER_SANITIZE_NUMBER_INT);
  2839. $type = filter_var($type,FILTER_SANITIZE_NUMBER_INT);
  2840. $random = filter_var($random,FILTER_SANITIZE_NUMBER_INT);
  2841. $active = filter_var($active,FILTER_SANITIZE_NUMBER_INT);
  2842. $results_disabled = filter_var($results_disabled,FILTER_SANITIZE_NUMBER_INT);
  2843. $max_attempt = filter_var($max_attempt,FILTER_SANITIZE_NUMBER_INT);
  2844. $feedback = filter_var($feedback,FILTER_SANITIZE_NUMBER_INT);
  2845. $sid = api_get_session_id();
  2846. // Save a new quiz
  2847. $sql = "INSERT INTO $tbl_quiz (title,type,random,active,results_disabled, ".
  2848. "max_attempt,start_time,end_time,feedback_type,expired_time, session_id) ".
  2849. " VALUES('".Database::escape_string($title)."',$type,$random,$active, ".
  2850. "$results_disabled,$max_attempt,'','',$feedback,$expired_time,$sid)";
  2851. $rs = Database::query($sql);
  2852. $quiz_id = Database::get_last_insert_id();
  2853. return $quiz_id;
  2854. }
  2855. function process_geometry() {
  2856. }
  2857. }
  2858. endif;