surveyUtil.class.php 143 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * This class offers a series of general utility functions for survey querying and display
  5. * @package chamilo.survey
  6. */
  7. class SurveyUtil
  8. {
  9. /**
  10. * Checks whether the given survey has a pagebreak question as the first
  11. * or the last question.
  12. * If so, break the current process, displaying an error message
  13. * @param integer $survey_id Survey ID (database ID)
  14. * @param boolean $continue Optional. Whether to continue the current
  15. * process or exit when breaking condition found. Defaults to true (do not break).
  16. * @return void
  17. */
  18. public static function check_first_last_question($survey_id, $continue = true)
  19. {
  20. // Table definitions
  21. $tbl_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  22. $course_id = api_get_course_int_id();
  23. // Getting the information of the question
  24. $sql = "SELECT * FROM $tbl_survey_question
  25. WHERE c_id = $course_id AND survey_id='".Database::escape_string($survey_id)."'
  26. ORDER BY sort ASC";
  27. $result = Database::query($sql);
  28. $total = Database::num_rows($result);
  29. $counter = 1;
  30. $error = false;
  31. while ($row = Database::fetch_array($result, 'ASSOC')) {
  32. if ($counter == 1 && $row['type'] == 'pagebreak') {
  33. Display::display_error_message(get_lang('PagebreakNotFirst'), false);
  34. $error = true;
  35. }
  36. if ($counter == $total && $row['type'] == 'pagebreak') {
  37. Display::display_error_message(get_lang('PagebreakNotLast'), false);
  38. $error = true;
  39. }
  40. $counter++;
  41. }
  42. if (!$continue && $error) {
  43. Display::display_footer();
  44. exit;
  45. }
  46. }
  47. /**
  48. * This function removes an (or multiple) answer(s) of a user on a question of a survey
  49. *
  50. * @param mixed The user id or email of the person who fills the survey
  51. * @param integer The survey id
  52. * @param integer The question id
  53. * @param integer The option id
  54. *
  55. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  56. * @version January 2007
  57. */
  58. public static function remove_answer($user, $survey_id, $question_id, $course_id)
  59. {
  60. $course_id = intval($course_id);
  61. // table definition
  62. $table_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
  63. $sql = "DELETE FROM $table_survey_answer
  64. WHERE
  65. c_id = $course_id AND
  66. user = '".Database::escape_string($user)."' AND
  67. survey_id = '".intval($survey_id)."' AND
  68. question_id = '".intval($question_id)."'";
  69. Database::query($sql);
  70. }
  71. /**
  72. * This function stores an answer of a user on a question of a survey
  73. *
  74. * @param mixed The user id or email of the person who fills the survey
  75. * @param integer Survey id
  76. * @param integer Question id
  77. * @param integer Option id
  78. * @param string Option value
  79. * @param array Survey data settings
  80. * @return bool False if insufficient data, true otherwise
  81. *
  82. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  83. * @version January 2007
  84. */
  85. public static function store_answer(
  86. $user,
  87. $survey_id,
  88. $question_id,
  89. $option_id,
  90. $option_value,
  91. $survey_data
  92. ) {
  93. // If the question_id is empty, don't store an answer
  94. if (empty($question_id)) {
  95. return false;
  96. }
  97. // Table definition
  98. $table_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
  99. // Make the survey anonymous
  100. if ($survey_data['anonymous'] == 1) {
  101. if (!isset($_SESSION['surveyuser'])) {
  102. $user = md5($user.time());
  103. $_SESSION['surveyuser'] = $user;
  104. } else {
  105. $user = $_SESSION['surveyuser'];
  106. }
  107. }
  108. $course_id = $survey_data['c_id'];
  109. $sql = "INSERT INTO $table_survey_answer (c_id, user, survey_id, question_id, option_id, value) VALUES (
  110. $course_id,
  111. '".Database::escape_string($user)."',
  112. '".Database::escape_string($survey_id)."',
  113. '".Database::escape_string($question_id)."',
  114. '".Database::escape_string($option_id)."',
  115. '".Database::escape_string($option_value)."'
  116. )";
  117. Database::query($sql);
  118. $insertId = Database::insert_id();
  119. $sql = "UPDATE $table_survey_answer SET answer_id = $insertId
  120. WHERE iid = $insertId";
  121. Database::query($sql);
  122. return true;
  123. }
  124. /**
  125. * This function checks the parameters that are used in this page
  126. *
  127. * @return string $people_filled The header, an error and the footer if any parameter fails, else it returns true
  128. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  129. * @version February 2007
  130. */
  131. public static function check_parameters($people_filled)
  132. {
  133. $error = false;
  134. // Getting the survey data
  135. $survey_data = SurveyManager::get_survey($_GET['survey_id']);
  136. // $_GET['survey_id'] has to be numeric
  137. if (!is_numeric($_GET['survey_id'])) {
  138. $error = get_lang('IllegalSurveyId');
  139. }
  140. // $_GET['action']
  141. $allowed_actions = array(
  142. 'overview',
  143. 'questionreport',
  144. 'userreport',
  145. 'comparativereport',
  146. 'completereport',
  147. 'deleteuserreport'
  148. );
  149. if (isset($_GET['action']) && !in_array($_GET['action'], $allowed_actions)) {
  150. $error = get_lang('ActionNotAllowed');
  151. }
  152. // User report
  153. if (isset($_GET['action']) && $_GET['action'] == 'userreport') {
  154. if ($survey_data['anonymous'] == 0) {
  155. foreach ($people_filled as $key => & $value) {
  156. $people_filled_userids[] = $value['invited_user'];
  157. }
  158. } else {
  159. $people_filled_userids = $people_filled;
  160. }
  161. if (isset($_GET['user']) && !in_array($_GET['user'], $people_filled_userids)) {
  162. $error = get_lang('UnknowUser');
  163. }
  164. }
  165. // Question report
  166. if (isset($_GET['action']) && $_GET['action'] == 'questionreport') {
  167. if (isset($_GET['question']) && !is_numeric($_GET['question'])) {
  168. $error = get_lang('UnknowQuestion');
  169. }
  170. }
  171. if ($error) {
  172. $tool_name = get_lang('Reporting');
  173. Display::display_header($tool_name);
  174. Display::display_error_message(get_lang('Error').': '.$error, false);
  175. Display::display_footer();
  176. exit;
  177. } else {
  178. return true;
  179. }
  180. }
  181. /**
  182. * This function deals with the action handling
  183. * @param array $survey_data
  184. * @param array $people_filled
  185. * @return void
  186. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  187. * @version February 2007
  188. */
  189. public static function handle_reporting_actions($survey_data, $people_filled)
  190. {
  191. $action = isset($_GET['action']) ? $_GET['action'] : null;
  192. // Getting the number of question
  193. $temp_questions_data = SurveyManager::get_questions($_GET['survey_id']);
  194. // Sorting like they should be displayed and removing the non-answer question types (comment and pagebreak)
  195. $my_temp_questions_data = $temp_questions_data == null ? array() : $temp_questions_data;
  196. $questions_data = array();
  197. foreach ($my_temp_questions_data as $key => & $value) {
  198. if ($value['type'] != 'comment' && $value['type'] != 'pagebreak') {
  199. $questions_data[$value['sort']] = $value;
  200. }
  201. }
  202. // Counting the number of questions that are relevant for the reporting
  203. $survey_data['number_of_questions'] = count($questions_data);
  204. if ($action == 'questionreport') {
  205. self::display_question_report($survey_data);
  206. }
  207. if ($action == 'userreport') {
  208. self::display_user_report($people_filled, $survey_data);
  209. }
  210. if ($action == 'comparativereport') {
  211. self::display_comparative_report();
  212. }
  213. if ($action == 'completereport') {
  214. self::display_complete_report($survey_data);
  215. }
  216. if ($action == 'deleteuserreport') {
  217. self::delete_user_report($_GET['survey_id'], $_GET['user']);
  218. }
  219. }
  220. /**
  221. * This function deletes the report of an user who wants to retake the survey
  222. * @param integer $survey_id
  223. * @param integer $user_id
  224. * @return void
  225. * @author Christian Fasanando Flores <christian.fasanando@dokeos.com>
  226. * @version November 2008
  227. */
  228. public static function delete_user_report($survey_id, $user_id)
  229. {
  230. $table_survey_answer = Database:: get_course_table(TABLE_SURVEY_ANSWER);
  231. $table_survey_invitation = Database:: get_course_table(TABLE_SURVEY_INVITATION);
  232. $table_survey = Database:: get_course_table(TABLE_SURVEY);
  233. $course_id = api_get_course_int_id();
  234. $survey_id = (int) $survey_id;
  235. $user_id = Database::escape_string($user_id);
  236. if (!empty($survey_id) && !empty($user_id)) {
  237. // delete data from survey_answer by user_id and survey_id
  238. $sql = "DELETE FROM $table_survey_answer
  239. WHERE c_id = $course_id AND survey_id = '".$survey_id."' AND user = '".$user_id."'";
  240. Database::query($sql);
  241. // update field answered from survey_invitation by user_id and survey_id
  242. $sql = "UPDATE $table_survey_invitation SET answered = '0'
  243. WHERE
  244. c_id = $course_id AND
  245. survey_code = (
  246. SELECT code FROM $table_survey
  247. WHERE
  248. c_id = $course_id AND
  249. survey_id = '".$survey_id."'
  250. ) AND
  251. user = '".$user_id."'";
  252. $result = Database::query($sql);
  253. }
  254. if ($result !== false) {
  255. $message = get_lang('SurveyUserAnswersHaveBeenRemovedSuccessfully').'<br />
  256. <a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action=userreport&survey_id='.$survey_id.'">'.
  257. get_lang('GoBack').'</a>';
  258. Display::display_confirmation_message($message, false);
  259. }
  260. }
  261. /**
  262. * This function displays the user report which is basically nothing more
  263. * than a one-page display of all the questions
  264. * of the survey that is filled with the answers of the person who filled the survey.
  265. *
  266. * @return string html code of the one-page survey with the answers of the selected user
  267. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  268. * @version February 2007 - Updated March 2008
  269. */
  270. public static function display_user_report($people_filled, $survey_data)
  271. {
  272. // Database table definitions
  273. $table_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  274. $table_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  275. $table_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
  276. $surveyId = isset($_GET['survey_id']) ? (int) $_GET['survey_id'] : 0;
  277. // Actions bar
  278. echo '<div class="actions">';
  279. echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?survey_id='.$surveyId.'&'.api_get_cidreq().'">'.
  280. Display::return_icon('back.png',get_lang('BackTo').' '.get_lang('ReportingOverview'),'',ICON_SIZE_MEDIUM).'</a>';
  281. if (isset($_GET['user'])) {
  282. if (api_is_allowed_to_edit()) {
  283. // The delete link
  284. echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action=deleteuserreport&survey_id='.$surveyId.'&'.api_get_cidreq().'&user='.Security::remove_XSS($_GET['user']).'" >'.
  285. Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_MEDIUM).'</a>';
  286. }
  287. // Export the user report
  288. echo '<a href="javascript: void(0);" onclick="document.form1a.submit();">'.
  289. Display::return_icon('export_csv.png', get_lang('ExportAsCSV'),'',ICON_SIZE_MEDIUM).'</a> ';
  290. echo '<a href="javascript: void(0);" onclick="document.form1b.submit();">'.
  291. Display::return_icon('export_excel.png', get_lang('ExportAsXLS'),'',ICON_SIZE_MEDIUM).'</a> ';
  292. echo '<form id="form1a" name="form1a" method="post" action="'.api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&survey_id='.$surveyId.'&'.api_get_cidreq().'&user_id='.Security::remove_XSS($_GET['user']).'">';
  293. echo '<input type="hidden" name="export_report" value="export_report">';
  294. echo '<input type="hidden" name="export_format" value="csv">';
  295. echo '</form>';
  296. echo '<form id="form1b" name="form1b" method="post" action="'.api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&survey_id='.$surveyId.'&'.api_get_cidreq().'&user_id='.Security::remove_XSS($_GET['user']).'">';
  297. echo '<input type="hidden" name="export_report" value="export_report">';
  298. echo '<input type="hidden" name="export_format" value="xls">';
  299. echo '</form>';
  300. echo '<form id="form2" name="form2" method="post" action="'.api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&survey_id='.$surveyId.'&'.api_get_cidreq().'">';
  301. }
  302. echo '</div>';
  303. // Step 1: selection of the user
  304. echo "<script>
  305. function jumpMenu(targ,selObj,restore) {
  306. eval(targ+\".location='\"+selObj.options[selObj.selectedIndex].value+\"'\");
  307. if (restore) selObj.selectedIndex=0;
  308. }
  309. </script>";
  310. echo get_lang('SelectUserWhoFilledSurvey').'<br />';
  311. echo '<select name="user" onchange="jumpMenu(\'parent\',this,0)">';
  312. echo '<option value="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action='.Security::remove_XSS($_GET['action']).'&survey_id='.Security::remove_XSS($_GET['survey_id']).'">'.get_lang('SelectUser').'</option>';
  313. foreach ($people_filled as $key => & $person) {
  314. if ($survey_data['anonymous'] == 0) {
  315. $name = $person['user_info']['complete_name_with_username'];
  316. $id = $person['user_id'];
  317. if ($id == '') {
  318. $id = $person['invited_user'];
  319. $name = $person['invited_user'];
  320. }
  321. } else {
  322. $name = get_lang('Anonymous') . ' ' . ($key + 1);
  323. $id = $person;
  324. }
  325. echo '<option value="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action='.Security::remove_XSS($_GET['action']).'&survey_id='.Security::remove_XSS($_GET['survey_id']).'&user='.Security::remove_XSS($id).'" ';
  326. if (isset($_GET['user']) && $_GET['user'] == $id) {
  327. echo 'selected="selected"';
  328. }
  329. echo '>'.$name.'</option>';
  330. }
  331. echo '</select>';
  332. $course_id = api_get_course_int_id();
  333. // Step 2: displaying the survey and the answer of the selected users
  334. if (isset($_GET['user'])) {
  335. Display::display_normal_message(
  336. get_lang('AllQuestionsOnOnePage'),
  337. false
  338. );
  339. // Getting all the questions and options
  340. $sql = "SELECT
  341. survey_question.question_id,
  342. survey_question.survey_id,
  343. survey_question.survey_question,
  344. survey_question.display,
  345. survey_question.max_value,
  346. survey_question.sort,
  347. survey_question.type,
  348. survey_question_option.question_option_id,
  349. survey_question_option.option_text,
  350. survey_question_option.sort as option_sort
  351. FROM $table_survey_question survey_question
  352. LEFT JOIN $table_survey_question_option survey_question_option
  353. ON
  354. survey_question.question_id = survey_question_option.question_id AND
  355. survey_question_option.c_id = $course_id
  356. WHERE
  357. survey_question.survey_id = '".Database::escape_string($_GET['survey_id'])."' AND
  358. survey_question.c_id = $course_id
  359. ORDER BY survey_question.sort, survey_question_option.sort ASC";
  360. $result = Database::query($sql);
  361. while ($row = Database::fetch_array($result, 'ASSOC')) {
  362. if ($row['type'] != 'pagebreak') {
  363. $questions[$row['sort']]['question_id'] = $row['question_id'];
  364. $questions[$row['sort']]['survey_id'] = $row['survey_id'];
  365. $questions[$row['sort']]['survey_question'] = $row['survey_question'];
  366. $questions[$row['sort']]['display'] = $row['display'];
  367. $questions[$row['sort']]['type'] = $row['type'];
  368. $questions[$row['sort']]['maximum_score'] = $row['max_value'];
  369. $questions[$row['sort']]['options'][$row['question_option_id']] = $row['option_text'];
  370. }
  371. }
  372. // Getting all the answers of the user
  373. $sql = "SELECT * FROM $table_survey_answer
  374. WHERE
  375. c_id = $course_id AND
  376. survey_id = '".intval($_GET['survey_id'])."' AND
  377. user = '".Database::escape_string($_GET['user'])."'";
  378. $result = Database::query($sql);
  379. while ($row = Database::fetch_array($result, 'ASSOC')) {
  380. $answers[$row['question_id']][] = $row['option_id'];
  381. $all_answers[$row['question_id']][] = $row;
  382. }
  383. // Displaying all the questions
  384. foreach ($questions as & $question) {
  385. // If the question type is a scoring then we have to format the answers differently
  386. switch ($question['type']) {
  387. case 'score':
  388. $finalAnswer = array();
  389. if (is_array($question) && is_array($all_answers)) {
  390. foreach ($all_answers[$question['question_id']] as $key => & $answer_array) {
  391. $finalAnswer[$answer_array['option_id']] = $answer_array['value'];
  392. }
  393. }
  394. break;
  395. case 'multipleresponse':
  396. $finalAnswer = isset($answers[$question['question_id']]) ? $answers[$question['question_id']] : '';
  397. break;
  398. default:
  399. $finalAnswer = '';
  400. if (isset($all_answers[$question['question_id']])) {
  401. $finalAnswer = $all_answers[$question['question_id']][0]['option_id'];
  402. }
  403. break;
  404. }
  405. $ch_type = 'ch_'.$question['type'];
  406. /** @var survey_question $display */
  407. $display = new $ch_type;
  408. $url = api_get_self();
  409. $form = new FormValidator('question', 'post', $url);
  410. $form->addHtml('<div class="survey_question_wrapper"><div class="survey_question">');
  411. $form->addHtml($question['survey_question']);
  412. $display->render($form, $question, $finalAnswer);
  413. $form->addHtml('</div></div>');
  414. $form->display();
  415. }
  416. }
  417. }
  418. /**
  419. * This function displays the report by question.
  420. *
  421. * It displays a table with all the options of the question and the number of users who have answered positively on the option.
  422. * The number of users who answered positive on a given option is expressed in an absolute number, in a percentage of the total
  423. * and graphically using bars
  424. * By clicking on the absolute number you get a list with the persons who have answered this.
  425. * You can then click on the name of the person and you will then go to the report by user where you see all the
  426. * answers of that user.
  427. *
  428. * @param array All the survey data
  429. * @return string html code that displays the report by question
  430. * @todo allow switching between horizontal and vertical.
  431. * @todo multiple response: percentage are probably not OK
  432. * @todo the question and option text have to be shortened and should expand when the user clicks on it.
  433. * @todo the pagebreak and comment question types should not be shown => removed from $survey_data before
  434. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  435. * @version February 2007 - Updated March 2008
  436. */
  437. public static function display_question_report($survey_data)
  438. {
  439. $singlePage = isset($_GET['single_page']) ? intval($_GET['single_page']) : 0;
  440. $course_id = api_get_course_int_id();
  441. // Database table definitions
  442. $table_survey_question = Database:: get_course_table(TABLE_SURVEY_QUESTION);
  443. $table_survey_question_option = Database:: get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  444. $table_survey_answer = Database:: get_course_table(TABLE_SURVEY_ANSWER);
  445. // Determining the offset of the sql statement (the n-th question of the survey)
  446. $offset = !isset($_GET['question']) ? 0 : intval($_GET['question']);
  447. $currentQuestion = isset($_GET['question']) ? intval($_GET['question']) : 0;
  448. $questions = array();
  449. $surveyId = intval($_GET['survey_id']);
  450. $action = Security::remove_XSS($_GET['action']);
  451. echo '<div class="actions">';
  452. echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?survey_id='.$surveyId.'">'.
  453. Display::return_icon('back.png',get_lang('BackTo').' '.get_lang('ReportingOverview'),'',ICON_SIZE_MEDIUM).'</a>';
  454. echo '</div>';
  455. if ($survey_data['number_of_questions'] > 0) {
  456. $limitStatement = null;
  457. if (!$singlePage) {
  458. echo '<div id="question_report_questionnumbers" class="pagination">';
  459. if ($currentQuestion != 0) {
  460. echo '<li><a href="' . api_get_path(WEB_CODE_PATH) . 'survey/reporting.php?action=' . $action . '&' . api_get_cidreq() . '&survey_id=' . $surveyId . '&question=' . ($offset - 1) . '">' . get_lang('PreviousQuestion') . '</a></li>';
  461. }
  462. for ($i = 1; $i <= $survey_data['number_of_questions']; $i++) {
  463. if ($offset != $i - 1) {
  464. echo '<li><a href="' . api_get_path(WEB_CODE_PATH) . 'survey/reporting.php?action=' . $action . '&' . api_get_cidreq() . '&survey_id=' . $surveyId . '&question=' . ($i - 1) . '">' . $i . '</a></li>';
  465. } else {
  466. echo '<li class="disabled"s><a href="#">' . $i . '</a></li>';
  467. }
  468. }
  469. if ($currentQuestion < ($survey_data['number_of_questions'] - 1)) {
  470. echo '<li><a href="' . api_get_path(WEB_CODE_PATH) . 'survey/reporting.php?action=' . $action . '&' . api_get_cidreq() . '&survey_id=' . $surveyId . '&question=' . ($offset + 1) . '">' . get_lang('NextQuestion') . '</li></a>';
  471. }
  472. echo '</ul>';
  473. echo '</div>';
  474. $limitStatement = " LIMIT $offset, 1";
  475. }
  476. // Getting the question information
  477. $sql = "SELECT * FROM $table_survey_question
  478. WHERE
  479. c_id = $course_id AND
  480. survey_id='".Database::escape_string($_GET['survey_id'])."' AND
  481. type<>'pagebreak' AND type<>'comment'
  482. ORDER BY sort ASC
  483. $limitStatement";
  484. $result = Database::query($sql);
  485. //$question = Database::fetch_array($result);
  486. while ($row = Database::fetch_array($result)) {
  487. $questions[$row['question_id']] = $row;
  488. }
  489. }
  490. foreach ($questions as $question) {
  491. $chartData = array();
  492. $options = array();
  493. echo '<div class="title-question">';
  494. echo strip_tags(isset($question['survey_question']) ? $question['survey_question'] : null);
  495. echo '</div>';
  496. if ($question['type'] == 'score') {
  497. /** @todo This function should return the options as this is needed further in the code */
  498. $options = self::display_question_report_score($survey_data, $question, $offset);
  499. } elseif ($question['type'] == 'open') {
  500. /** @todo Also get the user who has answered this */
  501. $sql = "SELECT * FROM $table_survey_answer
  502. WHERE
  503. c_id = $course_id AND
  504. survey_id='" . intval($_GET['survey_id']) . "' AND
  505. question_id = '" . intval($question['question_id']) . "'";
  506. $result = Database::query($sql);
  507. while ($row = Database::fetch_array($result, 'ASSOC')) {
  508. echo $row['option_id'] . '<hr noshade="noshade" size="1" />';
  509. }
  510. } else {
  511. // Getting the options ORDER BY sort ASC
  512. $sql = "SELECT * FROM $table_survey_question_option
  513. WHERE
  514. c_id = $course_id AND
  515. survey_id='" . intval($_GET['survey_id']) . "'
  516. AND question_id = '" . intval($question['question_id']) . "'
  517. ORDER BY sort ASC";
  518. $result = Database::query($sql);
  519. while ($row = Database::fetch_array($result, 'ASSOC')) {
  520. $options[$row['question_option_id']] = $row;
  521. }
  522. // Getting the answers
  523. $sql = "SELECT *, count(answer_id) as total FROM $table_survey_answer
  524. WHERE
  525. c_id = $course_id AND
  526. survey_id='" . intval($_GET['survey_id']) . "'
  527. AND question_id = '" . intval($question['question_id']) . "'
  528. GROUP BY option_id, value";
  529. $result = Database::query($sql);
  530. $number_of_answers = array();
  531. $data = array();
  532. while ($row = Database::fetch_array($result, 'ASSOC')) {
  533. if (!isset($number_of_answers[$row['question_id']])) {
  534. $number_of_answers[$row['question_id']] = 0;
  535. }
  536. $number_of_answers[$row['question_id']] += $row['total'];
  537. $data[$row['option_id']] = $row;
  538. }
  539. foreach ($options as $option) {
  540. $optionText = strip_tags($option['option_text']);
  541. $optionText = html_entity_decode($optionText);
  542. $votes = isset($data[$option['question_option_id']]['total']) ?
  543. $data[$option['question_option_id']]['total'] :
  544. '0';
  545. array_push($chartData, array('option' => $optionText, 'votes' => $votes));
  546. }
  547. $chartContainerId = 'chartContainer'.$question['question_id'];
  548. echo '<div id="'.$chartContainerId.'" class="col-md-12">';
  549. echo self::drawChart($chartData, false, $chartContainerId);
  550. // displaying the table: headers
  551. echo '<table class="display-survey table">';
  552. echo ' <tr>';
  553. echo ' <th>&nbsp;</th>';
  554. echo ' <th>' . get_lang('AbsoluteTotal') . '</th>';
  555. echo ' <th>' . get_lang('Percentage') . '</th>';
  556. echo ' <th>' . get_lang('VisualRepresentation') . '</th>';
  557. echo ' <tr>';
  558. // Displaying the table: the content
  559. if (is_array($options)) {
  560. foreach ($options as $key => & $value) {
  561. $absolute_number = null;
  562. if (isset($data[$value['question_option_id']])) {
  563. $absolute_number = $data[$value['question_option_id']]['total'];
  564. }
  565. if ($question['type'] == 'percentage' && empty($absolute_number)) {
  566. continue;
  567. }
  568. $number_of_answers[$option['question_id']] = isset($number_of_answers[$option['question_id']]) ? $number_of_answers[$option['question_id']] : 0;
  569. if ($number_of_answers[$option['question_id']] == 0) {
  570. $answers_number = 0;
  571. } else {
  572. $answers_number = $absolute_number / $number_of_answers[$option['question_id']] * 100;
  573. }
  574. echo ' <tr>';
  575. echo ' <td class="center">' . $value['option_text'] . '</td>';
  576. echo ' <td class="center">';
  577. if ($absolute_number != 0) {
  578. echo '<a href="' . api_get_path(WEB_CODE_PATH) . 'survey/reporting.php?action=' . $action . '&survey_id=' . $surveyId . '&question=' . $offset . '&viewoption=' . $value['question_option_id'] . '">' . $absolute_number . '</a>';
  579. } else {
  580. echo '0';
  581. }
  582. echo ' </td>';
  583. echo ' <td class="center">' . round($answers_number, 2) . ' %</td>';
  584. echo ' <td class="center">';
  585. $size = $answers_number * 2;
  586. if ($size > 0) {
  587. echo '<div style="border:1px solid #264269; background-color:#aecaf4; height:10px; width:' . $size . 'px">&nbsp;</div>';
  588. } else {
  589. echo '<div style="text-align: left;">' . get_lang("NoDataAvailable") . '</div>';
  590. }
  591. echo ' </td>';
  592. echo ' </tr>';
  593. }
  594. }
  595. // displaying the table: footer (totals)
  596. echo ' <tr>';
  597. echo ' <td class="total"><b>' . get_lang('Total') . '</b></td>';
  598. echo ' <td class="total"><b>' . ($number_of_answers[$option['question_id']] == 0 ? '0' : $number_of_answers[$option['question_id']]) . '</b></td>';
  599. echo ' <td class="total">&nbsp;</td>';
  600. echo ' <td class="total">&nbsp;</td>';
  601. echo ' </tr>';
  602. echo '</table>';
  603. echo '</div>';
  604. }
  605. }
  606. if (isset($_GET['viewoption'])) {
  607. echo '<div class="answered-people">';
  608. echo '<h4>'.get_lang('PeopleWhoAnswered').': '.strip_tags($options[Security::remove_XSS($_GET['viewoption'])]['option_text']).'</h4>';
  609. if (is_numeric($_GET['value'])) {
  610. $sql_restriction = "AND value='".Database::escape_string($_GET['value'])."'";
  611. }
  612. $sql = "SELECT user FROM $table_survey_answer
  613. WHERE
  614. c_id = $course_id AND
  615. option_id = '".Database::escape_string($_GET['viewoption'])."'
  616. $sql_restriction";
  617. $result = Database::query($sql);
  618. echo '<ul>';
  619. while ($row = Database::fetch_array($result, 'ASSOC')) {
  620. $user_info = api_get_user_info($row['user']);
  621. echo '<li><a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action=userreport&survey_id='.$surveyId.'&user='.$row['user'].'">'.
  622. $user_info['complete_name_with_username'].
  623. '</a></li>';
  624. }
  625. echo '</ul>';
  626. echo '</div>';
  627. }
  628. }
  629. /**
  630. * Display score data about a survey question
  631. * @param array Question info
  632. * @param integer The offset of results shown
  633. * @return void (direct output)
  634. */
  635. public static function display_question_report_score($survey_data, $question, $offset)
  636. {
  637. // Database table definitions
  638. $table_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  639. $table_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
  640. $course_id = api_get_course_int_id();
  641. // Getting the options
  642. $sql = "SELECT * FROM $table_survey_question_option
  643. WHERE
  644. c_id = $course_id AND
  645. survey_id='".Database::escape_string($_GET['survey_id'])."' AND
  646. question_id = '".Database::escape_string($question['question_id'])."'
  647. ORDER BY sort ASC";
  648. $result = Database::query($sql);
  649. while ($row = Database::fetch_array($result)) {
  650. $options[$row['question_option_id']] = $row;
  651. }
  652. // Getting the answers
  653. $sql = "SELECT *, count(answer_id) as total FROM $table_survey_answer
  654. WHERE
  655. c_id = $course_id AND
  656. survey_id='".Database::escape_string($_GET['survey_id'])."' AND
  657. question_id = '".Database::escape_string($question['question_id'])."'
  658. GROUP BY option_id, value";
  659. $result = Database::query($sql);
  660. $number_of_answers = 0;
  661. while ($row = Database::fetch_array($result)) {
  662. $number_of_answers += $row['total'];
  663. $data[$row['option_id']][$row['value']] = $row;
  664. }
  665. $chartData = array();
  666. foreach ($options as $option) {
  667. $optionText = strip_tags($option['option_text']);
  668. $optionText = html_entity_decode($optionText);
  669. for ($i = 1; $i <= $question['max_value']; $i++) {
  670. $votes = $data[$option['question_option_id']][$i]['total'];
  671. if (empty($votes)) {
  672. $votes = '0';
  673. }
  674. array_push(
  675. $chartData,
  676. array(
  677. 'serie' => $optionText,
  678. 'option' => $i,
  679. 'votes' => $votes
  680. )
  681. );
  682. }
  683. }
  684. echo '<div id="chartContainer" class="col-md-12">';
  685. echo self::drawChart($chartData, true);
  686. echo '</div>';
  687. // Displaying the table: headers
  688. echo '<table class="data_table">';
  689. echo ' <tr>';
  690. echo ' <th>&nbsp;</th>';
  691. echo ' <th>'.get_lang('Score').'</th>';
  692. echo ' <th>'.get_lang('AbsoluteTotal').'</th>';
  693. echo ' <th>'.get_lang('Percentage').'</th>';
  694. echo ' <th>'.get_lang('VisualRepresentation').'</th>';
  695. echo ' <tr>';
  696. // Displaying the table: the content
  697. foreach ($options as $key => & $value) {
  698. for ($i = 1; $i <= $question['max_value']; $i++) {
  699. $absolute_number = $data[$value['question_option_id']][$i]['total'];
  700. echo ' <tr>';
  701. echo ' <td>'.$value['option_text'].'</td>';
  702. echo ' <td>'.$i.'</td>';
  703. echo ' <td><a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action='.$action.'&survey_id='.Security::remove_XSS($_GET['survey_id']).'&question='.Security::remove_XSS($offset).'&viewoption='.$value['question_option_id'].'&value='.$i.'">'.$absolute_number.'</a></td>';
  704. echo ' <td>'.round($absolute_number/$number_of_answers*100, 2).' %</td>';
  705. echo ' <td>';
  706. $size = ($absolute_number/$number_of_answers*100*2);
  707. if ($size > 0) {
  708. echo ' <div style="border:1px solid #264269; background-color:#aecaf4; height:10px; width:'.$size.'px">&nbsp;</div>';
  709. }
  710. echo ' </td>';
  711. echo ' </tr>';
  712. }
  713. }
  714. // Displaying the table: footer (totals)
  715. echo ' <tr>';
  716. echo ' <td style="border-top:1px solid black"><b>'.get_lang('Total').'</b></td>';
  717. echo ' <td style="border-top:1px solid black">&nbsp;</td>';
  718. echo ' <td style="border-top:1px solid black"><b>'.$number_of_answers.'</b></td>';
  719. echo ' <td style="border-top:1px solid black">&nbsp;</td>';
  720. echo ' <td style="border-top:1px solid black">&nbsp;</td>';
  721. echo ' </tr>';
  722. echo '</table>';
  723. }
  724. /**
  725. * This functions displays the complete reporting
  726. * @return string HTML code
  727. * @todo open questions are not in the complete report yet.
  728. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  729. * @version February 2007
  730. */
  731. public static function display_complete_report($survey_data)
  732. {
  733. // Database table definitions
  734. $table_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  735. $table_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  736. $table_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
  737. $surveyId = isset($_GET['survey_id']) ? intval($_GET['survey_id']) : 0;
  738. $action = isset($_GET['action']) ? Security::remove_XSS($_GET['action']) : '';
  739. // Actions bar
  740. echo '<div class="actions">';
  741. echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?survey_id='.Security::remove_XSS($_GET['survey_id']).'">
  742. '.Display::return_icon('back.png',get_lang('BackTo').' '.get_lang('ReportingOverview'),'',ICON_SIZE_MEDIUM).'</a>';
  743. echo '<a class="survey_export_link" href="javascript: void(0);" onclick="document.form1a.submit();">
  744. '.Display::return_icon('export_csv.png',get_lang('ExportAsCSV'),'',ICON_SIZE_MEDIUM).'</a>';
  745. echo '<a class="survey_export_link" href="javascript: void(0);" onclick="document.form1b.submit();">
  746. '.Display::return_icon('export_excel.png',get_lang('ExportAsXLS'),'',ICON_SIZE_MEDIUM).'</a>';
  747. echo '</div>';
  748. // The form
  749. echo '<form id="form1a" name="form1a" method="post" action="'.api_get_self().'?action='.$action.'&survey_id='.$surveyId.'&'.api_get_cidreq().'">';
  750. echo '<input type="hidden" name="export_report" value="export_report">';
  751. echo '<input type="hidden" name="export_format" value="csv">';
  752. echo '</form>';
  753. echo '<form id="form1b" name="form1b" method="post" action="'.api_get_self().'?action='.$action.'&survey_id='.$surveyId.'&'.api_get_cidreq().'">';
  754. echo '<input type="hidden" name="export_report" value="export_report">';
  755. echo '<input type="hidden" name="export_format" value="xls">';
  756. echo '</form>';
  757. echo '<form id="form2" name="form2" method="post" action="'.api_get_self().'?action='.$action.'&survey_id='.$surveyId.'&'.api_get_cidreq().'">';
  758. // The table
  759. echo '<br /><table class="data_table" border="1">';
  760. // Getting the number of options per question
  761. echo ' <tr>';
  762. echo ' <th>';
  763. if (
  764. (isset($_POST['submit_question_filter']) && $_POST['submit_question_filter']) ||
  765. (isset($_POST['export_report']) && $_POST['export_report'])
  766. ) {
  767. echo '<button class="cancel" type="submit" name="reset_question_filter" value="'.get_lang('ResetQuestionFilter').'">'.get_lang('ResetQuestionFilter').'</button>';
  768. }
  769. echo '<button class="save" type="submit" name="submit_question_filter" value="'.get_lang('SubmitQuestionFilter').'">'.get_lang('SubmitQuestionFilter').'</button>';
  770. echo '</th>';
  771. $display_extra_user_fields = false;
  772. if (!(isset($_POST['submit_question_filter']) && $_POST['submit_question_filter'] ||
  773. isset($_POST['export_report']) && $_POST['export_report']) || !empty($_POST['fields_filter'])) {
  774. // Show user fields section with a big th colspan that spans over all fields
  775. $extra_user_fields = UserManager::get_extra_fields(0, 0, 5, 'ASC', false, true);
  776. $num = count($extra_user_fields);
  777. if ($num > 0 ) {
  778. echo '<th '.($num>0?' colspan="'.$num.'"':'').'>';
  779. echo '<label><input type="checkbox" name="fields_filter" value="1" checked="checked"/> ';
  780. echo get_lang('UserFields');
  781. echo '</label>';
  782. echo '</th>';
  783. $display_extra_user_fields = true;
  784. }
  785. }
  786. $course_id = api_get_course_int_id();
  787. $sql = "SELECT q.question_id, q.type, q.survey_question, count(o.question_option_id) as number_of_options
  788. FROM $table_survey_question q
  789. LEFT JOIN $table_survey_question_option o
  790. ON q.question_id = o.question_id
  791. WHERE
  792. q.survey_id = '".$surveyId."' AND
  793. q.c_id = $course_id AND
  794. o.c_id = $course_id
  795. GROUP BY q.question_id
  796. ORDER BY q.sort ASC";
  797. $result = Database::query($sql);
  798. $questions = [];
  799. while ($row = Database::fetch_array($result)) {
  800. // We show the questions if
  801. // 1. there is no question filter and the export button has not been clicked
  802. // 2. there is a quesiton filter but the question is selected for display
  803. if (!(isset($_POST['submit_question_filter']) && $_POST['submit_question_filter']) ||
  804. (is_array($_POST['questions_filter']) && in_array($row['question_id'], $_POST['questions_filter']))
  805. ) {
  806. // We do not show comment and pagebreak question types
  807. if ($row['type'] != 'comment' && $row['type'] != 'pagebreak') {
  808. echo ' <th';
  809. // <hub> modified tst to include percentage
  810. if ($row['number_of_options'] > 0 && $row['type'] != 'percentage') {
  811. // </hub>
  812. echo ' colspan="'.$row['number_of_options'].'"';
  813. }
  814. echo '>';
  815. echo '<label><input type="checkbox" name="questions_filter[]" value="'.$row['question_id'].'" checked="checked"/> ';
  816. echo $row['survey_question'];
  817. echo '</label>';
  818. echo '</th>';
  819. }
  820. // No column at all if it's not a question
  821. }
  822. $questions[$row['question_id']] = $row;
  823. }
  824. echo ' </tr>';
  825. // Getting all the questions and options
  826. echo ' <tr>';
  827. echo ' <th>&nbsp;</th>'; // the user column
  828. if (!(isset($_POST['submit_question_filter']) && $_POST['submit_question_filter'] ||
  829. isset($_POST['export_report']) && $_POST['export_report']) || !empty($_POST['fields_filter'])) {
  830. //show the fields names for user fields
  831. foreach($extra_user_fields as & $field) {
  832. echo '<th>'.$field[3].'</th>';
  833. }
  834. }
  835. // cells with option (none for open question)
  836. $sql = "SELECT
  837. sq.question_id, sq.survey_id,
  838. sq.survey_question, sq.display,
  839. sq.sort, sq.type, sqo.question_option_id,
  840. sqo.option_text, sqo.sort as option_sort
  841. FROM $table_survey_question sq
  842. LEFT JOIN $table_survey_question_option sqo
  843. ON sq.question_id = sqo.question_id
  844. WHERE
  845. sq.survey_id = '".$surveyId."' AND
  846. sq.c_id = $course_id AND
  847. sqo.c_id = $course_id
  848. ORDER BY sq.sort ASC, sqo.sort ASC";
  849. $result = Database::query($sql);
  850. $display_percentage_header = 1;
  851. $possible_answers = [];
  852. // in order to display only once the cell option (and not 100 times)
  853. while ($row = Database::fetch_array($result)) {
  854. // We show the options if
  855. // 1. there is no question filter and the export button has not been clicked
  856. // 2. there is a question filter but the question is selected for display
  857. if (!(isset($_POST['submit_question_filter']) && $_POST['submit_question_filter']) ||
  858. (is_array($_POST['questions_filter']) && in_array($row['question_id'], $_POST['questions_filter']))
  859. ) {
  860. // <hub> modif 05-05-2010
  861. // we do not show comment and pagebreak question types
  862. if ($row['type'] == 'open') {
  863. echo '<th>&nbsp;-&nbsp;</th>';
  864. $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
  865. $display_percentage_header = 1;
  866. } else if ($row['type'] == 'percentage' && $display_percentage_header) {
  867. echo '<th>&nbsp;%&nbsp;</th>';
  868. $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
  869. $display_percentage_header = 0;
  870. } else if ($row['type'] == 'percentage') {
  871. $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
  872. } else if ($row['type'] <> 'comment' && $row['type'] <> 'pagebreak' && $row['type'] <> 'percentage') {
  873. echo '<th>';
  874. echo $row['option_text'];
  875. echo '</th>';
  876. $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
  877. $display_percentage_header = 1;
  878. }
  879. //no column at all if the question was not a question
  880. // </hub>
  881. }
  882. }
  883. echo ' </tr>';
  884. // Getting all the answers of the users
  885. $old_user = '';
  886. $answers_of_user = array();
  887. $sql = "SELECT * FROM $table_survey_answer
  888. WHERE
  889. c_id = $course_id AND
  890. survey_id='".$surveyId."'
  891. ORDER BY answer_id, user ASC";
  892. $result = Database::query($sql);
  893. $i = 1;
  894. while ($row = Database::fetch_array($result)) {
  895. if ($old_user != $row['user'] && $old_user != '') {
  896. $userParam = $old_user;
  897. if ($survey_data['anonymous'] != 0) {
  898. $userParam = $i;
  899. $i++;
  900. }
  901. self::display_complete_report_row(
  902. $survey_data,
  903. $possible_answers,
  904. $answers_of_user,
  905. $userParam,
  906. $questions,
  907. $display_extra_user_fields
  908. );
  909. $answers_of_user=array();
  910. }
  911. if (isset($questions[$row['question_id']]) && $questions[$row['question_id']]['type'] != 'open') {
  912. $answers_of_user[$row['question_id']][$row['option_id']] = $row;
  913. } else {
  914. $answers_of_user[$row['question_id']][0] = $row;
  915. }
  916. $old_user = $row['user'];
  917. }
  918. $userParam = $old_user;
  919. if ($survey_data['anonymous'] != 0) {
  920. $userParam = $i;
  921. $i++;
  922. }
  923. self::display_complete_report_row(
  924. $survey_data,
  925. $possible_answers,
  926. $answers_of_user,
  927. $userParam,
  928. $questions,
  929. $display_extra_user_fields
  930. );
  931. // This is to display the last user
  932. echo '</table>';
  933. echo '</form>';
  934. }
  935. /**
  936. * This function displays a row (= a user and his/her answers) in the table of the complete report.
  937. *
  938. * @param array $survey_data
  939. * @param array Possible options
  940. * @param array User answers
  941. * @param mixed User ID or user details string
  942. * @param boolean Whether to show extra user fields or not
  943. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  944. * @version February 2007 - Updated March 2008
  945. */
  946. public static function display_complete_report_row(
  947. $survey_data,
  948. $possible_options,
  949. $answers_of_user,
  950. $user,
  951. $questions,
  952. $display_extra_user_fields = false
  953. ) {
  954. $user = Security::remove_XSS($user);
  955. echo '<tr>';
  956. if ($survey_data['anonymous'] == 0) {
  957. if (intval($user) !== 0) {
  958. $userInfo = api_get_user_info($user);
  959. if (!empty($userInfo)) {
  960. $user_displayed = $userInfo['complete_name_with_username'];
  961. } else {
  962. $user_displayed = '-';
  963. }
  964. echo '<th><a href="'.api_get_self().'?action=userreport&survey_id='.Security::remove_XSS($_GET['survey_id']).'&user='.$user.'">'.
  965. $user_displayed.'</a></th>'; // the user column
  966. } else {
  967. echo '<th>'.$user.'</th>'; // the user column
  968. }
  969. } else {
  970. echo '<th>' . get_lang('Anonymous') . ' ' . $user . '</th>';
  971. }
  972. if ($display_extra_user_fields) {
  973. // Show user fields data, if any, for this user
  974. $user_fields_values = UserManager::get_extra_user_data(intval($user), false, false, false, true);
  975. foreach ($user_fields_values as & $value) {
  976. echo '<td align="center">'.$value.'</td>';
  977. }
  978. }
  979. if (is_array($possible_options)) {
  980. // <hub> modified to display open answers and percentage
  981. foreach ($possible_options as $question_id => & $possible_option) {
  982. if ($questions[$question_id]['type'] == 'open') {
  983. echo '<td align="center">';
  984. echo $answers_of_user[$question_id]['0']['option_id'];
  985. echo '</td>';
  986. } else {
  987. foreach ($possible_option as $option_id => & $value) {
  988. if ($questions[$question_id]['type'] == 'percentage') {
  989. if (!empty($answers_of_user[$question_id][$option_id])) {
  990. echo "<td align='center'>";
  991. echo $answers_of_user[$question_id][$option_id]['value'];
  992. echo "</td>";
  993. }
  994. }
  995. else {
  996. echo '<td align="center">';
  997. if (!empty($answers_of_user[$question_id][$option_id])) {
  998. if ($answers_of_user[$question_id][$option_id]['value'] != 0) {
  999. echo $answers_of_user[$question_id][$option_id]['value'];
  1000. }
  1001. else {
  1002. echo 'v';
  1003. }
  1004. }
  1005. } // </hub>
  1006. }
  1007. }
  1008. }
  1009. }
  1010. echo '</tr>';
  1011. }
  1012. /**
  1013. * Quite similar to display_complete_report(), returns an HTML string
  1014. * that can be used in a csv file
  1015. * @todo consider merging this function with display_complete_report
  1016. * @return string The contents of a csv file
  1017. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1018. * @version February 2007
  1019. */
  1020. public static function export_complete_report($survey_data, $user_id = 0)
  1021. {
  1022. // Database table definitions
  1023. $table_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  1024. $table_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  1025. $table_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
  1026. // The first column
  1027. $return = ';';
  1028. // Show extra fields blank space (enough for extra fields on next line)
  1029. $extra_user_fields = UserManager::get_extra_fields(
  1030. 0,
  1031. 0,
  1032. 5,
  1033. 'ASC',
  1034. false,
  1035. true
  1036. );
  1037. $num = count($extra_user_fields);
  1038. $return .= str_repeat(';', $num);
  1039. $course_id = api_get_course_int_id();
  1040. $sql = "SELECT
  1041. questions.question_id,
  1042. questions.type,
  1043. questions.survey_question,
  1044. count(options.question_option_id) as number_of_options
  1045. FROM $table_survey_question questions
  1046. LEFT JOIN $table_survey_question_option options
  1047. ON questions.question_id = options.question_id AND options.c_id = $course_id
  1048. WHERE
  1049. questions.survey_id = '".intval($_GET['survey_id'])."' AND
  1050. questions.c_id = $course_id
  1051. GROUP BY questions.question_id
  1052. ORDER BY questions.sort ASC";
  1053. $result = Database::query($sql);
  1054. while ($row = Database::fetch_array($result)) {
  1055. // We show the questions if
  1056. // 1. there is no question filter and the export button has not been clicked
  1057. // 2. there is a quesiton filter but the question is selected for display
  1058. if (!(isset($_POST['submit_question_filter'])) ||
  1059. (isset($_POST['submit_question_filter']) &&
  1060. is_array($_POST['questions_filter']) &&
  1061. in_array($row['question_id'], $_POST['questions_filter']))
  1062. ) {
  1063. // We do not show comment and pagebreak question types
  1064. if ($row['type'] != 'comment' && $row['type'] != 'pagebreak') {
  1065. if ($row['number_of_options'] == 0 && $row['type'] == 'open') {
  1066. $return .= str_replace("\r\n",' ', api_html_entity_decode(strip_tags($row['survey_question']), ENT_QUOTES)).';';
  1067. } else {
  1068. for ($ii = 0; $ii < $row['number_of_options']; $ii++) {
  1069. $return .= str_replace("\r\n",' ', api_html_entity_decode(strip_tags($row['survey_question']), ENT_QUOTES)).';';
  1070. }
  1071. }
  1072. }
  1073. }
  1074. }
  1075. $return .= "\n";
  1076. // Getting all the questions and options
  1077. $return .= ';';
  1078. // Show the fields names for user fields
  1079. if (!empty($extra_user_fields)) {
  1080. foreach ($extra_user_fields as & $field) {
  1081. $return .= '"'.str_replace("\r\n",' ',api_html_entity_decode(strip_tags($field[3]), ENT_QUOTES)).'";';
  1082. }
  1083. }
  1084. $sql = "SELECT
  1085. survey_question.question_id,
  1086. survey_question.survey_id,
  1087. survey_question.survey_question,
  1088. survey_question.display,
  1089. survey_question.sort,
  1090. survey_question.type,
  1091. survey_question_option.question_option_id,
  1092. survey_question_option.option_text,
  1093. survey_question_option.sort as option_sort
  1094. FROM $table_survey_question survey_question
  1095. LEFT JOIN $table_survey_question_option survey_question_option
  1096. ON
  1097. survey_question.question_id = survey_question_option.question_id AND
  1098. survey_question_option.c_id = $course_id
  1099. WHERE
  1100. survey_question.survey_id = '".intval($_GET['survey_id'])."' AND
  1101. survey_question.c_id = $course_id
  1102. ORDER BY survey_question.sort ASC, survey_question_option.sort ASC";
  1103. $result = Database::query($sql);
  1104. $possible_answers = array();
  1105. $possible_answers_type = array();
  1106. while ($row = Database::fetch_array($result)) {
  1107. // We show the options if
  1108. // 1. there is no question filter and the export button has not been clicked
  1109. // 2. there is a question filter but the question is selected for display
  1110. if (!(isset($_POST['submit_question_filter'])) || (
  1111. is_array($_POST['questions_filter']) &&
  1112. in_array($row['question_id'], $_POST['questions_filter']))
  1113. ) {
  1114. // We do not show comment and pagebreak question types
  1115. if ($row['type'] != 'comment' && $row['type'] != 'pagebreak') {
  1116. $row['option_text'] = str_replace(array("\r","\n"),array('',''),$row['option_text']);
  1117. $return .= api_html_entity_decode(strip_tags($row['option_text']), ENT_QUOTES).';';
  1118. $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
  1119. $possible_answers_type[$row['question_id']] = $row['type'];
  1120. }
  1121. }
  1122. }
  1123. $return .= "\n";
  1124. // Getting all the answers of the users
  1125. $old_user = '';
  1126. $answers_of_user = array();
  1127. $sql = "SELECT * FROM $table_survey_answer
  1128. WHERE c_id = $course_id AND survey_id='".Database::escape_string($_GET['survey_id'])."'";
  1129. if ($user_id != 0) {
  1130. $sql .= "AND user='".Database::escape_string($user_id)."' ";
  1131. }
  1132. $sql .= "ORDER BY user ASC";
  1133. $open_question_iterator = 1;
  1134. $result = Database::query($sql);
  1135. while ($row = Database::fetch_array($result)) {
  1136. if ($old_user != $row['user'] && $old_user != '') {
  1137. $return .= self::export_complete_report_row(
  1138. $survey_data,
  1139. $possible_answers,
  1140. $answers_of_user,
  1141. $old_user,
  1142. true
  1143. );
  1144. $answers_of_user=array();
  1145. }
  1146. if($possible_answers_type[$row['question_id']] == 'open') {
  1147. $temp_id = 'open'.$open_question_iterator;
  1148. $answers_of_user[$row['question_id']][$temp_id] = $row;
  1149. $open_question_iterator++;
  1150. } else {
  1151. $answers_of_user[$row['question_id']][$row['option_id']] = $row;
  1152. }
  1153. $old_user = $row['user'];
  1154. }
  1155. // This is to display the last user
  1156. $return .= self::export_complete_report_row(
  1157. $survey_data,
  1158. $possible_answers,
  1159. $answers_of_user,
  1160. $old_user,
  1161. true
  1162. );
  1163. return $return;
  1164. }
  1165. /**
  1166. * Add a line to the csv file
  1167. *
  1168. * @param array Possible answers
  1169. * @param array User's answers
  1170. * @param mixed User ID or user details as string - Used as a string in the result string
  1171. * @param boolean Whether to display user fields or not
  1172. * @return string One line of the csv file
  1173. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1174. * @version February 2007
  1175. */
  1176. public static function export_complete_report_row(
  1177. $survey_data,
  1178. $possible_options,
  1179. $answers_of_user,
  1180. $user,
  1181. $display_extra_user_fields = false
  1182. ) {
  1183. $return = '';
  1184. if ($survey_data['anonymous'] == 0) {
  1185. if (intval($user) !== 0) {
  1186. $userInfo = api_get_user_info($user);
  1187. if (!empty($userInfo)) {
  1188. $user_displayed = $userInfo['complete_name_with_username'];
  1189. } else {
  1190. $user_displayed = '-';
  1191. }
  1192. $return .= $user_displayed.';';
  1193. } else {
  1194. $return .= $user.';';
  1195. }
  1196. } else {
  1197. $return .= '-;'; // The user column
  1198. }
  1199. if ($display_extra_user_fields) {
  1200. // Show user fields data, if any, for this user
  1201. $user_fields_values = UserManager::get_extra_user_data(
  1202. $user,
  1203. false,
  1204. false,
  1205. false,
  1206. true
  1207. );
  1208. foreach ($user_fields_values as & $value) {
  1209. $return .= '"'.str_replace('"', '""', api_html_entity_decode(strip_tags($value), ENT_QUOTES)).'";';
  1210. }
  1211. }
  1212. if (is_array($possible_options)) {
  1213. foreach ($possible_options as $question_id => $possible_option) {
  1214. if (is_array($possible_option) && count($possible_option) > 0) {
  1215. foreach ($possible_option as $option_id => & $value) {
  1216. $my_answer_of_user = !isset($answers_of_user[$question_id]) || isset($answers_of_user[$question_id]) && $answers_of_user[$question_id] == null ? array() : $answers_of_user[$question_id];
  1217. $key = array_keys($my_answer_of_user);
  1218. if (isset($key[0]) && substr($key[0], 0, 4) == 'open') {
  1219. $return .= '"'.
  1220. str_replace(
  1221. '"',
  1222. '""',
  1223. api_html_entity_decode(strip_tags($answers_of_user[$question_id][$key[0]]['option_id']), ENT_QUOTES)
  1224. ).
  1225. '"';
  1226. } elseif (!empty($answers_of_user[$question_id][$option_id])) {
  1227. //$return .= 'v';
  1228. if ($answers_of_user[$question_id][$option_id]['value'] != 0) {
  1229. $return .= $answers_of_user[$question_id][$option_id]['value'];
  1230. } else {
  1231. $return .= 'v';
  1232. }
  1233. }
  1234. $return .= ';';
  1235. }
  1236. }
  1237. }
  1238. }
  1239. $return .= "\n";
  1240. return $return;
  1241. }
  1242. /**
  1243. * Quite similar to display_complete_report(), returns an HTML string
  1244. * that can be used in a csv file
  1245. * @todo consider merging this function with display_complete_report
  1246. * @return string The contents of a csv file
  1247. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1248. * @version February 2007
  1249. */
  1250. public static function export_complete_report_xls($survey_data, $filename, $user_id = 0)
  1251. {
  1252. $course_id = api_get_course_int_id();
  1253. $surveyId = isset($_GET['survey_id']) ? (int) $_GET['survey_id'] : 0;
  1254. if (empty($course_id) || empty($surveyId)) {
  1255. return false;
  1256. }
  1257. $spreadsheet = new PHPExcel();
  1258. $spreadsheet->setActiveSheetIndex(0);
  1259. $worksheet = $spreadsheet->getActiveSheet();
  1260. $line = 1;
  1261. $column = 1; // Skip the first column (row titles)
  1262. // Show extra fields blank space (enough for extra fields on next line)
  1263. // Show user fields section with a big th colspan that spans over all fields
  1264. $extra_user_fields = UserManager::get_extra_fields(
  1265. 0,
  1266. 0,
  1267. 5,
  1268. 'ASC',
  1269. false,
  1270. true
  1271. );
  1272. $num = count($extra_user_fields);
  1273. for ($i = 0; $i < $num; $i++) {
  1274. $worksheet->setCellValueByColumnAndRow($column, $line, '');
  1275. $column++;
  1276. }
  1277. $display_extra_user_fields = true;
  1278. // Database table definitions
  1279. $table_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  1280. $table_survey_question_option = Database::get_course_table(TABLE_SURVEY_QUESTION_OPTION);
  1281. $table_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
  1282. // First line (questions)
  1283. $sql = "SELECT
  1284. questions.question_id,
  1285. questions.type,
  1286. questions.survey_question,
  1287. count(options.question_option_id) as number_of_options
  1288. FROM $table_survey_question questions
  1289. LEFT JOIN $table_survey_question_option options
  1290. ON questions.question_id = options.question_id AND options.c_id = $course_id
  1291. WHERE
  1292. questions.survey_id = $surveyId AND
  1293. questions.c_id = $course_id
  1294. GROUP BY questions.question_id
  1295. ORDER BY questions.sort ASC";
  1296. $result = Database::query($sql);
  1297. while ($row = Database::fetch_array($result)) {
  1298. // We show the questions if
  1299. // 1. there is no question filter and the export button has not been clicked
  1300. // 2. there is a quesiton filter but the question is selected for display
  1301. if (!(isset($_POST['submit_question_filter'])) ||
  1302. (isset($_POST['submit_question_filter']) && is_array($_POST['questions_filter']) &&
  1303. in_array($row['question_id'], $_POST['questions_filter']))
  1304. ) {
  1305. // We do not show comment and pagebreak question types
  1306. if ($row['type'] != 'comment' && $row['type'] != 'pagebreak') {
  1307. if ($row['number_of_options'] == 0 && $row['type'] == 'open') {
  1308. $worksheet->setCellValueByColumnAndRow(
  1309. $column,
  1310. $line,
  1311. api_html_entity_decode(
  1312. strip_tags($row['survey_question']),
  1313. ENT_QUOTES
  1314. )
  1315. );
  1316. $column++;
  1317. } else {
  1318. for ($ii = 0; $ii < $row['number_of_options']; $ii ++) {
  1319. $worksheet->setCellValueByColumnAndRow(
  1320. $column,
  1321. $line,
  1322. api_html_entity_decode(
  1323. strip_tags($row['survey_question']),
  1324. ENT_QUOTES
  1325. )
  1326. );
  1327. $column++;
  1328. }
  1329. }
  1330. }
  1331. }
  1332. }
  1333. $line++;
  1334. $column = 1;
  1335. // Show extra field values
  1336. if ($display_extra_user_fields) {
  1337. // Show the fields names for user fields
  1338. foreach ($extra_user_fields as & $field) {
  1339. $worksheet->setCellValueByColumnAndRow(
  1340. $column,
  1341. $line,
  1342. api_html_entity_decode(strip_tags($field[3]), ENT_QUOTES)
  1343. );
  1344. $column++;
  1345. }
  1346. }
  1347. // Getting all the questions and options (second line)
  1348. $sql = "SELECT
  1349. survey_question.question_id,
  1350. survey_question.survey_id,
  1351. survey_question.survey_question,
  1352. survey_question.display,
  1353. survey_question.sort,
  1354. survey_question.type,
  1355. survey_question_option.question_option_id,
  1356. survey_question_option.option_text,
  1357. survey_question_option.sort as option_sort
  1358. FROM $table_survey_question survey_question
  1359. LEFT JOIN $table_survey_question_option survey_question_option
  1360. ON
  1361. survey_question.question_id = survey_question_option.question_id AND
  1362. survey_question_option.c_id = $course_id
  1363. WHERE
  1364. survey_question.survey_id = $surveyId AND
  1365. survey_question.c_id = $course_id
  1366. ORDER BY survey_question.sort ASC, survey_question_option.sort ASC";
  1367. $result = Database::query($sql);
  1368. $possible_answers = array();
  1369. $possible_answers_type = array();
  1370. while ($row = Database::fetch_array($result)) {
  1371. // We show the options if
  1372. // 1. there is no question filter and the export button has not been clicked
  1373. // 2. there is a quesiton filter but the question is selected for display
  1374. if (!isset($_POST['submit_question_filter']) ||
  1375. (isset($_POST['questions_filter']) && is_array($_POST['questions_filter']) &&
  1376. in_array($row['question_id'], $_POST['questions_filter']))
  1377. ) {
  1378. // We do not show comment and pagebreak question types
  1379. if ($row['type'] != 'comment' && $row['type'] != 'pagebreak') {
  1380. $worksheet->setCellValueByColumnAndRow(
  1381. $column,
  1382. $line,
  1383. api_html_entity_decode(
  1384. strip_tags($row['option_text']),
  1385. ENT_QUOTES
  1386. )
  1387. );
  1388. $possible_answers[$row['question_id']][$row['question_option_id']] = $row['question_option_id'];
  1389. $possible_answers_type[$row['question_id']] = $row['type'];
  1390. $column++;
  1391. }
  1392. }
  1393. }
  1394. // Getting all the answers of the users
  1395. $line ++;
  1396. $column = 0;
  1397. $old_user = '';
  1398. $answers_of_user = array();
  1399. $sql = "SELECT * FROM $table_survey_answer
  1400. WHERE c_id = $course_id AND survey_id = $surveyId";
  1401. if ($user_id != 0) {
  1402. $sql .= " AND user='".intval($user_id)."' ";
  1403. }
  1404. $sql .= " ORDER BY user ASC";
  1405. $open_question_iterator = 1;
  1406. $result = Database::query($sql);
  1407. while ($row = Database::fetch_array($result)) {
  1408. if ($old_user != $row['user'] && $old_user != '') {
  1409. $return = self::export_complete_report_row_xls(
  1410. $survey_data,
  1411. $possible_answers,
  1412. $answers_of_user,
  1413. $old_user,
  1414. true
  1415. );
  1416. foreach ($return as $elem) {
  1417. $worksheet->setCellValueByColumnAndRow($column, $line, $elem);
  1418. $column++;
  1419. }
  1420. $answers_of_user = array();
  1421. $line++;
  1422. $column = 0;
  1423. }
  1424. if ($possible_answers_type[$row['question_id']] == 'open') {
  1425. $temp_id = 'open'.$open_question_iterator;
  1426. $answers_of_user[$row['question_id']][$temp_id] = $row;
  1427. $open_question_iterator++;
  1428. } else {
  1429. $answers_of_user[$row['question_id']][$row['option_id']] = $row;
  1430. }
  1431. $old_user = $row['user'];
  1432. }
  1433. $return = self::export_complete_report_row_xls(
  1434. $survey_data,
  1435. $possible_answers,
  1436. $answers_of_user,
  1437. $old_user,
  1438. true
  1439. );
  1440. // this is to display the last user
  1441. foreach ($return as $elem) {
  1442. $worksheet->setCellValueByColumnAndRow($column, $line, $elem);
  1443. $column++;
  1444. }
  1445. $file = api_get_path(SYS_ARCHIVE_PATH).api_replace_dangerous_char($filename);
  1446. $writer = new PHPExcel_Writer_Excel2007($spreadsheet);
  1447. $writer->save($file);
  1448. DocumentManager::file_send_for_download($file, true, $filename);
  1449. return null;
  1450. }
  1451. /**
  1452. * Add a line to the csv file
  1453. *
  1454. * @param array Possible answers
  1455. * @param array User's answers
  1456. * @param mixed User ID or user details as string - Used as a string in the result string
  1457. * @param boolean Whether to display user fields or not
  1458. * @return string One line of the csv file
  1459. */
  1460. public static function export_complete_report_row_xls(
  1461. $survey_data,
  1462. $possible_options,
  1463. $answers_of_user,
  1464. $user,
  1465. $display_extra_user_fields = false
  1466. ) {
  1467. $return = array();
  1468. if ($survey_data['anonymous'] == 0) {
  1469. if (intval($user) !== 0) {
  1470. $userInfo = api_get_user_info($user);
  1471. if ($userInfo) {
  1472. $user_displayed = $userInfo['complete_name_with_username'];
  1473. } else {
  1474. $user_displayed = '-';
  1475. }
  1476. $return[] = $user_displayed;
  1477. } else {
  1478. $return[] = $user;
  1479. }
  1480. } else {
  1481. $return[] = '-'; // The user column
  1482. }
  1483. if ($display_extra_user_fields) {
  1484. //show user fields data, if any, for this user
  1485. $user_fields_values = UserManager::get_extra_user_data(
  1486. intval($user),
  1487. false,
  1488. false,
  1489. false,
  1490. true
  1491. );
  1492. foreach ($user_fields_values as $value) {
  1493. $return[] = api_html_entity_decode(strip_tags($value), ENT_QUOTES);
  1494. }
  1495. }
  1496. if (is_array($possible_options)) {
  1497. foreach ($possible_options as $question_id => & $possible_option) {
  1498. if (is_array($possible_option) && count($possible_option) > 0) {
  1499. foreach ($possible_option as $option_id => & $value) {
  1500. $my_answers_of_user = isset($answers_of_user[$question_id]) ? $answers_of_user[$question_id] : [];
  1501. $key = array_keys($my_answers_of_user);
  1502. if (isset($key[0]) && substr($key[0], 0, 4) == 'open') {
  1503. $return[] = api_html_entity_decode(strip_tags($answers_of_user[$question_id][$key[0]]['option_id']), ENT_QUOTES);
  1504. } elseif (!empty($answers_of_user[$question_id][$option_id])) {
  1505. if ($answers_of_user[$question_id][$option_id]['value'] != 0) {
  1506. $return[] = $answers_of_user[$question_id][$option_id]['value'];
  1507. } else {
  1508. $return[] = 'v';
  1509. }
  1510. } else {
  1511. $return[] = '';
  1512. }
  1513. }
  1514. }
  1515. }
  1516. }
  1517. return $return;
  1518. }
  1519. /**
  1520. * This function displays the comparative report which allows you to compare two questions
  1521. * A comparative report creates a table where one question is on the x axis and a second question is on the y axis.
  1522. * In the intersection is the number of people who have answerd positive on both options.
  1523. *
  1524. * @return string HTML code
  1525. *
  1526. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1527. * @version February 2007
  1528. */
  1529. public static function display_comparative_report()
  1530. {
  1531. // Allowed question types for comparative report
  1532. $allowed_question_types = array(
  1533. 'yesno',
  1534. 'multiplechoice',
  1535. 'multipleresponse',
  1536. 'dropdown',
  1537. 'percentage',
  1538. 'score'
  1539. );
  1540. $surveyId = isset($_GET['survey_id']) ? (int) $_GET['survey_id'] : 0;
  1541. // Getting all the questions
  1542. $questions = SurveyManager::get_questions($surveyId);
  1543. // Actions bar
  1544. echo '<div class="actions">';
  1545. echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?survey_id='.$surveyId.'&'.api_get_cidreq().'">'.
  1546. Display::return_icon('back.png', get_lang('BackTo').' '.get_lang('ReportingOverview'),'',ICON_SIZE_MEDIUM).'</a>';
  1547. echo '</div>';
  1548. // Displaying an information message that only the questions with predefined answers can be used in a comparative report
  1549. Display::display_normal_message(get_lang('OnlyQuestionsWithPredefinedAnswers'), false);
  1550. $xAxis = isset($_GET['xaxis']) ? Security::remove_XSS($_GET['xaxis']) : '';
  1551. $yAxis = isset($_GET['yaxis']) ? Security::remove_XSS($_GET['yaxis']) : '';
  1552. $url = api_get_self().'?'.api_get_cidreq().'&action='.Security::remove_XSS($_GET['action']).'&survey_id='.$surveyId.'&xaxis='.$xAxis.'&y='.$yAxis;
  1553. $form = new FormValidator('compare', 'get', $url);
  1554. $form->addHidden('action', Security::remove_XSS($_GET['action']));
  1555. $form->addHidden('survey_id', $surveyId);
  1556. $optionsX = ['----'];
  1557. $optionsY = ['----'];
  1558. $defaults = [];
  1559. foreach ($questions as $key => & $question) {
  1560. if (is_array($allowed_question_types)) {
  1561. if (in_array($question['type'], $allowed_question_types)) {
  1562. //echo '<option value="'.$question['question_id'].'"';
  1563. if (isset($_GET['xaxis']) && $_GET['xaxis'] == $question['question_id']) {
  1564. $defaults['xaxis'] = $question['question_id'];
  1565. }
  1566. if (isset($_GET['yaxis']) && $_GET['yaxis'] == $question['question_id']) {
  1567. $defaults['yaxis'] = $question['question_id'];
  1568. }
  1569. $optionsX[$question['question_id']] = api_substr(strip_tags($question['question']), 0, 50);
  1570. $optionsY[$question['question_id']] = api_substr(strip_tags($question['question']), 0, 50);
  1571. }
  1572. }
  1573. }
  1574. $form->addSelect('xaxis', get_lang('SelectXAxis'), $optionsX);
  1575. $form->addSelect('yaxis', get_lang('SelectYAxis'), $optionsY);
  1576. $form->addButtonSearch(get_lang('CompareQuestions'));
  1577. $form->setDefaults($defaults);
  1578. $form->display();
  1579. // Getting all the information of the x axis
  1580. if (is_numeric($xAxis)) {
  1581. $question_x = SurveyManager::get_question($xAxis);
  1582. }
  1583. // Getting all the information of the y axis
  1584. if (is_numeric($yAxis)) {
  1585. $question_y = SurveyManager::get_question($yAxis);
  1586. }
  1587. if (is_numeric($xAxis) && is_numeric($yAxis)) {
  1588. // Getting the answers of the two questions
  1589. $answers_x = self::get_answers_of_question_by_user($surveyId, $xAxis);
  1590. $answers_y = self::get_answers_of_question_by_user($surveyId, $yAxis);
  1591. // Displaying the table
  1592. $tableHtml = '<table border="1" class="data_table">';
  1593. $xOptions = array();
  1594. // The header
  1595. $tableHtml .= '<tr>';
  1596. for ($ii = 0; $ii <= count($question_x['answers']); $ii++) {
  1597. if ($ii == 0) {
  1598. $tableHtml .= '<th>&nbsp;</th>';
  1599. } else {
  1600. if ($question_x['type'] == 'score') {
  1601. for ($x = 1; $x <= $question_x['maximum_score']; $x++) {
  1602. $tableHtml .= '<th>'.$question_x['answers'][($ii-1)].'<br />'.$x.'</th>';
  1603. }
  1604. $x = '';
  1605. } else {
  1606. $tableHtml .= '<th>'.$question_x['answers'][($ii-1)].'</th>';
  1607. }
  1608. $optionText = strip_tags($question_x['answers'][$ii-1]);
  1609. $optionText = html_entity_decode($optionText);
  1610. array_push($xOptions, trim($optionText));
  1611. }
  1612. }
  1613. $tableHtml .= '</tr>';
  1614. $chartData = array();
  1615. // The main part
  1616. for ($ij = 0; $ij < count($question_y['answers']); $ij++) {
  1617. $currentYQuestion = strip_tags($question_y['answers'][$ij]);
  1618. $currentYQuestion = html_entity_decode($currentYQuestion);
  1619. // The Y axis is a scoring question type so we have more rows than the options (actually options * maximum score)
  1620. if ($question_y['type'] == 'score') {
  1621. for ($y = 1; $y <= $question_y['maximum_score']; $y++) {
  1622. $tableHtml .= '<tr>';
  1623. for ($ii = 0; $ii <= count($question_x['answers']); $ii++) {
  1624. if ($question_x['type'] == 'score') {
  1625. for ($x = 1; $x <= $question_x['maximum_score']; $x++) {
  1626. if ($ii == 0) {
  1627. $tableHtml .= '<th>'.$question_y['answers'][($ij)].' '.$y.'</th>';
  1628. break;
  1629. } else {
  1630. $tableHtml .= '<td align="center">';
  1631. $votes = self::comparative_check(
  1632. $answers_x,
  1633. $answers_y,
  1634. $question_x['answersid'][($ii - 1)],
  1635. $question_y['answersid'][($ij)],
  1636. $x,
  1637. $y
  1638. );
  1639. $tableHtml .= $votes;
  1640. array_push(
  1641. $chartData,
  1642. array(
  1643. 'serie' => array($currentYQuestion, $xOptions[$ii-1]),
  1644. 'option' => $x,
  1645. 'votes' => $votes
  1646. )
  1647. );
  1648. $tableHtml .= '</td>';
  1649. }
  1650. }
  1651. } else {
  1652. if ($ii == 0) {
  1653. $tableHtml .= '<th>'.$question_y['answers'][$ij].' '.$y.'</th>';
  1654. } else {
  1655. $tableHtml .= '<td align="center">';
  1656. $votes = self::comparative_check(
  1657. $answers_x,
  1658. $answers_y,
  1659. $question_x['answersid'][($ii - 1)],
  1660. $question_y['answersid'][($ij)],
  1661. 0,
  1662. $y
  1663. );
  1664. $tableHtml .= $votes;
  1665. array_push(
  1666. $chartData,
  1667. array(
  1668. 'serie' => array($currentYQuestion, $xOptions[$ii-1]),
  1669. 'option' => $y,
  1670. 'votes' => $votes
  1671. )
  1672. );
  1673. $tableHtml .= '</td>';
  1674. }
  1675. }
  1676. }
  1677. $tableHtml .= '</tr>';
  1678. }
  1679. }
  1680. // The Y axis is NOT a score question type so the number of rows = the number of options
  1681. else {
  1682. $tableHtml .= '<tr>';
  1683. for ($ii = 0; $ii <= count($question_x['answers']); $ii++) {
  1684. if ($question_x['type'] == 'score') {
  1685. for ($x = 1; $x <= $question_x['maximum_score']; $x++) {
  1686. if ($ii == 0) {
  1687. $tableHtml .= '<th>'.$question_y['answers'][$ij].'</th>';
  1688. break;
  1689. } else {
  1690. $tableHtml .= '<td align="center">';
  1691. $votes = self::comparative_check(
  1692. $answers_x,
  1693. $answers_y,
  1694. $question_x['answersid'][($ii-1)],
  1695. $question_y['answersid'][($ij)],
  1696. $x,
  1697. 0
  1698. );
  1699. $tableHtml .= $votes;
  1700. array_push(
  1701. $chartData,
  1702. array(
  1703. 'serie' => array($currentYQuestion, $xOptions[$ii-1]),
  1704. 'option' => $x,
  1705. 'votes' => $votes
  1706. )
  1707. );
  1708. $tableHtml .= '</td>';
  1709. }
  1710. }
  1711. } else {
  1712. if ($ii == 0) {
  1713. $tableHtml .= '<th>'.$question_y['answers'][($ij)].'</th>';
  1714. } else {
  1715. $tableHtml .= '<td align="center">';
  1716. $votes = self::comparative_check($answers_x, $answers_y, $question_x['answersid'][($ii-1)], $question_y['answersid'][($ij)]);
  1717. $tableHtml .= $votes;
  1718. array_push(
  1719. $chartData,
  1720. array(
  1721. 'serie' => $xOptions[$ii-1],
  1722. 'option' => $currentYQuestion,
  1723. 'votes' => $votes
  1724. )
  1725. );
  1726. $tableHtml .= '</td>';
  1727. }
  1728. }
  1729. }
  1730. $tableHtml .= '</tr>';
  1731. }
  1732. }
  1733. $tableHtml .= '</table>';
  1734. echo '<div id="chartContainer" class="col-md-12">';
  1735. echo self::drawChart($chartData, true);
  1736. echo '</div>';
  1737. echo $tableHtml;
  1738. }
  1739. }
  1740. /**
  1741. * Get all the answers of a question grouped by user
  1742. *
  1743. * @param integer $survey_id Survey ID
  1744. * @param integer $question_id Question ID
  1745. * @return array Array containing all answers of all users, grouped by user
  1746. *
  1747. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1748. * @version February 2007 - Updated March 2008
  1749. */
  1750. public static function get_answers_of_question_by_user($survey_id, $question_id)
  1751. {
  1752. $course_id = api_get_course_int_id();
  1753. $table_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
  1754. $sql = "SELECT * FROM $table_survey_answer
  1755. WHERE c_id = $course_id AND survey_id='".intval($survey_id)."'
  1756. AND question_id='".intval($question_id)."'
  1757. ORDER BY USER ASC";
  1758. $result = Database::query($sql);
  1759. $return = [];
  1760. while ($row = Database::fetch_array($result)) {
  1761. if ($row['value'] == 0) {
  1762. $return[$row['user']][] = $row['option_id'];
  1763. } else {
  1764. $return[$row['user']][] = $row['option_id'].'*'.$row['value'];
  1765. }
  1766. }
  1767. return $return;
  1768. }
  1769. /**
  1770. * Count the number of users who answer positively on both options
  1771. *
  1772. * @param array All answers of the x axis
  1773. * @param array All answers of the y axis
  1774. * @param integer x axis value (= the option_id of the first question)
  1775. * @param integer y axis value (= the option_id of the second question)
  1776. * @return integer Number of users who have answered positively to both options
  1777. *
  1778. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1779. * @version February 2007
  1780. */
  1781. public static function comparative_check(
  1782. $answers_x,
  1783. $answers_y,
  1784. $option_x,
  1785. $option_y,
  1786. $value_x = 0,
  1787. $value_y = 0
  1788. ) {
  1789. if ($value_x == 0) {
  1790. $check_x = $option_x;
  1791. } else {
  1792. $check_x = $option_x.'*'.$value_x;
  1793. }
  1794. if ($value_y == 0) {
  1795. $check_y = $option_y;
  1796. } else {
  1797. $check_y = $option_y.'*'.$value_y;
  1798. }
  1799. $counter = 0;
  1800. if (is_array($answers_x)) {
  1801. foreach ($answers_x as $user => & $answers) {
  1802. // Check if the user has given $option_x as answer
  1803. if (in_array($check_x, $answers)) {
  1804. // Check if the user has given $option_y as an answer
  1805. if (!is_null($answers_y[$user]) && in_array($check_y, $answers_y[$user])) {
  1806. $counter++;
  1807. }
  1808. }
  1809. }
  1810. }
  1811. return $counter;
  1812. }
  1813. /**
  1814. * Get all the information about the invitations of a certain survey
  1815. *
  1816. * @return array Lines of invitation [user, code, date, empty element]
  1817. *
  1818. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1819. * @version January 2007
  1820. *
  1821. * @todo use survey_id parameter instead of $_GET
  1822. */
  1823. public static function get_survey_invitations_data()
  1824. {
  1825. $course_id = api_get_course_int_id();
  1826. // Database table definition
  1827. $table_survey_invitation = Database::get_course_table(TABLE_SURVEY_INVITATION);
  1828. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  1829. $sql = "SELECT
  1830. survey_invitation.user as col1,
  1831. survey_invitation.invitation_code as col2,
  1832. survey_invitation.invitation_date as col3,
  1833. '' as col4
  1834. FROM $table_survey_invitation survey_invitation
  1835. LEFT JOIN $table_user user
  1836. ON survey_invitation.user = user.user_id
  1837. WHERE
  1838. survey_invitation.c_id = $course_id AND
  1839. survey_invitation.survey_id = '".intval($_GET['survey_id'])."' AND
  1840. session_id='".api_get_session_id()."' ";
  1841. $res = Database::query($sql);
  1842. $data = [];
  1843. while ($row = Database::fetch_array($res)) {
  1844. $data[] = $row;
  1845. }
  1846. return $data;
  1847. }
  1848. /**
  1849. * Get the total number of survey invitations for a given survey (through $_GET['survey_id'])
  1850. *
  1851. * @return integer Total number of survey invitations
  1852. *
  1853. * @todo use survey_id parameter instead of $_GET
  1854. *
  1855. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1856. * @version January 2007
  1857. */
  1858. public static function get_number_of_survey_invitations()
  1859. {
  1860. $course_id = api_get_course_int_id();
  1861. // Database table definition
  1862. $table_survey_invitation = Database::get_course_table(TABLE_SURVEY_INVITATION);
  1863. $sql = "SELECT count(user) AS total
  1864. FROM $table_survey_invitation
  1865. WHERE
  1866. c_id = $course_id AND
  1867. survey_id='".intval($_GET['survey_id'])."' AND
  1868. session_id='".api_get_session_id()."' ";
  1869. $res = Database::query($sql);
  1870. $row = Database::fetch_array($res,'ASSOC');
  1871. return $row['total'];
  1872. }
  1873. /**
  1874. * Save the invitation mail
  1875. *
  1876. * @param string Text of the e-mail
  1877. * @param integer Whether the mail contents are for invite mail (0, default) or reminder mail (1)
  1878. *
  1879. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1880. * @version January 2007
  1881. */
  1882. public static function save_invite_mail($mailtext, $mail_subject, $reminder = 0)
  1883. {
  1884. $course_id = api_get_course_int_id();
  1885. // Database table definition
  1886. $table_survey = Database::get_course_table(TABLE_SURVEY);
  1887. // Reminder or not
  1888. if ($reminder == 0) {
  1889. $mail_field = 'invite_mail';
  1890. } else {
  1891. $mail_field = 'reminder_mail';
  1892. }
  1893. $sql = "UPDATE $table_survey SET
  1894. mail_subject='".Database::escape_string($mail_subject)."',
  1895. $mail_field = '".Database::escape_string($mailtext)."'
  1896. WHERE c_id = $course_id AND survey_id = '".intval($_GET['survey_id'])."'";
  1897. Database::query($sql);
  1898. }
  1899. /**
  1900. * This function saves all the invitations of course users and additional users in the database
  1901. * and sends the invitations by email
  1902. *
  1903. * @param array Users array can be both a list of course uids AND a list of additional emailaddresses
  1904. * @param string Title of the invitation, used as the title of the mail
  1905. * @param string Text of the invitation, used as the text of the mail.
  1906. * The text has to contain a **link** string or this will automatically be added to the end
  1907. * @return int
  1908. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  1909. * @author Julio Montoya - Adding auto-generated link support
  1910. * @version January 2007
  1911. *
  1912. */
  1913. public static function saveInvitations(
  1914. $users_array,
  1915. $invitation_title,
  1916. $invitation_text,
  1917. $reminder = 0,
  1918. $sendmail = 0,
  1919. $remindUnAnswered = 0
  1920. ) {
  1921. if (!is_array($users_array)) {
  1922. // Should not happen
  1923. return 0;
  1924. }
  1925. // Getting the survey information
  1926. $survey_data = SurveyManager::get_survey($_GET['survey_id']);
  1927. $survey_invitations = self::get_invitations($survey_data['survey_code']);
  1928. $already_invited = self::get_invited_users($survey_data['code']);
  1929. // Remind unanswered is a special version of remind all reminder
  1930. $exclude_users = array();
  1931. if ($remindUnAnswered == 1) { // Remind only unanswered users
  1932. $reminder = 1;
  1933. $exclude_users = SurveyManager::get_people_who_filled_survey($_GET['survey_id']);
  1934. }
  1935. $counter = 0; // Nr of invitations "sent" (if sendmail option)
  1936. $course_id = api_get_course_int_id();
  1937. $session_id = api_get_session_id();
  1938. $result = CourseManager::separateUsersGroups($users_array);
  1939. $groupList = $result['groups'];
  1940. $users_array = $result['users'];
  1941. foreach ($groupList as $groupId) {
  1942. $userGroupList = GroupManager::getStudents($groupId);
  1943. $userGroupIdList = array_column($userGroupList, 'user_id');
  1944. $users_array = array_merge($users_array, $userGroupIdList);
  1945. $params = array(
  1946. 'c_id' => $course_id,
  1947. 'session_id' => $session_id,
  1948. 'group_id' => $groupId,
  1949. 'survey_code' => $survey_data['code']
  1950. );
  1951. $invitationExists = self::invitationExists(
  1952. $course_id,
  1953. $session_id,
  1954. $groupId,
  1955. $survey_data['code']
  1956. );
  1957. if (empty($invitationExists)) {
  1958. self::save_invitation($params);
  1959. }
  1960. }
  1961. $users_array = array_unique($users_array);
  1962. foreach ($users_array as $key => $value) {
  1963. if (!isset($value) || $value == '') {
  1964. continue;
  1965. }
  1966. // Skip user if reminding only unanswered people
  1967. if (in_array($value, $exclude_users)) {
  1968. continue;
  1969. }
  1970. // Get the unique invitation code if we already have it
  1971. if ($reminder == 1 && array_key_exists($value, $survey_invitations)) {
  1972. $invitation_code = $survey_invitations[$value]['invitation_code'];
  1973. } else {
  1974. $invitation_code = md5($value.microtime());
  1975. }
  1976. $new_user = false; // User not already invited
  1977. // Store the invitation if user_id not in $already_invited['course_users'] OR email is not in $already_invited['additional_users']
  1978. $addit_users_array = isset($already_invited['additional_users']) && !empty($already_invited['additional_users']) ? explode(';', $already_invited['additional_users']) : array();
  1979. $my_alredy_invited = $already_invited['course_users'] == null ? array() : $already_invited['course_users'];
  1980. if ((is_numeric($value) && !in_array($value, $my_alredy_invited)) ||
  1981. (!is_numeric($value) && !in_array($value, $addit_users_array))
  1982. ) {
  1983. $new_user = true;
  1984. if (!array_key_exists($value, $survey_invitations)) {
  1985. $params = array(
  1986. 'c_id' => $course_id,
  1987. 'session_id' => $session_id,
  1988. 'user' => $value,
  1989. 'survey_code' => $survey_data['code'],
  1990. 'invitation_code' => $invitation_code,
  1991. 'invitation_date' => api_get_utc_datetime()
  1992. );
  1993. self::save_invitation($params);
  1994. }
  1995. }
  1996. // Send the email if checkboxed
  1997. if (($new_user || $reminder == 1) && $sendmail != 0) {
  1998. // Make a change for absolute url
  1999. if (isset($invitation_text)) {
  2000. $invitation_text = api_html_entity_decode($invitation_text, ENT_QUOTES);
  2001. $invitation_text = str_replace('src="../../', 'src="'.api_get_path(WEB_PATH), $invitation_text);
  2002. $invitation_text = trim(stripslashes($invitation_text));
  2003. }
  2004. self::send_invitation_mail($value, $invitation_code, $invitation_title, $invitation_text);
  2005. $counter++;
  2006. }
  2007. }
  2008. return $counter; // Number of invitations sent
  2009. }
  2010. /**
  2011. * @param $params
  2012. * @return bool|int
  2013. */
  2014. public static function save_invitation($params)
  2015. {
  2016. // Database table to store the invitations data
  2017. $table = Database::get_course_table(TABLE_SURVEY_INVITATION);
  2018. if (!empty($params['c_id']) &&
  2019. (!empty($params['user']) || !empty($params['group_id'])) &&
  2020. !empty($params['survey_code'])
  2021. ) {
  2022. $insertId = Database::insert($table, $params);
  2023. if ($insertId) {
  2024. $sql = "UPDATE $table SET survey_invitation_id = $insertId
  2025. WHERE iid = $insertId";
  2026. Database::query($sql);
  2027. }
  2028. return $insertId;
  2029. }
  2030. return false;
  2031. }
  2032. /**
  2033. * @param int $courseId
  2034. * @param int $sessionId
  2035. * @param int $groupId
  2036. * @param string $surveyCode
  2037. * @return int
  2038. */
  2039. public static function invitationExists($courseId, $sessionId, $groupId, $surveyCode)
  2040. {
  2041. $table = Database::get_course_table(TABLE_SURVEY_INVITATION);
  2042. $courseId = intval($courseId);
  2043. $sessionId = intval($sessionId);
  2044. $groupId = intval($groupId);
  2045. $surveyCode = Database::escape_string($surveyCode);
  2046. $sql = "SELECT survey_invitation_id FROM $table
  2047. WHERE
  2048. c_id = $courseId AND
  2049. session_id = $sessionId AND
  2050. group_id = $groupId AND
  2051. survey_code = '$surveyCode'
  2052. ";
  2053. $result = Database::query($sql);
  2054. return Database::num_rows($result);
  2055. }
  2056. /**
  2057. * Send the invitation by mail.
  2058. *
  2059. * @param int invitedUser - the userId (course user) or emailaddress of additional user
  2060. * $param string $invitation_code - the unique invitation code for the URL
  2061. * @return void
  2062. */
  2063. public static function send_invitation_mail(
  2064. $invitedUser,
  2065. $invitation_code,
  2066. $invitation_title,
  2067. $invitation_text
  2068. ) {
  2069. $_user = api_get_user_info();
  2070. $_course = api_get_course_info();
  2071. // Replacing the **link** part with a valid link for the user
  2072. $survey_link = api_get_path(WEB_CODE_PATH).'survey/fillsurvey.php?course='.$_course['code'].'&invitationcode='.$invitation_code;
  2073. $text_link = '<a href="'.$survey_link.'">'.get_lang('ClickHereToAnswerTheSurvey')."</a><br />\r\n<br />\r\n".get_lang('OrCopyPasteTheFollowingUrl')." <br />\r\n ".$survey_link;
  2074. $replace_count = 0;
  2075. $full_invitation_text = api_str_ireplace('**link**', $text_link ,$invitation_text, $replace_count);
  2076. if ($replace_count < 1) {
  2077. $full_invitation_text = $full_invitation_text."<br />\r\n<br />\r\n".$text_link;
  2078. }
  2079. // Sending the mail
  2080. $sender_name = api_get_person_name($_user['firstName'], $_user['lastName'], null, PERSON_NAME_EMAIL_ADDRESS);
  2081. $sender_email = $_user['mail'];
  2082. $sender_user_id = api_get_user_id();
  2083. $replyto = array();
  2084. if (api_get_setting('survey_email_sender_noreply') == 'noreply') {
  2085. $noreply = api_get_setting('noreply_email_address');
  2086. if (!empty($noreply)) {
  2087. $replyto['Reply-to'] = $noreply;
  2088. $sender_name = $noreply;
  2089. $sender_email = $noreply;
  2090. $sender_user_id = null;
  2091. }
  2092. }
  2093. // Optionally: finding the e-mail of the course user
  2094. if (is_numeric($invitedUser)) {
  2095. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  2096. $sql = "SELECT firstname, lastname, email FROM $table_user
  2097. WHERE user_id='".Database::escape_string($invitedUser)."'";
  2098. $result = Database::query($sql);
  2099. $row = Database::fetch_array($result);
  2100. $recipient_email = $row['email'];
  2101. $recipient_name = api_get_person_name($row['firstname'], $row['lastname'], null, PERSON_NAME_EMAIL_ADDRESS);
  2102. MessageManager::send_message(
  2103. $invitedUser,
  2104. $invitation_title,
  2105. $full_invitation_text,
  2106. [],
  2107. [],
  2108. null,
  2109. null,
  2110. null,
  2111. null,
  2112. $sender_user_id
  2113. );
  2114. } else {
  2115. /** @todo check if the address is a valid email */
  2116. $recipient_email = $invitedUser;
  2117. @api_mail_html(
  2118. $recipient_name,
  2119. $recipient_email,
  2120. $invitation_title,
  2121. $full_invitation_text,
  2122. $sender_name,
  2123. $sender_email,
  2124. $replyto
  2125. );
  2126. }
  2127. }
  2128. /**
  2129. * This function recalculates the number of users who have been invited and updates the survey table with this value.
  2130. *
  2131. * @param string Survey code
  2132. * @return void
  2133. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2134. * @version January 2007
  2135. */
  2136. public static function update_count_invited($survey_code)
  2137. {
  2138. $course_id = api_get_course_int_id();
  2139. // Database table definition
  2140. $table_survey_invitation = Database::get_course_table(TABLE_SURVEY_INVITATION);
  2141. $table_survey = Database::get_course_table(TABLE_SURVEY);
  2142. // Counting the number of people that are invited
  2143. $sql = "SELECT count(user) as total
  2144. FROM $table_survey_invitation
  2145. WHERE
  2146. c_id = $course_id AND
  2147. survey_code = '".Database::escape_string($survey_code)."' AND
  2148. user <> ''
  2149. ";
  2150. $result = Database::query($sql);
  2151. $row = Database::fetch_array($result);
  2152. $total_invited = $row['total'];
  2153. // Updating the field in the survey table
  2154. $sql = "UPDATE $table_survey
  2155. SET invited = '".Database::escape_string($total_invited)."'
  2156. WHERE
  2157. c_id = $course_id AND
  2158. code = '".Database::escape_string($survey_code)."'
  2159. ";
  2160. Database::query($sql);
  2161. }
  2162. /**
  2163. * This function gets all the invited users for a given survey code.
  2164. *
  2165. * @param string Survey code
  2166. * @param string optional - course database
  2167. * @return array Array containing the course users and additional users (non course users)
  2168. *
  2169. * @todo consider making $defaults['additional_users'] also an array
  2170. *
  2171. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2172. * @author Julio Montoya, adding c_id fixes - Dec 2012
  2173. * @version January 2007
  2174. */
  2175. public static function get_invited_users($survey_code, $course_code = '', $session_id = 0)
  2176. {
  2177. if (!empty($course_code)) {
  2178. $course_info = api_get_course_info($course_code);
  2179. $course_id = $course_info['real_id'];
  2180. } else {
  2181. $course_id = api_get_course_int_id();
  2182. }
  2183. if (empty($session_id)) {
  2184. $session_id = api_get_session_id();
  2185. }
  2186. $table_survey_invitation = Database::get_course_table(TABLE_SURVEY_INVITATION);
  2187. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  2188. // Selecting all the invitations of this survey AND the additional emailaddresses (the left join)
  2189. $order_clause = api_sort_by_first_name() ? ' ORDER BY firstname, lastname' : ' ORDER BY lastname, firstname';
  2190. $sql = "SELECT user, group_id
  2191. FROM $table_survey_invitation as table_invitation
  2192. WHERE
  2193. table_invitation.c_id = $course_id AND
  2194. survey_code='".Database::escape_string($survey_code)."' AND
  2195. session_id = $session_id
  2196. ";
  2197. $defaults = array();
  2198. $defaults['course_users'] = array();
  2199. $defaults['additional_users'] = array(); // Textarea
  2200. $defaults['users'] = array(); // user and groups
  2201. $result = Database::query($sql);
  2202. while ($row = Database::fetch_array($result)) {
  2203. if (is_numeric($row['user'])) {
  2204. $defaults['course_users'][] = $row['user'];
  2205. $defaults['users'][] = 'USER:'.$row['user'];
  2206. } else {
  2207. if (!empty($row['user'])) {
  2208. $defaults['additional_users'][] = $row['user'];
  2209. }
  2210. }
  2211. if (isset($row['group_id']) && !empty($row['group_id'])) {
  2212. $defaults['users'][] = 'GROUP:'.$row['group_id'];
  2213. }
  2214. }
  2215. if (!empty($defaults['course_users'])) {
  2216. $user_ids = implode("','", $defaults['course_users']);
  2217. $sql = "SELECT user_id FROM $table_user WHERE user_id IN ('$user_ids') $order_clause";
  2218. $result = Database::query($sql);
  2219. $fixed_users = array();
  2220. while ($row = Database::fetch_array($result)) {
  2221. $fixed_users[] = $row['user_id'];
  2222. }
  2223. $defaults['course_users'] = $fixed_users;
  2224. }
  2225. if (!empty($defaults['additional_users'])) {
  2226. $defaults['additional_users'] = implode(';', $defaults['additional_users']);
  2227. }
  2228. return $defaults;
  2229. }
  2230. /**
  2231. * Get all the invitations
  2232. *
  2233. * @param string Survey code
  2234. * @return array Database rows matching the survey code
  2235. *
  2236. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2237. * @version September 2007
  2238. */
  2239. public static function get_invitations($survey_code)
  2240. {
  2241. $course_id = api_get_course_int_id();
  2242. // Database table definition
  2243. $table_survey_invitation = Database::get_course_table(TABLE_SURVEY_INVITATION);
  2244. $sql = "SELECT * FROM $table_survey_invitation
  2245. WHERE
  2246. c_id = $course_id AND
  2247. survey_code = '".Database::escape_string($survey_code)."'";
  2248. $result = Database::query($sql);
  2249. $return = array();
  2250. while ($row = Database::fetch_array($result)) {
  2251. $return[$row['user']] = $row;
  2252. }
  2253. return $return;
  2254. }
  2255. /**
  2256. * This function displays the form for searching a survey
  2257. *
  2258. * @return void (direct output)
  2259. *
  2260. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2261. * @version January 2007
  2262. *
  2263. * @todo use quickforms
  2264. * @todo consider moving this to surveymanager.inc.lib.php
  2265. */
  2266. public static function display_survey_search_form()
  2267. {
  2268. $url = api_get_path(WEB_CODE_PATH).'survey/survey_list.php?search=advanced&'.api_get_cidreq();
  2269. $form = new FormValidator('search', 'get', $url);
  2270. $form->addHeader(get_lang('SearchASurvey'));
  2271. $form->addText('keyword_title', get_lang('Title'));
  2272. $form->addText('keyword_code', get_lang('Code'));
  2273. $form->addSelectLanguage('keyword_language', get_lang('Language'));
  2274. $form->addHidden('cidReq', api_get_course_id());
  2275. $form->addButtonSearch(get_lang('Search'), 'do_search');
  2276. $form->display();
  2277. }
  2278. /**
  2279. * Show table only visible by DRH users
  2280. */
  2281. public static function displaySurveyListForDrh()
  2282. {
  2283. $parameters = array();
  2284. $parameters['cidReq'] = api_get_course_id();
  2285. // Create a sortable table with survey-data
  2286. $table = new SortableTable(
  2287. 'surveys',
  2288. 'get_number_of_surveys',
  2289. 'get_survey_data_drh',
  2290. 2
  2291. );
  2292. $table->set_additional_parameters($parameters);
  2293. $table->set_header(0, '', false);
  2294. $table->set_header(1, get_lang('SurveyName'));
  2295. $table->set_header(2, get_lang('SurveyCode'));
  2296. $table->set_header(3, get_lang('NumberOfQuestions'));
  2297. $table->set_header(4, get_lang('Author'));
  2298. $table->set_header(5, get_lang('AvailableFrom'));
  2299. $table->set_header(6, get_lang('AvailableUntil'));
  2300. $table->set_header(7, get_lang('Invite'));
  2301. $table->set_header(8, get_lang('Anonymous'));
  2302. $table->set_header(9, get_lang('Modify'), false, 'width="150"');
  2303. $table->set_column_filter(8, 'anonymous_filter');
  2304. $table->set_column_filter(9, 'modify_filter_drh');
  2305. $table->display();
  2306. }
  2307. /**
  2308. * This function displays the sortable table with all the surveys
  2309. *
  2310. * @return void (direct output)
  2311. *
  2312. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2313. * @version January 2007
  2314. */
  2315. public static function display_survey_list()
  2316. {
  2317. $parameters = array();
  2318. $parameters['cidReq'] = api_get_course_id();
  2319. if (isset($_GET['do_search']) && $_GET['do_search']) {
  2320. $message = get_lang('DisplaySearchResults').'<br />';
  2321. $message .= '<a href="'.api_get_self().'?'.api_get_cidreq().'">'.get_lang('DisplayAll').'</a>';
  2322. Display::display_normal_message($message, false);
  2323. }
  2324. // Create a sortable table with survey-data
  2325. $table = new SortableTable(
  2326. 'surveys',
  2327. 'get_number_of_surveys',
  2328. 'get_survey_data',
  2329. 2
  2330. );
  2331. $table->set_additional_parameters($parameters);
  2332. $table->set_header(0, '', false);
  2333. $table->set_header(1, get_lang('SurveyName'));
  2334. $table->set_header(2, get_lang('SurveyCode'));
  2335. $table->set_header(3, get_lang('NumberOfQuestions'));
  2336. $table->set_header(4, get_lang('Author'));
  2337. //$table->set_header(5, get_lang('Language'));
  2338. //$table->set_header(6, get_lang('Shared'));
  2339. $table->set_header(5, get_lang('AvailableFrom'));
  2340. $table->set_header(6, get_lang('AvailableUntil'));
  2341. $table->set_header(7, get_lang('Invite'));
  2342. $table->set_header(8, get_lang('Anonymous'));
  2343. $table->set_header(9, get_lang('Modify'), false, 'width="150"');
  2344. $table->set_column_filter(8, 'anonymous_filter');
  2345. $table->set_column_filter(9, 'modify_filter');
  2346. $table->set_form_actions(array('delete' => get_lang('DeleteSurvey')));
  2347. $table->display();
  2348. }
  2349. /**
  2350. * Survey list for coach
  2351. */
  2352. public static function display_survey_list_for_coach()
  2353. {
  2354. $parameters = array();
  2355. $parameters['cidReq']=api_get_course_id();
  2356. if (isset($_GET['do_search'])) {
  2357. $message = get_lang('DisplaySearchResults').'<br />';
  2358. $message .= '<a href="'.api_get_self().'?'.api_get_cidreq().'">'.get_lang('DisplayAll').'</a>';
  2359. Display::display_normal_message($message, false);
  2360. }
  2361. // Create a sortable table with survey-data
  2362. $table = new SortableTable(
  2363. 'surveys_coach',
  2364. 'get_number_of_surveys_for_coach',
  2365. 'get_survey_data_for_coach',
  2366. 2
  2367. );
  2368. $table->set_additional_parameters($parameters);
  2369. $table->set_header(0, '', false);
  2370. $table->set_header(1, get_lang('SurveyName'));
  2371. $table->set_header(2, get_lang('SurveyCode'));
  2372. $table->set_header(3, get_lang('NumberOfQuestions'));
  2373. $table->set_header(4, get_lang('Author'));
  2374. //$table->set_header(5, get_lang('Language'));
  2375. //$table->set_header(6, get_lang('Shared'));
  2376. $table->set_header(5, get_lang('AvailableFrom'));
  2377. $table->set_header(6, get_lang('AvailableUntil'));
  2378. $table->set_header(7, get_lang('Invite'));
  2379. $table->set_header(8, get_lang('Anonymous'));
  2380. $table->set_header(9, get_lang('Modify'), false, 'width="130"');
  2381. $table->set_column_filter(8, 'anonymous_filter');
  2382. $table->set_column_filter(9, 'modify_filter_for_coach');
  2383. $table->display();
  2384. }
  2385. /**
  2386. * This function changes the modify column of the sortable table
  2387. *
  2388. * @param integer $survey_id the id of the survey
  2389. * @param bool $drh
  2390. * @return string html code that are the actions that can be performed on any survey
  2391. *
  2392. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2393. * @version January 2007
  2394. */
  2395. public static function modify_filter($survey_id, $drh = false)
  2396. {
  2397. $survey_id = Security::remove_XSS($survey_id);
  2398. $return = '';
  2399. if ($drh) {
  2400. return '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?'.api_get_cidreq().'&survey_id='.$survey_id.'">'.
  2401. Display::return_icon('stats.png', get_lang('Reporting'),'',ICON_SIZE_SMALL).'</a>';
  2402. }
  2403. // Coach can see that only if the survey is in his session
  2404. if (api_is_allowed_to_edit() ||
  2405. api_is_element_in_the_session(TOOL_SURVEY, $survey_id)
  2406. ) {
  2407. $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/create_new_survey.php?'.api_get_cidreq().'&action=edit&survey_id='.$survey_id.'">'.Display::return_icon('edit.png', get_lang('Edit'),'',ICON_SIZE_SMALL).'</a>';
  2408. if (SurveyManager::survey_generation_hash_available()) {
  2409. $return .= Display::url(
  2410. Display::return_icon('new_link.png', get_lang('GenerateSurveyAccessLink'),'',ICON_SIZE_SMALL),
  2411. api_get_path(WEB_CODE_PATH).'survey/generate_link.php?survey_id='.$survey_id.'&'.api_get_cidreq()
  2412. );
  2413. }
  2414. $return .= Display::url(
  2415. Display::return_icon('copy.png', get_lang('DuplicateSurvey'), '', ICON_SIZE_SMALL),
  2416. 'survey_list.php?action=copy_survey&survey_id='.$survey_id.'&'.api_get_cidreq()
  2417. );
  2418. $return .= ' <a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_list.php?'.api_get_cidreq().'&action=empty&survey_id='.$survey_id.'" onclick="javascript: if(!confirm(\''.addslashes(api_htmlentities(get_lang("EmptySurvey").'?')).'\')) return false;">'.
  2419. Display::return_icon('clean.png', get_lang('EmptySurvey'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
  2420. }
  2421. $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/preview.php?'.api_get_cidreq().'&survey_id='.$survey_id.'">'.
  2422. Display::return_icon('preview_view.png', get_lang('Preview'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
  2423. $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_invite.php?'.api_get_cidreq().'&survey_id='.$survey_id.'">'.
  2424. Display::return_icon('mail_send.png', get_lang('Publish'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
  2425. $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?'.api_get_cidreq().'&survey_id='.$survey_id.'">'.
  2426. Display::return_icon('stats.png', get_lang('Reporting'),'',ICON_SIZE_SMALL).'</a>';
  2427. if (api_is_allowed_to_edit() ||
  2428. api_is_element_in_the_session(TOOL_SURVEY, $survey_id)
  2429. ) {
  2430. $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_list.php?'.api_get_cidreq().'&action=delete&survey_id='.$survey_id.'" onclick="javascript: if(!confirm(\''.addslashes(api_htmlentities(get_lang("DeleteSurvey").'?', ENT_QUOTES)).'\')) return false;">'.
  2431. Display::return_icon('delete.png', get_lang('Delete'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
  2432. }
  2433. return $return;
  2434. }
  2435. public static function modify_filter_for_coach($survey_id)
  2436. {
  2437. $survey_id = Security::remove_XSS($survey_id);
  2438. //$return = '<a href="create_new_survey.php?'.api_get_cidreq().'&action=edit&survey_id='.$survey_id.'">'.Display::return_icon('edit.gif', get_lang('Edit')).'</a>';
  2439. //$return .= '<a href="survey_list.php?'.api_get_cidreq().'&action=delete&survey_id='.$survey_id.'" onclick="javascript:if(!confirm(\''.addslashes(api_htmlentities(get_lang("DeleteSurvey").'?', ENT_QUOTES)).'\')) return false;">'.Display::return_icon('delete.gif', get_lang('Delete')).'</a>';
  2440. //$return .= '<a href="create_survey_in_another_language.php?id_survey='.$survey_id.'">'.Display::return_icon('copy.gif', get_lang('Copy')).'</a>';
  2441. //$return .= '<a href="survey.php?survey_id='.$survey_id.'">'.Display::return_icon('add.gif', get_lang('Add')).'</a>';
  2442. $return = '<a href="'.api_get_path(WEB_CODE_PATH).'survey/preview.php?'.api_get_cidreq().'&survey_id='.$survey_id.'">'.Display::return_icon('preview_view.png', get_lang('Preview'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
  2443. $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_invite.php?'.api_get_cidreq().'&survey_id='.$survey_id.'">'.Display::return_icon('mail_send.png', get_lang('Publish'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
  2444. $return .= '<a href="'.api_get_path(WEB_CODE_PATH).'survey/survey_list.php?'.api_get_cidreq().'&action=empty&survey_id='.$survey_id.'" onclick="javascript: if(!confirm(\''.addslashes(api_htmlentities(get_lang("EmptySurvey").'?', ENT_QUOTES)).'\')) return false;">'.Display::return_icon('clean.png', get_lang('EmptySurvey'),'',ICON_SIZE_SMALL).'</a>&nbsp;';
  2445. return $return;
  2446. }
  2447. /**
  2448. * Returns "yes" when given parameter is one, "no" for any other value
  2449. * @param integer Whether anonymous or not
  2450. * @return string "Yes" or "No" in the current language
  2451. */
  2452. public static function anonymous_filter($anonymous)
  2453. {
  2454. if ($anonymous == 1) {
  2455. return get_lang('Yes');
  2456. } else {
  2457. return get_lang('No');
  2458. }
  2459. }
  2460. /**
  2461. * This function handles the search restriction for the SQL statements
  2462. *
  2463. * @return string Part of a SQL statement or false on error
  2464. *
  2465. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2466. * @version January 2007
  2467. */
  2468. public static function survey_search_restriction()
  2469. {
  2470. if (isset($_GET['do_search'])) {
  2471. if ($_GET['keyword_title'] != '') {
  2472. $search_term[] = 'title like "%" \''.Database::escape_string($_GET['keyword_title']).'\' "%"';
  2473. }
  2474. if ($_GET['keyword_code'] != '') {
  2475. $search_term[] = 'code =\''.Database::escape_string($_GET['keyword_code']).'\'';
  2476. }
  2477. if ($_GET['keyword_language'] != '%') {
  2478. $search_term[] = 'lang =\''.Database::escape_string($_GET['keyword_language']).'\'';
  2479. }
  2480. $my_search_term = ($search_term == null) ? array() : $search_term;
  2481. $search_restriction = implode(' AND ', $my_search_term);
  2482. return $search_restriction;
  2483. } else {
  2484. return false;
  2485. }
  2486. }
  2487. /**
  2488. * This function calculates the total number of surveys
  2489. *
  2490. * @return integer Total number of surveys
  2491. *
  2492. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2493. * @version January 2007
  2494. */
  2495. public static function get_number_of_surveys()
  2496. {
  2497. $table_survey = Database::get_course_table(TABLE_SURVEY);
  2498. $course_id = api_get_course_int_id();
  2499. $search_restriction = self::survey_search_restriction();
  2500. if ($search_restriction) {
  2501. $search_restriction = 'WHERE c_id = '.$course_id.' AND '.$search_restriction;
  2502. } else {
  2503. $search_restriction = "WHERE c_id = $course_id";
  2504. }
  2505. $sql = "SELECT count(survey_id) AS total_number_of_items
  2506. FROM ".$table_survey.' '.$search_restriction;
  2507. $res = Database::query($sql);
  2508. $obj = Database::fetch_object($res);
  2509. return $obj->total_number_of_items;
  2510. }
  2511. /**
  2512. * @return int
  2513. */
  2514. public static function get_number_of_surveys_for_coach()
  2515. {
  2516. $survey_tree = new SurveyTree();
  2517. return count($survey_tree->surveylist);
  2518. }
  2519. /**
  2520. * This function gets all the survey data that is to be displayed in the sortable table
  2521. *
  2522. * @param int $from
  2523. * @param int $number_of_items
  2524. * @param int $column
  2525. * @param string $direction
  2526. * @param bool $isDrh
  2527. * @return array
  2528. *
  2529. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2530. * @author Julio Montoya <gugli100@gmail.com>, Beeznest - Adding intvals
  2531. * @version January 2007
  2532. */
  2533. public static function get_survey_data($from, $number_of_items, $column, $direction, $isDrh = false)
  2534. {
  2535. $table_survey = Database::get_course_table(TABLE_SURVEY);
  2536. $table_user = Database::get_main_table(TABLE_MAIN_USER);
  2537. $table_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  2538. $_user = api_get_user_info();
  2539. // Searching
  2540. $search_restriction = self::survey_search_restriction();
  2541. if ($search_restriction) {
  2542. $search_restriction = ' AND '.$search_restriction;
  2543. }
  2544. $from = intval($from);
  2545. $number_of_items = intval($number_of_items);
  2546. $column = intval($column);
  2547. if (!in_array(strtolower($direction), array('asc', 'desc'))) {
  2548. $direction = 'asc';
  2549. }
  2550. // Condition for the session
  2551. $session_id = api_get_session_id();
  2552. $condition_session = api_get_session_condition($session_id);
  2553. $course_id = api_get_course_int_id();
  2554. $sql = "SELECT
  2555. survey.survey_id AS col0,
  2556. survey.title AS col1,
  2557. survey.code AS col2,
  2558. count(survey_question.question_id) AS col3,
  2559. ".(api_is_western_name_order() ? "CONCAT(user.firstname, ' ', user.lastname)" : "CONCAT(user.lastname, ' ', user.firstname)")." AS col4,
  2560. survey.avail_from AS col5,
  2561. survey.avail_till AS col6,
  2562. survey.invited AS col7,
  2563. survey.anonymous AS col8,
  2564. survey.survey_id AS col9,
  2565. survey.session_id AS session_id,
  2566. survey.answered,
  2567. survey.invited
  2568. FROM $table_survey survey
  2569. LEFT JOIN $table_survey_question survey_question
  2570. ON (survey.survey_id = survey_question.survey_id AND survey_question.c_id = $course_id)
  2571. LEFT JOIN $table_user user
  2572. ON (survey.author = user.user_id)
  2573. WHERE survey.c_id = $course_id
  2574. $search_restriction
  2575. $condition_session
  2576. GROUP BY survey.survey_id
  2577. ORDER BY col$column $direction
  2578. LIMIT $from,$number_of_items";
  2579. $res = Database::query($sql);
  2580. $surveys = array();
  2581. $array = array();
  2582. while ($survey = Database::fetch_array($res)) {
  2583. $array[0] = $survey[0];
  2584. $array[1] = Display::url(
  2585. $survey[1],
  2586. api_get_path(WEB_CODE_PATH).'survey/survey.php?survey_id='.$survey[0].'&'.api_get_cidreq()
  2587. );
  2588. // Validation when belonging to a session
  2589. $session_img = api_get_session_image($survey['session_id'], $_user['status']);
  2590. $array[2] = $survey[2] . $session_img;
  2591. $array[3] = $survey[3];
  2592. $array[4] = $survey[4];
  2593. $array[5] = $survey[5];
  2594. $array[6] = $survey[6];
  2595. $array[7] =
  2596. Display::url(
  2597. $survey['answered'],
  2598. api_get_path(WEB_CODE_PATH).'survey/survey_invitation.php?view=answered&survey_id='.$survey[0].'&'.api_get_cidreq()
  2599. ).' / '.
  2600. Display::url(
  2601. $survey['invited'],
  2602. api_get_path(WEB_CODE_PATH).'survey/survey_invitation.php?view=invited&survey_id='.$survey[0].'&'.api_get_cidreq()
  2603. );
  2604. $array[8] = $survey[8];
  2605. $array[9] = $survey[9];
  2606. if ($isDrh) {
  2607. $array[1] = $survey[1];
  2608. $array[7] = strip_tags($array[7]);
  2609. }
  2610. $surveys[] = $array;
  2611. }
  2612. return $surveys;
  2613. }
  2614. /**
  2615. * @param $from
  2616. * @param $number_of_items
  2617. * @param $column
  2618. * @param $direction
  2619. * @return array
  2620. */
  2621. public static function get_survey_data_for_coach($from, $number_of_items, $column, $direction)
  2622. {
  2623. $survey_tree = new SurveyTree();
  2624. //$last_version_surveys = $survey_tree->get_last_children_from_branch($survey_tree->surveylist);
  2625. $last_version_surveys = $survey_tree->surveylist;
  2626. $list = array();
  2627. foreach ($last_version_surveys as & $survey) {
  2628. $list[]=$survey['id'];
  2629. }
  2630. if (count($list) > 0) {
  2631. $list_condition = " AND survey.survey_id IN (".implode(',',$list).") ";
  2632. } else {
  2633. $list_condition = '';
  2634. }
  2635. $from = intval($from);
  2636. $number_of_items = intval($number_of_items);
  2637. $column = intval($column);
  2638. if (!in_array(strtolower($direction), array('asc', 'desc'))) {
  2639. $direction = 'asc';
  2640. }
  2641. $table_survey = Database:: get_course_table(TABLE_SURVEY);
  2642. $table_survey_question = Database:: get_course_table(TABLE_SURVEY_QUESTION);
  2643. $table_user = Database:: get_main_table(TABLE_MAIN_USER);
  2644. $course_id = api_get_course_int_id();
  2645. $sql = "SELECT
  2646. survey.survey_id AS col0,
  2647. survey.title AS col1,
  2648. survey.code AS col2,
  2649. count(survey_question.question_id) AS col3,
  2650. ".(api_is_western_name_order() ? "CONCAT(user.firstname, ' ', user.lastname)" : "CONCAT(user.lastname, ' ', user.firstname)")." AS col4,
  2651. survey.avail_from AS col5,
  2652. survey.avail_till AS col6,
  2653. CONCAT('<a href=\"survey_invitation.php?view=answered&survey_id=',survey.survey_id,'\">',survey.answered,'</a> / <a href=\"survey_invitation.php?view=invited&survey_id=',survey.survey_id,'\">',survey.invited, '</a>') AS col7,
  2654. survey.anonymous AS col8,
  2655. survey.survey_id AS col9
  2656. FROM $table_survey survey
  2657. LEFT JOIN $table_survey_question survey_question
  2658. ON (survey.survey_id = survey_question.survey_id AND survey.c_id = survey_question.c_id),
  2659. $table_user user
  2660. WHERE survey.author = user.user_id AND survey.c_id = $course_id $list_condition ";
  2661. $sql .= " GROUP BY survey.survey_id";
  2662. $sql .= " ORDER BY col$column $direction ";
  2663. $sql .= " LIMIT $from,$number_of_items";
  2664. $res = Database::query($sql);
  2665. $surveys = array();
  2666. while ($survey = Database::fetch_array($res)) {
  2667. $surveys[] = $survey;
  2668. }
  2669. return $surveys;
  2670. }
  2671. /**
  2672. * Display all the active surveys for the given course user
  2673. *
  2674. * @param int $user_id
  2675. *
  2676. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  2677. * @version April 2007
  2678. */
  2679. public static function getSurveyList($user_id)
  2680. {
  2681. $_course = api_get_course_info();
  2682. $course_id = $_course['real_id'];
  2683. $user_id = intval($user_id);
  2684. $sessionId = api_get_session_id();
  2685. // Database table definitions
  2686. $table_survey_question = Database::get_course_table(TABLE_SURVEY_QUESTION);
  2687. $table_survey_invitation = Database::get_course_table(TABLE_SURVEY_INVITATION);
  2688. $table_survey_answer = Database::get_course_table(TABLE_SURVEY_ANSWER);
  2689. $table_survey = Database:: get_course_table(TABLE_SURVEY);
  2690. $sql = "SELECT question_id
  2691. FROM $table_survey_question
  2692. WHERE c_id = $course_id";
  2693. $result = Database::query($sql);
  2694. $all_question_id = array();
  2695. while ($row = Database::fetch_array($result, 'ASSOC')) {
  2696. $all_question_id[] = $row;
  2697. }
  2698. $count = 0;
  2699. for ($i = 0; $i < count($all_question_id); $i++) {
  2700. $sql = 'SELECT COUNT(*) as count
  2701. FROM '.$table_survey_answer.'
  2702. WHERE
  2703. c_id = '.$course_id.' AND
  2704. question_id='.intval($all_question_id[$i]['question_id']).' AND
  2705. user = '.$user_id;
  2706. $result = Database::query($sql);
  2707. while ($row = Database::fetch_array($result, 'ASSOC')) {
  2708. if ($row['count'] == 0) {
  2709. $count++;
  2710. break;
  2711. }
  2712. }
  2713. if ($count > 0) {
  2714. $link_add = true;
  2715. break;
  2716. }
  2717. }
  2718. echo '<table id="list-survey" class="table ">';
  2719. echo '<tr>';
  2720. echo ' <th>'.get_lang('SurveyName').'</th>';
  2721. echo ' <th>'.get_lang('Anonymous').'</th>';
  2722. echo '</tr>';
  2723. $now = api_get_utc_datetime();
  2724. $sql = "SELECT *
  2725. FROM $table_survey survey INNER JOIN
  2726. $table_survey_invitation survey_invitation
  2727. ON (
  2728. survey.code = survey_invitation.survey_code AND
  2729. survey.c_id = survey_invitation.c_id
  2730. )
  2731. WHERE
  2732. survey_invitation.user = $user_id AND
  2733. survey.avail_from <= '".$now."' AND
  2734. survey.avail_till >= '".$now."' AND
  2735. survey.c_id = $course_id AND
  2736. survey.session_id = $sessionId AND
  2737. survey_invitation.c_id = $course_id
  2738. ";
  2739. $result = Database::query($sql);
  2740. while ($row = Database::fetch_array($result, 'ASSOC')) {
  2741. echo '<tr>';
  2742. if ($row['answered'] == 0) {
  2743. echo '<td>';
  2744. echo Display::return_icon('statistics.png', get_lang('CreateNewSurvey'), array(),ICON_SIZE_TINY);
  2745. echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/fillsurvey.php?course='.$_course['sysCode'].'&invitationcode='.$row['invitation_code'].'&cidReq='.$_course['sysCode'].'">'.$row['title'].'</a></td>';
  2746. } else {
  2747. echo '<td>';
  2748. echo Display::return_icon('statistics_na.png', get_lang('CreateNewSurvey'), array(),ICON_SIZE_TINY);
  2749. echo '<a href="'.api_get_path(WEB_CODE_PATH).'survey/reporting.php?action=questionreport&cidReq='.$_course['sysCode'].'&id_session='.$row['session_id'].'&gidReq=0&origin=&survey_id='.$row['survey_id'].'">'.$row['title'].'</a></td>';
  2750. }
  2751. echo '<td class="center">';
  2752. echo ($row['anonymous'] == 1) ? get_lang('Yes') : get_lang('No');
  2753. echo '</td>';
  2754. echo '</tr>';
  2755. }
  2756. echo '</table>';
  2757. }
  2758. /**
  2759. * Creates a multi array with the user fields that we can show. We look the visibility with the api_get_setting function
  2760. * The username is always NOT able to change it.
  2761. * @author Julio Montoya Armas <gugli100@gmail.com>, Chamilo: Personality Test modification
  2762. * @return array[value_name][name]
  2763. * array[value_name][visibilty]
  2764. */
  2765. public static function make_field_list()
  2766. {
  2767. // LAST NAME and FIRST NAME
  2768. $field_list_array = array();
  2769. $field_list_array['lastname']['name'] = get_lang('LastName');
  2770. $field_list_array['firstname']['name'] = get_lang('FirstName');
  2771. if (api_get_setting('profile', 'name') != 'true') {
  2772. $field_list_array['firstname']['visibility'] = 0;
  2773. $field_list_array['lastname']['visibility'] = 0;
  2774. } else {
  2775. $field_list_array['firstname']['visibility'] = 1;
  2776. $field_list_array['lastname']['visibility'] = 1;
  2777. }
  2778. $field_list_array['username']['name'] = get_lang('Username');
  2779. $field_list_array['username']['visibility'] = 0;
  2780. // OFFICIAL CODE
  2781. $field_list_array['official_code']['name'] = get_lang('OfficialCode');
  2782. if (api_get_setting('profile', 'officialcode') != 'true') {
  2783. $field_list_array['official_code']['visibility'] = 1;
  2784. } else {
  2785. $field_list_array['official_code']['visibility'] = 0;
  2786. }
  2787. // EMAIL
  2788. $field_list_array['email']['name'] = get_lang('Email');
  2789. if (api_get_setting('profile', 'email') != 'true') {
  2790. $field_list_array['email']['visibility'] = 1;
  2791. } else {
  2792. $field_list_array['email']['visibility'] = 0;
  2793. }
  2794. // PHONE
  2795. $field_list_array['phone']['name'] = get_lang('Phone');
  2796. if (api_get_setting('profile', 'phone') != 'true') {
  2797. $field_list_array['phone']['visibility'] = 0;
  2798. } else {
  2799. $field_list_array['phone']['visibility'] = 1;
  2800. }
  2801. // LANGUAGE
  2802. $field_list_array['language']['name'] = get_lang('Language');
  2803. if (api_get_setting('profile', 'language') != 'true') {
  2804. $field_list_array['language']['visibility'] = 0;
  2805. } else {
  2806. $field_list_array['language']['visibility'] = 1;
  2807. }
  2808. // EXTRA FIELDS
  2809. $extra = UserManager::get_extra_fields(0, 50, 5, 'ASC');
  2810. foreach ($extra as $id => $field_details) {
  2811. if ($field_details[6] == 0) {
  2812. continue;
  2813. }
  2814. switch ($field_details[2]) {
  2815. case UserManager::USER_FIELD_TYPE_TEXT:
  2816. $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
  2817. if ($field_details[7] == 0) {
  2818. $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
  2819. } else {
  2820. $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
  2821. }
  2822. break;
  2823. case UserManager::USER_FIELD_TYPE_TEXTAREA:
  2824. $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
  2825. if ($field_details[7] == 0) {
  2826. $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
  2827. } else {
  2828. $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
  2829. }
  2830. break;
  2831. case UserManager::USER_FIELD_TYPE_RADIO:
  2832. $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
  2833. if ($field_details[7] == 0) {
  2834. $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
  2835. } else {
  2836. $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
  2837. }
  2838. break;
  2839. case UserManager::USER_FIELD_TYPE_SELECT:
  2840. $get_lang_variables = false;
  2841. if (in_array($field_details[1], array('mail_notify_message', 'mail_notify_invitation', 'mail_notify_group_message'))) {
  2842. $get_lang_variables = true;
  2843. }
  2844. if ($get_lang_variables) {
  2845. $field_list_array['extra_'.$field_details[1]]['name'] = get_lang($field_details[3]);
  2846. } else {
  2847. $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
  2848. }
  2849. if ($field_details[7] == 0) {
  2850. $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
  2851. } else {
  2852. $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
  2853. }
  2854. break;
  2855. case UserManager::USER_FIELD_TYPE_SELECT_MULTIPLE:
  2856. $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
  2857. if ($field_details[7] == 0) {
  2858. $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
  2859. } else {
  2860. $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
  2861. }
  2862. break;
  2863. case UserManager::USER_FIELD_TYPE_DATE:
  2864. $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
  2865. if ($field_details[7] == 0) {
  2866. $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
  2867. } else {
  2868. $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
  2869. }
  2870. break;
  2871. case UserManager::USER_FIELD_TYPE_DATETIME:
  2872. $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
  2873. if ($field_details[7] == 0) {
  2874. $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
  2875. } else {
  2876. $field_list_array['extra_'.$field_details[1]]['visibility'] = 1;
  2877. }
  2878. break;
  2879. case UserManager::USER_FIELD_TYPE_DOUBLE_SELECT:
  2880. $field_list_array['extra_'.$field_details[1]]['name'] = $field_details[3];
  2881. if ($field_details[7] == 0) {
  2882. $field_list_array['extra_'.$field_details[1]]['visibility'] = 0;
  2883. } else {
  2884. $field_list_array['extra_'.$field_details[1]]['visibility']=1;
  2885. }
  2886. break;
  2887. case UserManager::USER_FIELD_TYPE_DIVIDER:
  2888. //$form->addElement('static',$field_details[1], '<br /><strong>'.$field_details[3].'</strong>');
  2889. break;
  2890. }
  2891. }
  2892. return $field_list_array;
  2893. }
  2894. /**
  2895. * @author Isaac Flores Paz <florespaz@bidsoftperu.com>
  2896. * @param int $user_id - User ID
  2897. * @param string $survey_code
  2898. * @param int $user_id_answer - User in survey answer table (user id or anonymus)
  2899. *
  2900. * @return boolean
  2901. */
  2902. public static function show_link_available($user_id, $survey_code, $user_answer)
  2903. {
  2904. $table_survey = Database:: get_course_table(TABLE_SURVEY);
  2905. $table_survey_invitation = Database:: get_course_table(TABLE_SURVEY_INVITATION);
  2906. $table_survey_answer = Database:: get_course_table(TABLE_SURVEY_ANSWER);
  2907. $table_survey_question = Database:: get_course_table(TABLE_SURVEY_QUESTION);
  2908. $survey_code = Database::escape_string($survey_code);
  2909. $user_id = intval($user_id);
  2910. $user_answer = Database::escape_string($user_answer);
  2911. $course_id = api_get_course_int_id();
  2912. $sql = 'SELECT COUNT(*) as count
  2913. FROM '.$table_survey_invitation.'
  2914. WHERE
  2915. user='.$user_id.' AND
  2916. survey_code="'.$survey_code.'" AND
  2917. answered="1" AND
  2918. c_id = '.$course_id;
  2919. $sql2 = 'SELECT COUNT(*) as count FROM '.$table_survey.' s
  2920. INNER JOIN '.$table_survey_question.' q
  2921. ON s.survey_id=q.survey_id
  2922. WHERE
  2923. s.code="'.$survey_code.'" AND
  2924. q.type NOT IN("pagebreak","comment") AND s.c_id = '.$course_id.' AND q.c_id = '.$course_id.' ';
  2925. $sql3 = 'SELECT COUNT(DISTINCT question_id) as count
  2926. FROM '.$table_survey_answer.'
  2927. WHERE survey_id=(
  2928. SELECT survey_id FROM '.$table_survey.'
  2929. WHERE
  2930. code = "'.$survey_code.'" AND
  2931. c_id = '.$course_id.'
  2932. ) AND
  2933. user="'.$user_answer.'" AND
  2934. c_id = '.$course_id;
  2935. $result = Database::query($sql);
  2936. $result2 = Database::query($sql2);
  2937. $result3 = Database::query($sql3);
  2938. $row = Database::fetch_array($result, 'ASSOC');
  2939. $row2 = Database::fetch_array($result2, 'ASSOC');
  2940. $row3 = Database::fetch_array($result3, 'ASSOC');
  2941. if ($row['count'] == 1 && $row3['count'] != $row2['count']) {
  2942. return true;
  2943. } else {
  2944. return false;
  2945. }
  2946. }
  2947. /**
  2948. * Display survey question chart
  2949. * @param array $chartData
  2950. * @param boolean $hasSerie Tells if the chart has a serie. False by default
  2951. * @param string $chartContainerId
  2952. * @return string (direct output)
  2953. */
  2954. public static function drawChart($chartData, $hasSerie = false, $chartContainerId = 'chartContainer')
  2955. {
  2956. $htmlChart = '';
  2957. if (api_browser_support("svg")) {
  2958. $htmlChart .= api_get_js("d3/d3.v3.5.4.min.js");
  2959. $htmlChart .= api_get_js("dimple.v2.1.2.min.js") . '
  2960. <script type="text/javascript">
  2961. var svg = dimple.newSvg("#'.$chartContainerId.'", "100%", 400);
  2962. var data = [';
  2963. $serie = array();
  2964. $order = array();
  2965. foreach ($chartData as $chartDataElement) {
  2966. $htmlChart .= '{"';
  2967. if (!$hasSerie) {
  2968. $htmlChart .= get_lang("Option") . '":"' . $chartDataElement['option'] . '", "';
  2969. array_push($order, $chartDataElement['option']);
  2970. } else {
  2971. if (!is_array($chartDataElement['serie'])) {
  2972. $htmlChart .= get_lang("Option") . '":"' . $chartDataElement['serie'] . '", "' .
  2973. get_lang("Score") . '":"' . $chartDataElement['option'] . '", "';
  2974. array_push($serie, $chartDataElement['serie']);
  2975. } else {
  2976. $htmlChart .= get_lang("Serie") . '":"' . $chartDataElement['serie'][0] . '", "' .
  2977. get_lang("Option") . '":"' . $chartDataElement['serie'][1] . '", "' .
  2978. get_lang("Score") . '":"' . $chartDataElement['option'] . '", "';
  2979. }
  2980. }
  2981. $htmlChart .= get_lang("Votes") . '":"' . $chartDataElement['votes'] .
  2982. '"},';
  2983. }
  2984. rtrim($htmlChart, ",");
  2985. $htmlChart .= '];
  2986. var myChart = new dimple.chart(svg, data);
  2987. myChart.addMeasureAxis("y", "' . get_lang("Votes") . '");';
  2988. if (!$hasSerie) {
  2989. $htmlChart .= 'var xAxisCategory = myChart.addCategoryAxis("x", "' . get_lang("Option") . '");
  2990. xAxisCategory.addOrderRule(' . json_encode($order) . ');
  2991. myChart.addSeries("' . get_lang("Option") . '", dimple.plot.bar);';
  2992. } else {
  2993. if (!is_array($chartDataElement['serie'])) {
  2994. $serie = array_values(array_unique($serie));
  2995. $htmlChart .= 'var xAxisCategory = myChart.addCategoryAxis("x", ["' . get_lang("Option") . '","' . get_lang("Score") . '"]);
  2996. xAxisCategory.addOrderRule(' . json_encode($serie) . ');
  2997. xAxisCategory.addGroupOrderRule("' . get_lang("Score") . '");
  2998. myChart.addSeries("' . get_lang("Option") . '", dimple.plot.bar);';
  2999. } else {
  3000. $htmlChart .= 'myChart.addCategoryAxis("x", ["' . get_lang("Option") . '","' . get_lang("Score") . '"]);
  3001. myChart.addSeries("' . get_lang("Serie") . '", dimple.plot.bar);';
  3002. }
  3003. }
  3004. $htmlChart .= 'myChart.draw();
  3005. </script>';
  3006. }
  3007. return $htmlChart;
  3008. }
  3009. /**
  3010. * Set a flag to the current survey as answered by the current user
  3011. * @param string $surveyCode The survey code
  3012. * @param int $courseId The course ID
  3013. */
  3014. public static function flagSurveyAsAnswered($surveyCode, $courseId)
  3015. {
  3016. $currentUserId = api_get_user_id();
  3017. $flag = sprintf("%s-%s-%d", $courseId, $surveyCode, $currentUserId);
  3018. if (!isset($_SESSION['filled_surveys'])) {
  3019. $_SESSION['filled_surveys'] = array();
  3020. }
  3021. $_SESSION['filled_surveys'][] = $flag;
  3022. }
  3023. /**
  3024. * Check whether a survey was answered by the current user
  3025. * @param string $surveyCode The survey code
  3026. * @param int $courseId The course ID
  3027. * @return boolean
  3028. */
  3029. public static function isSurveyAnsweredFlagged($surveyCode, $courseId)
  3030. {
  3031. $currentUserId = api_get_user_id();
  3032. $flagToCheck = sprintf("%s-%s-%d", $courseId, $surveyCode, $currentUserId);
  3033. if (!isset($_SESSION['filled_surveys'])) {
  3034. return false;
  3035. }
  3036. if (!is_array($_SESSION['filled_surveys'])) {
  3037. return false;
  3038. }
  3039. foreach ($_SESSION['filled_surveys'] as $flag) {
  3040. if ($flagToCheck != $flag) {
  3041. continue;
  3042. }
  3043. return true;
  3044. }
  3045. return false;
  3046. }
  3047. /**
  3048. * Check if the current survey has answers
  3049. *
  3050. * @param int $surveyId
  3051. * @return boolean return true if the survey has answers, false otherwise
  3052. */
  3053. public static function checkIfSurveyHasAnswers($surveyId)
  3054. {
  3055. $tableSurveyAnswer = Database::get_course_table(TABLE_SURVEY_ANSWER);
  3056. $courseId = api_get_course_int_id();
  3057. $surveyId = (int)$surveyId;
  3058. if (empty($courseId) || empty($surveyId)) {
  3059. return false;
  3060. }
  3061. $sql = "SELECT * FROM $tableSurveyAnswer
  3062. WHERE
  3063. c_id = $courseId AND
  3064. survey_id = '".$surveyId."'
  3065. ORDER BY answer_id, user ASC";
  3066. $result = Database::query($sql);
  3067. $response = Database::affected_rows($result);
  3068. return $response > 0;
  3069. }
  3070. }