����JFIFXX�����    $.' ",#(7),01444'9=82<.342  2!!22222222222222222222222222222222222222222222222222����"��4�� ���,�PG"Z_�4�˷����kjز�Z�,F+��_z�,�© �����zh6�٨�ic�fu���#ډb���_�N�?��wQ���5-�~�I���8����TK<5o�Iv-�����k�_U_�����~b�M��d����Ӝ�U�Hh��?]��E�w��Q���k�{��_}qFW7HTՑ��Y��F�?_�'ϔ��_�Ջt��=||I ��6�έ"�����D���/[�k�9���Y�8ds|\���Ҿp6�Ҵ���]��.����6�z<�v��@]�i%��$j��~�g��J>��no����pM[me�i$[����s�o�ᘨ�˸ nɜG-�ĨU�ycP�3.DB�li�;��hj���x7Z^�N�h������N3u{�:j�x�힞��#M&��jL P@_���� P��&��o8������9�����@Sz6�t7#O�ߋ �s}Yf�T���lmr����Z)'N��k�۞p����w\�Tȯ?�8`�O��i{wﭹW�[�r�� ��Q4F�׊���3m&L�=��h3����z~��#�\�l :�F,j@�� ʱ�wQT����8�"kJO���6�֚l����}���R�>ډK���]��y����&����p�}b��;N�1�m�r$�|��7�>e�@B�TM*-iH��g�D�)� E�m�|�ؘbҗ�a��Ҿ����t4���o���G��*oCN�rP���Q��@z,|?W[0�����:�n,jWiE��W��$~/�hp\��?��{(�0���+�Y8rΟ�+����>S-S����VN;�}�s?.����� w�9��˟<���Mq4�Wv'��{)0�1mB��V����W[�����8�/<� �%���wT^�5���b��)iM� pg�N�&ݝ��VO~�q���u���9� ����!��J27����$O-���! �:�%H��� ـ����y�ΠM=t{!S�� oK8������t<����è:a������[�����ա�H���~��w��Qz`�po�^ ����Q��n� �,uu�C�$ ^���,������8�#��:�6��e�|~���!�3�3.�\0��q��o�4`.|� ����y�Q�`~;�d�ׯ,��O�Zw�������`73�v�܋�<���Ȏ�� ـ4k��5�K�a�u�=9Yd��$>x�A�&�� j0� ���vF��� Y�|�y��� ~�6�@c��1vOp�Ig����4��l�OD���L����� R���c���j�_�uX6��3?nk��Wy�f;^*B� ��@�~a�`��Eu������+���6�L��.ü>��}y���}_�O�6�͐�:�YrG�X��kG�����l^w���~㒶sy��Iu�!� W ��X��N�7BV��O��!X�2����wvG�R�f�T#�����t�/?���%8�^�W�aT��G�cL�M���I��(J����1~�8�?aT ���]����AS�E��(��*E}� 2��#I/�׍qz��^t�̔���b�Yz4x���t�){ OH��+(E��A&�N�������XT��o��"�XC��'���)}�J�z�p� ��~5�}�^����+�6����w��c��Q�|Lp�d�H��}�(�.|����k��c4^�"�����Z?ȕ ��a<�L�!039C� �Eu�C�F�Ew�ç ;�n?�*o���B�8�bʝ���'#Rqf���M}7����]����s2tcS{�\icTx;�\��7K���P���ʇ Z O-��~��c>"��?�������P��E��O�8��@�8��G��Q�g�a�Վ���󁶠�䧘��_%#r�>�1�z�a��eb��qcPѵ��n���#L��� =��׀t� L�7�`��V���A{�C:�g���e@�w1 Xp3�c3�ġ����p��M"'-�@n4���fG��B3�DJ�8[Jo�ߐ���gK)ƛ��$���� ���8�3�����+���� �����6�ʻ���� ���S�kI�*KZlT _`���?��K����QK�d����B`�s}�>���`��*�>��,*@J�d�oF*����弝��O}�k��s��]��y�ߘ��c1G�V���<=�7��7����6�q�PT��tXԀ�!9*4�4Tހ3XΛex�46���Y��D ����� �BdemDa����\�_l,��G�/���֌7���Y�](�xTt^%�GE�����4�}bT���ڹ�����;Y)���B�Q��u��>J/J �⮶.�XԄ��j�ݳ�+E��d ��r�5�_D�1 ��o�� �B�x�΢�#���<��W�����8���R6�@g�M�.��� dr�D��>(otU��@x=��~v���2� ӣ�d�oBd��3�eO�6�㣷�����ݜ6��6Y��Qz`��S��{���\P�~z m5{J/L��1������<�e�ͅPu�b�]�ϔ���'������f�b� Zpw��c`"��i���BD@:)ִ�:�]��hv�E�w���T�l��P���"Ju�}��وV J��G6��. J/�Qgl߭�e�����@�z�Zev2u�)]կ�����7x���s�M�-<ɯ�c��r�v�����@��$�ޮ}lk���a���'����>x��O\�ZFu>�����ck#��&:��`�$�ai�>2Δ����l���oF[h��lE�ܺ�Πk:)���`�� $[6�����9�����kOw�\|���8}������ބ:��񶐕��I�A1/�=�2[�,�!��.}gN#�u����b��� ~��݊��}34q����d�E��Lc��$��"�[q�U�硬g^��%B �z���r�pJ�ru%v\h1Y�ne`ǥ:g���pQM~�^�Xi� ��`S�:V29.�P���V�?B�k�� AEvw%�_�9C�Q����wKekPؠ�\�;Io d�{ ߞo�c1eP����\� `����E=���@K<�Y���eڼ�J���w����{av�F�'�M�@/J��+9p���|]�����Iw &`��8���&M�hg��[�{��Xj��%��Ӓ�$��(����ʹN���<>�I���RY���K2�NPlL�ɀ)��&e����B+ь����( � �JTx���_?EZ� }@ 6�U���뙢ط�z��dWI�n` D����噥�[��uV��"�G&Ú����2g�}&m��?ċ�"����Om#��������� ��{�ON��"S�X��Ne��ysQ���@Fn��Vg���dX�~nj�]J�<�K]:��FW��b�������62�=��5f����JKw��bf�X�55��~J �%^����:�-�QIE��P��v�nZum� z � ~ə ���� ���ة����;�f��\v���g�8�1��f24;�V���ǔ�)����9���1\��c��v�/'Ƞ�w�������$�4�R-��t���� e�6�/�ġ �̕Ecy�J���u�B���<�W�ַ~�w[B1L۲�-JS΂�{���΃������A��20�c#��@ 0!1@AP"#2Q`$3V�%45a6�FRUq��� ����^7ׅ,$n�������+��F�`��2X'��0vM��p�L=������5��8������u�p~���.�`r�����\���O��,ư�0oS ��_�M�����l���4�kv\JSd���x���SW�<��Ae�IX����������$I���w�:S���y���›R��9�Q[���,�5�;�@]�%���u�@ *ro�lbI �� ��+���%m:�͇ZV�����u�̉����θau<�fc�.����{�4Ա� �Q����*�Sm��8\ujqs]{kN���)qO�y�_*dJ�b�7���yQqI&9�ԌK!�M}�R�;������S�T���1���i[U�ɵz�]��U)V�S6���3$K{�ߊ<�(� E]Զ[ǼENg�����'�\?#)Dkf��J���o��v���'�%ƞ�&K�u�!��b�35LX�Ϸ��63$K�a�;�9>,R��W��3�3� d�JeTYE.Mϧ��-�o�j3+y��y^�c�������VO�9NV\nd�1 ��!͕_)a�v;����թ�M�lWR1��)El��P;��yوÏ�u 3�k�5Pr6<�⒲l�!˞*��u־�n�!�l:����UNW ��%��Chx8vL'��X�@��*��)���̮��ˍ��� ���D-M�+J�U�kvK����+�x8��cY������?�Ԡ��~3mo��|�u@[XeY�C�\Kp�x8�oC�C�&����N�~3-H���� ��MX�s�u<`���~"WL��$8ξ��3���a�)|:@�m�\���^�`�@ҷ)�5p+��6���p�%i)P M���ngc�����#0Aruz���RL+xSS?���ʮ}()#�t��mˇ!��0}}y����<�e� �-ή�Ԩ��X������ MF���ԙ~l L.3���}�V뽺�v�����멬��Nl�)�2����^�Iq��a��M��qG��T�����c3#������3U�Ǎ���}��לS�|qa��ڃ�+���-��2�f����/��bz��ڐ�� �ݼ[2�ç����k�X�2�* �Z�d���J�G����M*9W���s{��w���T��x��y,�in�O�v��]���n����P�$�JB@=4�OTI�n��e�22a\����q�d���%�$��(���:���: /*�K[PR�fr\nڙdN���F�n�$�4�[�� U�zƶ����� �mʋ���,�ao�u 3�z� �x��Kn����\[��VFmbE;�_U��&V�Gg�]L�۪&#n%�$ɯ�dG���D�TI=�%+AB�Ru#��b4�1�»x�cs�YzڙJG��f��Il��d�eF'T� iA��T���uC�$����Y��H?����[!G`}���ͪ� �纤Hv\������j�Ex�K���!���OiƸ�Yj�+u-<���'q����uN�*�r\��+�]���<�wOZ.fp�ێ��,-*)V?j-kÊ#�`�r��dV����(�ݽBk�����G�ƛk�QmUڗe��Z���f}|����8�8��a���i��3'J�����~G_�^���d�8w������ R�`(�~�.��u���l�s+g�bv���W���lGc}��u���afE~1�Ue������Z�0�8�=e�� f@/�jqEKQQ�J��oN��J���W5~M>$6�Lt�;$ʳ{���^��6�{����v6���ķܰg�V�cnn �~z�x�«�,2�u�?cE+Ș�H؎�%�Za�)���X>uW�Tz�Nyo����s���FQƤ��$��*�&�LLXL)�1�" L��eO��ɟ�9=���:t��Z���c��Ž���Y?�ӭV�wv�~,Y��r�ۗ�|�y��GaF�����C�����.�+� ���v1���fήJ�����]�S��T��B��n5sW}y�$��~z�'�c ��8 ��� ,! �p��VN�S��N�N�q��y8z˱�A��4��*��'������2n<�s���^ǧ˭P�Jޮɏ�U�G�L�J�*#��<�V��t7�8����TĜ>��i}K%,���)[��z�21z ?�N�i�n1?T�I�R#��m-�����������������1����lA�`��fT5+��ܐ�c�q՝��ʐ��,���3�f2U�եmab��#ŠdQ�y>\��)�SLY����w#��.���ʑ�f��� ,"+�w�~�N�'�c�O�3F�������N<���)j��&��,-� �љ���֊�_�zS���TǦ����w�>��?�������n��U仆�V���e�����0���$�C�d���rP �m�׈e�Xm�Vu� �L��.�bֹ��� �[Դaզ���*��\y�8�Է:�Ez\�0�Kq�C b��̘��cө���Q��=0Y��s�N��S.���3.���O�o:���#���v7�[#߫ ��5�܎�L���Er4���9n��COWlG�^��0k�%<���ZB���aB_���������'=��{i�v�l�$�uC���mƎҝ{�c㱼�y]���W�i ��ߧc��m�H� m�"�"�����;Y�ߝ�Z�Ǔ�����:S#��|}�y�,/k�Ld� TA�(�AI$+I3��;Y*���Z��}|��ӧO��d�v��..#:n��f>�>���ȶI�TX��� 8��y����"d�R�|�)0���=���n4��6ⲑ�+��r<�O�܂~zh�z����7ܓ�HH�Ga롏���nCo�>������a ���~]���R���̲c?�6(�q�;5%� |�uj�~z8R=X��I�V=�|{v�Gj\gc��q����z�؋%M�ߍ����1y��#��@f^���^�>N�����#x#۹��6�Y~�?�dfPO��{��P�4��V��u1E1J �*|���%���JN��`eWu�zk M6���q t[�� ��g�G���v��WIG��u_ft����5�j�"�Y�:T��ɐ���*�;� e5���4����q$C��2d�}���� _S�L#m�Yp��O�.�C�;��c����Hi#֩%+) �Ӎ��ƲV���SYź��g |���tj��3�8���r|���V��1#;.SQ�A[���S������#���`n�+���$��$I �P\[�@�s��(�ED�z���P��])8�G#��0B��[ى��X�II�q<��9�~[Z멜�Z�⊔IWU&A>�P~�#��dp<�?����7���c��'~���5 ��+$���lx@�M�dm��n<=e�dyX��?{�|Aef ,|n3�<~z�ƃ�uۧ�����P��Y,�ӥQ�*g�#먙R�\���;T��i,��[9Qi歉����c>]9�� ��"�c��P�� �Md?٥��If�ت�u��k��/����F��9�c*9��Ǎ:�ØF���z�n*�@|I�ށ9����N3{'��[�'ͬ�Ҳ4��#}��!�V� Fu��,�,mTIk���v C�7v���B�6k�T9��1�*l� '~��ƞF��lU��'�M ����][ΩũJ_�{�i�I�n��$���L�� j��O�dx�����kza۪��#�E��Cl����x˘�o�����V���ɞ�ljr��)�/,�߬h�L��#��^��L�ф�,íMƁe�̩�NB�L�����iL����q�}��(��q��6IçJ$�W�E$��:������=#����(�K�B����zђ <��K(�N�۫K�w��^O{!����)�H���>x�������lx�?>Պ�+�>�W���,Ly!_�D���Ō�l���Q�!�[ �S����J��1��Ɛ�Y}��b,+�Lo�x�ɓ)����=�y�oh�@�꥟/��I��ѭ=��P�y9��� �ۍYӘ�e+�p�Jnϱ?V\SO%�(�t� ���=?MR�[Ș�����d�/ ��n�l��B�7j� ��!�;ӥ�/�[-���A�>�dN�sLj ��,ɪv��=1c�.SQ�O3�U���ƀ�ܽ�E����������̻��9G�ϷD�7(�}��Ävӌ\�y�_0[w ���<΍>����a_��[0+�L��F.�޺��f�>oN�T����q;���y\��bՃ��y�jH�<|q-eɏ�_?_9+P���Hp$�����[ux�K w�Mw��N�ی'$Y2�=��q���KB��P��~������Yul:�[<����F1�2�O���5=d����]Y�sw:���Ϯ���E��j,_Q��X��z`H1,#II ��d�wr��P˂@�ZJV����y$�\y�{}��^~���[:N����ߌ�U�������O��d�����ؾe��${p>G��3c���Ė�lʌ�� ת��[��`ϱ�-W����dg�I��ig2��� ��}s ��ؤ(%#sS@���~���3�X�nRG�~\jc3�v��ӍL��M[JB�T��s3}��j�Nʖ��W����;7��ç?=X�F=-�=����q�ߚ���#���='�c��7���ڑW�I(O+=:uxq�������������e2�zi+�kuG�R��������0�&e�n���iT^J����~\jy���p'dtG��s����O��3����9* �b#Ɋ�� p������[Bws�T�>d4�ۧs���nv�n���U���_�~,�v����ƜJ1��s�� �QIz��)�(lv8M���U=�;����56��G���s#�K���MP�=��LvyGd��}�VwWBF�'�à �?MH�U�g2�� ����!�p�7Q��j��ڴ����=��j�u��� Jn�A s���uM������e��Ɔ�Ҕ�!)'��8Ϣ�ٔ��ޝ(��Vp���צ֖d=�IC�J�Ǡ{q������kԭ�߸���i��@K����u�|�p=..�*+����x�����z[Aqġ#s2a�Ɗ���RR�)*HRsi�~�a &f��M��P����-K�L@��Z��Xy�'x�{}��Zm+���:�)�) IJ�-i�u���� ���ܒH��'�L(7�y�GӜq���� j��� 6ߌg1�g�o���,kر���tY�?W,���p���e���f�OQS��!K�۟cҒA�|ս�j�>��=⬒��˧L[�� �߿2JaB~R��u�:��Q�] �0H~���]�7��Ƽ�I���(}��cq '�ήET���q�?f�ab���ӥvr� �)o��-Q��_'����ᴎo��K������;��V���o��%���~OK ����*��b�f:���-ťIR��`B�5!RB@���ï�� �u �̯e\�_U�_������� g�ES��3�������QT��a����x����U<~�c?�*�#]�MW,[8O�a�x��]�1bC|踤�P��lw5V%�)�{t�<��d��5���0i�XSU��m:��Z�┵�i�"��1�^B�-��P�hJ��&)O��*�D��c�W��vM��)����}���P��ܗ-q����\mmζZ-l@�}��a��E�6��F�@��&Sg@���ݚ�M����� ȹ 4����#p�\H����dYDo�H���"��\��..R�B�H�z_�/5˘����6��KhJR��P�mƶi�m���3�,#c�co��q�a)*Pt����R�m�k�7x�D�E�\Y�閣_X�<���~�)���c[[�BP����6�Yq���S��0����%_����;��Àv�~�| VS؇ ��'O0��F0��\���U�-�d@�����7�SJ*z��3n��y��P����O���������m�~�P�3|Y��ʉr#�C�<�G~�.,! ���bqx���h~0=��!ǫ�jy����l�O,�[B��~��|9��ٱ����Xly�#�i�B��g%�S��������tˋ���e���ې��\[d�t)��.+u�|1 ������#�~Oj����hS�%��i.�~X���I�H�m��0n���c�1uE�q��cF�RF�o���7� �O�ꮧ� ���ۛ{��ʛi5�rw?׌#Qn�TW��~?y$��m\�\o����%W� ?=>S�N@�� �Ʈ���R����N�)�r"C�:��:����� �����#��qb��Y�. �6[��2K����2u�Ǧ�HYR��Q�MV��� �G�$��Q+.>�����nNH��q�^��� ����q��mM��V��D�+�-�#*�U�̒ ���p욳��u:�������IB���m���PV@O���r[b= �� ��1U�E��_Nm�yKbN�O���U�}�the�`�|6֮P>�\2�P�V���I�D�i�P�O;�9�r�mAHG�W�S]��J*�_�G��+kP�2����Ka�Z���H�'K�x�W�MZ%�O�YD�Rc+o��?�q��Ghm��d�S�oh�\�D�|:W������UA�Qc yT�q������~^�H��/��#p�CZ���T�I�1�ӏT����4��"�ČZ�����}��`w�#�*,ʹ�� ��0�i��課�Om�*�da��^gJ݅{���l�e9uF#T�ֲ��̲�ٞC"�q���ߍ ոޑ�o#�XZTp����@ o�8��(jd��xw�]�,f���`~�|,s��^����f�1���t��|��m�򸄭/ctr��5s��7�9Q�4�H1꠲BB@l9@���C�����+�wp�xu�£Yc�9��?`@#�o�mH�s2��)�=��2�.�l����jg�9$�Y�S�%*L������R�Y������7Z���,*=�䷘$�������arm�o�ϰ���UW.|�r�uf����IGw�t����Zwo��~5 ��YյhO+=8fF�)�W�7�L9lM�̘·Y���֘YLf�큹�pRF���99.A �"wz��=E\Z���'a� 2��Ǚ�#;�'}�G���*��l��^"q��+2FQ� hj��kŦ��${���ޮ-�T�٭cf�|�3#~�RJ����t��$b�(R��(����r���dx� >U b�&9,>���%E\� Ά�e�$��'�q't��*�א���ެ�b��-|d���SB�O�O��$�R+�H�)�܎�K��1m`;�J�2�Y~9��O�g8=vqD`K[�F)k�[���1m޼c��n���]s�k�z$@��)!I �x՝"v��9=�ZA=`Ɠi �:�E��)`7��vI��}d�YI�_ �o�:ob���o ���3Q��&D&�2=�� �Ά��;>�h����y.*ⅥS������Ӭ�+q&����j|UƧ����}���J0��WW< ۋS�)jQR�j���Ư��rN)�Gű�4Ѷ(�S)Ǣ�8��i��W52���No˓� ۍ%�5brOn�L�;�n��\G����=�^U�dI���8$�&���h��'���+�(������cȁ߫k�l��S^���cƗjԌE�ꭔ��gF���Ȓ��@���}O���*;e�v�WV���YJ\�]X'5��ղ�k�F��b 6R�o՜m��i N�i����>J����?��lPm�U��}>_Z&�KK��q�r��I�D�Չ~�q�3fL�:S�e>���E���-G���{L�6p�e,8��������QI��h��a�Xa��U�A'���ʂ���s�+טIjP�-��y�8ۈZ?J$��W�P� ��R�s�]��|�l(�ԓ��sƊi��o(��S0��Y� 8�T97.�����WiL��c�~�dxc�E|�2!�X�K�Ƙਫ਼�$((�6�~|d9u+�qd�^3�89��Y�6L�.I�����?���iI�q���9�)O/뚅����O���X��X�V��ZF[�یgQ�L��K1���RҖr@v�#��X�l��F���Нy�S�8�7�kF!A��sM���^rkp�jP�DyS$N���q��nxҍ!U�f�!eh�i�2�m���`�Y�I�9r�6� �TF���C}/�y�^���Η���5d�'��9A-��J��>{�_l+�`��A���[�'��յ�ϛ#w:݅�%��X�}�&�PSt�Q�"�-��\縵�/����$Ɨh�Xb�*�y��BS����;W�ջ_mc�����vt?2}1�;qS�d�d~u:2k5�2�R�~�z+|HE!)�Ǟl��7`��0�<�,�2*���Hl-��x�^����'_TV�gZA�'j� ^�2Ϊ��N7t�����?w�� �x1��f��Iz�C-Ȗ��K�^q�;���-W�DvT�7��8�Z�������� hK�(P:��Q- �8�n�Z���܃e貾�<�1�YT<�,�����"�6{/ �?�͟��|1�:�#g��W�>$����d��J��d�B��=��jf[��%rE^��il:��B���x���Sּ�1հ��,�=��*�7 fcG��#q� �eh?��2�7�����,�!7x��6�n�LC�4x��},Geǝ�tC.��vS �F�43��zz\��;QYC,6����~;RYS/6���|2���5���v��T��i����������mlv��������&� �nRh^ejR�LG�f���? �ۉҬܦƩ��|��Ȱ����>3����!v��i�ʯ�>�v��オ�X3e���_1z�Kȗ\<������!�8���V��]��?b�k41�Re��T�q��mz��TiOʦ�Z��Xq���L������q"+���2ۨ��8}�&N7XU7Ap�d�X��~�׿��&4e�o�F��� �H����O���č�c�� 懴�6���͉��+)��v;j��ݷ�� �UV�� i��� j���Y9GdÒJ1��詞�����V?h��l����l�cGs�ځ�������y�Ac�����\V3�? �� ܙg�>qH�S,�E�W�[�㺨�uch�⍸�O�}���a��>�q�6�n6����N6�q������N ! 1AQaq�0@����"2BRb�#Pr���3C`��Scst���$4D���%Td�� ?���N����a��3��m���C���w��������xA�m�q�m���m������$����4n淿t'��C"w��zU=D�\R+w�p+Y�T�&�պ@��ƃ��3ޯ?�Aﶂ��aŘ���@-�����Q�=���9D��ռ�ѻ@��M�V��P��܅�G5�f�Y<�u=,EC)�<�Fy'�"�&�չ�X~f��l�KԆV��?�� �W�N����=(� �;���{�r����ٌ�Y���h{�١������jW����P���Tc�����X�K�r��}���w�R��%��?���E��m�� �Y�q|����\lEE4���r���}�lsI�Y������f�$�=�d�yO����p�����yBj8jU�o�/�S��?�U��*������ˍ�0������u�q�m [�?f����a�� )Q�>����6#������� ?����0UQ����,IX���(6ڵ[�DI�MNލ�c&���υ�j\��X�R|,4��� j������T�hA�e��^���d���b<����n�� �즇�=!���3�^�`j�h�ȓr��jẕ�c�,ٞX����-����a�ﶔ���#�$��]w�O��Ӫ�1y%��L�Y<�wg#�ǝ�̗`�x�xa�t�w��»1���o7o5��>�m뭛C���Uƃߜ}�C���y1Xνm�F8�jI���]����H���ۺиE@I�i;r�8ӭ����V�F�Շ| ��&?�3|x�B�MuS�Ge�=Ӕ�#BE5G�����Y!z��_e��q�р/W>|-�Ci߇�t�1ޯќd�R3�u��g�=0 5��[?�#͏��q�cf���H��{ ?u�=?�?ǯ���}Z��z���hmΔ�BFTW�����<�q�(v� ��!��z���iW]*�J�V�z��gX֧A�q�&��/w���u�gYӘa���; �i=����g:��?2�dž6�ى�k�4�>�Pxs����}������G�9��3 ���)gG�R<>r h�$��'nc�h�P��Bj��J�ҧH� -��N1���N��?��~��}-q!=��_2hc�M��l�vY%UE�@|�v����M2�.Y[|y�"Eï��K�ZF,�ɯ?,q�?v�M 80jx�"�;�9vk�����+ ֧�� �ȺU��?�%�vcV��mA�6��Qg^M����A}�3�nl� QRN�l8�kkn�'�����(��M�7m9و�q���%ޟ���*h$Zk"��$�9��: �?U8�Sl��,,|ɒ��xH(ѷ����Gn�/Q�4�P��G�%��Ա8�N��!� �&�7�;���eKM7�4��9R/%����l�c>�x;������>��C�:�����t��h?aKX�bhe�ᜋ^�$�Iհ �hr7%F$�E��Fd���t��5���+�(M6�t����Ü�UU|zW�=a�Ts�Tg������dqP�Q����b'�m���1{|Y����X�N��b �P~��F^F:����k6�"�j!�� �I�r�`��1&�-$�Bevk:y���#yw��I0��x��=D�4��tU���P�ZH��ڠ底taP��6����b>�xa����Q�#� WeF��ŮNj�p�J* mQ�N����*I�-*�ȩ�F�g�3 �5��V�ʊ�ɮ�a��5F���O@{���NX��?����H�]3��1�Ri_u��������ѕ�� ����0��� F��~��:60�p�͈�S��qX#a�5>���`�o&+�<2�D����: �������ڝ�$�nP���*)�N�|y�Ej�F�5ټ�e���ihy�Z �>���k�bH�a�v��h�-#���!�Po=@k̆IEN��@��}Ll?j�O������߭�ʞ���Q|A07x���wt!xf���I2?Z��<ץ�T���cU�j��]��陎Ltl �}5�ϓ��$�,��O�mˊ�;�@O��jE��j(�ا,��LX���LO���Ц�90�O �.����a��nA���7������j4 ��W��_ٓ���zW�jcB������y՗+EM�)d���N�g6�y1_x��p�$Lv:��9�"z��p���ʙ$��^��JԼ*�ϭ����o���=x�Lj�6�J��u82�A�H�3$�ٕ@�=Vv�]�'�qEz�;I˼��)��=��ɯ���x �/�W(V���p�����$ �m�������u�����񶤑Oqˎ�T����r��㠚x�sr�GC��byp�G��1ߠ�w e�8�$⿄����/�M{*}��W�]˷.�CK\�ުx���/$�WPw���r� |i���&�}�{�X� �>��$-��l���?-z���g����lΆ���(F���h�vS*���b���߲ڡn,|)mrH[���a�3�ר�[1��3o_�U�3�TC�$��(�=�)0�kgP���� ��u�^=��4 �WYCҸ:��vQ�ר�X�à��tk�m,�t*��^�,�}D*� �"(�I��9R����>`�`��[~Q]�#af��i6l��8���6�:,s�s�N6�j"�A4���IuQ��6E,�GnH��zS�HO�uk�5$�I�4��ؤ�Q9�@��C����wp�BGv[]�u�Ov���0I4���\��y�����Q�Ѹ��~>Z��8�T��a��q�ޣ;z��a���/��S��I:�ܫ_�|������>=Z����8:�S��U�I�J��"IY���8%b8���H��:�QO�6�;7�I�S��J��ҌAά3��>c���E+&jf$eC+�z�;��V����� �r���ʺ������my�e���aQ�f&��6�ND��.:��NT�vm�<- u���ǝ\MvZY�N�NT��-A�>jr!S��n�O 1�3�Ns�%�3D@���`������ܟ 1�^c<���� �a�ɽ�̲�Xë#�w�|y�cW�=�9I*H8�p�^(4���՗�k��arOcW�tO�\�ƍR��8����'�K���I�Q�����?5�>[�}��yU�ײ -h��=��% q�ThG�2�)���"ו3]�!kB��*p�FDl�A���,�eEi�H�f�Ps�����5�H:�Փ~�H�0Dت�D�I����h�F3�������c��2���E��9�H��5�zԑ�ʚ�i�X�=:m�xg�hd(�v����׊�9iS��O��d@0ڽ���:�p�5�h-��t�&���X�q�ӕ,��ie�|���7A�2���O%P��E��htj��Y1��w�Ѓ!����  ���� ࢽ��My�7�\�a�@�ţ�J �4�Ȼ�F�@o�̒?4�wx��)��]�P��~�����u�����5�����7X ��9��^ܩ�U;Iꭆ 5 �������eK2�7(�{|��Y׎ �V��\"���Z�1� Z�����}��(�Ǝ"�1S���_�vE30>���p;� ΝD��%x�W�?W?v����o�^V�i�d��r[��/&>�~`�9Wh��y�;���R��� ;;ɮT��?����r$�g1�K����A��C��c��K��l:�'��3 c�ﳯ*"t8�~l��)���m��+U,z��`(�>yJ�?����h>��]��v��ЍG*�{`��;y]��I�T� ;c��NU�fo¾h���/$���|NS���1�S�"�H��V���T���4��uhǜ�]�v;���5�͠x��'C\�SBpl���h}�N����� A�Bx���%��ޭ�l��/����T��w�ʽ]D�=����K���ž�r㻠l4�S�O?=�k �M:� ��c�C�a�#ha���)�ѐxc�s���gP�iG��{+���x���Q���I= �� z��ԫ+ �8"�k�ñ�j=|����c ��y��CF��/��*9ж�h{ �?4�o� ��k�m�Q�N�x��;�Y��4膚�a�w?�6�>e]�����Q�r�:����g�,i"�����ԩA�*M�<�G��b�if��l^M��5� �Ҩ�{����6J��ZJ�����P�*�����Y���ݛu�_4�9�I8�7���������,^ToR���m4�H��?�N�S�ѕw��/S��甍�@�9H�S�T��t�ƻ���ʒU��*{Xs�@����f�����֒Li�K{H�w^���������Ϥm�tq���s� ���ք��f:��o~s��g�r��ט� �S�ѱC�e]�x���a��) ���(b-$(�j>�7q�B?ӕ�F��hV25r[7 Y� }L�R��}����*sg+��x�r�2�U=�*'WS��ZDW]�WǞ�<��叓���{�$�9Ou4��y�90-�1�'*D`�c�^o?(�9��u���ݐ��'PI&� f�Jݮ�������:wS����jfP1F:X �H�9dԯ���˝[�_54 �}*;@�ܨ�� ð�yn�T���?�ןd�#���4rG�ͨ��H�1�|-#���Mr�S3��G�3�����)�.᧏3v�z֑��r����$G"�`j �1t��x0<Ɔ�Wh6�y�6��,œ�Ga��gA����y��b��)��h�D��ß�_�m��ü �gG;��e�v��ݝ�nQ� ��C����-�*��o���y�a��M��I�>�<���]obD��"�:���G�A��-\%LT�8���c�)��+y76���o�Q�#*{�(F�⽕�y����=���rW�\p���۩�c���A���^e6��K������ʐ�cVf5$�'->���ՉN"���F�"�UQ@�f��Gb~��#�&�M=��8�ט�JNu9��D��[̤�s�o�~������ G��9T�tW^g5y$b��Y'��س�Ǵ�=��U-2 #�MC�t(�i� �lj�@Q 5�̣i�*�O����s�x�K�f��}\��M{E�V�{�υ��Ƈ�����);�H����I��fe�Lȣr�2��>��W�I�Ȃ6������i��k�� �5�YOxȺ����>��Y�f5'��|��H+��98pj�n�.O�y�������jY��~��i�w'������l�;�s�2��Y��:'lg�ꥴ)o#'Sa�a�K��Z� �m��}�`169�n���"���x��I ��*+� }F<��cГ���F�P�������ֹ*�PqX�x۩��,� ��N�� �4<-����%����:��7����W���u�`����� $�?�I��&����o��o��`v�>��P��"��l���4��5'�Z�gE���8���?��[�X�7(��.Q�-��*���ތL@̲����v��.5���[��=�t\+�CNܛ��,g�SQnH����}*F�G16���&:�t��4ُ"A��̣��$�b �|����#rs��a�����T�� ]�<�j��BS�('$�ɻ� �wP;�/�n��?�ݜ��x�F��yUn�~mL*-�������Xf�wd^�a�}��f�,=t�׵i�.2/wpN�Ep8�OР���•��R�FJ� 55TZ��T �ɭ�<��]��/�0�r�@�f��V��V����Nz�G��^���7hZi����k��3�,kN�e|�vg�1{9]_i��X5y7� 8e]�U����'�-2,���e"����]ot�I��Y_��n�(JҼ��1�O ]bXc���Nu�No��pS���Q_���_�?i�~�x h5d'�(qw52] ��'ޤ�q��o1�R!���`ywy�A4u���h<קy���\[~�4�\ X�Wt/� 6�����n�F�a8��f���z �3$�t(���q��q�x��^�XWeN'p<-v�!�{�(>ӽDP7��ո0�y)�e$ٕv�Ih'Q�EA�m*�H��RI��=:��� ���4牢) �%_iN�ݧ�l]� �Nt���G��H�L��� ɱ�g<���1V�,�J~�ٹ�"K��Q�� 9�HS�9�?@��k����r�;we݁�]I�!{ �@�G�[�"��`���J:�n]�{�cA�E����V��ʆ���#��U9�6����j�#Y�m\��q�e4h�B�7��C�������d<�?J����1g:ٳ���=Y���D�p�ц� ׈ǔ��1�]26؜oS�'��9�V�FVu�P�h�9�xc�oq�X��p�o�5��Ա5$�9W�V(�[Ak�aY錎qf;�'�[�|���b�6�Ck��)��#a#a˙��8���=äh�4��2��C��4tm^ �n'c���]GQ$[Wҿ��i���vN�{Fu ��1�gx��1┷���N�m��{j-,��x�� Ūm�ЧS�[�s���Gna���䑴�� x�p 8<������97�Q���ϴ�v�aϚG��Rt�Һ׈�f^\r��WH�JU�7Z���y)�vg=����n��4�_)y��D'y�6�]�c�5̪�\� �PF�k����&�c;��cq�$~T�7j ���nç]�<�g ":�to�t}�159�<�/�8������m�b�K#g'I'.W�����6��I/��>v��\�MN��g���m�A�yQL�4u�Lj�j9��#44�t��l^�}L����n��R��!��t��±]��r��h6ٍ>�yҏ�N��fU�� ���� Fm@�8}�/u��jb9������he:A�y�ծw��GpΧh�5����l}�3p468��)U��d��c����;Us/�֔�YX�1�O2��uq�s��`hwg�r~�{ R��mhN��؎*q 42�*th��>�#���E����#��Hv�O����q�}�����6�e��\�,Wk�#���X��b>��p}�դ��3���T5��†��6��[��@�P�y*n��|'f�֧>�lư΂�̺����SU�'*�q�p�_S�����M�� '��c�6�����m�� ySʨ;M��r���Ƌ�m�Kxo,���Gm�P��A�G�:��i��w�9�}M(�^�V��$ǒ�ѽ�9���|���� �a����J�SQ�a���r�B;����}���ٻ֢�2�%U���c�#�g���N�a�ݕ�'�v�[�OY'��3L�3�;,p�]@�S��{ls��X�'���c�jw�k'a�.��}�}&�� �dP�*�bK=ɍ!����;3n�gΊU�ߴmt�'*{,=SzfD� A��ko~�G�aoq�_mi}#�m�������P�Xhύ����mxǍ�΂���巿zf��Q���c���|kc�����?���W��Y�$���_Lv����l߶��c���`?����l�j�ݲˏ!V��6����U�Ђ(A���4y)H���p�Z_�x��>���e��R��$�/�`^'3qˏ�-&Q�=?��CFVR �D�fV�9��{�8g�������n�h�(P"��6�[�D���< E�����~0<@�`�G�6����Hг�cc�� �c�K.5��D��d�B���`?�XQ��2��ٿyqo&+�1^� DW�0�ꊩ���G�#��Q�nL3��c���������/��x ��1�1[y�x�პCW��C�c�UĨ80�m�e�4.{�m��u���I=��f�����0QRls9���f���������9���~f�����Ǩ��a�"@�8���ȁ�Q����#c�ic������G��$���G���r/$W�(��W���V�"��m�7�[m�A�m����bo��D� j����۳� l���^�k�h׽����� ��#� iXn�v��eT�k�a�^Y�4�BN��ĕ��0 !01@Q"2AaPq3BR������?���@4�Q�����T3,���㺠�W�[=JK�Ϟ���2�r^7��vc�:�9 �E�ߴ�w�S#d���Ix��u��:��Hp��9E!�� V 2;73|F��9Y���*ʬ�F��D����u&���y؟��^EA��A��(ɩ���^��GV:ݜDy�`��Jr29ܾ�㝉��[���E;Fzx��YG��U�e�Y�C���� ����v-tx����I�sם�Ę�q��Eb�+P\ :>�i�C'�;�����k|z�رn�y]�#ǿb��Q��������w�����(�r|ӹs��[�D��2v-%��@;�8<a���[\o[ϧw��I!��*0�krs)�[�J9^��ʜ��p1)� "��/_>��o��<1����A�E�y^�C��`�x1'ܣn�p��s`l���fQ��):�l����b>�Me�jH^?�kl3(�z:���1ŠK&?Q�~�{�ٺ�h�y���/�[��V�|6��}�KbX����mn[-��7�5q�94�������dm���c^���h� X��5��<�eޘ>G���-�}�دB�ޟ� ��|�rt�M��V+�]�c?�-#ڛ��^ǂ}���Lkr���O��u�>�-D�ry� D?:ޞ�U��ǜ�7�V��?瓮�"�#���r��չģVR;�n���/_� ؉v�ݶe5d�b9��/O��009�G���5n�W����JpA�*�r9�>�1��.[t���s�F���nQ� V 77R�]�ɫ8����_0<՜�IF�u(v��4��F�k�3��E)��N:��yڮe��P�`�1}�$WS��J�SQ�N�j�ٺ��޵�#l���ј(�5=��5�lǏmoW�v-�1����v,W�mn��߀$x�<����v�j(����c]��@#��1������Ǔ���o'��u+����;G�#�޸��v-lη��/(`i⣍Pm^���ԯ̾9Z��F��������n��1��� ��]�[��)�'������:�֪�W��FC����� �B9،!?���]��V��A�Վ�M��b�w��G F>_DȬ0¤�#�QR�[V��kz���m�w�"��9ZG�7'[��=�Q����j8R?�zf�\a�=��O�U����*oB�A�|G���2�54 �p��.w7� �� ��&������ξxGHp� B%��$g�����t�Џ򤵍z���HN�u�Я�-�'4��0��;_��3 !01"@AQa2Pq#3BR������?��ʩca��en��^��8���<�u#��m*08r��y�N"�<�Ѳ0��@\�p��� �����Kv�D��J8�Fҽ� �f�Y��-m�ybX�NP����}�!*8t(�OqѢ��Q�wW�K��ZD��Δ^e��!� ��B�K��p~�����e*l}z#9ң�k���q#�Ft�o��S�R����-�w�!�S���Ӥß|M�l޶V��!eˈ�8Y���c�ЮM2��tk���� ������J�fS����Ö*i/2�����n]�k�\���|4yX�8��U�P.���Ы[���l��@"�t�<������5�lF���vU�����W��W��;�b�cД^6[#7@vU�xgZv��F�6��Q,K�v��� �+Ъ��n��Ǣ��Ft���8��0��c�@�!�Zq s�v�t�;#](B��-�nῃ~���3g������5�J�%���O������n�kB�ĺ�.r��+���#�N$?�q�/�s�6��p��a����a��J/��M�8��6�ܰ"�*������ɗud"\w���aT(����[��F��U՛����RT�b���n�*��6���O��SJ�.�ij<�v�MT��R\c��5l�sZB>F��<7�;EA��{��E���Ö��1U/�#��d1�a�n.1ě����0�ʾR�h��|�R��Ao�3�m3 ��%�� ���28Q� ��y��φ���H�To�7�lW>����#i`�q���c����a��� �m,B�-j����݋�'mR1Ήt�>��V��p���s�0IbI�C.���1R�ea�����]H�6����������4B>��o��](��$B���m�����a�!=��?�B� K�Ǿ+�Ծ"�n���K��*��+��[T#�{E�J�S����Q�����s�5�:�U�\wĐ�f�3����܆&�)����I���Ԇw��E T�lrTf6Q|R�h:��[K�� �z��c֧�G�C��%\��_�a�84��HcO�bi��ؖV��7H �)*ģK~Xhչ0��4?�0��� �E<���}3���#���u�?�� ��|g�S�6ꊤ�|�I#Hڛ� �ա��w�X��9��7���Ŀ%�SL��y6č��|�F�a 8���b��$�sק�h���b9RAu7�˨p�Č�_\*w��묦��F ����4D~�f����|(�"m���NK��i�S�>�$d7SlA��/�²����SL��|6N�}���S�˯���g��]6��; �#�.��<���q'Q�1|KQ$�����񛩶"�$r�b:���N8�w@��8$�� �AjfG|~�9F ���Y��ʺ��Bwؒ������M:I岎�G��`s�YV5����6��A �b:�W���G�q%l�����F��H���7�������Fsv7��k�� 403WebShell
403Webshell
Server IP : 54.89.25.11  /  Your IP : 216.73.216.255
Web Server : Apache/2.4.7 (Ubuntu)
System : Linux ip-172-31-88-18 3.13.0-74-generic #118-Ubuntu SMP Thu Dec 17 22:52:10 UTC 2015 x86_64
User : www-data ( 33)
PHP Version : 5.5.9-1ubuntu4.24
Disable Function : pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,
MySQL : ON  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : ON  |  Pkexec : ON
Directory :  /var/www/html/kalemon/module-old/Assessment/src/Assessment/Controller/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /var/www/html/kalemon/module-old/Assessment/src/Assessment/Controller/IndexController.php
<?php

