surveyUtil.class.php 143 KB

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