����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 : 198.54.115.249  /  Your IP : 216.73.216.121
Web Server : LiteSpeed
System : Linux server66.web-hosting.com 4.18.0-553.44.1.lve.el8.x86_64 #1 SMP Thu Mar 13 14:29:12 UTC 2025 x86_64
User : digigcnj ( 11081)
PHP Version : 8.0.30
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : OFF  |  Pkexec : OFF
Directory :  /var/softaculous/sitepad/editor/site-data/plugins/speedycache-pro/main/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /var/softaculous/sitepad/editor/site-data/plugins/speedycache-pro/main/image.php
<?php
/*
* SPEEDYCACHE
* https://speedycache.com/
* (c) SpeedyCache Team
*/

namespace SpeedyCache;

class Image{

	static function init(){
		global $speedycache, $speedycache_optm_method;
		
		$speedycache->image = array();
		$speedycache->image['upload_dir'] = wp_upload_dir();
		$speedycache->image['id'] = false;
		$speedycache->image['metadata'] = array();
		$speedycache->image['name'] = '';
		$speedycache->image['path'] = '';
		$speedycache->image['url'] = '';
		$speedycache->image['images'] = array();
		$speedycache->image['images_clone'] = array();
		$speedycache->image['disabled_method'] = 0;
		
		// Default settings for img optimization
		$speedycache->image['settings'] = array(
			'on_upload' => false,
			'automatic_optm' => false,
			'url_rewrite' => false,
			'compression_method' => 'gd',
			'compression_quality' => '70'
		);
		
		$speedycache_optm_method = array(
			'gd' => array(
				'title' => 'GD',
				'desc' => 'Compress using PHP\'s native Extension for compression and conversion.'
			),
			'imagick' => array(
				'title' => 'Imagick',
				'desc' => 'Imagick outputs better image quality after compression at the cost of a little bigger file size compared to GD.'
			),
			'cwebp' => array(
				'title' => 'cWebP',
				'desc' => 'cwebp is a utility which can be downloaded on your server and its fast and light on you server.'
			)
		);
		
		// Binaries for cwebp
		$speedycache->image['binaries'] = array(
			'WINNT' => ['cwebp-122-windows-x64.exe', 'gif2webp-122-windows-x64.exe'],
			'Linux' => ['cwebp-122-linux-x86-64', 'gif2webp-122-linux-x86-64']
		);
		
		if(array_key_exists(PHP_OS, $speedycache->image['binaries'])){
			$speedycache->image['cwebp_binary'] = $speedycache->image['binaries'][PHP_OS][0];
			$speedycache->image['cwebp_gif'] = $speedycache->image['binaries'][PHP_OS][1];
		}

		if($img_settings = get_option('speedycache_img')){
			$speedycache->image['settings'] = array_merge($speedycache->image['settings'], $img_settings);
			self::compression_method_checks();

			return;
		}
		
		self::compression_method_checks();
		update_option('speedycache_img', $speedycache->image['settings']);

	}

	static function total_reduction(){
		global $wpdb;
		
		$query = "SELECT sum(`meta_value`) as total FROM `".$wpdb->prefix."postmeta` WHERE `meta_key`= 'speedycache_optimisation_reduction'";
		$result = $wpdb->get_row( $query );
		
		if(!empty($result->total)){
			$reduced = ($result->total && $result->total > 0) ? $result->total : 0;
			
			return $reduced > 10000 ? $reduced/1000 : $reduced;	
		}
		
		return 0;
	}

	static function optimized_file_count(){
		global $wpdb;
		
		$query = "SELECT count(`meta_value`) as optimized FROM `".$wpdb->prefix."postmeta` WHERE `meta_key`= 'speedycache_optimisation'";
		$result = $wpdb->get_row($query);
		
		if($result->optimized && $result->optimized > 0){
			return $result->optimized;
		}
		
		return 0;
	}

	static function optm_img_count(){

		return self::count_query(array(
			'post_type' => 'attachment',
			'post_mime_type' => array('image/jpeg', 'image/png', 'image/gif'),
			'post_status' => 'inherit',
			'posts_per_page' => -1,
			'meta_query' => array(
				array(
					'key' => 'speedycache_optimisation',
					'compare' => 'EXISTS'
				),
				array(
					'key' => 'speedycache_optimisation',
					'value' => base64_encode('"destination_path"'),
					'compare' => 'LIKE'
				)
			)
		));
	}

	static function error_count(){

		return self::count_query(array(
			'post_type' => 'attachment',
			'post_mime_type' => array('image/jpeg', 'image/png', 'image/gif'),
			'post_status' => 'inherit',
			'posts_per_page' => -1,
			'meta_query' => array(
				array(
					'key' => 'speedycache_optimisation',
					'compare' => 'EXISTS'
				),
				array(
					'key' => 'speedycache_optimisation',
					'value' => base64_encode('"error_code"'),
					'compare' => 'LIKE'
				)
			)
		));
	}

	static function null_posts_groupby(){
		return '';
	}

	static function count_posts_fields(){
		return 'COUNT(*) as post_count_speedycache';
	}

	static function count_query($query_images_args){
		add_filter('posts_fields', '\SpeedyCache\Image::count_posts_fields');
		add_filter('posts_groupby', '\SpeedyCache\Image::null_posts_groupby');

		unset($query_images_args['offset']);
		unset($query_images_args['order']);
		unset($query_images_args['orderby']);

		$query_images_args['posts_per_page'] = -1;

		$query_image = new \WP_Query( $query_images_args );

		return $query_image->posts[0]->post_count_speedycache;
	}

	static function image_count(){

		return self::count_query(array(
			'post_type' => 'attachment',
			'post_mime_type' => array('image/jpeg', 'image/png', 'image/gif'),
			'post_status' => 'inherit',
			'posts_per_page' => -1,
			'meta_query' => array(
				array(
					'key' => '_wp_attachment_metadata',
					'compare' => 'EXISTS'
				)
			)
		));
	}

	static function uncompressed_count(){

		return self::count_query(array(
			'post_type' => 'attachment',
			'post_mime_type' => array('image/jpeg', 'image/png', 'image/gif'),
			'post_status' => 'inherit',
			'posts_per_page' => -1,
			'meta_query' => array(
				array(
					'key' => 'speedycache_optimisation',
					'compare' => 'NOT EXISTS'
				)
			)
		));
	}

	static function unoptimized(){
		global $speedycache;
		
		$tmp_image = array();

		$optimization_data = get_post_meta($speedycache->image['id'], 'speedycache_optimisation', true);
		$optm_json = base64_decode($optimization_data);
		
		if(empty($optm_json)){
			$percentage = 100 / count($speedycache->image['images']);
			
			return array('meta_optimized' => array(), 'images' => $speedycache->image['images'], 'total_reduction' => 0, 'percentage' => $percentage);
		}

		$optm_json = json_decode($optm_json, true);
		$meta_optimized = self::object_to_array($optm_json);
		$percentage = count($meta_optimized) * 100/count($speedycache->image['images']);
		
		foreach($speedycache->image['images'] as $key => $value){
			$exist = false;

			foreach($meta_optimized as $meta_key => $meta_value){
				if($value['file'] == $meta_value['file']){
					$exist = true;
					//break;
				}
			}

			if(empty($exist)){
				array_push($tmp_image, $value);
			}
		}

		//START: total reduction
		$total_reduction = 0;
		
		foreach($meta_optimized as $m_key => $m_value){
			$m_value['reduction'] = isset($m_value['reduction']) ? $m_value['reduction'] : 0;
			
			if($m_key == 0){
				$reduction = $m_value['reduction'];
			}
			
			$total_reduction += $m_value['reduction'];
		}
		//END: total reduction

		if(count($tmp_image) <= 0){
			return array('meta_optimized' => array(), 'images' => array(), 'total_reduction' => 0);
		}

		$last = speedycache_optget('last');
		if(!empty($last)){
			if(preg_match('/last-(\d+)/', $last, $last_number)){
				if(count($tmp_image) > 5){
					$tmp_image = array_slice($tmp_image, $last_number[1]*-1, 1);
				}
			}
		}

		return array('meta_optimized' => $meta_optimized, 'images' => array_slice($tmp_image, 0, 1), 'total_reduction' => $total_reduction, 'percentage' => $percentage);
	}

	static function object_to_array($obj){
		if(is_object($obj)){
			$obj = (array) $obj;
		}
		
		if(!is_array($obj)){
			$new = $obj;
			return $new;
		}
		
		$new = array();
		foreach($obj as $key => $val){
			$new[$key] = self::object_to_array($val);
		}
		return $new;
	}

	static function reorder_by_dimensions(){
		global $speedycache;
		
		$tmp = $speedycache->image['images'];

		foreach($tmp as $key => $value){
			$width_list[$key] = $value['width'];
		}

		array_multisort($width_list, SORT_DESC, $tmp);
		
		return $tmp;
	}

