surveyUtil.class.php 155 KB

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