surveyUtil.class.php 153 KB

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