	static function optimize_single($id = null){
		global $speedycache;

		if(!empty($id)){
			self::init();
		}

		self::set_id($id);
		self::set_meta_data();

		if(wp_next_scheduled('speedycache_auto_optm', array($speedycache->image['id']))){
			wp_clear_scheduled_hook('speedycache_auto_optm' , array($speedycache->image['id']));
		}

		if(empty($speedycache->image['id'])){
			return array('finish', 'success'); 
		}

		if(!isset($speedycache->image['metadata']['file']) && !empty($speedycache->image['id'])){
			$meta_optimized = array();
			$meta_optimized[0]['time'] = time();
			$meta_optimized[0]['id'] = $speedycache->image['id'];
			$meta_optimized[0]['error_code'] = 17;

			update_post_meta($speedycache->image['id'], 'speedycache_optimisation_reduction', 0);
			update_post_meta($speedycache->image['id'], 'speedycache_optimisation', base64_encode(json_encode($meta_optimized)));

			return array('Image has been optimized', 'success', $speedycache->image['id'], 100);
		}

		self::set_name();
		self::set_path();
		self::set_url();
		self::set_images();

		if(!empty($speedycache->image['id']) && count($speedycache->image['images']) == 0){
			$meta_optimized = array();
			$meta_optimized[0]['time'] = time();
			$meta_optimized[0]['id'] = $speedycache->image['id'];
			$meta_optimized[0]['error_code'] = 18;

			update_post_meta($speedycache->image['id'], 'speedycache_optimisation_reduction', 0);
			update_post_meta($speedycache->image['id'], 'speedycache_optimisation', base64_encode(json_encode($meta_optimized)));

			return array('Image has been optimized', 'success', $speedycache->image['id'], 100);
		}

		$error_exist = false;
		$meta_optimized = array();
		$total_reduction = 0;
		
		$speedycache->image['images'] = self::unique_array($speedycache->image['images']);
		$speedycache->image['images'] = self::reorder_by_dimensions();

		$speedycache->image['images_clone'] = $speedycache->image['images'];

		$unoptimized = self::unoptimized();
		$speedycache->image['images'] = $unoptimized['images'];
		$meta_optimized = $unoptimized['meta_optimized'];
		$total_reduction = $unoptimized['total_reduction'];
		$percentage = isset($unoptimized['percentage']) && $unoptimized['percentage'] ? $unoptimized['percentage'] : 0;

		if(count($speedycache->image['images']) == 0){
			return array('Image has been optimized', 'success', '', 100);
		}

		foreach($speedycache->image['images'] as $key => $value){
		
			$res = self::compress($value);
			
			if(!empty($res['success'])){
				$value['destination_path'] = $res['destination_path'];
				$value['reduction'] = $res['reduction'];

				$total_reduction += $value['reduction'];

				$value['time'] = time();
				$value['id'] = $speedycache->image['id'];
				
				array_push($meta_optimized, $value);
			}else{
				if(!isset($res['error_code']) && isset($res['error_message'])){
					return array($res['error_message'], 'error');
					break;
				}

				if(in_array($res['error_code'] , array(2, 6, 7, 11, 19, 20, 22, 23))){
					return array($res['error_message'], 'error');
					break;
				}

				$value['error_code'] = $res['error_code'];
				$error_exist = true;
			}

			$value['time'] = time();
			$value['id'] = $speedycache->image['id'];

			if(!empty($value['error_code'])){
				if($value['error_code'] != 8 || ($value['error_code'] == 8 && $key === 0)){
					array_push($meta_optimized, $value);
				}
			}
		}
		
		$percentage = self::update_meta($total_reduction, $meta_optimized);

		return array('Image has been optimized', 'success', $speedycache->image['id'], $percentage, $total_reduction);
	}

	static function update_meta($total_reduction, $meta_optimized){
		global $speedycache;
		
		if(isset($meta_optimized[0]) && isset($meta_optimized[0]['error_code']) && $meta_optimized[0]['error_code']){

			update_post_meta($speedycache->image['id'], 'speedycache_optimisation', base64_encode(json_encode($meta_optimized)));
			update_post_meta($speedycache->image['id'], 'speedycache_optimisation_reduction', 0);

			return 100;
		}

		$percentage = 0;
		$meta_temp = array();
		
		foreach($speedycache->image['images_clone'] as $key => $value){
			$backup_file = $value['file'];
			
			$value['file'] = preg_replace('/.(jpg|jpeg|png|gif)$/', '.webp', $value['file']);
			
			if(!file_exists($value['file']) || !file_exists($backup_file)){
				continue;
			}

			$diff = filesize($backup_file) - filesize($value['file']);
			$diff = $diff > 0 ? $diff : 0;

			$value['destination_path'] = $backup_file;
			$value['reduction'] = $diff;
			$value['time'] = time();
			$value['id'] = $speedycache->image['id'];

			array_push($meta_temp, $value);
		}

		foreach($meta_optimized as $m_key => $m_value){
			if(empty($m_value['error_code'])){
				continue;
			}

			$exist = false;

			for($i=0; $i < count($meta_temp); $i++){
				if($meta_temp['file'] == $m_value['file']){
					$exist = true;
				}
			}

			if(empty($exist)){
				$m_value['destination_path'] = '';
				$m_value['reduction'] = 0;
				$m_value['time'] = time();
				$m_value['id'] = $speedycache->image['id'];

				array_push($meta_temp, $m_value);
			}
		}
		
		if(count($meta_temp) > 0){
			$percentage = count($meta_temp)*100/count($speedycache->image['images_clone']);
		}else{
			$percentage = 0;
		}

		update_post_meta($speedycache->image['id'], 'speedycache_optimisation_reduction', $total_reduction);
		update_post_meta($speedycache->image['id'], 'speedycache_optimisation', base64_encode(json_encode($meta_temp)));

		return $percentage;
	}

	static function compress($source_image){
		global $speedycache;

		/*
			Error Codes
			2 = in backup folder parent folder not writable
			3 = no need to optimize
			4 = source is not writable
			5 = destination is not writable
			6 = ImageMagick library is not avaliable
			7 = Error via api
			8 = Source file does not exist
			9 = Image size exceed 5mb limit while processing
		   11 = Empty Name
		   12 = Forbidden
		   13 = CloudFlare to restrict access
		   14 = No Extension
		   15 = Image size is 0Kb
		   16 = Corrupted Image
		   17 = Empty Metadata
		   18 = No Image
		   19 = webp is not saved
		   20 = file size of destination_move_source_path is zero
		   21 = Unacceptable file type
		   22 = Unable to Convert Image using cwebp.
		   23 = The URL of the image has webp extension.
		*/

		// if the url starts with /wp-content
		if(preg_match('/^\/' . SPEEDYCACHE_WP_CONTENT_DIR . '/i', $source_image['url'])){
			$source_image['url'] = home_url().$source_image['url'];
		}

		$source_path = $source_image['file'];
		$res_backup = array('success' => true, 'error_message' => '');
		$webp_path = preg_replace('/.(jpe?g|png|gif)$/', '.webp', $source_path);

		if(strlen($speedycache->image['name']) === 0){
			return array('success' => false, 'error_code' => 11);
		}

		if(!file_exists($source_path)){
			return array('success' => false, 'error_code' => 8);
		}

		if(!pathinfo($source_image['url'], PATHINFO_EXTENSION)){
			return array('success' => false, 'error_code' => 14);
		}

		// If the URL of the image is a webp
		if(pathinfo($source_image['url'], PATHINFO_EXTENSION) == 'webp' && file_exists($webp_path)){
			return array('success' => false, 'error_code' => 23);
		}

		if(@filesize($source_path) > 5000000){
			return array("success" => false, 'error_code' => 9);
		}

		if(!self::allowed_mime($source_path)){
			return array('success' => false, 'error_code' => 21);
		}

		if(!self::path_is_image($source_path)){
			return array('success' => false, 'error_code' => 16);
		}

		if(filesize($source_path) == 0){
			return array('success' => false, 'error_code' => 15);
		}

		if(@rename($source_path, $source_path.'_writabletest')){
			rename($source_path.'_writabletest', $source_path);
		}else{
			return array('success' => false, 'error_message' => $source_path . ' is not writable', 'error_code' => 4);
		}

		$optm_result = self::start_optimization($source_path); // here we need to plugin compression static function
		
		if(empty($optm_result['success'])){
			//NOTE:Place some error Message here.
			return $optm_result;
		}

		if(!file_exists($webp_path)){
			return array('success' => false, 'error_code' => 19, 'error_message' => $webp_path . ' destination_path is not saved');
		}
		
		if(filesize($webp_path) <= 0){
			return array('success' => false, 'error_code' => 20, 'error_message' => $webp_path . ' file size of destination_path is zero');
		}

		$diff = self::compare_sizes($source_path, $webp_path);
		return array('success' => true, 'destination_path' => $webp_path, 'reduction' => $diff);
	}


	static function start_optimization($img){
		global $speedycache;

		if(empty($speedycache->image['settings']['compression_method'])){
			return array('success' => false,  'error_message' => __('The provided conversion method is not valid', 'speedycache-pro'));
		}

		switch($speedycache->image['settings']['compression_method']){
			case 'gd': 
				return self::gd_webp($img);
				
			case 'imagick':
				return self::imagick_webp($img);
				
			case 'cwebp':
				if(defined('SPEEDYCACHE_PRO')){					
					return \SpeedyCache\Image::cwebp_convert($img);
				}
				
				return array('success' => false, 'error_message' => 'SpeedyCache cwebp is a Pro feature');
				
			default:
				return array('success' => false,  'error_message' => 'The provided conversion method is not valid');
		}
	}

	static function path_is_image($source_path){
		$size = getimagesize($source_path);

		if(empty($size)){
			return false;
		}

		return true;
	}

	static function get_quality($img){
		$dimensions = $img->getImageGeometry();
		
		if($dimensions['width'] < 200 && $dimensions['height'] < 200){
			return 85;
		}

		return 90;
	}

