surveyUtil.class.php 150 KB

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