/**
 * @desc used of this controller for create Assessment
 * @author  Piron Corporation
 * @dev     Rizban Ahmad
 * @created on 21-03-2017
 */

namespace Assessment\Controller;

use Zend\Form\FormInterface;
use Zend\Db\TableGateway\TableGateway;
use Zend\View\Model\JsonModel;
use Zend\View\Model\ViewModel;
use Assessment\Form\CreateQuizForm;
use Assessment\Form\PublishForm;
use Assessment\Form\PullQusForm;
use Assessment\Model\CreateQuizInputFilter;
use Assessment\Model\PullQusInputFilter;
use Checkondispatch\Custom\AbstractSecureController;
use Aws\Sdk;
use Zend\Math\Rand;
use Zend\Json\Json;
use Zend\Validator\File\Size;
use Zend\Validator\File\Extension;
use Zend\Dom\Query;
use Zend\Validator\ValidatorChain;
use Zend\Session\Container;
use Assessment\Controller\questionFunctionTrait;
use Assessment\Controller\placementFunctionTrait;
use Assessment\Form\CurriculumHierarchyFilterForm;

class IndexController extends AbstractSecureController {

    use questionFunctionTrait;
    use placementFunctionTrait;
    use TestDetailTrait;


    public function __construct() {
        $this->container = new Container('auth');
        $this->authContainer = new Container('auth');
    }