	static function compare_sizes($source_path, $destination_path){
		$diff = filesize($source_path) - filesize($destination_path);

		return ($diff > 0) ? $diff : 1;
	}


	//TODO:: Will need it when we will add non webp compression
	static function create_backup_folder($destination_path){
		global $speedycache;
		
		$destination_path = str_replace($speedycache->image['upload_dir']['basedir'], '', $destination_path);
		$path_arr = explode('/', $destination_path);

		$path = $speedycache->image['upload_dir']['basedir'];

		for ($i=1; $i < count($path_arr) - 1; $i++){
			$parent_path = $path;
			$path = $path.'/'.$path_arr[$i];

			if(is_dir($path)){
				continue;
			}
			
			if(@mkdir($path, 0755, true)){
				//
			}else{
				//warning
				if($path_arr[$i] == 'speedycache-backup'){
					//toDO: to stop cron job and warn the user
				}

				return array('success' => false, 'error_message' => $parent_path.' is not writable', 'error_code' => 2);
			}
		}

		return array('success' => true, 'error_message' => '');
	}

	static function set_id($id = null){
		global $speedycache;
		
		$get_id = speedycache_optget('id');
		
		if(!empty($get_id)){
			$speedycache->image['id'] = intval($get_id);
		}elseif(!empty($id)){
			$speedycache->image['id'] = intval($id);
		}else{
			$speedycache->image['id'] = self::get_first_id();
		}
	}

	static function set_images(){
		global $speedycache;
		
		if(empty($speedycache->image['metadata']['file'])){
			return;
		}

		$arr = array(
			'file' => $speedycache->image['upload_dir']['basedir'].'/'.$speedycache->image['metadata']['file'],
			'url' => $speedycache->image['upload_dir']['baseurl'].'/'.$speedycache->image['metadata']['file'],
			'width' => $speedycache->image['metadata']['width'],
			'height' => $speedycache->image['metadata']['height'],
			'mime_type' => ''
		);
		
		array_push($speedycache->image['images'], $arr);

		$i = 0;
		$image_error = false;

		if(!is_array($speedycache->image['metadata']['sizes'])){
			if(empty($image_error)){
				self::not_in_metadata();
			}
		}

		foreach((array)$speedycache->image['metadata']['sizes'] as $key => $value){
			$value['url'] = $speedycache->image['url'].$value['file'];
			$value['file'] = $speedycache->image['path'].$value['file'];
			$value['mime_type'] = isset($value['mime-type']) ? $value['mime-type'] : '';

			unset($value['mime-type']);

			if($i == 0){
				if(self::not_found(self::get_correct_url($speedycache->image['upload_dir']['baseurl'].'/'.$speedycache->image['metadata']['file']))){
					$image_error = true;
					break;
				}
			}

			if(!self::not_found(self::get_correct_url($value['url'])) && self::allowed_mime($value['file'])){
				array_push($speedycache->image['images'], $value);
			}

			$i++;
		}

		if(empty($image_error)){
			self::not_in_metadata();
		}
	}

	static function get_correct_url($path){
		if(preg_match('/^\/'.SPEEDYCACHE_WP_CONTENT_DIR.'/i', $path)){
			
			// content_url() must return HTTP but it return /wp-content so we need to check
			if(content_url() == '/'.SPEEDYCACHE_WP_CONTENT_DIR && home_url() == site_url()){
				$path = home_url().$path;
			}
		}

		return $path;
	}

	static function not_in_metadata(){
		global $speedycache;
		
		$paths = array();

		foreach($speedycache->image['images'] as $key => $value){
			array_push($paths, $value['file']);
		}
		
		$files = glob($speedycache->image['path'].$speedycache->image['name'].'-'.'*');

		foreach((array)$files as $file){
			if(@filesize($file) > 1000000){
				continue;
			}

			if(!preg_match('/\.(jpg|jpeg|jpe|png|gif)$/i', $file)){
				continue;
			}

			$exp_dos = explode('/',$file);
			$basename = end($exp_dos);

			if(in_array($file, $paths)){
				continue;
			}
			
			if(!preg_match('/'.preg_quote($speedycache->image['name'], '/').'-(\d+)x(\d+)\..+/', $basename, $dimensions)){
				continue;
			}
			
			$value = array(
				'url' => $speedycache->image['url'].$basename,
				'file' => $file,
				'width' => $dimensions[1],
				'height' => $dimensions[2],
			);

			if(!self::not_found($value['url'])){
				array_push($speedycache->image['images'], $value);
			}
		}
	}

	static function set_path(){
		global $speedycache;
		
		$speedycache->image['path'] = $speedycache->image['upload_dir']['basedir'].'/'.preg_replace('/'.preg_quote($speedycache->image['name'], '/').'.+/', '', $speedycache->image['metadata']['file']);
	}

	static function set_url(){
		global $speedycache;
		
		$speedycache->image['url'] = $speedycache->image['upload_dir']['baseurl'].'/'.preg_replace('/'.preg_quote($speedycache->image['name'], '/').'.+/', '', $speedycache->image['metadata']['file']);
	}

	static function set_name(){
		global $speedycache;
		
		if(empty($speedycache->image['metadata'])){
			return;
		}

		if(isset($speedycache->image['metadata']['sizes']) && count($speedycache->image['metadata']['sizes']) > 0){
			$array_values = array_values($speedycache->image['metadata']['sizes']);
			$speedycache->image['name'] = preg_replace('/-'.$array_values[0]['width'].'x'.$array_values[0]['height'].'.+/', '', $array_values[0]['file']);

			if(!$speedycache->image['name']){
				$speedycache->image['name'] = substr($speedycache->image['metadata']['file'], strrpos($speedycache->image['metadata']['file'], '/') + 1);
			}
			
			return;
		}

		$info = pathinfo($speedycache->image['metadata']['file']);
		$speedycache->image['name'] =  basename($speedycache->image['metadata']['file'],'.'.$info['extension']);

		//$this->name = substr($this->metadata['file'], strrpos($this->metadata['file'], '/') + 1);
	}

	static function set_meta_data(){
		global $speedycache;
		
		$speedycache->image['metadata'] = wp_get_attachment_metadata($speedycache->image['id']);
	}

	//to get last image which is not optimized
	static function get_first_id(){

		$query_image = new \WP_Query(array(
			'order' => 'DESC',
			'orderby' => 'ID',
			'post_type' => 'attachment', 
			'post_mime_type' => 'image/jpeg, image/png, image/gif', 
			'post_status' => 'inherit',
			'posts_per_page' => 1,
			'meta_query' => array(
				array(
					'key' => 'speedycache_optimisation',
					'compare' => 'NOT EXISTS'
				),
				array(
					'key' => '_wp_attachment_metadata',
					'compare' => 'EXISTS'
				)
			)
		));

		return count($query_image->posts) == 1 ? $query_image->posts[0]->ID : false;
	}

	static function statics_data(){
		$res = array(
			'total_image_number' => self::image_count(),
			'error' => self::error_count(),
			'optimized' => self::optimized_file_count(),
			'uncompressed' => self::uncompressed_count(),
			'reduction' => self::total_reduction(),
			'percent' => 0,
		);

		if($res['optimized'] > 0){
			$res['percent'] = ($res['optimized'] - $res['error']) * 100/$res['optimized'];
		}else{
			$res['percent'] = 0;
		}
		
		$res['percent'] = number_format($res['percent'], 2);
		$res['reduction'] = $res['reduction'];
		
		return $res;
	}

	static function revert_all(){
		global $speedycache;
		
		if(!current_user_can('manage_options')){
			wp_die('Must Be admin');
		}

		$images = new \WP_Query(array(
			'order' => 'DESC',
			'orderby' => 'ID',
			'post_type' => 'attachment',
			'post_mime_type' => array('image/jpeg', 'image/png', 'image/gif'),
			'post_status' => 'inherit',
			'posts_per_page' => -1,
			'meta_query' => array(
				array(
					'key' => 'speedycache_optimisation',
					'compare' => 'EXISTS'
				)
			)
		));

		$failed = true;
		
		if(count($images->posts) <= 100){
			
			if($images->posts && count($images->posts) > 0){
				foreach($images->posts as $key => $post){
					$speedycache->image['id'] = $post->ID;
					$result = self::revert();
					
					if($result['success'] === true){
						$failed = false;
					}
				}
			}
			
			if(!empty($failed)){
				wp_send_json(array('success' => false, 'message' => __('Files can\'t be reverted', 'speedycache'))); 
			}
			
			wp_send_json(array('success' => true));
		}

		$schedule_posts = [];
		foreach($images->posts as $key => $post){
			
			if(100 === count($schedule_posts) || !empty($erase)){
				$schedule_posts = [];
			}

			$erase = false; // Flag to unset the $scheduled_posts
			
			$schedule_posts[] = $post->ID;

			// Check if we have reached 99 and make sure its not the last index
			if(count($schedule_posts) <= 99 && $key !== (count($images->posts) - 1)){
				continue;
			}
			
			// Skip if alredy on schedule list.
			if(wp_next_scheduled('speedycache_img_delete', array($schedule_posts))){
				$erase = true;
				continue;
			}
		
			$scheduled = self::get_optimization_schedule(array('speedycache_img_delete'));
			$time = time();
		
			if(!empty($scheduled) && isset(end($scheduled)['time'])){
				// getting the last index to get the last scheduled event
				$time = end($scheduled)['time'];
			}
			
			$final_schd_time = $time + 10;
		
			if(!wp_next_scheduled('speedycache_img_delete', array($schedule_posts))){
				wp_schedule_single_event($final_schd_time, 'speedycache_img_delete', array($schedule_posts));
				
				continue;
			}
		}

		wp_send_json(array('success' => true));
	}

