surveyUtil.class.php 155 KB

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