surveyUtil.class.php 150 KB

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