	// Schedule deletion of image to reduce load on the server at a single time.
	static function scheduled_delete($img_id){
		global $speedycache;
		
		if(empty($img_id)){
			return;
		}

		if(is_scalar($img_id)){
			$speedycache->image['id'] = $img_id;
			self::revert();
			return;
		}
		
		foreach($img_id as $id){
			$speedycache->image['id'] = $id;
			self::revert();
		}
	}

	// Reverts a single image
	static function revert(){
		global $speedycache;
		
		if(empty($speedycache->image['id'])){
			return array('success' => false);
		}
		
		$optimization_data = get_post_meta($speedycache->image['id'], 'speedycache_optimisation', true);
		
		if(empty($optimization_data)){
			return array('success' => false);
		}

		// optm = optimization
		$optm_json = base64_decode($optimization_data);
		$optm_json = json_decode($optm_json, true);
		
		if(empty($optm_json)){
			return array('success' => false);
		}

		if(!empty($optm_json) && is_array($optm_json) && count($optm_json) == 1 && !empty($optm_json[0])){
			if(!empty($optm_json[0]['error_code']) && $optm_json[0]['error_code'] == 18){
				delete_post_meta($speedycache->image['id'], 'speedycache_optimisation');
				delete_post_meta($speedycache->image['id'], 'speedycache_optimisation_reduction');

				return array('success' => true);
			}
		}

		$result = false;

		$optm_json = array_reverse($optm_json);
		$error_numbers = 0;
		
		foreach($optm_json as $key => $image){

			if(@!is_writable($image['file'])){
				if(isset($speedycache->image['metadata']['file']) && preg_match('/'.preg_quote($speedycache->image['metadata']['file'], '/').'/', $image['url'])){
					if(file_exists($image['file'])){
						$result = array('success' => true, 'message' => $image['file'].' is not writable');
						break;
					}
					
					delete_post_meta($speedycache->image['id'], 'speedycache_optimisation');
					delete_post_meta($speedycache->image['id'], 'speedycache_optimisation_reduction');
				}
			}

			if(
				!empty($image['url']) && 
				!preg_match('/\.webp$/', $image['url']) && 
				isset($image['destination_path']) && 
				file_exists($image['destination_path']) &&
				(pathinfo($image['destination_path'], PATHINFO_EXTENSION) !== 'webp') &&
				(pathinfo($image['file'], PATHINFO_EXTENSION) == 'webp')
			){
				@unlink($image['file']);

				delete_post_meta($speedycache->image['id'], 'speedycache_optimisation');
				delete_post_meta($speedycache->image['id'], 'speedycache_optimisation_reduction');
				$result = array('success' => true);
				
				continue;
			}

			if(!empty($image['error_code'])){
				if(isset($speedycache->image['metadata']['file']) && preg_match('/'.preg_quote($speedycache->image['metadata']['file'], '/').'/', $image['url'])){
					delete_post_meta($speedycache->image['id'], 'speedycache_optimisation');
					delete_post_meta($speedycache->image['id'], 'speedycache_optimisation_reduction');
					$result = array('success' => true);
				}else{
					$error_numbers++;

					if($error_numbers == count($optm_json)){
						delete_post_meta($speedycache->image['id'], 'speedycache_optimisation');
						delete_post_meta($speedycache->image['id'], 'speedycache_optimisation_reduction');
						$result = array('success' => true);
					}
				}
				
				continue;
			}

			if(preg_match('/'.preg_quote($speedycache->image['metadata']['file'], '/').'/', $image['url'])){
				delete_post_meta($speedycache->image['id'], 'speedycache_optimisation');
				delete_post_meta($speedycache->image['id'], 'speedycache_optimisation_reduction');
				$result = array('success' => true);
			}

		}
		
		return $result;
	}

	static function revert_on_delete($id){
		global $speedycache;
		
		if(!wp_attachment_is_image($id)){
			return;
		}
		
		$speedycache->image['id'] = $id;
		
		self::revert();
	}

	static function get_error_text($id){
		
		//Error Codes
		$errors = array(
			2 => __('In backup folder parent folder not writable', 'speedycache'),
			3 => __('No need to optimize', 'speedycache'),
			4 => __('Source is not writable', 'speedycache'),
			5 => __('Destination is not writable', 'speedycache'),
			6 => __('ImageMagick library is not avaliable', 'speedycache'),
			7 => __('Error via api', 'speedycache'),
			8 => __('Source file does not exist', 'speedycache'),
			9 => __('Image size exceed 20mb limit while processing', 'speedycache'),
		   11 => __('Empty Name', 'speedycache'),
		   12 => __('Forbidden', 'speedycache'),
		   13 => __('CloudFlare to restrict access', 'speedycache'),
		   14 => __('No Extension', 'speedycache'),
		   15 => __('Image size is 0Kb', 'speedycache'),
		   16 => __('Corrupted Image', 'speedycache'),
		   17 => __('Empty metadata', 'speedycache'),
		   18 => __('No Image', 'speedycache'),
		   19 => __('destination_move_source_path is not saved', 'speedycache'),
		   20 => __('file size of destination_move_source_path is zero', 'speedycache'),
		   21 => __('Unacceptable file type', 'speedycache'),
		   23 => __('WEBP create by other tool', 'speedycache'),
		);

		return isset($errors[$id]) ? $errors[$id] : 'Unkown error code';
	}

	// TODO:: Will use it when we will do non-webp compression
	static function backup_folder_exist(){
		global $speedycache;
		
		$backup_folder_path = $speedycache->image['upload_dir']['basedir'].'/speedycache-backup';

		if(is_dir($backup_folder_path)){
			return true;
		}

		if(@mkdir($backup_folder_path, 0755, true)){
			return true;
		}
		return false;

	}

	static function push_main_image($arr){
		if(!isset($arr[0]) || isset($arr[0]->error_code)){
			return $arr;
		}

		$main = clone $arr[0];
		$total_reduction = 0;

		foreach($arr as $std_key => $std_value){
			if(!isset($std_value->error_code)){
				if(isset($std_value->reduction) && $std_value->reduction){
					$total_reduction = $total_reduction + $std_value->reduction;
				}
			}
		}

		$main->reduction = $total_reduction;

		array_unshift($arr, $main);

		return $arr;
	}

	static function list_content($query_images_args = array()){
		global $speedycache;
		
		remove_filter('posts_fields', '\SpeedyCache\Image::count_posts_fields'); //was causing bug
		
		$query_image = new \WP_Query( $query_images_args );
		$return_output = '';
		
		if(empty($query_image->posts) || count($query_image->posts) <= 0){
			return self::get_empty_row();
		}
		
		$count = 0;
		foreach($query_image->posts as $key => $post){
			$count++;
			$value_json = get_post_meta($post->ID, 'speedycache_optimisation', true);
			$tmpvalue_json = base64_decode($value_json);
			
			$std = json_decode($tmpvalue_json);

			$revert = true;

			$std = self::push_main_image($std);
			
			foreach($std as $std_key => $std_value){
				
				$content = ($std_key === 0) ? self::get_row() : self::get_child_row();

				if(empty($content)){
					continue;
				}

				$std_value->destination_path = isset($std_value->destination_path) ? $std_value->destination_path : '';
				$std_value->reduction = isset($std_value->reduction) ? $std_value->reduction : 0;
				
				if($std_key === 0 && $revert){
					$revert_button = '';
				}else{
					$revert_button = 'display:none;';
				}

				if(isset($std_value->error_code) && $std_value->error_code == 8){
					$revert_button = 'display:none;';
				}

				if(file_exists($std_value->destination_path)){
					$backup_url = $std_value->url.'?v='.time();
					$backup_title = 'Original Image';
					$backup_error_style = '';
				}else{
					if(isset($std_value->error_code) && $std_value->error_code){
						$backup_url = get_edit_post_link($std_value->id);
						$backup_title = self::get_error_text($std_value->error_code);
						$backup_error_style = 'color: #FF0000;cursor:pointer;font-weight:bold;';
					}else{
						$backup_url = '#';
						$backup_title = '';
						$backup_error_style = '';
					}
				}
				
				$std_value->file = preg_replace('/.(jpg|jpeg|png|gif)$/','.webp', $std_value->file);
				
				if(file_exists($std_value->file)){
					$std_value->url = preg_replace('/.(jpg|jpeg|png|gif)$/','.webp', $std_value->url).'?v='.time();
				}else{
					$std_value->url = SPEEDYCACHE_PRO_URL.'/assets/images/no-image.png';
				}

				$short_code = array(
					'{{post_id}}',
					'{{attachment}}',
					'{{post_title}}',
					'{{url}}',
					'{{width}}',
					'{{height}}',
					'{{reduction}}',
					'{{date}}',
					'{{revert_button}}',
					'{{backup_url}}',
					'{{backup_title}}',
					'{{backup_error_style}}'
				);
				
				$datas = array(
					$std_value->id,
					$std_value->url,
					$post->post_title,
					$std_value->url,
					$std_value->width,
					$std_value->height,
					$std_value->reduction/1000,
					date('d-m-Y <br> H:i:s', $std_value->time),
					$revert_button,
					$backup_url,
					$backup_title,
					$backup_error_style
				);
			
				$return_output .= str_replace($short_code, $datas, $content);
			}
		}
		return $return_output;
	}