    /**
     * @desc set view property
     */
    public $acceptCriteria = [
        'Zend\View\Model\JsonModel' => ['application/json'],
        'Zend\View\Model\ViewModel' => ['text/html'],
    ];

    private function getTestPlugin() {
        if (!$this->testPlugin) {
            $this->testPlugin = new \Test\Controller\Plugin\TestCommonPlugin($this->getServiceLocator());
        }
        return $this->testPlugin;
    }

    

    /**
     * @dec use of this action for display quiz listing
     * @return render page.
     */
    public function indexAction() {
        $translator = $this->getServiceLocator()->get('translator');
        $config = $this->getServiceLocator()->get('config');
        $this->AssessmentPlugin()->setCustomLayout($this, 'assessmentLayout');
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $request = $this->getRequest();
        $requestData = $request->getPost()->toArray();
        $requestData['sortColumn'] = (isset($requestData['sortColumn']) && !empty($requestData['sortColumn'])) ? $requestData['sortColumn'] : "QUIZ_ID";
        $requestData['sortType'] = ( isset($requestData['sortType']) && !empty($requestData['sortType'])) ? $requestData['sortType'] : "DESC";
        $requestData['START'] = 0;
        $requestData['LENGTH'] = $config["RECORDS_PER_PAGE"];
        $createQuizTable = $this->initTable('Assessment\Model\CreateQuizTable');
        if ($request->isXmlHttpRequest()) {
            if (isset($_POST['searchfor']) && !empty($_POST['searchfor'])) {
                $requestData['searchKey'] = $_POST['searchfor'];
                $requestData['searchColumn'] = 'TITLE';
                $requestData['START'] = !empty($requestData['start']) ? $requestData['start'] : 0;
            } else { // code to display quiz listing while scrolling down by user
                $requestData['START'] = !empty($requestData['start']) ? $requestData['start'] : 0;
            }
            $quizList = $createQuizTable->getTestList($requestData);
            $htmlViewPart = new ViewModel();
            $htmlViewPart->setTerminal(true)
                    ->setTemplate('assessment/index/listquiz.phtml')
                    ->setVariables(array('quizData' => $quizList));
            $htmlOutput = $this->getServiceLocator()->get('viewrenderer')->render($htmlViewPart);
            $jsonModel = new JsonModel();
            $jsonModel->setVariables(array(
                'responseData' => $htmlOutput
            ));
            return $jsonModel;
        }
        $quizList = $createQuizTable->getTestList($requestData);
        $viewModel->setVariables(array('quizData' => $quizList));
        return $viewModel;
    }

    /*
     * @desc Use of this function for get Unique topic list from api that we have used in our questions
     */

    public function getExistTopicFromAPI() {
        $questionTable = $this->initTable('Assessment\Model\QuestionTable');
        $topicsIdsArr = $questionTable->getAllUniqTopicIds();
        $topicsIdsString = (!empty($topicsIdsArr)) ? implode(',', $topicsIdsArr) : '';

        return $topicFromApi = $this->getSubjectUnitTopicByTopicID($topicsIdsString);
    }

    /**
     * @dec Assessment listing
     * @return render page.
     */
    public function listAssessmentAction() {

        $this->AssessmentPlugin()->setCustomLayout($this, 'assessmentLayout');
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $viewModel->setVariables(array('data' => ''));
        return $viewModel;
    }

    /**
     * @dec list all response of users
     * @return render page.
     */
    public function studentResponsesAction() {

        $this->AssessmentPlugin()->setCustomLayout($this, 'assessmentLayout');
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $viewModel->setVariables(array('data' => ''));
        return $viewModel;
    }

    /**
     * @dec give result of users
     * @return render page.
     */
    public function resultAfterSubmitAction() {

        $this->AssessmentPlugin()->setCustomLayout($this, 'assessmentLayout');
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $viewModel->setVariables(array('data' => ''));
        return $viewModel;
    }

    /**
     * @dec give  user response
     * @return render page.
     */
    public function userResponseAction() {

        $this->AssessmentPlugin()->setCustomLayout($this, 'assessmentLayout');
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $viewModel->setVariables(array('data' => ''));
        return $viewModel;
    }

