surveyUtil.class.php 143 KB

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