	static function allowed_mime($filename){
		global $speedycache;
		
		$mimetype = false;

		if(!file_exists($filename)){
			return false;
		}

		if(function_exists('finfo_open')){
		   $finfo = finfo_open(FILEINFO_MIME_TYPE);
		   $mimetype = finfo_file($finfo, $filename);
		   finfo_close($finfo);
		}else if(function_exists('getimagesize')){
		   $img = getimagesize($filename);
		   $mimetype = $img['mime'];
		}else{
			echo 'not found mime_content_type';
			exit;
		}
		
		if(!empty($speedycache->image['settings']['compression_method']) && $speedycache->image['settings']['compression_method'] === 'cwebp' && self::gif2webp_exists()){
			if(preg_match('/(jpg|jpeg|jpe|png|gif)/i', $mimetype)){
				return true;
			}
			
			return false;
		}

		if(preg_match('/(jpg|jpeg|jpe|png)/i', $mimetype)){
			return true;
		}
		
		return false;
	}

	// Check if the image is available, the response code should be 200
	static function not_found($url){
		return false;
		
		$res = wp_remote_head($url, array('timeout' => 3 ));

		if(is_wp_error($res)){
			$url_header = @get_headers($url);

			if(preg_match('/200\s+OK/i', $url_header[0])){
				return false;
			}
			
			return true;
		}
		
		if($res['response']['code'] == 200){
			return false;
		}

		return true;
	}

	//Checks if the image is Unique
	static function unique_array($images){
		if(count($images) <= 1){
			return $images;
		}

		$arr = array();
		$images_tmp = array();

		foreach($images as $key => $value){
			if(!in_array($value['file'], $arr)){
				array_push($arr, $value['file']);
				array_push($images_tmp, $value);
			}
		}
		
		return $images_tmp;
	}
	//Template static functions Starts Here

	//Table row for the converted Image
	static function get_row(){
		return '<tr class="alternate author-self status-inherit" post-id="{{post_id}}">
			<td class="column-icon media-icon image-icon">
				<img width="39" height="60" src="{{attachment}}" class="attachment-80x60">
			</td>
			<td class="title column-title">
				<p style="margin-bottom: 0;"><a href="{{url}}" target="_blank">{{post_title}}</a></p>
				<p style="margin-bottom: 0;">
					<a style="{{backup_error_style}}" href="{{backup_url}}" target="_blank"><strong>{{backup_title}}</strong></a>
				</p>
			</td>
			<td class="author column-author speedycache-open-image-details" style="text-align: center;cursor: pointer;">{{reduction}}KB<span class="dashicons dashicons-arrow-down-alt2"></span></td>
			<td class="date column-date" style="text-align: center;">{{date}}</td>
			<td class="date column-date" style="text-align: center;">
			<div class="speedycache-revert" style="{{revert_button}}">
				<input type="hidden" value="{{post_id}}">
			</div>
			</td>
		</tr>';
	}

	//table row for different sizes of image.
	static function get_child_row(){
		
		return '<tr class="alternate author-self status-inherit" post-id="{{post_id}}" post-type="detail" style="display: none; padding-left: 20px;">
			<td class="column-icon media-icon" style="font-size:3.5em; color:#ccc;"><span class="dashicons dashicons-format-image"></span></td>
			<td class="title column-title">
				<p style="margin-bottom: 0;"><a href="{{url}}" target="_blank">{{post_title}}</a></p>
				<p style="margin-bottom: 0;">
					<a style="{{backup_error_style}}" href="{{backup_url}}" target="_blank"><strong>{{backup_title}}</strong></a>
				</p>
				<p style="margin-bottom: 0;">{{width}}x{{height}}</p>
			</td>
			<td class="author column-author" style="text-align: center;">{{reduction}}KB</td>
			<td class="date column-date" style="text-align: center;">{{date}}</td>
			<td class="date column-date" style="text-align: center;">
			</td>
		</tr>';
	}

	//No Image optimized
	static function get_empty_row(){
		return '<tr class="author-self status-inherit">
			<td colspan="4">No image has been optimized yet</td>
		</tr>';

	}

	//Paging for the converted Images Table
	static function paging(){ ?>
		<div class="tablenav bottom" style="padding:5px 16px 5px 19px">
			<div style="float:left;">
				<span class="deleteicon">
					<input type="text" style="height:28px;" placeholder="Search" id="speedycache-image-search-input" class="deletable" value="">
					<span class="cleared"></span>
				</span>
				<input type="submit" class="button action" value="Search" id="speedycache-image-search-button" name="filter_action">
			</div>
			<div style="float:left;padding-left:5px;">
				<select id="speedycache-image-list-filter" class="bulk-action-selector-top">
					<option value="" selected="selected">All</option>
					<option value='error_code'>Errors</option>
				</select>
			</div>
			<div style="float:left;padding-left:5px;">
				<select id="speedycache-image-per-page" class="bulk-action-selector-top">
					<option value="5" selected="selected">5</option>
					<option value="10">10</option>
					<option value="25">25</option>
				</select>
			</div>
			<div class="tablenav-pages">
				<span class="pagination-links">
					<a class="tablenav-pages-navspan button first-page disabled speedycache-image-list-first-page" aria-hidden="true" data-page-action="first-page">«</a>
					<a class="tablenav-pages-navspan button prev-page speedycache-image-list-prev-page" aria-hidden="true" data-page-action="prev-page">‹</a>
					<a class="paging-input"><label class="speedycache-current-page">1</label> / <span class="total-pages speedycache-total-pages">1</span></a>
					<a class="next-page button speedycache-image-list-next-page" data-page-action="next-page">›</a>
					<a class="last-page button speedycache-image-list-last-page" data-page-action="last-page">»</a>
				</span>
			</div>
			<br class="clear">
		</div>
	<?php
	}

	//Settings for Image Optimization
	static function settings(){
		global $speedycache, $speedycache_optm_method; 

		?>
		<div class="speedycache-block">
			<div class="speedycache-block-title"><h2><?php _e('Settings', 'speedycache'); ?></h2></div>
			<form class="speedycache-img-opt-settings">
				<div class="speedycache-option-wrap">
					<label for="speedycache_img_automatic_optm" class="speedycache-custom-checkbox">
						<input type="checkbox" id="speedycache_img_automatic_optm" name="img_automatic_optm" <?php echo (isset($speedycache->image['settings']['automatic_optm']) && $speedycache->image['settings']['automatic_optm']) ? ' checked="true"' : '';?>/>
						<div class="speedycache-input-slider"></div>
					</label>
					<div class="speedycache-option-info">
						<span class="speedycache-option-name"><?php esc_html_e('Automatic optimization', 'speedycache'); ?></span>
						<span class="speedycache-option-desc"><?php esc_html_e('Whenever user visits the website and there are images that haven\'t been converted to webp then that image(s) gets converted.', 'speedycache'); ?></span>
					</div>
				</div>
				<div class="speedycache-option-wrap">
					<label for="speedycache_img_on_upload" class="speedycache-custom-checkbox">
						<input type="checkbox" id="speedycache_img_on_upload" name="img_on_upload" <?php echo (isset($speedycache->image['settings']['on_upload']) && $speedycache->image['settings']['on_upload']) ? ' checked="true"' : '';?>/>
						<div class="speedycache-input-slider"></div>
					</label>
					<div class="speedycache-option-info">
						<span class="speedycache-option-name"><?php esc_html_e('Optimize on Image Upload', 'speedycache'); ?></span>
						<span class="speedycache-option-desc"><?php esc_html_e('Images will be added to a queue and will optimized after a certain interval to reduce load on the server.', 'speedycache'); ?></span>
					</div>
				</div>
				
				<div class="speedycache-option-wrap">
					<label for="speedycache_img_url_rewrite" class="speedycache-custom-checkbox">
						<input type="checkbox" id="speedycache_img_url_rewrite" name="img_url_rewrite" <?php echo (isset($speedycache->image['settings']['url_rewrite']) && $speedycache->image['settings']['url_rewrite']) ? ' checked="true"' : '';?>/>
						<div class="speedycache-input-slider"></div>
					</label>
					<div class="speedycache-option-info">
						<span class="speedycache-option-name"><?php esc_html_e('Rewrite Image URL\'s', 'speedycache'); ?></span>
						<span class="speedycache-option-desc"><?php esc_html_e('Rewrites the url of the image on the page to the webp version if webp version is avaliable.', 'speedycache'); ?></span>
					</div>
				</div>

				<div class="speedycache-option-wrap">
					<label for="speedycache_img_quality">
						<input type="number" id="speedycache_img_quality" name="img_compression_quality" value="<?php echo esc_attr($speedycache->image['settings']['compression_quality']);?>" min="50" step="5" max="90"/>
					</label>
					<div class="speedycache-option-info">
						<span class="speedycache-option-name"><?php esc_html_e('Compression Quality', 'speedycache'); ?></span>
						<span class="speedycache-option-desc"><?php esc_html_e('Higher the number higher will be the converted image quality in webp', 'speedycache'); ?></span>
					</div>
				</div>
				
				<div class="speedycache-block-title" style="flex-direction:column">
					<h4><?php esc_html_e('Conversion Methods', 'speedycache'); ?></h4>
					<p style="display:block; font-family: monospace; background-color: #f2f2f2; border-radius:6px; padding:10px;">
						<span style="color:var(--speedycache-red); font-weight:bold;"><span class="dashicons dashicons-info-outline"></span> Note: </span>
						<?php 
							esc_html_e('Only cwebp supports gif conversions to webp. But when you upload an image to ' . (defined('SITEPAD') ? 'Sitepad' : 'WordPress') . ' whether it be a jpg, png, or gif format, ' . (defined('SITEPAD') ? 'Sitepad' : 'WordPress') . ' creates different sizes of that image on upload so, in the process of resizing some resized version of gifs may lose their animation.', 'speedycache-pro');
						?>
					</p>
				</div>
				<?php foreach($speedycache_optm_method as $m_key => $method){ ?>
					<div class="speedycache-option-wrap <?php echo !$method['status'] ? ' speedycache-disabled-methods' : '' ?>">
						<label for="speedycache-img-<?php echo esc_attr($m_key);?>">
							<input type="radio" value="<?php echo esc_attr($m_key);?>" name="img_compression_method" id="speedycache-img-<?php echo esc_attr($m_key);?>" <?php echo (isset($speedycache->image['settings']['compression_method']) && $speedycache->image['settings']['compression_method'] == $m_key ? ' checked="true"' : '');?> <?php echo !$method['status'] ? ' disabled' : '' ?>/>
						</label>
						<div class="speedycache-option-info">
							<span class="speedycache-option-name"><?php echo esc_html($method['title']); ?></span>
							<span class="speedycache-option-desc"><?php echo esc_html($method['desc']); ?></span>
						</div>
						<?php 
						// TODO:: Need to fix this _e as it is a dynamic value we will need to use sprintf
						if(!$speedycache_optm_method[$m_key]['status']){ ?>
							<div class="speedycache-more-info" data-info="<?php echo esc_html($speedycache_optm_method[$m_key]['message']);?>" >
								<span class="dashicons dashicons-editor-help"></span>
							</div>
						<?php } ?>
							<div class="speedycache-img-method-actions">
						<?php 
						
						if($m_key == 'cwebp'){
							if(defined('SPEEDYCACHE_PRO') && !file_exists(wp_upload_dir()['basedir']. '/speedycache-binary/'.$speedycache->image['cwebp_binary'])){
								echo '<button style="margin-right:5px;" class="speedycache-button speedycache-btn-black speedycache-webp-download">Download Binary</button>';
							}
							
							if(defined('SPEEDYCACHE_PRO') && !self::gif2webp_exists()){
								echo '<button class="speedycache-button speedycache-btn-black speedycache-webp-download" style="margin-top:2px;" data-type="gif">Download Binary for GIF</button>';
							}
						}
						?>
						</div>
					</div>	
				<?php } ?>
			</form>
		</div>
	<?php 
	}


