surveyUtil.class.php 150 KB

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