    /**
     * @desc used of this action for render add/edit quiz (Test) page
     * @return JsonModel
     */
    public function addAction() {
        $config = $this->getServiceLocator()->get('config');
        $translator = $this->getServiceLocator()->get('translator');
        $this->AssessmentPlugin()->setCustomLayout($this, 'assessmentLayout');
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $ORG_ID = $this->container->authDetail['ORG_ID'];
        $utId = $this->container->authDetail['UT_ID'];
        //$countryList = $this->getCountries();
        $localGradeList = $this->getGradesLocal();
        $currHierarFilterForm = new CurriculumHierarchyFilterForm($localGradeList);
        $CreateQuizForm = new CreateQuizForm($translator);
        $PullQusForm = new PullQusForm();
        $PublishForm = new PublishForm();
        $isEssayTypeQuesExists = false;
        $createQuizTable = $this->initTable('Assessment\Model\CreateQuizTable');
        $questionTable = $this->initTable('Assessment\Model\QuestionTable');
        $curriculumTable = $this->initTable('Curriculum\Model\CurriculumTable');
        $createTestTable = $this->initTable('Test\Model\CreateQuizTable');
        $QnsTypeData = $questionTable->getQuestionsType();
        $bankData = $questionTable->getBankUUidByOrgId($ORG_ID);
        $uuid = !empty($bankData) ? $bankData['BANK_UUID'] : "";
        $QnsBankData = []; //$this->getTestPlugin()->getBank($uuid);
        $CognitiveData = $questionTable->fetchData('t_adm_cnf_cognitive', null, array('*'), 'COGNITIVE_ID DESC', true);
        $quizId = !empty($this->params('id')) ? $this->params('id') : '';

        /* Redirect with access test using another org Id */
        if (!empty($quizId)) {
            $orgId = $this->container->authDetail['ORG_ID'];
            $userType = $this->container->authDetail['USER_TYPE'];
            $oId = $createTestTable->getTestAuthentication($quizId);
            if ($orgId != $oId) {
                $config = $this->serviceLocator->get('config');
                $route = $config['user_auth_redirect'][$userType]['route'];
                $action = $config['user_auth_redirect'][$userType]['action'];
                return $this->redirect()->toRoute($route, array('action' => $action));
            }
        }
        /* ---- */

        $request = $this->getRequest();
        $requestData = $request->getQuery()->toArray();
        $qusList = $QuestionsData = $allQsnOfQuiz = $populateData = array();
        $quizTitle = $quiz_mode = $serverTopics = $qusIdsStr = ''; 
        $qusCount = $QusMark = $sumOfQusMark = 0;
        $questionTypeArray = $apiCognitive = [];
        $displayTabActived = ($this->params('edit') !== null) ? $this->params('edit') : 1;
        // cognitive from API
        /*$assessment_plugin = $this->AssessmentPlugin();                
        $cognitiveDataAPI = $assessment_plugin->getCognitive();
        foreach($cognitiveDataAPI as $apiCog) {
            $apiCognitive[$apiCog['COGNITIVE_ID']] = $apiCog['COGNITIVE_NAME'];
        }*/
        
        /** get all local cognitives. */
        $apiCognitive = $this->getCognitive();
        
        $quesType = $createQuizTable->fetchData('t_master_question_type', array('STATUS' => 'A'), array('*'));
        foreach($quesType as $ques_type) {
            $questionTypeArray[$ques_type['QUESTYPE_ID']] = $ques_type['QUES_TYPE'];
        }
        $lpId = (!empty($this->getRequest()->getQuery('lpId'))) ? $this->getRequest()->getQuery('lpId') : '';
        $lastQusId = (!empty($this->getRequest()->getQuery('lastQusId'))) ? $this->getRequest()->getQuery('lastQusId') : '';
        $quiz_type = (!empty($this->getRequest()->getQuery('test_type'))) ? $this->getRequest()->getQuery('test_type') : '';
        $edit_from = (!empty($this->getRequest()->getQuery('edit_from'))) ? $this->getRequest()->getQuery('edit_from') : '';
        $level_id = (!empty($this->getRequest()->getQuery('test_level'))) ? $this->getRequest()->getQuery('test_level') : 0;
        $test_subject = (!empty($this->getRequest()->getQuery('test_subject'))) ? $this->getRequest()->getQuery('test_subject') : '';
        $test_create_mode = (!empty($this->getRequest()->getQuery('test_create_mode'))) ? $this->getRequest()->getQuery('test_create_mode') : '';
        
        $this->layout()->setVariable('quiz_type', $quiz_type);
        if (!empty($quizId)) {
            $conditions = array('QUIZ_ID' => $quizId);
            $populateData = $createQuizTable->fetchData('t_master_test', $conditions, array('*'), '', false);
            if (empty($populateData)) {
                return $this->redirect()->toRoute('course', array('controller' => 'course', 'action' => 'list-course'));
            }
            $allQsnOfQuiz = $createQuizTable->getAllQsnByQuiz($quizId);
        }

        $paginData = [];
        $paginData['userId'] = $this->container->authDetail['USER_OID'];
        $topicArr = [0];
        $topicApiArr = [0];
        $gradeArr = [0];
        $subjectArr = [0];

        /** Used to prepare quiz-LP's topics as an array to get these topic associated question only(In 2nd tab of quiz). */
        $quiz_lp_topics = [];
        $quiz_lp_topics_array = [];
        if (!empty($quizId) && $quiz_type == 'ST') {
            $joins[] = ['t_cm_lessonplan_topic', 't_cm_lessonplan_topic.LESSONPLAN_ID = t_mgr_test_lessonplan.LESSONPLAN_ID', ['TOPIC_ID']];
            $joins[1] = ['t_cm_mgr_curriculum_outline', 't_cm_mgr_curriculum_outline.CAT_ID = t_cm_lessonplan_topic.TOPIC_ID', ['CAT_ID', 'ADM_REF_ID', 'CAT_NAME']];
            $quiz_lp_topics_data = $createQuizTable->fetchData('t_mgr_test_lessonplan', ['t_mgr_test_lessonplan.QUIZ_ID' => $quizId], ['LESSONPLAN_ID'], null, true, null, null, null, null, null, null, $joins);

            if (count($quiz_lp_topics_data)) {
                foreach ($quiz_lp_topics_data as $topicData) {
                    $quiz_lp_topics[] = $topicData['CAT_ID'];
                    $quiz_lp_topics_array[$topicData['CAT_ID']] = $topicData['CAT_NAME'];
                }
            }
            /** Only unique topic-id array for local. */
            $quiz_lp_topics = array_unique($quiz_lp_topics);

            /** Unique Key-value pair of topic-id and topic name respectively for local. */
            $quiz_lp_topics_array = array_unique($quiz_lp_topics_array);
        }

        if (!$test_subject) {
            if ($utId == 5) { // for admin
                $grades = $curriculumTable->fetchData('t_cm_mgr_grade', array('ORG_ID' => $this->container->authDetail['ORG_ID']), array('GRADE_ID'));
                if (!empty($grades)) {
                    foreach ($grades as $grade) {
                        $gradeArr[] = $grade["GRADE_ID"];
                    }
                }

                $subjects = $createQuizTable->fetchData('t_cm_mgr_subject', ['GRADE_ID' => $gradeArr], ['SUBJECT_ID']);
                if (!empty($subjects)) {
                    foreach ($subjects as $subject) {
                        $subjectArr[] = $subject["SUBJECT_ID"];
                    }
                }

                $topics = $createQuizTable->fetchData('t_cm_mgr_curriculum_outline', ['SUBJECT_ID' => $subjectArr], ['CAT_ID']);
                if (!empty($topics)) {
                    foreach ($topics as $topic) {
                        $topicArr[] = $topic["CAT_ID"];
                    }
                }
            } else if ($utId == 2) {
                $subjects = [0];
                $subjects = $curriculumTable->getAssignSubjectById($paginData['userId']);
                $topics = $createQuizTable->fetchData('t_cm_mgr_curriculum_outline', ['SUBJECT_ID' => $subjects], ['CAT_ID']);
                if (!empty($topics)) {
                    foreach ($topics as $topic) {
                        $topicArr[] = $topic["CAT_ID"];
                    }
                }
            }
        }

        /* Count */
        $paginData['topicId'] = (count($quiz_lp_topics) && $quiz_type == 'ST') ? $quiz_lp_topics :$topicArr;
        $totalQuestionsData = (!count($quiz_lp_topics) && $quiz_type == 'ST') ? [] : $questionTable->getAllQuestions($paginData);

        if ($displayTabActived == 3) {
            $serverTopics = (!empty($requestData['topicsFromServer'])) ? $requestData['topicsFromServer'] : '';
        }
        if ($displayTabActived == 2 && $request->isXmlHttpRequest()) {
            $requestData = $request->getPost();            
            if(!empty($test_create_mode) && $test_create_mode == 'AT') {                
                if(!empty($populateData)) {
                    $allQuesForTest = $createQuizTable->getAllQuesByQuizId($quizId);                                        
                    $qusCount = count($allQuesForTest);
                    if(!empty($allQuesForTest)) {
                        foreach($allQuesForTest as $questionArr) {
                            $QusMark += $questionArr['QUS_MARK'];
                            if(empty($questionArr['QUS_REF_ID'])) {
                                $qusIdsStr .= $questionArr['QUS_ID'].',';
                            }
                        }
                    }                   
                }                
                $viewModel->setVariables([
                    'testId' => $quizId,
                    'lpId' => $lpId,
                    'test_type' => $populateData['QUIZ_TYPE'],                    
                    'quiz_mode' => $populateData['QUIZ_MODE'],
                    'getLocalGrades' => $localGradeList,
                    'test_create_mode' => $test_create_mode,
                    'questionTypeArray' => $questionTypeArray,
                    'apiCognitive' => $apiCognitive,
                    'qusCount' => $qusCount,
                    'QusMark' => $QusMark,
                    'qusIdsStr' => substr($qusIdsStr, 0, -1),
                ]);
            } else {
            $serverTopics = (!empty($requestData['topicsFromServer'])) ? $requestData['topicsFromServer'] : '';
            $paginData['searchfor'] = (!empty($requestData['searchfor'])) ? $requestData['searchfor'] : null;
            $paginData['banktext'] = (!empty($requestData['banktext'])) ? $requestData['banktext'] : "";
            $paginData['difficultyLevel'] = (!empty($requestData['difficultyLevel'])) ? $requestData['difficultyLevel'] : "";
            $paginData['qnsType'] = (!empty($requestData['qnsType'])) ? $requestData['qnsType'] : "";
            $paginData['cognitiveId'] = (!empty($requestData['cognitiveId'])) ? $requestData['cognitiveId'] : null;
            $paginData['START'] = !empty($requestData['start']) ? $requestData['start'] : 0;
            $paginData['LENGTH'] = $config["RECORDS_PER_PAGE"];
            
            /** Get exploded topics when request comes from AJAX (as advance search) and handle other cases for topics as well. */
            $requestData['topicId'] = isset($requestData['topicId']) && gettype($requestData['topicId'] == 'string') ? explode(',', $requestData['topicId']) : (isset($requestData['topicId']) ? $requestData['topicId'] : []);
            $paginData['topicId'] = (isset($requestData['isAdvanceSearch']) && $requestData['isAdvanceSearch']) ? (!empty($requestData['topicId']) ? $requestData['topicId'] : [0]) : (((count($quiz_lp_topics) && $quiz_type == 'ST')) ? $quiz_lp_topics :(count($topicArr) ? $topicArr : null));            
            
            $allQsnOfQuiz = $createQuizTable->getAllQsnByQuiz($quizId);
            $QuestionsData = (!count($quiz_lp_topics) && $quiz_type == 'ST') ? [] : $questionTable->getAllQuestions($paginData);
            $getQuestionIds = (!count($quiz_lp_topics) && $quiz_type == 'ST') ? [] : $questionTable->getAllQuestions($paginData, false, true);

            /** Get all Question-id`s with or without search criteria */
            if (count($getQuestionIds)) {
                foreach ($getQuestionIds as $data) {
                    $all_local_ques_ids[] = $data['QUS_ID'];
                }
            }
            /* Count */
            $totalData['searchfor'] = (!empty($requestData['searchfor'])) ? $requestData['searchfor'] : null;
            $totalData['banktext'] = (!empty($requestData['banktext'])) ? $requestData['banktext'] : "";
            $totalData['difficultyLevel'] = (!empty($requestData['difficultyLevel'])) ? $requestData['difficultyLevel'] : "";
            $totalData['qnsType'] = (!empty($requestData['qnsType'])) ? $requestData['qnsType'] : "";
            $totalData['cognitiveId'] = (!empty($requestData['cognitiveId'])) ? $requestData['cognitiveId'] : null;
            $totalData['topicId'] = (isset($requestData['isAdvanceSearch']) && $requestData['isAdvanceSearch']) ? (!empty($requestData['topicId']) ? $requestData['topicId'] : [0]) : (((count($quiz_lp_topics) && $quiz_type == 'ST')) ? $quiz_lp_topics :(count($topicArr) ? $topicArr : null));
            $totalData['userId'] = $this->container->authDetail['USER_OID'];
            $totalFilterQuestionsData = (!count($quiz_lp_topics) && $quiz_type == 'ST') ? [] : $questionTable->getAllQuestions($totalData);
            /* ------ */
            $htmlViewPart = new ViewModel();
            $htmlViewPart->setTerminal(true)->setTemplate('assessment/index/search-filter-data.phtml')
                    ->setVariables(array(
                        'QuestionsData' => $QuestionsData,
                        'serverTopics' => $serverTopics,
                        'allQsnOfQuiz' => $allQsnOfQuiz,
                        'start' => $paginData['START'],
                        'lastQusId' => $lastQusId,
                        'totalFilterQuestionsData' => count($totalFilterQuestionsData),
                        'allLocalQuesIds' => isset($all_local_ques_ids) && count($all_local_ques_ids) ? $all_local_ques_ids : []
            ));
            $htmlOutput = $this->getServiceLocator()->get('viewrenderer')->render($htmlViewPart);
            $jsonModel = new JsonModel();
            $jsonModel->setVariables(array(
                'responseData' => $htmlOutput
            ));

            return $jsonModel;
        }
        }        
        //echo '<pre>';print_r($populateData);die;
        if (!empty($populateData)) { // if request comes for edit quiz
            $allQuesForTest = $createQuizTable->getAllQuesByQuizId($quizId);                                        
            $qusCount = count($allQuesForTest);
            if (!empty($allQuesForTest)) {
                foreach ($allQuesForTest as $questionArr) {
                    /** Set question mark if given else set as their default one. */
                    if ($questionArr['QUS_MARK']) {
                        $sumOfQusMark += $questionArr['QUS_MARK'];
                    } else {
                        /** Default marks for local question(s). */
                        if (empty($questionArr['QUS_REF_ID'])) {
                            $sumOfQusMark += $createQuizTable->getDefaulQuesMarkByQuesId($questionArr['QUS_ID']);
                        }
                    }
                    if (empty($questionArr['QUS_REF_ID'])) {
                        $qusIdsStr .= $questionArr['QUS_ID'] . ',';
                    }
                }
            }
            
            $quizTitle = $populateData->TITLE;
            $quiz_mode = $populateData->QUIZ_MODE;
            $quiz_type = $populateData->QUIZ_TYPE;
            $qusIdsStr = substr($qusIdsStr, 0, -1);
            $QusMark = $sumOfQusMark;
            $noOfQus = $createQuizTable->sumQusetion($quizId);
            $qusCount = $createQuizTable->countQuestion($quizId);
            $CreateQuizForm->bind($populateData);
            $startDaeArr = explode(' ', $populateData->ASSIGN_DATE);
            $date = isset($startDaeArr[0]) ? $startDaeArr[0] : '';
            $time = isset($startDaeArr[1]) ? $startDaeArr[1] : '';
            $CreateQuizForm->get('START_TIME')->setValue($time);
            $CreateQuizForm->get('ASSIGN_DATE')->setValue($date);
            if (!empty($populateData->END_DATE)) {
                $endDateArr = explode(' ', $populateData->END_DATE);
                $date = isset($endDateArr[0]) ? $endDateArr[0] : '';
                $time = isset($endDateArr[1]) ? $endDateArr[1] : '';
                $CreateQuizForm->get('END_TIME')->setValue($time);
                $CreateQuizForm->get('END_DATE')->setValue($date);
            }
            // Used to make 2 precsion decimal value
            if (!empty($populateData->CORRECTNESS)) {
                $formattedCorrectness = number_format($populateData->CORRECTNESS, 2);
                $formattedParticipation = number_format(1 - $populateData->CORRECTNESS, 2);
                $CreateQuizForm->get('CORRECTNESS')->setValue($formattedCorrectness);
                $CreateQuizForm->get('PARTICIPATION')->setValue($formattedParticipation);
            } else {
                $CreateQuizForm->get('CORRECTNESS')->setValue(1);
                $CreateQuizForm->get('PARTICIPATION')->setValue(0);
            }
            $qusList = $this->fetchQusByQuizId($createQuizTable, null, $quizId);
        }

        $topicsFromServer = [];
        $all_local_ques_ids = [];
        if ($displayTabActived == 2 || $displayTabActived == 3) {
            //$curriculumTable = $this->initTable('Curriculum\Model\CurriculumTable');
            //$topicsFromServer = $curriculumTable->getCategoryTreeWithOutDepth();

            /** Get all Question-id`s with or without search criteria */
            if (count($totalQuestionsData)) {
                foreach ($totalQuestionsData as $data) {
                    $all_local_ques_ids[] = $data['QUS_ID'];
                }
            }
        }
        if ($displayTabActived == 3 && count($allQsnOfQuiz) == 0) {
            return $this->redirect()->toRoute('assessment', array('controller' => 'index', 'action' => 'add', 'id' => $quizId, 'edit' => '2'),array('query'=>array('edit_from'=>$edit_from,'quiz_type'=>$quiz_type)));
        }
        if ($displayTabActived == 4) {
            /**
             * This block being check that, this test contains any essay type question or not
             */
            // check with local question
            $allLocalQsnTypeOfQuiz = $createQuizTable->getAllLocalQsnTypeByTestId($quizId);
            if (!empty($allLocalQsnTypeOfQuiz)) {
                foreach ($allLocalQsnTypeOfQuiz as $qus) {
                    if ($qus['QUS_TYPE'] == 1)
                        $isEssayTypeQuesExists = true;
                }
            }
            /**
             * End Block
             */
            foreach ($qusList as $checkMarks) {
                if ($checkMarks['QUS_MARK'] == 0) {
                    return $this->redirect()->toRoute('assessment', array('controller' => 'index', 'action' => 'add', 'id' => $quizId, 'edit' => '3'));
                }
            }
        }
        
        $viewModel->setVariables([
            'form' => $CreateQuizForm,
            'displayTabActived' => $displayTabActived,
            'quizId' => $quizId,
            'lpId' => $lpId,
            'data' => $qusList,
            'PullQusForm' => $PullQusForm,
            'quizTitle' => $quizTitle,
            'quiz_mode' => $quiz_mode,
            'QusMark' => $QusMark,
            'qusIdsStr' => $qusIdsStr,
            'questionTypeArray' => $questionTypeArray,
            'apiCognitive' => $apiCognitive,
            'getLocalGrades' => $localGradeList,
            'reviewQuiz' => $populateData,
            'noOfQus' => isset($noOfQus) ? $noOfQus : '',
            'PublishForm' => $PublishForm,
            'qusCount' => isset($qusCount) ? $qusCount : '',
            'QuestionsData' => $QuestionsData,
            'allQsnOfQuiz' => $allQsnOfQuiz,
            'QnsTypeData' => $QnsTypeData,
            'QnsBankData' => $QnsBankData,
            "cognitiveData" => $CognitiveData,
            'topicsFromServer' => $topicsFromServer,
            'totalQuestion' => count($totalQuestionsData),
            'serverTopics' => $serverTopics,
            'lastQusId' => $lastQusId,
            'quiz_type' => $quiz_type,
            'level_id' => $level_id,
            'currHierarFilterForm' => $currHierarFilterForm,
            'isEssayTypeQuesExists' => $isEssayTypeQuesExists,
            'allLocalQuesIds' => count($all_local_ques_ids) ? $all_local_ques_ids : [],
            'test_subject' => $test_subject,
            'quizTopicsArray' => (count($quiz_lp_topics_array) && $quiz_type == 'ST') ? $quiz_lp_topics_array : [],
            'edit_from'=>$edit_from
        ]);

        return $viewModel;
    }