	//Image Optimization Stats
	static function statics(){
		$res = self::statics_data();
		$ring_success = 100 - (int)$res['percent'];
		
		$scheduled = self::get_optimization_schedule(array('speedycache_auto_optm', 'speedycache_img_delete'));
		$scheduled_count = count($scheduled);
		
		//the css below is written in one line to make regex replace easy in js update.
	?>
		<style>
			@keyframes donut1 {
			0%{stroke-dasharray: 0, 100;}
			100%{stroke-dasharray: <?php echo esc_attr($res['percent'] .', ' . $ring_success);?>;}
		}
		</style>
		<div class="speedycache-block">
			<div class="speedycache-img-stats speedycache-admin-row">
				<div class="speedycache-is-block speedycache-img-graph">
					<div class="speedycache-card-body">
						<div class="speedycache-img-start-optm">
							<div class="speedycache-img-stat-info">
								<div class="speedycache-img-main-stat">
									<?php esc_html_e('Success', 'speedycache'); ?>
									<span class="speedycache-img-success-per"><?php echo esc_html($res['percent']);?>%</span>
								</div>
								<div class="speedycache-img-main-stat">
									<?php esc_html_e('Error', 'speedycache');?>
									<span class="speedycache-img-error-count" <?php echo $res['error'] > 0 ? 'style="color:#dc3545"' : '' ?>><?php echo esc_html($res['error']);?></span>
								</div>
								<div class="speedycache-img-main-stat">
									<?php esc_html_e('Scheduled', 'speedycache');?>
									<span class="speedycache-scheduled-count <?php echo $scheduled_count > 0 ? 'speedycache-scheduled-count-indicator' : '';?>" setting-id="speedycache-img-scheduled-modal"><?php echo esc_html($scheduled_count);?></span>
								</div>
							</div>
							<div class="speedycache-img-remain-optm">
								<span class="speedycache_img_optm_status" style="background-color:<?php echo $res['uncompressed'] > 0 ? '#EED202' : '#90ee90'?>"></span>
								<span>
								<?php 
									if($res['uncompressed'] > 0){
										echo esc_html($res['uncompressed']) . ' ';
										esc_html_e('Files needed to be optimized', 'speedycache');
									} else {
										esc_html_e('All images are optimized', 'speedycache');
									}	
								?></span>
									
							</div>
							<div class="speedycache-img-optimize-all" style="margin-left:auto;">
								<button class="speedycache-button speedycache-btn-black speedycache-img-optm-btn" setting-id="speedycache-modal-optimize-all"><?php esc_html_e('Optimize All', 'speedycache'); ?></button>
								<button class="speedycache-img-delete-all-conv speedycache-button speedycache-btn-transparent"><?php esc_html_e('Delete all conversions', 'speedycache'); ?></button>
							</div>
						</div>
					</div>
				</div>
		
				<div class="speedycache-is-block speedycache-img-count">
					<div>
						<div class="speedycache-img-opt-stat">
							<div class="speedycache-img-optm-count"><?php echo esc_html($res['optimized'] . '/' . $res['total_image_number']); ?></div>
							<div class="speedycache-img-optm-count-text"><?php echo esc_html_e('Image(s) optimized', 'speedycache'); ?>
							<?php echo esc_html_e('with total reduction of', 'speedycache'); ?> <span class="speedycache-img-reduced-size"><?php echo esc_html($res['reduction'] > 10000 ? round($res['reduction']/1000, 2).'MB' : $res['reduction'].'KB');?></span></div>
						</div>
					</div>
				</div>
			</div>
		</div>
		
		<div modal-id="speedycache-img-scheduled-modal" class="speedycache-modal">
			<div class="speedycache-modal-wrap">
				<div class="speedycache-modal-header">
					<div><?php esc_html_e('Scheduled Tasks', 'speedycache'); ?></div>
					<div title="Close Modal" class="speedycache-close-modal">
						<span class="dashicons dashicons-no"></span>
					</div>
				</div>
				<div class="speedycache-modal-content speedycache-info-modal">
					<?php if($scheduled_count < 1){ ?>
						<span><?php esc_html_e('No Image Scheduled', 'speedycache'); ?></span>
					<?php } else { ?>
					<!--<p style="text-align:center;"><?php //_e('Time Interval of the Schedule is 1 minute', 'speedycache');?></p>-->
					<table style="margin:auto; width: 100%;">
						<thead>
							<tr>
								<th class="speedycache-table-hitem" scope="col"><?php esc_html_e('Image', 'speedycache'); ?></th>
								<th class="speedycache-table-hitem" scope="col"><?php esc_html_e('Time', 'speedycache'); ?></th>
							</tr>
						</thead>
						<tbody>
							<?php
							foreach($scheduled as $key => $schedule){

								$time = $schedule['time'] - time();

								$time_str = 'in '.$time. ' seconds';
								
								if($time > 59){
									$time_str = 'in '. round($time/60, 1) . ' minute(s)';
								} else if($time <= 0){
									$time_str = 'now';
								}
								?>
							<tr>
								<td class="speedycache-table-item"><?php echo esc_html('Batch ' . ($key + 1)); ?></td>
								<td class="speedycache-table-item" style="text-align:right;"><?php echo esc_html($time_str);?> <span class="dashicons dashicons-clock"></span></td>
							</tr>
							<?php } ?>
							
						</tbody>
					</table>
					<?php } ?>
				</div>
			</div>
		</div>
		
		<div modal-id="speedycache-modal-all-img-revert" class="speedycache-modal">
			<div class="speedycache-modal-wrap">
				<div class="speedycache-modal-content">
					<span class="dashicons dashicons-info"></span>
					<h1><?php esc_html_e('Revert All Images!', 'speedycache'); ?></h1>
					<p><?php esc_html_e('Once deleted the changes won\'t be reversible.', 'speedycache'); ?></p>
					<div class="speedycache-modal-db-actions">
						<button class="speedycache-button speedycache-btn-black speedycache-db-confirm-yes"><?php esc_html_e('Yes', 'speedycache'); ?></button>
						<button class="speedycache-button speedycache-db-confirm-no"><?php esc_html_e('No', 'speedycache'); ?></button>
					</div>
				</div>
			</div>
		</div>
	<?php
	}
	//Templates Ends here

	//Need to create logs for Automatic Optimization
	static function log(){
		
	}

	static function compression_method_checks(){
		global $speedycache, $speedycache_optm_method;
		
		$gd = self::gd_check();
		$speedycache_optm_method['gd'] = array_merge($speedycache_optm_method['gd'], $gd);
		
		if(!$speedycache_optm_method['gd']['status']){
			$speedycache->image['disabled_method']++;
			self::change_method_if_not_available('gd');
		}
		
		$imagick = self::imagick_check();
		$speedycache_optm_method['imagick'] = array_merge($speedycache_optm_method['imagick'], $imagick);
		
		if(!$speedycache_optm_method['imagick']['status']){
			$speedycache->image['disabled_method']++;
			self::change_method_if_not_available('imagick');
		}
		
		$cwebp = self::cwebp_check();
		$speedycache_optm_method['cwebp'] = array_merge($speedycache_optm_method['cwebp'], $cwebp);
		
		if(!$speedycache_optm_method['cwebp']['status']){
			$speedycache->image['disabled_method']++;
			self::change_method_if_not_available('cwebp');
		}
	}

	// GD static function Starts here
	static function gd_check(){
		if(!extension_loaded('gd')){
			return array('status' => false, 'message' => 'You dont have GD PHP extension');
		}

		if(isset(gd_info()['WebP Support']) && !gd_info()['WebP Support']){
			return array('status' => false, 'message' => 'GD extension on your server dosen\'t support WEBP');
		}
		
		if(isset(gd_info()['WebP Support']) && gd_info()['WebP Support']){
			return array('status' => true, 'message' => 'Operational');
		}
	}

	static function gd_webp($file){
		global $speedycache, $speedycache_optm_method;

		if(isset($speedycache_optm_method['gd']['status']) && !$speedycache_optm_method['gd']['status']){
			return array('success' => false, 'error_message' => $speedycache_optm_method['gd']['message']);
		}
		
		$image_size = getimagesize($file);
		$width = $image_size[0];
		$height = $image_size[1];
		
		switch($image_size['mime']){
			case 'image/jpg':
			case 'image/jpeg':
				$source = imagecreatefromjpeg($file);
				break;
			
			case 'image/png':
				$source = imagecreatefrompng($file);
				break;
				
			case 'image/webp': 
				return array('success' => false, 'error_message' => 'File is alredy a WEBP file');
				
			default:
				return array('success' => false, 'error_message' => 'File has unsupported mime'.$image_size['mime']);
		}
		
		if(empty($source)){
			return false;
		}
		
		$dst = imagecreatetruecolor($width, $height);
		
		if(imagealphablending($dst, false) !== false){
			//change the RGB values if you need, but leave alpha at 127
			$transparent = imagecolorallocatealpha($dst, 255, 255, 255, 127);

			if($transparent !== false){
				//simpler than flood fill
				if(imagefilledrectangle($dst, 0, 0, $width, $height, $transparent) !== false){
					//restore default blending
					if(imagealphablending($dst, true) !== false){
						if(imagecopy($dst, $source, 0, 0, 0, 0, $width, $height) !== false){
							$success = true;
						}
					};
				}
			}
		}
		
		if(!$success){
			return array('success' => false, 'error_message' => 'Couldn\'t convert the given image.');
		}
		
		$webp_path = preg_replace('/.(jpe?g|png)$/', '.webp', $file);
		
		imagedestroy($source);
		imagewebp($dst, $webp_path, $speedycache->image['settings']['compression_quality']);
		imagedestroy($dst);
		
		if(!file_exists($webp_path)){
			return array('url' => $webp_path, 'success' => true, 'error_message' => 19);
		}

		return array(
			'url' => $webp_path,
			'success' => true,
			'error_message' => ''
		);
	}
	//GD Ends Here

	//Imagick static functions
	static function imagick_check(){
		
		if(!extension_loaded('imagick')){
			return array('status' => false, 'message' => 'Imagick extension isn\'t installed');
		}
		
		$image = new \Imagick();
		
		if(!in_array('WEBP', $image->queryFormats('WEBP'))){
			$image->clear();
			$image->destroy();
		
			return array('status' => false, 'message' => 'Imagick installed on your system is without WEBP support');
		}
		
		return array('status' => true, 'message' => 'Operational');
	}

	static function change_method_if_not_available($m_name){
		global $speedycache, $speedycache_optm_method;
		
		if($speedycache->image['settings']['compression_method'] != $m_name){
			return;
		}
		
		$valid_method = '';
		
		foreach($speedycache_optm_method as $key => $method){
			if($key == $m_name){
				continue;
			}
			
			if(!empty($method['status'])){
				$speedycache->image['settings']['compression_method'] = $key;
				return;
			}
		}

		$speedycache->image['settings']['compression_method'] = $valid_method;
	}

	//Conversion of image to webp
	static function imagick_webp($file){
		global $speedycache, $speedycache_optm_method;
		
		if(isset($speedycache_optm_method['imagick']['status']) && !$speedycache_optm_method['imagick']['status']){
			return array('success' => false, 'error_message' => $speedycache_optm_method['imagick']['message']);
		}
		
		$dest = preg_replace('/.(png|jpe?g)$/', '.webp', $file);
		
		$image = new \Imagick();
		$image->readImage($file);
		$image->setImageCompressionQuality($speedycache->image['settings']['compression_quality']);
		$image->setImageFormat('WEBP');
		
		if($image->writeImage($dest)){
			$image->clear();
			$image->destroy();
			
			return array('success' => true, 'error_message' => '');
		}
		
		$image->clear();
		$image->destroy();
		
		return array('success' => false, 'error_message' => 'File didn\'t got saved');
	}

	//cwebp static functions
	static function cwebp_check(){
		global $speedycache;
		
		if(!defined('SPEEDYCACHE_PRO')){
			return array('status' => false, 'message' => 'cwebp is a SPEEDYCACHE PRO feature.');
		}
		
		if(!function_exists('exec')){
			return array('status' => false, 'message' => 'You dont have access to exec static function hence you cant use cWebP for Image optimizations');
		}
		
		if(isset($speedycache->image['cwebp_binary'])){
			
			if(!file_exists(wp_upload_dir()['basedir'].'/speedycache-binary/'.$speedycache->image['cwebp_binary'])){
				return array('status' => false, 'message' => 'You don\'t have the cwebp Binary on your server.', 'downloaded' => false);
			} 
		}
		
		return array('status' => true, 'message' => 'Operational');
	}

	static function rewrite_url_to_webp($content){
		if(strpos(speedycache_optserver('HTTP_ACCEPT'), 'image/webp') < 0){
			return $content;
		}
		
		if( ! preg_match_all( '/<img\s[^>]+>/', $content, $matches, PREG_SET_ORDER ) ){
			return $content;
		}
		
		foreach($matches as $match){
			///(?i)(https?:\/\/|www.|\w+\.(png|jpe?g)$)[^\s]+/
			preg_match_all('/https?:\/(\/[^\/]+)+\.(?:jpe?g|png|gif)/', $match[0], $urls, PREG_SET_ORDER); 
			
			foreach($urls as $url){
				$file_url = preg_replace('/.(jpe?g|png|gif)$/', '.webp', $url[0]);
				
				$file_path = explode(SPEEDYCACHE_WP_CONTENT_DIR.'/uploads', $file_url);

				if(!isset($file_path[1]) || !file_exists(wp_upload_dir()['basedir'].$file_path[1])){
					continue;
				}
				
				$content = str_replace($url[0], $file_url, $content);
			}
		
		}
		
		return $content;
	}

	//Adding wp event for automatic optm on image upload
	static function convert_on_upload($id){
		global $speedycache;

		if(empty($speedycache->image['settings']['on_upload'])){
			return;
		}
		
		if(!wp_attachment_is_image($id)){
			return;
		}
		
		$scheduled = self::get_optimization_schedule(array('speedycache_auto_optm'));
		$time = time();
		
		if(!empty($scheduled) && isset(end($scheduled)['time'])){
			$time = end($scheduled)['time'];
		}
		
		// Convert after 5 minutes of upload
		if(!wp_next_scheduled('speedycache_auto_optm', array($id))){
			wp_schedule_single_event($time + 300, 'speedycache_auto_optm', array($id));
			return;
		}
	}

	//Optimizing image on Upload
	static function auto_optimize($img_id){
		self::optimize_single($img_id);
	}