    /**
     * @desc used of this action for save data to t_mgr_test_question table.
     * @updated by SAIF <shakeel.saif@veative.com>
     * @updated on 12.04.18
     * @return void | JSON
     */
    public function addQsnToAtTestAction() {
        $htmlViewPart = new ViewModel();
        $htmlViewPart->setTerminal(true);
        $postData = $this->getRequest()->getPost()->toArray();
        $QUZ_ID = $this->params('id');

        if (!empty($postData['allQuestions'])) {
            $createQuizTable = $this->initTable('Assessment\Model\CreateQuizTable');
            $allQuestions = substr($postData['allQuestions'], 0, -1);
            $allQuestionsArr = explode(",", $allQuestions);
            $createQuizTable->addQsnToAtTest($QUZ_ID, $allQuestionsArr);
        }
        $array['result'] = 1;
        echo json_encode($array);
        die;
    }

    /**
     * @desc used of this action for save API/LOCAL question(s) to t_mgr_test_question table.
     */
    public function addQsnToTestAction() {
        $request = $this->getRequest();
        $postData = $request->getPost()->toArray();
        $htmlViewPart = new ViewModel();
        $htmlViewPart->setTerminal(true);
        $QUZ_ID = $this->params('id');
        $createQuizTable = $this->initTable('Assessment\Model\CreateQuizTable');

        /** Single/Multiple Question(s) ADD case only. */
        if (!empty($postData['allQuestions'])) {
            $allQuestions = substr($postData['allQuestions'], 0, -1);
            $allQuestionsArr = explode(",", $allQuestions);
            $quesFromLocaldb = [];
            $quizStoredData = [];

            /** Get all Stored Question(s) in DB to match current Question(s) */
            if (!empty($QUZ_ID)) {
                $quizStoredDataArray = $createQuizTable->fetchData('t_mgr_test_question', ["QUZ_ID" => $QUZ_ID], ['QUS_ID']);
                foreach ($quizStoredDataArray as $quizData) {
                    $quizStoredData[] = $quizData['QUS_ID'];
                }
            }

            foreach ($allQuestionsArr as $quesId) {
                /** Skip LOCAL current Question into array after DELETE from DB. */
                if ($postData['action'] == 'DELETE') {
                    $createQuizTable->deleteData('t_mgr_test_question', ["QUZ_ID" => $QUZ_ID, "QUS_ID" => $quesId]);
                    continue;
                }
                /** Skip LOCAL current Question into array if this one already stored in DB. */
                if (count($quizStoredData) && in_array($quesId, $quizStoredData)) {
                    continue;
                }
                $quesFromLocaldb[] = $quesId;
            }

            /** Multiple ADD and Delete from LOCAL Tab. */
            if (!empty($quesFromLocaldb)) {
                if ($postData['action'] == 'ADD') {
                    $createQuizTable->addQsnToTest($QUZ_ID, $quesFromLocaldb);
                } else {
                    $createQuizTable->deleteData('t_mgr_test_question', ["QUZ_ID" => $QUZ_ID, "QUS_ID" => $quesFromLocaldb]);
                }
            }
        }

        /** Get displayed Question count after ADD/Delete. */
        if (!empty($QUZ_ID)) {
            $countData = $createQuizTable->countData('t_mgr_test_question', ["QUZ_ID" => $QUZ_ID]);
        }

        $array['result'] = 1;
        $array['data_count'] = $countData;
        echo json_encode($array);
        die;
    }

    /**
     * @desc used to store uploading image locallay
     */
    public function uploadTempAction() {
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $viewModel->setTerminal(true);
        $request = $this->getRequest();
        $postData = $request->getFiles()->toArray();
        $path = $postData['file']['name'];
        $ext = pathinfo($path, PATHINFO_EXTENSION);
        $time = time();
        $fileName = $time . '.' . $ext;
        $movefile = move_uploaded_file($postData['file']['tmp_name'], getcwd() . "/public/upload/" . $fileName);
        $filedetails['path'] = $this->returnBasePath() . "/upload/" . $fileName;
        $filedetails['BACKING_FILE'] = $fileName;

        echo json_encode($filedetails);
        die;
    }

    /**
     * @Desc To upload summernote images locally and after form submit, this will go to S3.
     */
    public function uploadSummernoteImageAction() {
        $config = $this->getServiceLocator()->get('config');
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $viewModel->setTerminal(true);
        $request = $this->getRequest();
        $fileArray = $request->getFiles()->toArray();
        $postRequest = $request->getPost()->toArray();
        $path = $fileArray['file']['name'];
        $ext = pathinfo($path, PATHINFO_EXTENSION);
        $fileName = time() . '.' . $ext;
        $fileArray['file']['name'] = $fileName;
        $type = strtolower(end(explode('.', $fileName)));
        $formid = $this->params('id');
        $formname = $config['QUES_TYPE_URL'][$formid];
        $movefile = move_uploaded_file($fileArray['file']['tmp_name'], getcwd() . "/public/upload/" . $fileName);
        $filedetails['detail']['fullPath'] = $this->returnBasePath() . "/upload/" . $fileName;
        ;
        $filedetails['detail']['BACKING_FILE'] = $fileName;
        echo json_encode($filedetails);
        die;
    }

    /**
     * @desc used to save cropped subject image
     */
    public function saveCropedImgAction() {
        if (!empty($_REQUEST['fileName'])) {
            $jpeg_quality = 95;
            $fileName = end(explode("/", $_POST['fileName']));
            $targ_w = isset($_POST['width']) ? $_POST['width'] : 750;
            $targ_h = isset($_POST['height']) ? $_POST['height'] : 421;
            $targetDir = "public/upload/";
            $src = $targetDir . $fileName;
            $thumb = $targetDir . $fileName;
            $type = strtolower(end(explode('.', $fileName)));
            if ($type == 'jpeg' || $type == 'jpg') {
                $img_r = imagecreatefromjpeg($src);
                $dst_r = ImageCreateTrueColor($targ_w, $targ_h);
                imagecopyresampled($dst_r, $img_r, 0, 0, $_POST['x'], $_POST['y'], $targ_w, $targ_h, $_POST['w'], $_POST['h']);
                imagejpeg($dst_r, $thumb, $jpeg_quality);
            } else if ($type == 'gif') {
                $img_r = imagecreatefromgif($src);
                $dst_r = imagecreatetruecolor($targ_w, $targ_h);
                imagecopyresampled($dst_r, $img_r, 0, 0, $_POST['x'], $_POST['y'], $targ_w, $targ_h, $_POST['w'], $_POST['h']);
                imagegif($dst_r, $thumb, $jpeg_quality);
            } else if ($type == 'png') {
                $img_r = imagecreatefrompng($src);
                $dst_r = imagecreatetruecolor($targ_w, $targ_h);
                /* Added to prevent black bg for png images */
                imagealphablending($dst_r, false);
                imagesavealpha($dst_r, true);
                $transparent = imagecolorallocatealpha($dst_r, 255, 255, 255, 127);
                imagefilledrectangle($dst_r, 0, 0, $targ_w, $targ_h, $transparent);
                /* ---- */
                @imagecopyresampled($dst_r, $img_r, 0, 0, $_POST['x'], $_POST['y'], $targ_w, $targ_h, $_POST['w'], $_POST['h']);
                imagepng($dst_r, $thumb);
            }
            $dataPath = $this->returnBasePath() . "/upload/" . $fileName;
            $filePath = getcwd() . '/public/upload/' . $fileName;
            chmod($filePath, 0777);
            $ret = ['BACKING_FILE' => $fileName, 'status' => true, 'fullPath' => $dataPath];
            echo json_encode($ret);
            die;
        }
    }

    /**
     * @desc used to display unit listing as per unit id
     */
    public function awsUploadAction() {
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $viewModel->setTerminal(true);
        if (!empty($_POST['fileName']) && !empty($_POST['repository'])) {
            $this->uploadS3File($_POST['fileName'], $_POST['repository']);
        } else {
            $response['fileName'] = '';
            $response['repository'] = '';
            $response['message'] = 'File name and Repository name are missing';
            echo json_encode($response);
            die;
        }
    }

    /**
     * @desc used of this action for save data to create and edit quiz
     */
    public function saveTestAction() {
        $this->AssessmentPlugin()->setCustomLayout($this, 'assessmentLayout');
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $createQuizTable = $this->initTable('Assessment\Model\CreateQuizTable');
        $translator = $this->getServiceLocator()->get('translator');
        $result = ['result' => false, 'message' => ''];
        $request = $this->getRequest();
        $createdBy = $this->authContainer->authDetail['USER_OID'];
        $data = $request->getPost()->toArray();        
        $requestData = $request->getQuery()->toArray();
        $edit_from = !empty($data['edit_from'])? '&edit_from='.$data['edit_from'] : null;
        /** Get Test-ID incase of ST from Route else from post request. */
        $data['QUIZ_ID'] = !empty($data['QUIZ_ID']) ? $data['QUIZ_ID'] : (!empty($this->params('id')) ? $this->params('id') : null);
        /** Get Test-Name incase of ST from query else from post request. */
        $postTestName = isset($data['TEST_NAME']) ? $data['TEST_NAME'] : null;
        $data['TEST_NAME'] = (isset($requestData['TEST_NAME']) && $requestData['test_type'] == 'ST') ? $requestData['TEST_NAME'] : $postTestName;
        /** Get Quiz-Type incase of ST from query else from post request. */
        $data['QUIZ_TYPE'] = isset($requestData['test_type']) ? $requestData['test_type'] : $data['QUIZ_TYPE'];

        $lpId = !empty($data['lpId']) ? $data['lpId'] : "";
        if ($request->isXmlHttpRequest()) {
            if (empty($data['TEST_NAME'])) {
                $result = ['result' => false, 'message' => ['TEST_NAME' => ['isEmpty' => $translator->translate("Value is required and can't be empty")]]];
            } else if (!empty($data['QUIZ_ID'])) {
                $updateData = [
                    'TITLE' => $data['TEST_NAME'],
                    'QUIZ_MODE' => (isset($data['TEST_TYPE_CREATION']) && $data['TEST_TYPE_CREATION'] == 'AT') ? 'A' : 'M',
                ];
                $updateOnContTable = [
                    'CONT_TITLE' => $data['TEST_NAME'],
                    'UPDATED_BY' => $createdBy,
                    'UPDATED_ON' => date('Y-m-d H:i:s')
                ];
                $createQuizTable->updateData('t_master_test', $updateData, array('QUIZ_ID' => $data['QUIZ_ID']));
                $cont_data = $createQuizTable->fetchData('t_master_test', array('QUIZ_ID' => $data['QUIZ_ID']), ['CONT_ID', 'QUIZ_TYPE'], null, false);
                $quzType = (!empty($cont_data['QUIZ_TYPE'])) ? $cont_data['QUIZ_TYPE'] : null;
                $displayTabActived = 2;
                
                if ($quzType == 'GT') {
                    $createQuizTable->updateData('t_cm_cnf_content', $updateOnContTable, ['CONT_ID' => $cont_data['CONT_ID']]);
                    $result = ['result' => true, 'redirectUrl' => $this->returnBasePath() . '/assessment/add/' . $data['QUIZ_ID'] . '/' . $displayTabActived . '?lpId=' . $lpId.$edit_from];
                } else if ($data['QUIZ_TYPE'] == 'FT' && $data['TEST_TYPE_CREATION'] == 'AT') {                        
                        $result = ['result' => true, 'redirectUrl' => $this->returnBasePath() . '/assessment/add/' . $data['QUIZ_ID'] . '/' . $displayTabActived . '?test_type=' . $data['QUIZ_TYPE'].'&test_create_mode=AT'];
                } else {
                    $result = ['result' => true, 'redirectUrl' => $this->returnBasePath() . '/assessment/add/' . $data['QUIZ_ID'] . '/' . $displayTabActived . '?test_type=' . $data['QUIZ_TYPE'].$edit_from];
                }
            } else {
                if ($data['QUIZ_TYPE'] == 'GT') {
                    $contentData = [
                        'LESSONPLAN_ID' => $data['lpId'],
                        'CONT_TITLE' => $data['TEST_NAME'],
                        'CONTTYPE_ID' => $data['CONTTYPE_ID'],
                        'STATUS' => 'A',
                        'CREATED_ON' => date('Y-m-d H:i:s'),
                        'CREATED_BY' => $createdBy,
                    ];
                    $contId = $createQuizTable->insertData('t_cm_cnf_content', $contentData);
                } else {
                    $contId = 0;
                }
                $insertData = [
                    'CONT_ID' => $contId,
                    'SUBJECT_ID' => !empty($data['TEST_SUBJECT']) ? $data['TEST_SUBJECT'] : null,
                    'TITLE' => $data['TEST_NAME'],
                    'STATUS' => 'A',
                    'QUIZ_TYPE' => $data['QUIZ_TYPE'],
                    'QUIZ_MODE' => (isset($data['TEST_TYPE_CREATION']) && $data['TEST_TYPE_CREATION'] == 'AT') ? 'A' : 'M',
                    'PLC_LEVEL_ID' => $data['PLC_LEVEL_ID'],
                    'CREATED_BY' => $createdBy,
                    'CREATED_ON' => date('Y-m-d H:i:s'),
                        // 'PUBLISH' => 'Y',
                ];
                $quizId = $createQuizTable->insertData('t_master_test', $insertData);
                $displayTabActived = 2;
                if ($lpId && $data['QUIZ_TYPE'] == 'GT') {
                    $result = ['result' => true, 'redirectUrl' => $this->returnBasePath() . '/assessment/add/' . $quizId . '/' . $displayTabActived . '?lpId=' . $lpId];
                } else if ($data['QUIZ_TYPE'] == 'FT' && $data['TEST_TYPE_CREATION'] == 'AT') {                        
                        $result = ['result' => true, 'redirectUrl' => $this->returnBasePath() . '/assessment/add/' . $quizId . '/' . $displayTabActived . '?test_type=' . $data['QUIZ_TYPE'].'&test_create_mode=AT'];
                } else {
                    $result = ['result' => true, 'redirectUrl' => $this->returnBasePath() . '/assessment/add/' . $quizId . '/' . $displayTabActived . '?test_type=' . $data['QUIZ_TYPE'].$edit_from];
                }
            }
            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
            $viewModel->setVariables(['data' => $result]);
            return $viewModel;
        }
    }