	//Whenever user visits a page and there are images that dont have a webp versions then those images are set to be converted.
	static function optimize_on_fly($content){
		global $wpdb, $speedycache;

		//Sitepad dosen't have this static function.
		if(function_exists('wp_filter_content_tags')){
			$content = wp_filter_content_tags($content);
		}

		if(!preg_match_all('/<img\s[^>]+>|background:\s*url\(["\']?(.*?)["\']?\)/i', $content, $matches, PREG_SET_ORDER)){
			return $content;
		}
		
		$queued_images = 0;
		foreach($matches as $match){
			// If the page has a lot of images, then the process could get slower.
			if($queued_images >= 10){
				break;
			}

			// pl-image{post-id} will work only after Pagelayer 1.9.0
			if(!preg_match('/(?:wp|pl)-image-([\d]+)/i', $match[0], $post_id)){
				/*
				* This is for compatibility with other editors and for inline css background url
				* what we do here is look for either img src url or background:url()
				* Then we attempt to get id from the URL.
				*/
				//<img(?:[^>]|[^\/>]).*src[\s*]?=[\s*]?"(.+?)" just in case the one used causes bugs
				if(strpos($match[0], 'background:url') === FALSE && !preg_match('/<img.*?src="(.*?)"/', $match[0], $url)){
					continue;
				}
				
				if(strpos($match[0], 'background:url') !== FALSE){
					$image_url = sanitize_url($match[1]);
				} else {
					$image_url = sanitize_url($url[1]);
				}

				$post_id = (int) attachment_url_to_postid($image_url);
				
				if(empty($post_id)){
					$file = basename($image_url);
					$like = '%'.$wpdb->esc_like($file) .'%';
					$query = $wpdb->prepare("SELECT `post_id` FROM `".$wpdb->prefix."postmeta` WHERE `meta_value` LIKE %s", $like);
					$post_id = (int) $wpdb->get_var($query);
				}

				if(empty($post_id)){
					continue;
				}
			}
		
			if(empty($post_id)){
				continue;
			}
			
			// If we captured post id through wp-image|pl-image
			if(is_array($post_id) && isset($post_id[1])){
				$post_id = intval($post_id[1]);
			}

			// If the image is already scheduled for optimization then just skip it.
			if(wp_next_scheduled('speedycache_auto_optm', array($post_id))){
				continue;
			}
			
			if(!get_post($post_id)){
				continue;
			}

			$optimized = (int) $wpdb->get_var($wpdb->prepare("SELECT 1 as optimized FROM `".$wpdb->prefix."postmeta` WHERE `meta_key`= 'speedycache_optimisation' AND `post_id`=%d LIMIT 1", $post_id));
			
			if($optimized > 0){
				continue;
			}
			
			$scheduled = self::get_optimization_schedule(array('speedycache_auto_optm'));
			$time = time();
		
			if(!empty($scheduled) && isset(end($scheduled)['time'])){
				// getting the last index to get the last scheduled event
				$time = end($scheduled)['time'];
				$final_schd_time = $time + 30;
			} else {
				$final_schd_time = $time;
			}

			if(!wp_next_scheduled('speedycache_auto_optm', array($post_id))){
				wp_schedule_single_event($final_schd_time, 'speedycache_auto_optm', array($post_id));
				$queued_images++;
				
				continue;
			}
		}

		return $content;
	}

	// Returns an array of cron event "speedycache_auto_optm"
	static function get_optimization_schedule($event_name){
		$cron = _get_cron_array();
		
		if(empty($cron)){
			return false;
		}
		
		$scheduled = array();
		
		foreach($cron as $key => $crn){
			foreach($crn as $e_key => $event){
				if(!in_array($e_key, $event_name)){
					continue;
				}

				foreach($event as $evt){
					$args = $evt['args'][0];
				}
				
				array_push($scheduled, array('name' => get_the_title($args), 'time' => $key));
			}
		}
		
		return $scheduled;
	}

	static function gif2webp_exists(){
		global $speedycache;
		
		if(file_exists(wp_upload_dir()['basedir']. '/speedycache-binary/'.$speedycache->image['cwebp_gif'])){
			return true;
		}
		
		return false;
	}
	
	static function download_cwebp(){
		global $speedycache;

		check_ajax_referer('speedycache_ajax_nonce', 'security');
		
		$binary_name = $speedycache->image['cwebp_binary'];
		
		$type = speedycache_optget('type');
		
		switch($type){
			case 'gif':
				$binary_name = $speedycache->image['cwebp_gif'];
				break;
				
			case 'cwebp':
				$binary_name = $speedycache->image['cwebp_binary'];
				break;
				
			default:
				return;
		}
		
		$binary_path = wp_upload_dir()['basedir'].'/speedycache-binary';
		
		if(!file_exists($binary_path)){
			@mkdir($binary_path);
		}
		
		//If The binary alredy exists on the server
		if(file_exists($binary_path.'/'.$binary_name)){
			wp_send_json(array('success' => false, 'error_message' => 'Binary Exists already.'));
		}
		
		$resp = wp_remote_get(SPEEDYCACHE_API.'/files/cwebp/'.$binary_name);
		$json = wp_remote_get(SPEEDYCACHE_API.'/files/hash.json');
		
		$hash = json_decode($json['body'], true);
		$file = $resp['body'];
		
		if(!$hash){
			wp_send_json(array('success' => false, 'error_message' => 'Unable to verify the downloaded binary.'));
		}
		
		if(!$file){
			wp_send_json(array('success' => false, 'error_message' => 'Could not download the file please try again later.'));
		}
		
		$binary_file = $binary_path.'/'.$binary_name;
		
		file_put_contents($binary_file, $file);
		
		if(!file_exists($binary_file)){
			wp_send_json(array('success' => false, 'error_message' => 'There was issue downloading the binary.'));
		}
		
		if(hash_file('md5', $binary_file) != $hash[$binary_name]){
			@unlink($binary_path.'/'.$binary_name);
			wp_send_json(array('success' => false, 'error_message' => 'Hash of the file downloaded didn\'t match'));
		}

		@chmod($binary_file, 0755);
		
		$output = null;
		$res = null;

		if(!function_exists('exec')){
			wp_send_json(array('success' => false, 'error_message' => 'Your server dosen\'t supports exec'));
		}

		$exec_name = $type === 'gif' ? 'gf2webp' : 'cwebp';

		/*
		* To check if the binary is supported by the server.
		*/
		exec('"'.$binary_file.'"  '.$exec_name.' -version 2>&1', $output, $res);
		
		if($res != 0){
			wp_send_json(array('success' => false, 'error_messsage' => 'The binary for cwebp isn\'t supported by your server'));
		}
		
		if($type = 'gif'){
			$speedycache->image['cwebp_gif'] = $binary_name;
		} else {
			$speedycache->image['cwebp_binary'] = $binary_name;
		}
		
		wp_send_json(array('success' => true));
	}

	static function cwebp_convert($file){
		global $speedycache, $speedycache_optm_method;
		
		if(isset($speedycache_optm_method['cwebp']['status']) && !$speedycache_optm_method['cwebp']['status']){
			return array('success' => false, 'error_message' => $speedycache_optm_method['cwebp']['message']);
		}
			
		$mime = mime_content_type($file);
		
		if($mime == 'image/gif'){
			$binary_path = wp_upload_dir()['basedir']. '/speedycache-binary/'.$speedycache->image['cwebp_gif'];
			$binary_name = 'gif2webp';
		} else {
			$binary_path = wp_upload_dir()['basedir']. '/speedycache-binary/'.$speedycache->image['cwebp_binary'];
			$binary_name = 'cwebp';
		}
		
		$output_file = preg_replace('/.(jpe?g|png|gif)$/', '.webp', $file);
		

		$res = null;
		$output = null;
		
		if(!file_exists($binary_path)){
			return array('success' => false, 'error_message' => 'The binary to use cwebp not found');
		}
		
		/*
		*	-- Use "" around the paths in exec, as without "" can cause a bug on some servers installs. 
		*	-- The Structure of the command below is :- 
		*	"path_of_binary" cwebp -q [quality_in_int] "original_file_path" -o "output_file.webp"
		*	-- 2>&1 is used to redirect stderr to same place as stdout
		*	https://www.brianstorti.com/understanding-shell-script-idiom-redirect/
		*/
		exec('"'.$binary_path.'" '.$binary_name.' -q '.$speedycache->image['settings']['compression_quality'].' "'.$file. '" -o "'. $output_file. '" 2>&1', $output, $res);
		
		if($res != 0){
			return array('success' => false, 'error_message' => 'Couldn\'t convert the given image using cwebp.', 'error_code' => 22);
		}
		
		return array('success' => true, 'error_message' => '', 'dest' => $output_file);
	}
	
	static function list_image_html(){
	?>
	<div id="speedycache-image-list">
		<?php \SpeedyCache\Image::paging(); ?>
		<div style="width:100%; overflow-x:auto;">
			<table class="wp-list-table widefat fixed media" style="width: 95%; margin-left: 20px;">
				<thead>
					<tr style="height: 35px;">
						<th scope="col" id="icon" class="manage-column column-icon" style=""></th>
						<th scope="col" id="title" class="manage-column column-title sortable desc" style="width: 323px;">
							<span style="padding-left: 8px;"><?php esc_html_e('File Name', 'speedycache'); ?></span>
						</th>
						<th scope="col" id="author" class="manage-column column-author sortable desc" style="width: 120px;text-align: center;">
							<span><?php esc_html_e('Reduction', 'speedycache'); ?></span>
						</th>
						<th scope="col" id="date" class="manage-column column-date sortable asc" style="width: 91px;text-align: center;">
							<span><?php esc_html_e('Date', 'speedycache'); ?></span>
						</th>
						<th scope="col" id="date" class="manage-column column-date sortable asc" style="width: 60px;text-align: center;">
							<span><?php esc_html_e('Revert', 'speedycache'); ?></span>
						</th>	
					</tr>
				</thead>
				<tbody id="the-list">
					<?php 
						$query_images_args = array();

						$query_images_args['order'] = 'DESC';
						$query_images_args['orderby'] = 'ID';
						$query_images_args['post_type'] = 'attachment';
						$query_images_args['post_mime_type'] = array('image/jpeg', 'image/png', 'image/gif');
						$query_images_args['post_status'] = 'inherit';
						$query_images_args['posts_per_page'] = 5;
						$query_images_args['meta_query'] = array(
							array(
								'key' => 'speedycache_optimisation',
								'compare' => 'EXISTS'
							)
						);

						echo \SpeedyCache\Image::list_content($query_images_args);
					?>
				</tbody>
			</table>
		</div>
	</div>
	<?php 
	}

}


Youez - 2016 - github.com/yon3zu
LinuXploit