    /*
     * @desc Use of this action to upload file on AWS server
     * @param string $filename
     * @param string $repositoryName
     * @return json
     */

    public function uploadS3File($filename, $repositoryName, $api = null) {
        if (empty($api)) {
            //$viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
            //$viewModel->setTerminal(true);
        }
        $config = $this->serviceLocator->get('config');
        $bucket = $config['s3bucket'];
        $aws = $this->getServiceLocator()->get(Sdk::class);
        $client = $aws->createS3();
        $sourceFile = getcwd() . '/public/upload/' . $filename;
        $src = 'public/upload/' . $filename;
        if (!file_exists($sourceFile)) {
            return ['BACKING_FILE' => $filename, 'message' => 'File not exist'];
        }
        $key = $repositoryName . $filename;
        //if AWS enable,use aws client object
        if ($config['AWS_ENABLE']) {
            $result = $client->putObject(array(
                'Bucket' => $bucket,
                'Key' => $key,
                'SourceFile' => $sourceFile,
                'ACL' => 'public-read'
            ));
            // delete file after upload on s3 
            if (file_exists($sourceFile)) {
                unlink($sourceFile);
            }
        }

        return ['BACKING_FILE' => $filename, 'message' => 'File uploaded successfully'];
    }

    /**
     * @desc used of this action for save data to create and edit quiz
     */
    public function savedataAction() {
        $this->AssessmentPlugin()->setCustomLayout($this, 'assessmentLayout');
        $config = $this->getServiceLocator()->get('config');
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $translator = $this->getServiceLocator()->get('translator');
        $CreateQuizForm = new CreateQuizForm($translator);
        $createQuizTable = $this->initTable('Assessment\Model\CreateQuizTable');
        $result = ['result' => false, 'message' => ''];
        $request = $this->getRequest();
        $data = $request->getPost()->toArray();
        $CreateQuizInputFilter = new CreateQuizInputFilter($data);
        if ($request->isXmlHttpRequest()) {
            $CreateQuizForm->setInputFilter($CreateQuizInputFilter->getInputFilter());
            if (!empty($data['Time_Limit'])) {
                $data['TIME_LIMIT_DURATION'] = empty($data['Time_Limit']) ? '00:00:00' : $data['TIME_LIMIT_DURATION'];
            }
            if (!empty($data['Allow_Multiple_Attempts'])) {
                $data['ALLOWED_ATTEMPT_NO'] = empty($data['Allowed_Attempt']) ? 0 : $data['ALLOWED_ATTEMPT_NO'];
            } else {
                $data['ALLOWED_ATTEMPT_NO'] = 1;
            }
            $this->setValidationFalse($data, $CreateQuizInputFilter);
            $CreateQuizForm->setData($request->getPost());
            if ($CreateQuizForm->isValid()) {
                if ((empty($data['TIME_LIMIT_DURATION']) || $data['TIME_LIMIT_DURATION'] == '00:00:00') && (!empty($data['Time_Limit']))) {
                    $result = ['result' => false, 'message' => ['TIME_LIMIT_DURATION' => ['isEmpty' => "Value is required and can't be empty"]]];
                    if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                        $viewModel = new JsonModel();
                    }
                    $viewModel->setVariables(['data' => $result]);
                    return $viewModel;
                }
                
                /** Added blank value incase of test type is PT only else all working as they were. */
                if ($data['QUIZ_TYPE'] != 'PT') {
                    $data['ASSIGN_DATE'] = $data['ASSIGN_DATE'] . ' ' . $data['START_TIME'];
                    $data['END_DATE'] = $data['END_DATE'] . ' ' . $data['END_TIME'];
                } else {
                    $data['ASSIGN_DATE'] = $data['END_DATE'] = '';
                    $data['ALLOWED_ATTEMPT_NO'] = null;
                }

                if ($data['QUIZ_ID']) {
                    $createdBy = $this->authContainer->authDetail['USER_OID'];
                    $quizDuration = $data['TIME_LIMIT_DURATION'];
                    $updateData = [
                        'TITLE' => $data['TITLE'],
                        'INSTRUCTION' => $data['INSTRUCTION'],
                        'TIME_LIMIT_DURATION' => ($quizDuration == '00:00:00') ? null : $quizDuration,
                        'QUIZ_SCORE_KEEP' => $data['QUIZ_SCORE_KEEP'],
                        'ALLOWED_ATTEMPT_NO' => $data['ALLOWED_ATTEMPT_NO'],
                        'APPEARANCE' => 'SOQ',
                        'ASSIGN_DATE' => $data['ASSIGN_DATE'],
                        'END_DATE' => $data['END_DATE'],
                        'IS_SCRATCHPAD' => $data['IS_SCRATCHPAD'],
                        'GRADE_RELEASE' => $data['GRADE_RELEASE'],
                        'CORRECTNESS' => $data['CORRECTNESS'],
                        'RESPONSE_TIME' => $data['RESPONSE_TIME'],
                        'Quiz_Response' => $data['Quiz_Response'],
                        'CUT_SCORE' => !empty($data['CUT_SCORE']) ? $data['CUT_SCORE'] : null,
                        'PUBLISH' => 'Y',
                        'UPDATED_BY' => $createdBy,
                        'UPDATED_ON' => date('Y-m-d H:i:s')
                    ];

                    // to do if image name found			
                    if ($config['AWS_ENABLE']) {
                        if (!empty($data['TEST_IMG'])) {
                            $updateData['TEST_IMG'] = $data['TEST_IMG'];
                            $ret = $this->uploadS3File($data['TEST_IMG'], 'TEST/');
                        }
                    }
                    $createQuizTable->updateData('t_master_test', $updateData, array('QUIZ_ID' => $data['QUIZ_ID']));

                    $updateOnContTable = [
                        'CONT_TITLE' => $data['TITLE'],
                        'UPDATED_BY' => $createdBy,
                        'UPDATED_ON' => date('Y-m-d H:i:s')
                    ];

                    $cont_data = $createQuizTable->fetchData('t_master_test', array('QUIZ_ID' => $data['QUIZ_ID']), ['CONT_ID'], null, false);
                    $createQuizTable->updateData('t_cm_cnf_content', $updateOnContTable, ['CONT_ID' => $cont_data['CONT_ID']]);
                }
                $lpId = $data['lpId'];
                $edit_from = !empty($data['edit_from'])? $data['edit_from']: null;
                $test_type = !empty($data['QUIZ_TYPE'])? $data['QUIZ_TYPE']: null;
                $subjectId = "";
                
                
                if ($lpId && empty($edit_from)) {
                    $redirectUrl = $this->returnBasePath() . "/grade/lesson-plan";
                    $subjectData = $createQuizTable->fetchData('t_cm_lessonplan_master', ['LESSONPLAN_ID' => $lpId], ['SUBJECT_ID'], null, false);
                    $subjectId = !empty($subjectData) ? $subjectData['SUBJECT_ID'] : "";
                } else if ($edit_from == 'quiz') {
                    $redirectUrl = $this->returnBasePath() . "/test/quiz";
                } else if ($edit_from == 'PT') {
                    $redirectUrl = $this->returnBasePath() . '/test/index';
                } else if ($test_type == 'ST' || $test_type == 'FT') {
                    $subjectData = $createQuizTable->fetchData('t_master_test', ['QUIZ_ID' => $data['QUIZ_ID']], ['SUBJECT_ID'], null, false);
                    $subjectId = !empty($subjectData) ? $subjectData['SUBJECT_ID'] : "";
                    $redirectUrl = $this->returnBasePath() . "/grade/lesson-plan/" . $subjectId;
                } else {
                    $redirectUrl = $this->returnBasePath() . "/test/index";
                }

//                if ($lpId) {
//                    if ($this->container->authDetail['EDIT_FROM'] == 'quiz') {
//                        $redirectUrl = $this->returnBasePath() . "/test/quiz";
//                    } else {
//                        $redirectUrl = $this->returnBasePath() . "/grade/lesson-plan";
//                    }
//                } else {
//                    $redirectUrl = $this->returnBasePath() . "/test/index";
//                }
                
                $result = ['result' => true, 'redirectUrl' => $redirectUrl, 'lpId' => $lpId, 'subjectId' => $subjectId];
            } else {
                $result = ['result' => false, 'message' => $CreateQuizForm->getMessages()];
            }
            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
            $viewModel->setVariables(['data' => $result]);
            return $viewModel;
        }
    }

    /**
     * @desc used of this function for set validation false if dependent check box is un-check
     * @param array $data
     * @param obj $CreateQuizInputFilter
     */
    private function setValidationFalse($data, $CreateQuizInputFilter) {
        if (!empty($data['Allow_Multiple_Attempts'])) {
            $CreateQuizInputFilter->getInputFilter()->get('QUIZ_SCORE_KEEP')->setRequired(true);
        }
        if (!empty($data['Allowed_Attempt'])) {
            $CreateQuizInputFilter->getInputFilter()->get('ALLOWED_ATTEMPT_NO')->setRequired(true);
        }
        if (!empty($data['Time_Limit'])) {
            $CreateQuizInputFilter->getInputFilter()->get('TIME_LIMIT_DURATION')->setRequired(false);
//            $CreateQuizInputFilter->getInputFilter()->get('TIME_LIMIT_DURATION')->getValidatorChain()->addByName(
//                'between', array(
//                    'min' => 1,
//                    'max' => 300,
//                    'messages' => array(
//                        \Zend\Validator\Between::NOT_BETWEEN => 'Invalid input, only value between 1 to 300 allowed.',
//                    ),
//                    )
//            );
        } 
        if (isset($data['QUIZ_TYPE']) && $data['QUIZ_TYPE'] == 'PT') {
            $CreateQuizInputFilter->getInputFilter()->get('CUT_SCORE')->setRequired(false);
            $CreateQuizInputFilter->getInputFilter()->get('ASSIGN_DATE')->setRequired(false);
            $CreateQuizInputFilter->getInputFilter()->get('START_TIME')->setRequired(false);
            $CreateQuizInputFilter->getInputFilter()->get('END_DATE')->setRequired(false);
            $CreateQuizInputFilter->getInputFilter()->get('END_TIME')->setRequired(false);
            $CreateQuizInputFilter->getInputFilter()->get('ALLOWED_ATTEMPT_NO')->setRequired(false);
            $CreateQuizInputFilter->getInputFilter()->get('QUIZ_SCORE_KEEP')->setRequired(true);
        }
    }

    /**
     * @desc used of this function for open popup dynamically
     * @return render page
     */
    public function openPopupAction() {
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $requestData = $this->getRequest()->getQuery()->toArray();
        $translator = $this->getServiceLocator()->get('translator');
        $viewModel = $this->AssessmentPlugin()->openPopUp($viewModel, $requestData);
        //$viewModel = $this->CommonClass()->openPopUp($viewModel,$requestData);
        $fileName = $requestData['file'];
        if (isset($requestData['QUIZ_ID'])) {
            $QUIZ_ID = $requestData['QUIZ_ID'];
        }
        if (isset($requestData['id'])) {
            $QUIZ_ID = $requestData['id'];
        }
        if ($fileName == 'popup_delete_confirmation') {
            $createQuizTable = $this->initTable('Assessment\Model\CreateQuizTable');
            $res = $createQuizTable->fetchData('t_usr_quiz_attempt', ['QUIZ_ID' => $QUIZ_ID], array('*'), null, true);
            $viewModel->setVariables(['result' => $res]);
            return $viewModel;
        } else if ($fileName == 'popup_quizattemp') {
            $utId = $this->container->authDetail['UT_ID'];
            $type = isset($requestData['quiz_type'])? $requestData['quiz_type'] : '';
            $gradeId = isset($requestData['gradeId'])? $requestData['gradeId'] : '';
            $levelId = isset($requestData['level_id'])? $requestData['level_id'] : '';
            $createQuizTable = $this->initTable('Assessment\Model\CreateQuizTable');
            $res = $createQuizTable->fetchData('t_usr_quiz_attempt', ['QUIZ_ID' => $requestData['QUIZ_ID'], 'USER_OID' => $requestData['USER_OID']], array('*'), "CREATED_DATE Desc", true);	
            $viewModel->setVariables(['result' => $res, 'utId' => $utId, 'type'=>$type, 'gradeId'=>$gradeId, 'levelId'=>$levelId]);

            return $viewModel;
        } else if ($fileName == 'popup_delete_test_file') {
            $quesId = $requestData['id'];
            $viewModel->setVariables(array(
                'result' => '',
            ));
            return $viewModel;
        } else if ($fileName == 'popup_essay_marks') {
            $AttemptID = $requestData['AttemptID'];
            $QuestionID = $requestData['QuestionID'];
            $viewModel->setVariables(array(
                'AttemptID' => $AttemptID,
                'QuestionID' => $QuestionID,
            ));
            return $viewModel;
        } else if ($fileName == 'popup_test_type') {
//            $countryList = $this->getCountries();
            $userId = $this->container->authDetail['USER_OID'];
            $utId = $this->container->authDetail['UT_ID'];
            $orgId = $this->container->authDetail['ORG_ID'];
            $createQuizTable = $this->initTable('Assessment\Model\CreateQuizTable');
            $gradeList = [];
            if ($utId == 2) {
                $gradeList = $createQuizTable->getGradesByUserId($userId);
            } else {
                $gradeList = $createQuizTable->getGradesForAdmin($orgId);
            }
            $form = new \Assessment\Form\TestTypeForm($gradeList, $translator);
            $viewModel->setVariables(array(
                'form' => $form
            ));
            return $viewModel;
        } else {
            $viewModel->setVariables(['quizId' => (!empty($QUIZ_ID)) ? $QUIZ_ID : 0]);
            return $viewModel;
        }
    }

    /*
     * @desc Used of this function to get question list from 
     * question bank module and render as question listing on pull question popup
     */

    public function qusListAction() {
        $this->AssessmentPlugin()->setCustomLayout($this, 'assessmentLayout');
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $quizId = $this->params('id');
        $request = $this->getRequest();
        if ($request->isXmlHttpRequest()) {
            $viewModel->setTerminal(true);
            $requestData = $request->getQuery()->toArray();
            $retJsonArrData = $this->getQuizQusList($requestData, $quizId);
            $jsonModel = new JsonModel();
            $jsonModel->setVariables($retJsonArrData);
            return $jsonModel;
        }
        return $viewModel;
    }

    /*
     * @desc Used of this function to get question list from 
     * question bank module and render as question listing on pull question popup
     */

    private function getQuizQusList($requestData, $quizId) {
        $createQuizTable = $this->initTable('Assessment\Model\CreateQuizTable');
        $sortColumnsArr = array(1 => 't_master_question.QUESTION_TEXT', 2 => 't_master_question.QUK');
        $pagingData = $this->AssessmentPlugin()->setAndGetPagingDataWithFilter($sortColumnsArr, $requestData, 't_master_question.QUS_ID');
        $getData = $createQuizTable->getAllList($pagingData);
        //$mcqType = $createQuizTable->getQuizType();
        $totalData = $createQuizTable->countTotalQus($pagingData);
        $retArrData = $this->getJsonArrayOfQuizQus($getData, $pagingData['START'], $createQuizTable, $quizId);
        $retJsonArrData = array(
            "draw" => (isset($requestData['draw'])) ? $requestData['draw'] : '',
            "recordsTotal" => $totalData,
            "recordsFiltered" => $totalData,
            "result" => $retArrData
        );
        return $retJsonArrData;
    }

    /*
     * @desc Used of this function to get question list from 
     * question bank module and render as question listing on pull question popup
     */

    public function getJsonArrayOfQuizQus($getData, $start, $createQuizTable, $quizId) {
        $tabl2 = $this->initTable('Assessment\Model\CreateQuizTable');
        $retArrData = array();
        if (count($getData)) {
            $i = 0;
            foreach ($getData as $data) {
                $resArr = $tabl2->checkQusExist($data['QUS_ID'], $quizId);
                $isCheckBoxReadOnly = !empty($resArr) ? 'disabled' : '';
                $retArrData[$i][] = '<input type="checkbox" ' . $isCheckBoxReadOnly . ' class="styled quspullpopup" value="' . $data['QUS_ID'] . '" name="qus[]">';
                $retArrData[$i][] = $this->replaceCkeditorData($data['QUESTION_TEXT']);
                $retArrData[$i][] = substr($data['QUK'], 0, 8);
                $i++;
            }
        }
        return $retArrData;
    }

    /**
     * @desc used of this function to render pulled qustion from qustion listing popp
     * and linked questions with creating quiz by inserting interface table.
     */
    public function pullQuestionAction() {
        $createQuizTable = $this->initTable('Assessment\Model\CreateQuizTable');
        $PullQusForm = new PullQusForm();
        $PullQusInputFilter = new PullQusInputFilter();
        $request = $this->getRequest();
        $res = '';
        if ($request->isXmlHttpRequest()) {
            $data = $request->getPost()->toArray();
            $quizId = $data['QUIZ_ID'];
            if (!empty($data['qus'])) {
                foreach ($data['qus'] as $dataV) {
                    $res = $createQuizTable->checkQusExist($dataV, $quizId);
                    if (empty($res)) {
                        $insertData = [
                            'QUS_ID' => $dataV,
                            'QUZ_ID' => $quizId
                        ];
                        $createQuizTable->insertDataQuizQus($insertData);
                    }
                }
            }
        }
        $data = $this->fetchQusByQuizId($createQuizTable, null, $quizId);
        $view = new ViewModel(array('data' => $data, 'PullQusForm' => $PullQusForm));
        //disable layout if request by ajax
        $view->setTerminal($this->getRequest()->isXmlHttpRequest());
        return $view;
    }

    /**
     * @desc used of this function for delete pulled question while creating new quiz
     * @return json message
     */
    public function deletePullQuesAction() {
        $request = $this->getRequest();
        if ($request->isXmlHttpRequest()) {
            $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
            $viewModel->setTerminal(true);
            $postData = $request->getPost()->toArray();
            $quizId = $postData['quizId'];
            $qusId = $postData['qusId'];
            $createQuizTable = $this->initTable('Assessment\Model\CreateQuizTable');
            $isDeleted = $createQuizTable->deleteRecord($quizId, $qusId);
            $jsonModel = new JsonModel();
            $jsonModel->setVariables(array(
                'result' => 'Record Deleted'
            ));

            return $jsonModel;
        }
    }

    /**
     * @desc used of this function for save pull qustion
     */
    public function savePullAction() {
        $PullQusForm = new PullQusForm();
        $PullQusInputFilter = new PullQusInputFilter();
        $createQuizTable = $this->initTable('Assessment\Model\CreateQuizTable');
        $result = ['result' => false, 'message' => ''];
        $this->AssessmentPlugin()->setCustomLayout($this, 'assessmentLayout');
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $request = $this->getRequest();
        $errorMessage = "Value is required and can't be empty";
        if ($request->isXmlHttpRequest()) { 
            $data = $request->getPost()->toArray();
            $conditions = array('QUIZ_ID' => $data['QUZ_ID']);
            $populateData = $createQuizTable->fetchData('t_master_test', $conditions, array('*'), '', false);
            //$PullQusForm->setInputFilter($PullQusInputFilter->getInputFilter());
            //$PullQusForm->setData($request->getPost());
            $orderCount = 1;
            $noOfQus = 0;
            $qsnCount = 0;
            $totalMarks = 0;
            //if ($PullQusForm->isValid()) {
            foreach ($data['QUS_ID'] as $QUSIDK => $QUSIDV) {
                $updateData = ['QUS_MARK' => $data['QUS_MARK'][$QUSIDK], 'QUS_ORDER' => $orderCount];
                $createQuizTable->updateMark($updateData, $data['QUZ_ID'], $QUSIDV);
                $noOfQus = $noOfQus + $data['QUS_MARK'][$QUSIDK];
                $orderCount++;
                $qsnCount++;
                $totalMarks = $totalMarks + $data['QUS_MARK'][$QUSIDK];
            }
            //}

            $totalArr = array();
            $totalArr["TOTAL_QUES"] = $qsnCount;
            $totalArr["TOTAL_MARKS"] = $totalMarks;
            $conditionsArr["QUIZ_ID"] = $data['QUZ_ID'];
            $createQuizTable->updateData('t_master_test', $totalArr, $conditionsArr);


            $jsonModel = new JsonModel(array(
                'qusCount' => count($data['QUS_ID']),
                'noOfQus' => $noOfQus,
                'reviewQuiz' => $populateData,
                'PublishForm' => new PublishForm(),
                'QUIZ_ID' => $data['QUZ_ID'][0],
                'displayTabActived' => 4,
                'quiz_type' => !empty($data['QUIZ_TYPE']) ? $data['QUIZ_TYPE'] : '',
                'edit_from' => !empty($data['edit_from']) ? $data['edit_from'] : '',
            ));

            return $jsonModel;
        }
    }

    /**
     * @desc used of this function for retrive question by quiz id
     */
    private function fetchQusByQuizId($createQuizTable, $data, $quizId) {
        $res = $createQuizTable->pullQusById($data['qus'], $quizId);
        $questionTable = $this->initTable('Assessment\Model\QuestionTable');
        foreach ($res as $dataK => $data) {
            $res[$dataK]['QUESTION_TEXT'] = $this->replaceCkeditorData($data['QUESTION_TEXT']);
            $res[$dataK]['TOPIC_IDS'] = $questionTable->getAllUniqTopicIds($data['QUS_ID']);
        }
        return $res;
    }

    /**
     * @desc used of this function for update order of qustion 
     * while creating/updating quiz (Not using for now but will use in future)
     */
    public function updateorderAction() {
        $translator = $this->getServiceLocator()->get('translator');
        $CreateQuizForm = new CreateQuizForm($translator);
        $createQuizTable = $this->initTable('Assessment\Model\CreateQuizTable');
        $result = ['result' => false, 'message' => ''];
        $this->AssessmentPlugin()->setCustomLayout($this, 'assessmentLayout');
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $request = $this->getRequest();
        if ($request->isXmlHttpRequest()) {
            $data = $request->getPost()->toArray();
            $orderCount = 1;
            foreach ($data['item'] as $dataV) {
                $arrData = explode('and', $dataV);
                $data = ['QUS_ORDER' => $orderCount];
                $createQuizTable->updateOrder($data, $arrData[1], $arrData[2]);
                $orderCount++;
            }
            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
            $result = ['result' => true];
            $viewModel->setVariables(['data' => $result]);
            return $viewModel;
        }
    }

    /**
     * @desc used of this function for review & publish the quiz
     */
    public function publishAction() {
        $request = $this->getRequest();
        $createQuizTable = $this->initTable('Assessment\Model\CreateQuizTable');
        $postData = $request->getPost()->toArray();
        if ($request->getMethod() == 'POST') {
            $postData = $request->getPost()->toArray();
            $data = ['PUBLISH' => 'Y', 'STATUS' => 'A'];
            $QUZ_ID = $postData['pubquizId'];
            $conditions = array('QUIZ_ID' => $QUZ_ID);
            $createQuizTable->updateData('t_master_test', $data, $conditions);
            $redPath = $this->returnBasePath() . '/assessment/index';
            return $this->redirect()->toUrl($redPath);
        }
    }

    /**
     * @desc used of this function for delete whole quiz
     * @return json message
     */
    public function deleteDataAction() {
        $request = $this->getRequest();
        if ($request->isXmlHttpRequest()) {

            $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
            $viewModel->setTerminal(true);
            $requestData = $request->getQuery()->toArray();
            $deleteAction = $requestData['deleteAction'];
            $ID = $requestData['ID'];
            if ($deleteAction == 'delete_content') {
                $createQuizTable = $this->initTable('Assessment\Model\CreateQuizTable');
                /* Get test image */
                $getImage = $createQuizTable->fetchData('t_master_test', ['QUIZ_ID' => $ID], ['TEST_IMG']);
                $img = $getImage[0]['TEST_IMG'];
                $key = 'TEST/' . $img;
                $this->AssessmentPlugin()->removeS3File($key);
                $res = $createQuizTable->updateData('t_master_test', ['TEST_IMG' => ''], ['QUIZ_ID' => $ID]);
            } else {
                $createQuizTable = $this->initTable('Assessment\Model\CreateQuizTable');
                $isDeleted = $createQuizTable->deleteQuizRecord($ID);
            }
            $jsonModel = new JsonModel();
            $jsonModel->setVariables(array(
                'result' => 1
            ));
            return $jsonModel;
        }
    }

    /**
     * @desc used of this function for display attemp list
     * @return json message
     */
    public function quizattemptAction() {
        $translator = $this->getServiceLocator()->get('translator');
        $createQuizTable = $this->initTable('Assessment\Model\CreateQuizTable');
        $this->AssessmentPlugin()->setCustomLayout($this, 'assessmentLayout');
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $quizId = $this->params('lpId');
        $ORG_ID = $this->authContainer->authDetail['ORG_ID'];
        $quizRes = $createQuizTable->getTitleByContId($quizId, true, $ORG_ID)->current();
        $quizTitle = isset($quizRes->CONT_TITLE) ? $quizRes->CONT_TITLE : '';
        $request = $this->getRequest();
        if ($request->isXmlHttpRequest()) {
            $viewModel->setTerminal(true);
            $requestData = $request->getQuery()->toArray();
            $retJsonArrData = $this->attemptList($requestData, $quizId);
            $jsonModel = new JsonModel();
            $jsonModel->setVariables($retJsonArrData);
            return $jsonModel;
        }
        $viewModel->setVariables(['quizId' => $quizId, 'quizTitle' => $quizTitle]);
        return $viewModel;
    }

    //get attempt list
    private function attemptList($requestData, $quizId) {
        $createQuizTable = $this->initTable('Assessment\Model\CreateQuizTable');
        $sortColumnsArr = array(0 => 't_usr_user.FIRST_NAME', 1 => 't_usr_quiz_attempt.CREATED_DATE', 2 => 't_usr_quiz_attempt.QUIZ_FINISH_TIME');
        $pagingData = $this->AssessmentPlugin()->setAndGetPagingDataWithFilter($sortColumnsArr, $requestData, 't_master_test.QUIZ_ID');
        //ORG_ID
        $ORG_ID = $this->authContainer->authDetail['ORG_ID'];
        $getData = $createQuizTable->getAttemptAllList($pagingData, $quizId);
        $totalData = $createQuizTable->countAttemptTotal($pagingData, $quizId);
        $retArrData = $this->getJsonArrayOfAttempt($getData, $pagingData['START'], $createQuizTable);
        $retJsonArrData = array(
            "draw" => (isset($requestData['draw'])) ? $requestData['draw'] : '',
            "recordsTotal" => $totalData,
            "recordsFiltered" => $totalData,
            "result" => $retArrData
        );
        return $retJsonArrData;
    }

    // make attempt data in json format as per DataTable JSON requirements
    public function getJsonArrayOfAttempt($getData, $start, $createQuizTable) {
        $translator = $this->getServiceLocator()->get('translator');
        $config = $this->getServiceLocator()->get('config');
        $retArrData = array();
        if (count($getData)) {
            $i = 0;
            foreach ($getData as $data) {
                $viewReport = $this->returnBasePath() . '/student-quiz/quizreport/' . $data['QUIZ_ATTEMPT_ID'];
                $retArrData[$i][] = $data['FIRST_NAME'] . ' ' . $data['LAST_NAME'];
                $retArrData[$i][] = date('d-m-Y H:i:s', strtotime($data['CREATED_DATE']));
                $retArrData[$i][] = gmdate("H:i:s", $data['QUIZ_FINISH_TIME']);
                $retArrData[$i][] = '<a target="_blank" class="btn btn-primary btn-sm" href="' . $viewReport . '" >' . $translator->translate("View Report") . '</a>';
                $i++;
            }
        }
        return $retArrData;
    }

    public function checkquizAction() {
        $request = $this->getRequest();
        if ($request->isXmlHttpRequest()) {
            $jsonModel = new JsonModel();
            $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
            $viewModel->setTerminal(true);
            $requestData = $request->getPost()->toArray();
            $quizId = $requestData['quizId'];
            $createQuizTable = $this->initTable('Assessment\Model\CreateQuizTable');
            $res = $createQuizTable->checkQuizGreater($quizId);
            $res2 = $createQuizTable->checkQuizExpired($quizId);
            if (!empty($res) && !empty($res->ASSIGN_DATE) && $res->ASSIGN_DATE != '0000-00-00 00:00:00') {
                $result = ['result' => 1, 'date' => date('d-m-Y H:i:s', strtotime($res->ASSIGN_DATE))];
            } else if (!empty($res2) && !empty($res2->END_DATE) && $res2->END_DATE != '0000-00-00 00:00:00') {
                $result = ['result' => 2, 'date' => date('d-m-Y H:i:s', strtotime($res2->END_DATE))];
            } else {
                $result = ['result' => ''];
            }
            $jsonModel->setVariables($result);
            return $jsonModel;
        }
    }

    public function isExistLevelAction() {
        $translator = $this->getServiceLocator()->get('translator');
        $request = $this->getRequest();
        $postData = $request->getPost();
        $levelId = (!empty($postData['levelId'])) ? $postData['levelId'] : 0;
        $createQuizTable = $this->initTable('Assessment\Model\CreateQuizTable');
        $data = $createQuizTable->isExistPlLevel($levelId);
        if ($data > 0) {
            $result = ['success' => 'false', 'message' => $translator->translate('Test is already created.')];
        } else {
            $result = ['success' => 'success'];
        }
        $jsonModel = new JsonModel();
        $jsonModel->setVariables($result);
        return $jsonModel;
    }

    public function studentReportsAction() {
        $_SESSION['url'] = '';
        $_SESSION['ass'] = '';
        $quiz_id = !empty($this->params('id')) ? $this->params('id') : '';
        if (!empty($quiz_id)) {
            $lang = (!empty($this->container->language)) ? $this->container->language : 'en';
            $this->CommonClass()->setCustomLayout($this, 'homeLayout');
            $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
            $dbadapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
            $teacher_id = $this->container->authDetail['USER_OID'];
            $studentTable = $this->initTable('Student\Model\StudentTable');
            $quizcheck = $studentTable->getQuizByUserId($quiz_id, $teacher_id);
            
            if (empty($quizcheck)) {
                return $this->redirect()->toRoute('test', array('controller' => 'test', 'action' => 'quiz'));
            }
            $quizName = $studentTable->getQuizDeatil($quiz_id);

           //echo "<pre>"; print_r($quizName); die;

            if ($quizName[0]["QUIZ_TYPE"] == "PT") {
                $allStudent = $studentTable->getAllStudentbyPlcLevelID($quizName[0]["PLC_LEVEL_ID"]);
            } else if ($quizName[0]["QUIZ_TYPE"] == "ST" || $quizName[0]["QUIZ_TYPE"] == "FT") {
                $allStudent = $studentTable->getAllStudentbyQuizIdForStAndFt($quiz_id);
            } else {
                // this is for GT
                $allStudent = $studentTable->getAllStudentbyQuizId($quiz_id);
            }

            $getQuestionDetail = $studentTable->getAllQusestionbyQuizId($quiz_id);
            //print_r($getQuestionDetail);
//         echo "<pre>";
//          print_r($getQuestionDetail);
            $getQuestionDetailIs = array();
            if (sizeof($getQuestionDetail >= 1)) {
                foreach ($getQuestionDetail as $getQuestionDetails) {
                    $getQuestionDetailIs[$getQuestionDetails['QUS_ID']] = array(
                        "QUZ_QUS_ID" => $getQuestionDetails['QUZ_QUS_ID'],
                        "QUZ_ID" => $getQuestionDetails['QUZ_ID'],
                        "QUS_ID" => $getQuestionDetails['QUS_ID'],
                        "QUS_REF_ID" => $getQuestionDetails['QUS_REF_ID'],
                        "QUS_ORDER" => $getQuestionDetails['QUS_ORDER'],
                        "QUS_MARK" => $getQuestionDetails['QUS_MARK'],
                    );
                }
            } else {
                $getQuestionDetailIs = array();
            }

            //       print_r($getQuestionDetailIs);
//        die;

            $viewModel->setVariables(['quizName' => $quizName, 'allstudent' => $allStudent, 'studentCount' => count($allStudent), 'getQuestionDetail' => $getQuestionDetailIs]);
            return $viewModel;
        } else {
            return $this->redirect()->toRoute('test', array('action' => 'quiz'));
        }
    }

    /**
     * @desc Use of this function for get all grades by school from Local.
     * @return array
     */
    public function getGradesLocal($cco = null) {
        $teacherid = $this->container->authDetail['USER_OID'];
        $questionTable = $this->initTable('Assessment\Model\QuestionTable');
        $curriculumTable = $this->initTable('Curriculum\Model\CurriculumTable');
        $translator = $this->getServiceLocator()->get('translator');
        $orgId = $this->container->authDetail['ORG_ID'];
        $utid = $this->container->authDetail['UT_ID'];
        if (empty($cco)) {
            if ($utid == 2) {
                $subjects = $curriculumTable->getAssignSubjectById($teacherid);
                if (empty($subjects)) {
                    $subjects = [0];
                }
                $join[] = ['t_cm_mgr_grade', 't_cm_mgr_grade.GRADE_ID = t_cm_mgr_subject.GRADE_ID'];
                $join[] = ['t_cm_cnf_standard', 't_cm_cnf_standard.STANDARD_ID = t_cm_mgr_grade.STANDARD_ID', ['STANDARD_NAME']];
                $getAllgrades = $questionTable->fetchData('t_cm_mgr_subject', ['t_cm_mgr_subject.SUBJECT_ID' => $subjects], ['*'], '', true, '', '', '', '', '', '', $join);
            } else {
                $join[] = ['t_cm_cnf_standard', 't_cm_cnf_standard.STANDARD_ID = t_cm_mgr_grade.STANDARD_ID', ['STANDARD_NAME']];
                $getAllgrades = $questionTable->fetchData('t_cm_mgr_grade', ['t_cm_mgr_grade.ORG_ID' => $orgId], ['*'], null, true, null, null, null, null, null, null, $join);
            }

            $result = ['' => $translator->translate('Select Grade')];
            if (count($getAllgrades)) {
                if (empty($cco)) {
                    foreach ($getAllgrades as $grade_data) {
                        $result[$grade_data['GRADE_ID']] = (isset($grade_data['STANDARD_NAME']) ? $grade_data['STANDARD_NAME'].' > ' : '').$grade_data['GRADE_NAME'];
                    }
                } else {
                    foreach ($getAllgrades as $grade_data) {
                        if (!empty($grade_data['ADM_REF_ID'])) {
                            $result[$grade_data['GRADE_ID']] = (isset($grade_data['STANDARD_NAME']) ? $grade_data['STANDARD_NAME'].' > ' : '').$grade_data['GRADE_NAME'];
                        }
                    }
                }
            }
        } else {
            $result = ['' => $translator->translate('Select Grade')];
            $config = $this->serviceLocator->get('config');
            $this->dropDownApiUrl = $config['CCO_URL'];
            $selected_id = 1;
            //standard id start 
            //$dataArray = $this->apiCall()->getCcoGradeList($this->container->authDetail['PROJECT_UUID']);
            $dataArray = array();
            if (empty($this->container->authDetail['PROJECT_UUID'])) {
                $dataArray = array();
            }

            $standardid = (!empty($dataArray[0]["STANDARD_ID"])) ? $dataArray[0]["STANDARD_ID"] : "";
            //standard id end 
            $response = $this->HttpClientRequest()->clientRequest($this->dropDownApiUrl . '/api/standard?standardId=' . $standardid . '&flag=1', '', 'GET');
            // $html = '<option value="">' . $translator->translate('Grade') . '</option>';
            if ($response->isSuccess()) {
                $grades = json_decode($response->getBody(), true);
                if (count($grades['detail']) > 0) {
                    foreach ($grades['detail'] as $data) {
                        $result[$data['GRADE_ID']] = $data['GRADE_Name'];
//                    $html .= '<option value="' . $data['GRADE_ID'] . '">' . $data['GRADE_Name'] . '</option>';
                    }
                }
            }
        }

        return $result;
    }
    
    
    /*
     * @desc    Used to get country/course/subject/topic filteration
     */

    public function getAjaxAction() {
        $data = $this->getAjaxRequestAction();
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $viewModel->setTerminal(true);
        echo $data;
        die;
    }
    
    /**
     * @desc    Used to get country/course/subject/topic filteration
     */
    public function getAjax2Action() {
        $data = $this->getAjaxRequestLocal();
        $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
        $viewModel->setTerminal(true);
        echo $data;
        die;
    }
    
        /**
     * @desc used to get local DB data by AJAX request.
     * @return string
     */
        public function getAjaxRequestLocal() {
        $html = '';
        $teacherid = $this->container->authDetail['USER_OID'];
        $utid = $this->container->authDetail['UT_ID'];
        $curriculumTable = $this->initTable('Curriculum\Model\CurriculumTable');
        $this->translator = $this->serviceLocator->get('translator');
        $assessmentTable = $this->initTable('Assessment\Model\QuestionTable');
        $postData = $this->request->getPost()->toArray();
        if ($this->request->isPost() && $this->request->isXmlHttpRequest()) {
            $selected_id = $postData['id'];
            $request_type = $postData['request_type'];
            switch ($request_type) {
                case 'getLocalSubjects':
                    if ($utid == 2) {
                        $subjects = $curriculumTable->getAssignSubjectById($teacherid);
                        if (empty($subjects)) {
                            $subjects = [0];
                        }
                        $response = $assessmentTable->fetchData('t_cm_mgr_subject', ['GRADE_ID' => $selected_id, 'SUBJECT_ID' => $subjects], ['SUBJECT_ID', 'SUBJECT_NAME']);
                    } else {
                        $response = $assessmentTable->fetchData('t_cm_mgr_subject', ['GRADE_ID' => $selected_id], ['SUBJECT_ID', 'SUBJECT_NAME']);
                    }
                    $html = '<option value="">' . $this->translator->translate('Select Subject') . '</option>';
                    if (!empty($response)) {
                        foreach ($response as $data) {
                            $html .= '<option value="' . $data['SUBJECT_ID'] . '">' . $data['SUBJECT_NAME'] . '</option>';
                        }
                    }
                    return $html;
                    break;
                case "getLocalTopicsWithDropDown":
                    $response = $assessmentTable->fetchData('t_cm_mgr_curriculum_outline', ['SUBJECT_ID' => $selected_id, 'CAT_FLAG' => 'T'], ['CAT_ID', 'CAT_NAME']);
                    $html = '<option value="">' . $this->translator->translate('Select Topic') . '</option>';
                    if (!empty($response)) {
                        foreach ($response as $data) {
                            $html .= '<option value="' . $data['CAT_ID'] . '">' . $data['CAT_NAME'] . '</option>';
                        }
                    }
                    return $html;
                    break;
            }
        }
    }
    
    /**
     * @desc used to get automative test's question filtering data and maniputae/estimated them.
     * @updated by SAIF <shakeel.saif@veative.com>
     * @updated on 12.04.18
     * @return JsonModel
     */
    public function getAutomativeTestFilterDataAction() {
        $request = $this->getRequest();
        if ($request->isXmlHttpRequest()) {
            $questionMark = $questionCount = 0;
            $total_local_ques_ids = '';
            $localQuesLimit = 1000;
            $localTopicIds = $question_types = $difficulty_levels = $ques_ids = $cognitive_dropdowns = [];
            $viewModel = $this->acceptableviewmodelselector($this->acceptCriteria);
            $viewModel->setTerminal(true);
            $createQuizTable = $this->initTable('Assessment\Model\CreateQuizTable');
            $postData = $request->getPost()->toArray();
            $topicArr = [0];
            $total_ques_details_DB = $createQuizTable->fetchData('t_mgr_test_question', ['QUZ_ID' => $postData['quiz_id']], ['QUS_ID', 'QUS_MARK'], null, true);
            $topics = $createQuizTable->fetchData('t_b2c_cm_mgr_curriculum_outline', array(), array('CAT_ID'));
            if (!empty($topics)) {
                foreach ($topics as $topic) {
                    $topicArr[] = $topic["CAT_ID"];
                }
            }
            if (!empty($postData['topic'])) {
                $topicArray = explode(',', rtrim($postData['topic'], ','));
                foreach ($topicArray as $topicId) {
                    $localTopicIds[] = $topicId;
                }
            } else {
                if (!empty($postData['question_type']) || !empty($postData['difficulty_level']) || !empty($postData['cognitive_dropdown']) || !empty($postData['question_number'])) {
                    $localTopicIds = $topicArr;
                }
            }

            /** Searching Criteria for LOCAL requests only. */
            if (!empty($localTopicIds)) {
                if (!empty($postData['question_type'])) {
                    $question_types = explode(',', rtrim($postData['question_type'], ','));
                }
                if (!empty($postData['difficulty_level'])) {
                    $difficulty_levels = explode(',', rtrim($postData['difficulty_level'], ','));
                }
                if (!empty($postData['cognitive_dropdown'])) {
                    $cognitive_dropdowns = explode(',', rtrim($postData['cognitive_dropdown'], ','));
                }
                /** if user ask for limited number of question for different question types like essay type 5, fill in blank type 4 etc. */
                if (!empty($postData['question_number'])) {
                    $question_numbers = explode(',', rtrim($postData['question_number'], ','));
                    for ($i = 0; $i < count($question_numbers); $i++) {
                        $localSearchArr = array(
                            'topicId' => $localTopicIds,
                            'qnsType' => isset($question_types[$i]) ? $question_types[$i] : (isset($question_types[0]) ? $question_types[0] : ''),
                            'cognitiveId' => !empty($cognitive_dropdowns[$i]) ? $cognitive_dropdowns[$i] : '',
                            'difficultyLevel' => !empty($difficulty_levels[$i]) ? $difficulty_levels[$i] : '',
                            'localQuesLimit' => $question_numbers[$i],
                        );
                        /** Total count for Questions from LOCAL. */
                        $questionsListDBArray[] = $questionsListDB = $createQuizTable->getAllQuestion($localSearchArr, '', true, true);
                        $questionCount += count($questionsListDB);
                    }

                    /** get all added filter-criteria question-ID(s) and their mark(s). */
                    $quesListDBArray = array_map("unserialize", array_unique(array_map("serialize", array_filter($questionsListDBArray))));
                    foreach ($quesListDBArray as $valArray) {
                        foreach ($valArray as $val) {
                            $ques_ids[] = $val['QUS_ID'];
                            if (in_array($val['QUS_ID'], array_column($total_ques_details_DB, 'QUS_ID'))) {
                                $questionMark += 0;
                            } else {
                                $questionMark += $val['QUES_MARK'];
                            }
                        }
                    }
                } else {
                    /** if user did not ask for limited number of question for different question types. */
                    $localSearchArr = array(
                        'topicId' => $localTopicIds,
                        'qnsType' => $question_types,
                        'cognitiveId' => $cognitive_dropdowns,
                        'difficultyLevel' => $difficulty_levels,
                        'localQuesLimit' => $localQuesLimit,
                    );
                    /** Total count for Questions from LOCAL. */
                    $questionsListDB = $createQuizTable->getAllQuestion($localSearchArr, '', true, true);
                    $questionCount = count($questionsListDB);
                    foreach ($questionsListDB as $val) {
                        $ques_ids[] = $val['QUS_ID'];
                        if (in_array($val['QUS_ID'], array_column($total_ques_details_DB, 'QUS_ID'))) {
                            $questionMark += 0;
                        } else {
                            $questionMark += $val['QUES_MARK'];
                        }
                    }
                }
            }

            /** Appropriate question-marks as of unique Question-ID(s) found.(By SAIF on 23.03.18) */
            $total_local_ques_ids = $ques_ids;
            $total_ques_ids_DB = [];

            /** get all different and unique question-ID(s) which are not in DB. (By SAIF on 23.03.18) */
            if (count($total_ques_details_DB)) {
                /** Locally stored question-ID(s). */
                $total_ques_ids_DB = array_column($total_ques_details_DB, 'QUS_ID');
            }

            /** get total question-ID(s) whether exists in DB or not.(By SAIF on 23.03.18) */
            $total_ques_ids = array_diff($total_local_ques_ids, $total_ques_ids_DB);
            $totalQuesIds = count($total_ques_ids) ? $total_ques_ids : $total_ques_ids_DB;

            /** get question marks if stored in DB with new question(s) else zero for no-change.(By SAIF on 23.03.18) */
            $total_ques_marks = count($total_ques_ids) ? $questionMark : 0;

            $jsonModel = new JsonModel();
            $jsonModel->setVariables(array(
                'questionCount' => count($total_ques_ids),
                'questionMark' => $total_ques_marks,
                'total_ques_ids' => implode(',', $totalQuesIds),
                'presaved_ques_ids_DB' => $total_ques_ids_DB
            ));

            return $jsonModel;
        }
    }

}

Youez - 2016 - github.com/yon3zu
LinuXploit