RIFF¤ WEBPVP8 ˜ ðÑ *ôô>‘HŸK¥¤"§£±¨àð ....................................../////.===Shadow-Here===./////................................................ > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < ------------------------------------------------------------------------------------------------------------------- /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// RIFF¤ WEBPVP8 ˜ ðÑ *ôô>‘HŸK¥¤"§£±¨àð enü¹%½_F‘åè¿2ºQú³íªú`N¿­3ÿƒügµJžaÿ¯ÿ°~¼ÎùnúîÞÖô•òíôÁÉß®Sm¥Ü/ ‡ó˜f£Ùà<˜„xëJ¢Ù€SO3x<ªÔ©4¿+ç¶A`q@Ì“Úñè™ÍÿJÌ´ª-˜ÆtÊÛL]Ïq*‘Ý”ì#ŸÌÏãY]@ê`¿ /ªfkØB4·®£ó z—Üw¥Pxù–ÞLШKÇN¾AkÙTf½è'‰g gÆv›Øuh~ a˜Z— ïj*á¥t d£“uÒ ¨`K˜¹ßþ]b>˜]_ÏÔ6W—è2r4x•íÖ…"ƒÖNîä!¦å Ú}ýxGøÌ —@ ;ÆÚŠ=ɾ1ý8lªË¥ô ^yf®Œ¢u&2©nÙÇ›ñÂñŒ³ aPo['½»øFùà­+4ê“$!lövlüÞ=;N®3ð‚õ›DÉKòÞ>ÄÍ ¥ˆuߤ#ˆ$6ù™¥îЇy’ÍB¼ çxÛ;X"WL£R÷͝*ó-¶Zu}º.s¸sšXqù–DþÿvªhüïwyŸ ¯é³lÀ:KCûÄ£Ëá\…­ ~—ýóî ¼ûûÜTÓüÇy…ŽÆvc»¾×U ñ¸žþоP÷¦ó:Ò¨¨5;Ð#&#ÖúñläÿÁœ GxÉ­/ñ‡áQðìYÉtÒw޼GÔ´zàÒò ð*ëzƒ•4~H]Ø‹f ñÓÈñ`NåWçs'ÆÏW^ø¹!XžµmQ5ÃËoLœÎ: ÞËÍ¥J ù…î èo£ßPÎñ¶ž8.Œ]ʵ~5›ÙË-ù*8ÙÖß±~ ©¹rÓê‚j¶d¸{^Q'˜±Crß ÚH—#¥¥QlÀ×ëã‡DÜ«èî þ&Çæžî;ŽÏºò6ÒLÃXy&ZŒ'j‚¢Ù€IßÚù+–MGi‰*jE€‘JcÜ ÓÌ EÏÚj]o˜ Þr <¾U ûŪæÍ/šÝH¥˜b”¼ ÁñßX GP›ï2›4WŠÏà×£…íÓk†¦H·ÅíMh–*nó÷à]ÁjCº€b7<ب‹¨5車bp2:Á[UªM„QŒçiNMa#<5›áËó¸HýÊ"…×Éw¹¦ì2º–x<›»a±¸3Weü®FÝ⑱ö–î–³|LPÈ~çð~Çå‡|º kD¢µÏàÆAI %1À% ¹Ò – ”ϝS¦‰4&¶£°à Öý”û_Ò Áw°A«Å€?mÇÛgHÉ/8)á¾ÛìáöŽP í¨PŸNÙµº¦‡§Ùš"ÿ«>+ªÕ`Ê÷‡‚ß Õû˜þãÇ-PÍ.¾XV‘€ dÜ"þ4¹ ±Oú‘©t¥¦FªÄÃÄ•b‚znýu½—#cDs˜ÃiÑOˆñ×QO=*IAÊ,¶ŽZƒ;‡wøXè%EÐk:F±Ú” .Ѽ+Áu&Ç`."pÈÉw o&¿dE6‘’EqTuK@Ì¥ã™À(Êk(h‰,H}RÀIXÛš3µ1©_OqÚÒJAñ$ÊÙÜ;D3çŒ[þùœh¬Ã³™ö6ç†NY".Ú‰ï[ªŸŒ '²Ð öø_¨ÂÉ9ué¶³ÒŠõTàîMØ#û¯gN‡bÙ놚X„ö …ÉeüÌ^J ‹€.œ$Æ)βÄeæW#óüßĺŸ€ ÀzwV 9oä»f4V*uB «Ë†¹ì¯žR霓æHXa=&“I4K;¯ç‹h×·"UŠ~<•╪Vêª&ÍSÃÆÅ?ÔqÎ*mTM ˜›µwêd#[C¡©§‘D<©àb†–ÁœøvH/,í:¯( ²£|4-„Æövv„Yͼ™^Á$ˆ„¢Û[6yB.åH*V¨æ?$=˜Ñ€•ñ·­(VlŸ‘ nÀt8W÷´Bûba?q9ú¶Xƒl«ÿ\ù¶’þòUÐj/õ¢Ìµ³g$ƒÎR!¸»|Oߍë’BhîÚÑ¢ñåŒJ„®„£2Ð3•ô02Nt…!£Í]Ïc½Qÿ?ˆ<&ÃA¾Ú,JˆijÌ#5yz„‰Î|ÊŽ5QÏ:‹ÐaóVÔxW—CpeÏzÐïíçôÿÅ_[hãsÐ_/ŽTÝ?BîˆííV$<¿i>²F¬_Eß¿ †bÊŒº­ÿ®Z H“C}”¬,Mp ý/Bá£w>˜YV°aƒúh+cŠ- r/[%|üUMHäQ°X»|û/@|°¥Ð !BÔ Ç¢Ä©š+Õì D«7ìN¶ŽðÔ " ƶ’ÖçtA‰Û×}{tþz­¾GÍ›k¹OEJR$ Â׃ «ëÁ"oÉôž$oUK(Ä)Ãz³Ê-‹êN[Ò3Œñbï8P 4ƒ×q¢bo|?<ÛX¬òÄͰL–±›(™ûG?ýË©ÚÄ–ÂDØÐ_Ç¡ô ¾–ÄÏø ×e8Ë©$ÄF¹Å‹ì[©óìl:F¾f´‹‹Xì²ï®\¬ôùƒ ÿat¥óèÒùHß0äe‚;ü×h:ÆWðHž=Ã8骣"kœ'Y?³}Tûè€>?0l›e1Lòñ„aæKÆw…hÖŠùW…ÈÆÄ0ši·›[pcwËþñiêíY/~-Á5˜!¿†A›™Mÿþ(±“t@â“ö2­´TG5yé]çå僳 .·ÍïçÝ7UÚ±Ð/Nè»,_Ï ùdj7\ï Wì4›„»c¸àešg#ÒÊ⥭áØo5‘?ÌdÝô¯ ¹kzsƒ=´#ëÉK›Ø´±-¥eW?‡çßtòTã…$Ý+qÿ±ƒ÷_3Ô¥í÷:æ–ž<·Ö‡‰Å¢ š‡%Ô—utÌÈìðžgÖÀz²À—ï÷Óîäõ{K'´È÷³yaÏÁjƒô}ž§®æÊydÕÈë5¯èˆõvÕ©ã*çD„ “z„Ó‡^^xÂ3M§A´JG‚öï 3W'ˆ.OvXè¡ÊÕª?5º7†˜(˜Ç¶#çê’¶!ÌdZK§æ 0fãaN]òY³RV ™î$®K2R¨`W!1Ôó\;Ý ýB%qæK•&ÓÈe9È0êI±žeŸß -ú@žQr¦ ö4»M¼Áè¹µmw 9 EÆE_°2ó„ŸXKWÁ×Hóì^´²GѝF©óäR†¦‰ç"V»eØ<3ùd3ÿÚ¤Žú“Gi" —‘_ÙËÎ~Üö¯¥½Î»üŸEÚŽåmÞþí ;ÞólËΦMzA"Âf(´òá;Éï(/7½ûñÌ­cïÕçлþÝz¾-ÍvÑ“pH­–ðÓj$¸Äû¤‚‘ãUBË-n“2åPkS5&‹Â|+g^œ®Ì͆d!OïäîU«c;{Û!ÅŽ«ëZ9Ókóˆ]¯ƒ›né `ÇÒ+tÆš (ØKá¾—=3œ®•vuMñg²\ï Ec€ 05±d™‡×iÇ×›UúvÌ¢£Èþ¡ÕØô¶ßÎA"ß±#Ö²ˆÊŸ¦*Ä~ij|àø.-¼'»Ú¥£h ofº¦‡VsR=N½„Î v˜Z*SÌ{=jÑB‹tê…;’HžH¯8–îDù8ñ¢|Q•bÛçš–‹m³“ê¨ åÏ^m¬Žãþ©ïêO‡½6] µÆ„Ooòü ²x}N¦Ë3ïé¿»€›HA˜m%çÞ/¿í7Fø“‹léUk)É°Œµ8Q8›:ÀŠeT*šõ~ôڝG6 ¢}`ùH­–”¡k ‰P1>š†®9z11!X wKfmÁ¦xÑ,N1Q”–æB¶M…ÒÃv6SMˆhU¬ÊPŽï‘öj=·CŒ¯u¹ƒVIЃsx4’ömÛýcå¡¶7ßŠß 57^\wÒÐÆ k§h,Œý î«q^R½3]J¸ÇðN ‚çU¬ôº^Áì} ³f©Õœ§ˆã:FÄÈ‚é(€™?àýÓüè1Gô£¼éj‚OÅñ  #>×—ßtà 0G¥Åa뀐kßhc™À_ÉñÞ#±)GD" YîäË-ÿÙ̪ ¹™a¯´¢E\ÝÒö‚;™„ë]_ p8‰o¡ñ+^÷ 3‘'dT4œŽ ðVë½° :¬víÑ«£tßÚS-3¶“þ2 †üüʨòrš¹M{É_¤`Û¨0ìjœøJ‡:÷ÃáZ˜†@GP&œÑDGÏs¡þ¦þDGú‘1Yá9Ôþ¼ ûø…§÷8&–ÜÑnÄ_m®^üÆ`;ÉVÁJ£?â€-ßê}suÍ2sõA NÌúA磸‘îÿÚ»ƒìö·á¿±tÑÐ"Tÿü˜[@/äj¬€uüªìù¥Ý˜á8Ý´sõj 8@rˆð äþZÇD®ÿUÏ2ùôõrBzÆÏÞž>Ì™xœ“ wiÎ×7_… ¸ \#€MɁV¶¥üÕÿPÔ9Z‡ø§É8#H:ƒ5ÀÝå9ÍIŒ5åKÙŠ÷qÄ>1AÈøžj"µÂд/ªnÀ qªã}"iŸBå˜ÓÛŽ¦…&ݧ;G@—³b¯“•"´4í¨ôM¨åñC‹ïùÉó¯ÓsSH2Ý@ßáM‡ˆKÀªÛUeø/4\gnm¥‹ŸŒ qÄ b9ÞwÒNÏ_4Ég³ú=܆‚´ •â¥õeíþkjz>éÚyU«Íӝ݃6"8/ø{=Ô¢»G¥ äUw°W«,ô—¿ãㆅү¢³xŠUû™yŒ (øSópÐ 9\åTâ»—*oG$/×ÍT†Y¿1¤Þ¢_‡ ¼ „±ÍçèSaÓ 3ÛMÁBkxs‰’R/¡¤ˆÙçª(*õ„üXÌ´ƒ E§´¬EF"Ù”R/ÐNyÆÂ^°?™6¡œïJ·±$§?º>ÖüœcNÌù¯G ‹ñ2ЁBB„^·úìaz¨k:#¨Æ¨8LÎõލ£^§S&cŒÐU€ü(‡F±Š¼&P>8ÙÁ ‰ p5?0ÊÆƒZl¸aô š¼¡}gÿ¶zÆC²¹¬ÎÖG*HB¡O<º2#ñŒAƒ–¡B˜´É$¥›É:FÀÔx¾u?XÜÏÓvN©RS{2ʈãk9rmP¼Qq̳ è¼ÐFׄ^¡Öì fE“F4A…!ì/…¦Lƒ… … $%´¾yã@CI¬ á—3PþBÏNÿ<ý°4Ü ËÃ#ØÍ~âW«rEñw‹eùMMHß²`¬Öó½íf³:‹k˜¯÷}Z!ã¿<¥,\#öµÀ¯aÒNÆIé,Ћ–lŽ#Àæ9ÀÒS·I’½-Ïp Äz¤Š Â* ­íÄ9­< h>׍3ZkËU¹§˜ŒŠ±f­’¤º³Q ÏB?‹#µíÃ¥®@(Gs«†vI¥Mµ‹Á©e~2ú³ÁP4ìÕi‚²Ê^ö@-DþÓàlÜOÍ]n"µã:žpsŽ¢:! Aõ.ç~ÓBûH÷JCÌ]õVƒd «ú´QÙEA–¯¯Œ!.ˆˆëQ±ù œ·Ì!Õâ )ùL„ÅÀlÚè5@B…o´Æ¸XÓ&Û…O«˜”_#‡ƒ„ûÈt!¤ÁÏ›ÎÝŠ?c9 â\>lÓÁVÄÑ™£eØY]:fÝ–—ù+p{™ðè û³”g±OƒÚSù£áÁÊ„ä,ï7š²G ÕÌBk)~ÑiCµ|h#u¤¶îK¨² #²vݯGãeÖ϶ú…¾múÀ¶þÔñ‚Š9'^($¤§ò “š½{éúp÷J›ušS¹áªCÂubÃH9™D™/ZöØÁ‡¦ÝÙŸ·kð*_”.C‹{áXó€‡c¡c€§/šò/&éš÷,àéJþ‰X›fµ“C¨œ®r¬"kL‰Â_q…Z–.ÉL~O µ›zn‚¹À¦Öª7\àHµšÖ %»ÇníV[¥*Õ;ƒ#½¾HK-ÖIÊdÏEÚ#=o÷Óò³´Š: Ç?{¾+9›–‘OEáU·S€˜j"ÄaÜ ŒÛWt› á–c#a»pÔZÞdŽtWê=9éöÊ¢µ~ ë ;Öe‡Œ®:bî3±ýê¢wà¼îpêñ¹¾4 zc¾ðÖÿzdêŒÑÒŝÀ‰s6¤í³ÎÙB¿OZ”+F¤á‡3@Ñëäg©·Ž ˆèª<ù@É{&S„œÕúÀA)‰h:YÀ5^ÂÓŒ°õäU\ ùËÍû#²?Xe¬tu‰^zÒÔãë¼ÛWtEtû …‚g¶Úüâî*moGè¨7%u!]PhÏd™Ý%Îx: VÒ¦ôÊD3ÀŽKÛËãvÆî…N¯ä>Eró–ð`5 Œ%u5XkñÌ*NU%¶áœÊ:Qÿú»“úzyÏ6å-၇¾ ´ ÒÊ]y žO‘w2Äøæ…H’²f±ÎÇ.ª|¥'gîV•Ü .̘¯€šòü¤U~Ù†*¢!?ò wý,}´°ÔÞnïoKq5µb!áÓ3"vAßH¡³¡·G(ÐÎ0Îò¼MG!/ài®@—¬04*`…«é8ªøøló“ˆÊ”èù¤…ßÊoÿé'ËuÌÖ5×È¡§ˆˆfŽë9}hìâ_!!¯  B&Ëö¶‰ÀAÙNVŸ Wh›¸®XÑJì¨ú“¿÷3uj²˜¨ÍÎìë±aúŠÝå¯ð*Ó¨ôJ“yºØ)m°WýOè68†ŸÏ2—‰Ïüꪫٚ¥‹l1 ø ÏÄFjêµvÌbü¦èÝx:X±¢H=MÐß—,ˆÉÇ´(9ú¾^ÅÚ4¿m‡$âX‘å%(AlZo@½¨UOÌÕ”1ø¸jÎÀÃÃ_ µ‘Ü.œº¦Ut: Æï’!=¯uwû#,“pþÇúŒø(é@?³ü¥‘Mo §—s@Œ#)§ŒùkL}NOÆêA›¸~r½¼ÙA—HJ«eˆÖ´*¡ÓpÌŸö.m<-"³ûÈ$¬_6­åf£ïÚâj1y§ÕJ½@dÞÁr&Í\Z%D£Íñ·AZ Û³øüd/ªAi†/Й~  ‡âĮҮÏh§°b—›Û«mJžòG'[ÈYýŒ¦9psl ýÁ ®±f¦x,‰½tN ‚Xª9 ÙÖH.«Lo0×?͹m¡å†Ѽ+›2ƒF ±Ê8 7Hցϓ²Æ–m9…òŸï]Â1äN†VLâCˆU .ÿ‰Ts +ÅÎx(%¦u]6AF Š ØF鈄‘ |¢¶c±soŒ/t[a¾–û:s·`i햍ê›ËchÈ…8ßÀUÜewŒðNOƒõD%q#éû\9¤x¹&UE×G¥ Í—™$ð E6-‡¼!ýpãÔM˜ Âsìe¯ñµK¢Ç¡ùôléœ4Ö£”À Š®Ðc ^¨À}ÙËŸ§›ºê{ÊuÉC ×Sr€¤’fÉ*j!úÓ’Gsùìoîßîn%ò· àc Wp÷$¨˜)û»H ×8ŽÒ€Zj¤3ÀÙºY'Ql¦py{-6íÔCeiØp‘‡XÊîÆUߢ܂ž£Xé¼Y8þ©ëgñß}é.ÎógÒ„ÃØËø¯»™§Xýy M%@NŠ À(~áÐvu7&•,Ù˜ó€uP‡^^®=_E„jt’ 403WebShell
403Webshell
Server IP : 104.225.223.251  /  Your IP : 216.73.216.41
Web Server : Apache/2.4.41 (Ubuntu)
System : Linux agtdemo03 5.4.0-216-generic #236-Ubuntu SMP Fri Apr 11 19:53:21 UTC 2025 x86_64
User : root ( 0)
PHP Version : 7.4.3-4ubuntu2.29
Disable Function : pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : OFF  |  Sudo : ON  |  Pkexec : ON
Directory :  /home/web/dev.agtindia.co.in/prima-world/wp-content/plugins/wp-seopress-pro/inc/admin/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /home/web/dev.agtindia.co.in/prima-world/wp-content/plugins/wp-seopress-pro/inc/admin//cron.php
<?php
if ( ! defined('ABSPATH')) {
    exit;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
//Request Google PageSpeed Insights
///////////////////////////////////////////////////////////////////////////////////////////////////
function seopress_request_page_speed_fn($cron = false) {
    $options = get_option('seopress_pro_option_name');

    //Save URLs field
    if (isset($_POST['seopress_ps_url'])) {
        $options['seopress_ps_url'] = sanitize_textarea_field($_POST['seopress_ps_url']);
        update_option('seopress_pro_option_name', $options);
    } elseif (isset($options['seopress_ps_url'])) {
        $seopress_get_site_url = $options['seopress_ps_url'];
    } else {
        $seopress_get_site_url = get_home_url();
    }

    $options = get_option('seopress_pro_option_name');

    //Save API key
    if (isset($_POST['seopress_ps_api_key'])) {
        $options['seopress_ps_api_key'] = sanitize_textarea_field($_POST['seopress_ps_api_key']);
        update_option('seopress_pro_option_name', $options);
    }

    $options = get_option('seopress_pro_option_name');

    $seopress_google_api_key = ! empty($options['seopress_ps_api_key']) ? $options['seopress_ps_api_key'] : 'AIzaSyBqvSx2QrqbEqZovzKX8znGpTosw7KClHQ';
    $seopress_get_site_url = ! empty($options['seopress_ps_url']) ? $options['seopress_ps_url'] : get_home_url();

    delete_transient('seopress_results_page_speed');
    delete_transient('seopress_results_page_speed_desktop');

    $args = ['timeout' => 30, 'blocking' => true];

    //Mobile
    if (false === ($seopress_results_page_speed_cache = get_transient('seopress_results_page_speed'))) {
        $seopress_results_page_speed = wp_remote_retrieve_body(wp_remote_get('https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=' . $seopress_get_site_url . '&key=' . $seopress_google_api_key . '&screenshot=true&strategy=mobile&category=performance&category=seo&category=best-practices&locale=' . get_locale(), $args));
        $seopress_results_page_speed_cache = $seopress_results_page_speed;
        set_transient('seopress_results_page_speed', $seopress_results_page_speed_cache, 1 * DAY_IN_SECONDS);
    }

    //Desktop
    if (false === ($seopress_results_page_speed_desktop_cache = get_transient('seopress_results_page_speed_desktop'))) {
        $seopress_results_page_speed_desktop = wp_remote_retrieve_body(wp_remote_get('https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=' . $seopress_get_site_url . '&key=' . $seopress_google_api_key . '&screenshot=true&strategy=desktop&category=performance&locale=' . get_locale(), $args));
        $seopress_results_page_speed_desktop_cache = $seopress_results_page_speed_desktop;
        set_transient('seopress_results_page_speed_desktop', $seopress_results_page_speed_desktop_cache, 1 * DAY_IN_SECONDS);
    }
    $data = ['url' => add_query_arg('ps', 'done', remove_query_arg(['data_permalink', 'ps'], admin_url('admin.php?page=seopress-pro-page&ps=done#tab=tab_seopress_page_speed')))];

    if ($cron === false) {
        wp_send_json_success($data);
    }
    exit();
}
/**
 * Request Page Speed Insights by CRON.
 *
 * @since 5.3
 * @param boolean Is is a CRON request?
 *
 * @author Benjamin
 */
function seopress_request_page_speed_insights_cron() {
    seopress_request_page_speed_fn(true);
}
add_action('seopress_page_speed_insights_cron', 'seopress_request_page_speed_insights_cron');

function seopress_request_page_speed() {
    check_ajax_referer('seopress_request_page_speed_nonce');

    if (current_user_can(seopress_capability('manage_options', 'cron')) && is_admin()) {
        seopress_request_page_speed_fn();
    }
}
add_action('wp_ajax_seopress_request_page_speed', 'seopress_request_page_speed');

///////////////////////////////////////////////////////////////////////////////////////////////////
//Request Google Analytics
///////////////////////////////////////////////////////////////////////////////////////////////////
use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient;
use Google\Analytics\Data\V1beta\DateRange;
use Google\Analytics\Data\V1beta\Dimension;
use Google\Analytics\Data\V1beta\OrderBy;
use Google\Analytics\Data\V1beta\Metric;
use Google\ApiCore\ApiException;
use Google\Auth\OAuth2;

function seopress_request_google_analytics_fn($clear = false) {
    if (function_exists('seopress_google_analytics_dashboard_widget_option') && seopress_google_analytics_dashboard_widget_option() === '1') {
        exit();
    }

    /**
     * @deprecated 5.9.0
     * @uses seopress_get_service('GoogleAnalyticsOption')
     */
    function seopress_google_analytics_auth_option() {
        $service = seopress_get_service('GoogleAnalyticsOption');

        if ( ! empty($service) || ! method_exists($service, 'getAuth')) {
            $data = get_option('seopress_google_analytics_option_name');
            if (isset($data['seopress_google_analytics_auth'])) {
                return $data['seopress_google_analytics_auth'];
            }
        }

        return $service->getAuth();
    }

    /**
    * @deprecated 5.9.0
    * @uses seopress_get_service('GoogleAnalyticsOption')
    */
    function seopress_google_analytics_auth_client_id_option() {
        $service = seopress_get_service('GoogleAnalyticsOption');

        if ( ! empty($service) || ! method_exists($service, 'getAuthClientId')) {
            $data = get_option('seopress_google_analytics_option_name');
            if (isset($data['seopress_google_analytics_auth_client_id'])) {
                return $data['seopress_google_analytics_auth_client_id'];
            }
        }

        return $service->getAuthClientId();
    }

    /**
     * @deprecated 5.9.0
     * @uses seopress_get_service('GoogleAnalyticsOption')
     */
    function seopress_google_analytics_auth_secret_id_option() {
        $service = seopress_get_service('GoogleAnalyticsOption');

        if ( ! empty($service) || ! method_exists($service, 'getAuthSecretId')) {
            $data = get_option('seopress_google_analytics_option_name');
            if (isset($data['seopress_google_analytics_auth_secret_id'])) {
                return $data['seopress_google_analytics_auth_secret_id'];
            }
        }

        return $service->getAuthSecretId();
    }


    /**
     * @deprecated 5.9.0
     * @uses seopress_pro_get_service('GoogleAnalyticsPro')
     */
    function seopress_google_analytics_auth_token_option() {
        return seopress_pro_get_service('GoogleAnalyticsOptionPro')->getAccessToken();
    }

    /**
    * @deprecated 5.9.0
    * @uses seopress_pro_get_service('GoogleAnalyticsPro')
    */
    function seopress_google_analytics_refresh_token_option() {
        return seopress_pro_get_service('GoogleAnalyticsOptionPro')->getRefreshToken();
    }

    /**
     * @deprecated 5.9.0
     * @uses seopress_pro_get_service('GoogleAnalyticsPro')
     */
    function seopress_google_analytics_debug_option() {
        return seopress_pro_get_service('GoogleAnalyticsOptionPro')->getDebug();
    }

    /**
     * @deprecated 5.9.0
     * @uses seopress_get_service('GoogleAnalyticsOption')
     */
    function seopress_google_analytics_ga4_2_option() {
       return seopress_get_service('GoogleAnalyticsOption')->getGA4();
    }

    /**
     * @deprecated 5.9.0
     * @uses seopress_get_service('GoogleAnalyticsOption')
     */
    function seopress_google_analytics_ga4_property_id_option() {
        $service = seopress_get_service('GoogleAnalyticsOption');

        if ( ! empty($service) || ! method_exists($service, 'getGA4PropertId')) {
            $data = get_option('seopress_google_analytics_option_name');
            if (isset($data['seopress_google_analytics_ga4_property_id'])) {
                return $data['seopress_google_analytics_ga4_property_id'];
            }
        }

        return $service->getGA4PropertId();
    }

    if (('' != seopress_google_analytics_auth_option() || '' != seopress_google_analytics_ga4_property_id_option() ) && '' != seopress_google_analytics_auth_token_option()) {

        try {
            // get saved data
            if ( ! $widget_options = get_option('seopress_ga_dashboard_widget_options')) {
                $widget_options = [];
            }

            // check if saved data contains content
            $seopress_ga_dashboard_widget_options_period = isset($widget_options['period']) ? $widget_options['period'] : false;

            $seopress_ga_dashboard_widget_options_type = isset($widget_options['type']) ? $widget_options['type'] : 'ga_sessions';

            // custom content saved by control callback, modify output
            if ($seopress_ga_dashboard_widget_options_period) {
                $period = $seopress_ga_dashboard_widget_options_period;
            } else {
                $period = '30daysAgo';
            }

            if ('' != seopress_google_analytics_auth_client_id_option()) {
                $client_id = seopress_google_analytics_auth_client_id_option();
            }

            if ('' != seopress_google_analytics_auth_secret_id_option()) {
                $client_secret = seopress_google_analytics_auth_secret_id_option();
            }

            $ga_account = 'ga:' . seopress_google_analytics_auth_option();
            $redirect_uri = admin_url('admin.php?page=seopress-google-analytics');

            require_once SEOPRESS_PRO_PLUGIN_DIR_PATH . '/vendor/autoload.php';

            $oauth = new OAuth2([
                'scope' => 'https://www.googleapis.com/auth/analytics.readonly',
                'tokenCredentialUri' => 'https://oauth2.googleapis.com/token',
                'authorizationUri' => 'https://accounts.google.com/o/oauth2/auth',
                'clientId' => seopress_google_analytics_auth_client_id_option(),
                'clientSecret' => seopress_google_analytics_auth_secret_id_option(),
                'redirectUri' => admin_url('admin.php?page=seopress-google-analytics'),
            ]);

            $client = new Google_Client();
            $client->setApplicationName('Client_Library_Examples');
            $client->setClientId($client_id);
            $client->setClientSecret($client_secret);
            $client->setRedirectUri($redirect_uri);
            $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
            $client->setApprovalPrompt('force');   // mandatory to get this fucking refreshtoken
            $client->setAccessType('offline'); // mandatory to get this fucking refreshtoken

            $client->setAccessToken(seopress_google_analytics_debug_option());

            if ($client->isAccessTokenExpired()) {
                $client->refreshToken(seopress_google_analytics_debug_option());

                $seopress_new_access_token = $client->getAccessToken(seopress_google_analytics_debug_option());

                $seopress_google_analytics_options = get_option('seopress_google_analytics_option_name1');
                $seopress_google_analytics_options['access_token'] = $seopress_new_access_token['access_token'];
                $seopress_google_analytics_options['refresh_token'] = $seopress_new_access_token['refresh_token'];
                $seopress_google_analytics_options['debug'] = $seopress_new_access_token;
                update_option('seopress_google_analytics_option_name1', $seopress_google_analytics_options, 'yes');
            }

            $service = new Google_Service_AnalyticsReporting($client);

            $oauth->setAccessToken(seopress_google_analytics_auth_token_option());
            $oauth->setRefreshToken(seopress_google_analytics_refresh_token_option());

            // GA4 Stats
            $all = [];

            //Get GA4 property ID
            $property_id = '';
            if (seopress_google_analytics_ga4_property_id_option()) {
                $property_id = seopress_google_analytics_ga4_property_id_option();

                //Get GA4 data
                $ga4_data = new BetaAnalyticsDataClient(['credentials' => $oauth]);

                // sessions
                $sessions = $ga4_data->runReport(
                    [
                        'property' => 'properties/' . $property_id,
                        'dateRanges' => [
                            new DateRange([
                                'start_date' => $period,
                                'end_date' => 'today',
                            ]),
                        ],
                        'dimensions' => [new Dimension([
                            'name' => 'date',
                        ]),
                        ],
                        'metrics' => [new Metric([
                            'name' => 'sessions',
                        ]),
                        ],
                        'orderBys' => [
                            new OrderBy([
                                'dimension' => new OrderBy\DimensionOrderBy([
                                    'dimension_name' => 'date',
                                    'order_type' => OrderBy\DimensionOrderBy\OrderType::ALPHANUMERIC
                                ]),
                                'desc' => false,
                            ]),
                        ],
                    ]
                );

                $users = $ga4_data->runReport(
                    [
                        'property' => 'properties/' . $property_id,
                        'dateRanges' => [
                            new DateRange([
                                'start_date' => $period,
                                'end_date' => 'today',
                            ]),
                        ],
                        'dimensions' => [new Dimension([
                            'name' => 'date',
                        ]),
                        ],
                        'metrics' => [new Metric([
                            'name' => 'totalUsers',
                        ]),
                        ],
                        'orderBys' => [
                            new OrderBy([
                                'dimension' => new OrderBy\DimensionOrderBy([
                                    'dimension_name' => 'date',
                                    'order_type' => OrderBy\DimensionOrderBy\OrderType::ALPHANUMERIC
                                ]),
                                'desc' => false,
                            ]),
                        ],
                    ]
                );

                $pageviews = $ga4_data->runReport(
                    [
                        'property' => 'properties/' . $property_id,
                        'dateRanges' => [
                            new DateRange([
                                'start_date' => $period,
                                'end_date' => 'today',
                            ]),
                        ],
                        'dimensions' => [new Dimension([
                            'name' => 'date',
                        ]),
                        ],
                        'metrics' => [new Metric([
                            'name' => 'screenPageViews',
                        ]),
                        ],
                        'orderBys' => [
                            new OrderBy([
                                'dimension' => new OrderBy\DimensionOrderBy([
                                    'dimension_name' => 'date',
                                    'order_type' => OrderBy\DimensionOrderBy\OrderType::ALPHANUMERIC
                                ]),
                                'desc' => false,
                            ]),
                        ],
                    ]
                );

                $avgSessionDuration = $ga4_data->runReport(
                    [
                        'property' => 'properties/' . $property_id,
                        'dateRanges' => [
                            new DateRange([
                                'start_date' => $period,
                                'end_date' => 'today',
                            ]),
                        ],
                        'dimensions' => [new Dimension([
                            'name' => 'date',
                        ]),
                        ],
                        'metrics' => [new Metric([
                            'name' => 'userEngagementDuration',
                        ]),
                        ],
                        'orderBys' => [
                            new OrderBy([
                                'dimension' => new OrderBy\DimensionOrderBy([
                                    'dimension_name' => 'date',
                                    'order_type' => OrderBy\DimensionOrderBy\OrderType::ALPHANUMERIC
                                ]),
                                'desc' => false,
                            ]),
                        ],
                    ]
                );

                $results = [
                    'sessions' => $sessions,
                    'users' => $users,
                    'pageviews' => $pageviews,
                    'avgSessionDuration' => $avgSessionDuration
                ];

                foreach ($results as $key => $value) {
                    foreach ($value->getRows() as $row) {
                        $all[0][$key][$row->getDimensionValues()[0]->getValue()] = $row->getMetricValues()[0]->getValue();
                    }
                }
            }

            if (true === $clear) {
                delete_transient('seopress_results_google_analytics');
            }

            if (false === ($seopress_results_google_analytics_cache = get_transient('seopress_results_google_analytics'))) {
                $seopress_results_google_analytics_cache = [];

                //////GA4/////////////
                if (seopress_google_analytics_ga4_property_id_option()) {
                    $seopress_results_google_analytics_cache['sessions'] = isset($all[0]['sessions']) && is_array($all[0]['sessions']) ? array_sum($all[0]['sessions']) : 0;
                    $seopress_results_google_analytics_cache['users'] = isset($all[0]['users']) && is_array($all[0]['users']) ? array_sum($all[0]['users']) : 0;
                    $seopress_results_google_analytics_cache['pageviews'] = isset($all[0]['pageviews']) && is_array($all[0]['pageviews']) ? array_sum($all[0]['pageviews']) : 0;


                    $seopress_results_google_analytics_cache['avgSessionDuration'] = 0;
                    if (isset($all[0]['avgSessionDuration']) && is_array($all[0]['avgSessionDuration'])) {
                        $sum = array_sum($all[0]['avgSessionDuration']);
                        $divided = count($all[0]['avgSessionDuration']);
                        if ($divided === 0) {
                            $divided = 1;
                        }

                        $seopress_results_google_analytics_cache['avgSessionDuration'] = gmdate('i:s', $sum / $divided);
                    }


                    switch ($seopress_ga_dashboard_widget_options_type) {
                        case 'ga_sessions':
                            $ga_sessions_rows = $all[0]['sessions'];
                            $seopress_ga_dashboard_widget_options_title = __('Sessions', 'wp-seopress-pro');
                            break;
                        case 'ga_users':
                            $ga_sessions_rows = $all[0]['users'];
                            $seopress_ga_dashboard_widget_options_title = __('Users', 'wp-seopress-pro');
                            break;
                        case 'ga_pageviews':
                            $ga_sessions_rows = $all[0]['pageviews'];
                            $seopress_ga_dashboard_widget_options_title = __('Page Views', 'wp-seopress-pro');
                            break;
                        case 'ga_avgSessionDuration':
                            $ga_sessions_rows = $all[0]['avgSessionDuration'];
                            $seopress_ga_dashboard_widget_options_title = __('Session Duration', 'wp-seopress-pro');
                            break;
                        default:
                            $ga_sessions_rows = $all[0]['sessions'];
                            $seopress_ga_dashboard_widget_options_title = __('Sessions', 'wp-seopress-pro');
                    }

                    function seopress_ga_dashboard_4_get_sessions_labels($ga_date) {
                        $labels = [];
                        foreach ($ga_date as $key => $value) {
                            array_push($labels, date_i18n(get_option('date_format'), strtotime($key)));
                        }

                        return $labels;
                    }

                    function seopress_ga_dashboard_4_get_sessions_data($ga_sessions_rows) {
                        $data = [];
                        foreach ($ga_sessions_rows as $key => $value) {
                            array_push($data, $value);
                        }

                        return $data;
                    }
                    $seopress_results_google_analytics_cache['sessions_graph_labels'] = seopress_ga_dashboard_4_get_sessions_labels($ga_sessions_rows);
                    $seopress_results_google_analytics_cache['sessions_graph_data'] = seopress_ga_dashboard_4_get_sessions_data($ga_sessions_rows);
                    $seopress_results_google_analytics_cache['sessions_graph_title'] = $seopress_ga_dashboard_widget_options_title;
                } else {

                    ////////////////////////////////////////////////////////////////////////////////////////
                    //Request Google Stats
                    ////////////////////////////////////////////////////////////////////////////////////////

                    //DATE RANGE
                    ////////////////////////////////////////////////////////////////////////////////////////

                    // Date
                    $dateRange = new Google_Service_AnalyticsReporting_DateRange();
                    $dateRange->setStartDate($period);
                    $dateRange->setEndDate('today');

                    //METRICS
                    ////////////////////////////////////////////////////////////////////////////////////////

                    // Sessions
                    $sessions = new Google_Service_AnalyticsReporting_Metric();
                    $sessions->setExpression('ga:sessions');
                    $sessions->setAlias('sessions');

                    // Users
                    $users = new Google_Service_AnalyticsReporting_Metric();
                    $users->setExpression('ga:users');
                    $users->setAlias('users');

                    // Page Views
                    $pageviews = new Google_Service_AnalyticsReporting_Metric();
                    $pageviews->setExpression('ga:pageviews');
                    $pageviews->setAlias('pageviews');

                    // Page Views per session
                    $pageviewsPerSession = new Google_Service_AnalyticsReporting_Metric();
                    $pageviewsPerSession->setExpression('ga:pageviewsPerSession');
                    $pageviewsPerSession->setAlias('pageviewsPerSession');

                    // Average session duration
                    $avgSessionDuration = new Google_Service_AnalyticsReporting_Metric();
                    $avgSessionDuration->setExpression('ga:avgSessionDuration');
                    $avgSessionDuration->setAlias('avgSessionDuration');

                    // Bounce rate
                    $bounceRate = new Google_Service_AnalyticsReporting_Metric();
                    $bounceRate->setExpression('ga:bounceRate');
                    $bounceRate->setAlias('bounceRate');

                    // % New sessions
                    $percentNewSessions = new Google_Service_AnalyticsReporting_Metric();
                    $percentNewSessions->setExpression('ga:percentNewSessions');
                    $percentNewSessions->setAlias('percentNewSessions');

                    // Total events
                    $totalEvents = new Google_Service_AnalyticsReporting_Metric();
                    $totalEvents->setExpression('ga:totalEvents');
                    $totalEvents->setAlias('totalEvents');

                    // Unique events
                    $uniqueEvents = new Google_Service_AnalyticsReporting_Metric();
                    $uniqueEvents->setExpression('ga:uniqueEvents');
                    $uniqueEvents->setAlias('uniqueEvents');

                    //DIMENSIONS
                    ////////////////////////////////////////////////////////////////////////////////////////

                    // Date
                    $date = new Google_Service_AnalyticsReporting_Dimension();
                    $date->setName('ga:date');

                    // Language
                    $language = new Google_Service_AnalyticsReporting_Dimension();
                    $language->setName('ga:language');

                    // Country
                    $country = new Google_Service_AnalyticsReporting_Dimension();
                    $country->setName('ga:country');

                    // Device Category
                    $deviceCategory = new Google_Service_AnalyticsReporting_Dimension();
                    $deviceCategory->setName('ga:deviceCategory');

                    // Browser
                    $browser = new Google_Service_AnalyticsReporting_Dimension();
                    $browser->setName('ga:browser');

                    // Social Network
                    $socialNetwork = new Google_Service_AnalyticsReporting_Dimension();
                    $socialNetwork->setName('ga:socialNetwork');

                    // Channel Grouping
                    $channelGrouping = new Google_Service_AnalyticsReporting_Dimension();
                    $channelGrouping->setName('ga:channelGrouping');

                    // Source
                    $source = new Google_Service_AnalyticsReporting_Dimension();
                    $source->setName('ga:source');

                    // Full Referrer
                    $fullReferrer = new Google_Service_AnalyticsReporting_Dimension();
                    $fullReferrer->setName('ga:fullReferrer');

                    // Page Title
                    $pageTitle = new Google_Service_AnalyticsReporting_Dimension();
                    $pageTitle->setName('ga:pageTitle');

                    // Event Category
                    $eventCategory = new Google_Service_AnalyticsReporting_Dimension();
                    $eventCategory->setName('ga:eventCategory');

                    // Event Action
                    $eventAction = new Google_Service_AnalyticsReporting_Dimension();
                    $eventAction->setName('ga:eventAction');

                    // Event Label
                    $eventLabel = new Google_Service_AnalyticsReporting_Dimension();
                    $eventLabel->setName('ga:eventLabel');

                    //ORDERS
                    ////////////////////////////////////////////////////////////////////////////////////////

                    // Order by user desc
                    $order_by_users_desc = new Google_Service_AnalyticsReporting_OrderBy();
                    $order_by_users_desc->setFieldName('ga:users');
                    $order_by_users_desc->setOrderType('VALUE');
                    $order_by_users_desc->setSortOrder('DESCENDING');

                    // Order by page views desc
                    $order_by_pageviews_desc = new Google_Service_AnalyticsReporting_OrderBy();
                    $order_by_pageviews_desc->setFieldName('ga:pageviews');
                    $order_by_pageviews_desc->setOrderType('VALUE');
                    $order_by_pageviews_desc->setSortOrder('DESCENDING');

                    // Order by total events desc
                    $order_by_events_desc = new Google_Service_AnalyticsReporting_OrderBy();
                    $order_by_events_desc->setFieldName('ga:totalEvents');
                    $order_by_events_desc->setOrderType('VALUE');
                    $order_by_events_desc->setSortOrder('DESCENDING');

                    //REPORTS
                    ////////////////////////////////////////////////////////////////////////////////////////

                    // Sessions, Users, Page Views, Page Views Per Session, Average Session Duration, Bounce Rate, New Sessions, Total Events and Unique Events by Date
                    $request_by_date = new Google_Service_AnalyticsReporting_ReportRequest();
                    $request_by_date->setViewId(seopress_google_analytics_auth_option());
                    $request_by_date->setDateRanges($dateRange);
                    $request_by_date->setDimensions([$date]);
                    $request_by_date->setMetrics([$sessions, $users, $pageviews, $pageviewsPerSession, $avgSessionDuration, $bounceRate, $percentNewSessions, $totalEvents, $uniqueEvents]);
                    $request_by_date->setSamplingLevel('SMALL');

                    // Users by language
                    $request_users_by_language = new Google_Service_AnalyticsReporting_ReportRequest();
                    $request_users_by_language->setViewId(seopress_google_analytics_auth_option());
                    $request_users_by_language->setDateRanges($dateRange);
                    $request_users_by_language->setDimensions([$language]);
                    $request_users_by_language->setMetrics([$users]);
                    $request_users_by_language->setSamplingLevel('SMALL');
                    $request_users_by_language->setOrderBys($order_by_users_desc);

                    // Users by country
                    $request_users_by_country = new Google_Service_AnalyticsReporting_ReportRequest();
                    $request_users_by_country->setViewId(seopress_google_analytics_auth_option());
                    $request_users_by_country->setDateRanges($dateRange);
                    $request_users_by_country->setDimensions([$country]);
                    $request_users_by_country->setMetrics([$users]);
                    $request_users_by_country->setSamplingLevel('SMALL');
                    $request_users_by_country->setOrderBys($order_by_users_desc);

                    // Users by device category
                    $request_users_by_device_cat = new Google_Service_AnalyticsReporting_ReportRequest();
                    $request_users_by_device_cat->setViewId(seopress_google_analytics_auth_option());
                    $request_users_by_device_cat->setDateRanges($dateRange);
                    $request_users_by_device_cat->setDimensions([$deviceCategory]);
                    $request_users_by_device_cat->setMetrics([$users]);
                    $request_users_by_device_cat->setSamplingLevel('SMALL');
                    $request_users_by_device_cat->setOrderBys($order_by_users_desc);

                    // Users by Browser
                    $request_users_by_browser = new Google_Service_AnalyticsReporting_ReportRequest();
                    $request_users_by_browser->setViewId(seopress_google_analytics_auth_option());
                    $request_users_by_browser->setDateRanges($dateRange);
                    $request_users_by_browser->setDimensions([$browser]);
                    $request_users_by_browser->setMetrics([$users]);
                    $request_users_by_browser->setSamplingLevel('SMALL');
                    $request_users_by_browser->setOrderBys($order_by_users_desc);

                    // Users by Social Networks
                    $request_users_by_social_network = new Google_Service_AnalyticsReporting_ReportRequest();
                    $request_users_by_social_network->setViewId(seopress_google_analytics_auth_option());
                    $request_users_by_social_network->setDateRanges($dateRange);
                    $request_users_by_social_network->setDimensions([$socialNetwork]);
                    $request_users_by_social_network->setMetrics([$users]);
                    $request_users_by_social_network->setSamplingLevel('SMALL');
                    $request_users_by_social_network->setOrderBys($order_by_users_desc);

                    // Users by Channel
                    $request_users_by_channel = new Google_Service_AnalyticsReporting_ReportRequest();
                    $request_users_by_channel->setViewId(seopress_google_analytics_auth_option());
                    $request_users_by_channel->setDateRanges($dateRange);
                    $request_users_by_channel->setDimensions([$channelGrouping]);
                    $request_users_by_channel->setMetrics([$users]);
                    $request_users_by_channel->setSamplingLevel('SMALL');

                    // Users by Source
                    $request_users_by_source = new Google_Service_AnalyticsReporting_ReportRequest();
                    $request_users_by_source->setViewId(seopress_google_analytics_auth_option());
                    $request_users_by_source->setDateRanges($dateRange);
                    $request_users_by_source->setDimensions([$source]);
                    $request_users_by_source->setMetrics([$users]);
                    $request_users_by_source->setSamplingLevel('SMALL');
                    $request_users_by_source->setOrderBys($order_by_users_desc);

                    // Users by Referrer
                    $request_users_by_ref = new Google_Service_AnalyticsReporting_ReportRequest();
                    $request_users_by_ref->setViewId(seopress_google_analytics_auth_option());
                    $request_users_by_ref->setDateRanges($dateRange);
                    $request_users_by_ref->setDimensions([$fullReferrer]);
                    $request_users_by_ref->setMetrics([$users]);
                    $request_users_by_ref->setSamplingLevel('SMALL');
                    $request_users_by_ref->setOrderBys($order_by_users_desc);

                    // Page Views by Page Title
                    $request_page_views_page_title = new Google_Service_AnalyticsReporting_ReportRequest();
                    $request_page_views_page_title->setViewId(seopress_google_analytics_auth_option());
                    $request_page_views_page_title->setDateRanges($dateRange);
                    $request_page_views_page_title->setDimensions([$pageTitle]);
                    $request_page_views_page_title->setMetrics([$pageviews]);
                    $request_page_views_page_title->setSamplingLevel('SMALL');
                    $request_page_views_page_title->setOrderBys($order_by_pageviews_desc);

                    // Event Cat
                    $request_events_by_cat = new Google_Service_AnalyticsReporting_ReportRequest();
                    $request_events_by_cat->setViewId(seopress_google_analytics_auth_option());
                    $request_events_by_cat->setDateRanges($dateRange);
                    $request_events_by_cat->setDimensions([$eventCategory]);
                    $request_events_by_cat->setMetrics([$totalEvents]);
                    $request_events_by_cat->setSamplingLevel('SMALL');
                    $request_events_by_cat->setOrderBys($order_by_events_desc);

                    // Event Action
                    $request_events_by_action = new Google_Service_AnalyticsReporting_ReportRequest();
                    $request_events_by_action->setViewId(seopress_google_analytics_auth_option());
                    $request_events_by_action->setDateRanges($dateRange);
                    $request_events_by_action->setDimensions([$eventAction]);
                    $request_events_by_action->setMetrics([$totalEvents]);
                    $request_events_by_action->setSamplingLevel('SMALL');
                    $request_events_by_action->setOrderBys($order_by_events_desc);

                    // Event Label
                    $request_events_by_label = new Google_Service_AnalyticsReporting_ReportRequest();
                    $request_events_by_label->setViewId(seopress_google_analytics_auth_option());
                    $request_events_by_label->setDateRanges($dateRange);
                    $request_events_by_label->setDimensions([$eventLabel]);
                    $request_events_by_label->setMetrics([$totalEvents]);
                    $request_events_by_label->setSamplingLevel('SMALL');
                    $request_events_by_label->setOrderBys($order_by_events_desc);

                    //BATCH REPORT
                    ////////////////////////////////////////////////////////////////////////////////////////

                    function seopress_analytics_get_reports($reports) {
                        $return = [];

                        for ($reportIndex = 0; $reportIndex < count($reports); ++$reportIndex) {
                            $report = $reports[$reportIndex];
                            $header = $report->getColumnHeader();
                            $dimensionHeaders = $header->getDimensions();
                            $metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
                            $rows = $report->getData()->getRows();

                            for ($rowIndex = 0; $rowIndex < count($rows); ++$rowIndex) {
                                $row = $rows[$rowIndex];
                                $dimensions = $row->getDimensions();
                                $metrics = $row->getMetrics();
                                for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); ++$i) {
                                    $return[$dimensionHeaders[$i]][] = $dimensions[$i];
                                }

                                for ($j = 0; $j < count($metrics); ++$j) {
                                    $values = $metrics[$j]->getValues();
                                    for ($k = 0; $k < count($values); ++$k) {
                                        $entry = $metricHeaders[$k];
                                        $return[$entry->getName()][] = $values[$k];
                                    }
                                }
                            }
                        }

                        return $return;
                    }

                    $all = [];

                    $requests = [
                        $request_by_date,
                        $request_users_by_country,
                        $request_users_by_device_cat,
                        $request_users_by_browser,
                        $request_users_by_social_network,
                        $request_users_by_channel,
                        $request_users_by_source,
                        $request_users_by_ref,
                        $request_page_views_page_title,
                        $request_events_by_cat,
                        $request_events_by_action,
                        $request_events_by_label,
                        $request_users_by_language,
                    ];

                    foreach ($requests as $key => $request) {
                        $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
                        $body->setReportRequests([$request]);
                        $body = $service->reports->batchGet($body);

                        $all[$key] = seopress_analytics_get_reports($body);
                    }

                    ////////////////////////////////////////////////////////////////////////////////////////
                    //Saving datas
                    ////////////////////////////////////////////////////////////////////////////////////////
                    $seopress_results_google_analytics_cache['sessions'] = isset($all[0]['sessions']) && $all[0]['sessions'] !== null ? array_sum($all[0]['sessions']) : 0;
                    $seopress_results_google_analytics_cache['users'] = isset($all[0]['users']) && $all[0]['users'] !== null ? array_sum($all[0]['users']) : 0;
                    $seopress_results_google_analytics_cache['pageviews'] = isset($all[0]['pageviews']) && $all[0]['pageviews'] !== null ? array_sum($all[0]['pageviews']) : 0;

                    $seopress_results_google_analytics_cache['pageviewsPerSession'] = 0;
                    if (isset($all[0]['pageviewsPerSession']) && $all[0]['pageviewsPerSession'] !== null) {
                        $divided = isset($all[0]['pageviewsPerSession']) && $all[0]['pageviewsPerSession'] !== null ? count($all[0]['pageviewsPerSession']) : 1;
                        if ($divided === 0) {
                            $divided = 1;
                        }

                        $seopress_results_google_analytics_cache['pageviewsPerSession'] = round(array_sum($all[0]['pageviewsPerSession']) / $divided, 2);
                    }


                    $seopress_results_google_analytics_cache['avgSessionDuration'] = 0;
                    if (isset($all[0]['avgSessionDuration']) && $all[0]['avgSessionDuration'] !== null) {
                        $divided = isset($all[0]['avgSessionDuration']) && $all[0]['avgSessionDuration'] !== null ? count($all[0]['avgSessionDuration']) : 1;
                        if ($divided === 0) {
                            $divided = 1;
                        }
                        $avg = array_sum($all[0]['avgSessionDuration']);
                        $seopress_results_google_analytics_cache['avgSessionDuration'] = gmdate('i:s', round($avg / $divided));
                    }

                    $seopress_results_google_analytics_cache['bounceRate'] = 0;
                    if (isset($all[0]['bounceRate']) && $all[0]['bounceRate'] !== null) {
                        $divided = isset($all[0]['bounceRate']) && $all[0]['bounceRate'] !== null ? count($all[0]['bounceRate']) : 1;
                        if ($divided === 0) {
                            $divided = 1;
                        }
                        $seopress_results_google_analytics_cache['bounceRate'] = round(array_sum($all[0]['bounceRate']) / $divided, 2);
                    }

                    $seopress_results_google_analytics_cache['percentNewSessions'] = 0;
                    if (isset($all[0]['percentNewSessions']) && $all[0]['percentNewSessions'] !== null) {
                        $divided = isset($all[0]['percentNewSessions']) && $all[0]['percentNewSessions'] !== null ? count($all[0]['percentNewSessions']) : 1;
                        if ($divided === 0) {
                            $divided = 1;
                        }
                        $seopress_results_google_analytics_cache['percentNewSessions'] = round(array_sum($all[0]['percentNewSessions']) / $divided, 2);
                    }

                    $seopress_results_google_analytics_cache['language'] = $all[12];
                    $seopress_results_google_analytics_cache['country'] = $all[1];
                    $seopress_results_google_analytics_cache['deviceCategory'] = $all[2];
                    $seopress_results_google_analytics_cache['browser'] = $all[3];
                    $seopress_results_google_analytics_cache['socialNetwork'] = $all[4];
                    $seopress_results_google_analytics_cache['channelGrouping'] = $all[5];
                    $seopress_results_google_analytics_cache['source'] = $all[6];
                    $seopress_results_google_analytics_cache['fullReferrer'] = $all[7];
                    $seopress_results_google_analytics_cache['contentpageviews'] = $all[8];
                    $seopress_results_google_analytics_cache['totalEvents'] = $all[0]['totalEvents'] ? $all[0]['totalEvents'] : '';
                    $seopress_results_google_analytics_cache['uniqueEvents'] = $all[0]['uniqueEvents'] ? $all[0]['uniqueEvents'] : '';
                    $seopress_results_google_analytics_cache['eventCategory'] = $all[9];
                    $seopress_results_google_analytics_cache['eventAction'] = $all[10];
                    $seopress_results_google_analytics_cache['eventLabel'] = $all[11];

                    switch ($seopress_ga_dashboard_widget_options_type) {
                        case 'ga_sessions':
                            $ga_sessions_rows = $all[0]['sessions'];
                            $seopress_ga_dashboard_widget_options_title = __('Sessions', 'wp-seopress-pro');
                            break;
                        case 'ga_users':
                            $ga_sessions_rows = $all[0]['users'];
                            $seopress_ga_dashboard_widget_options_title = __('Users', 'wp-seopress-pro');
                            break;
                        case 'ga_pageviews':
                            $ga_sessions_rows = $all[0]['pageviews'];
                            $seopress_ga_dashboard_widget_options_title = __('Page Views', 'wp-seopress-pro');
                            break;
                        case 'ga_pageviewsPerSession':
                            $ga_sessions_rows = $all[0]['pageviewsPerSession'];
                            $seopress_ga_dashboard_widget_options_title = __('Page Views Per Session', 'wp-seopress-pro');
                            break;
                        case 'ga_avgSessionDuration':
                            $ga_sessions_rows = $all[0]['avgSessionDuration'];
                            $seopress_ga_dashboard_widget_options_title = __('Average Session Duration', 'wp-seopress-pro');
                            break;
                        case 'ga_bounceRate':
                            $ga_sessions_rows = $all[0]['bounceRate'];
                            $seopress_ga_dashboard_widget_options_title = __('Bounce Rate', 'wp-seopress-pro');
                            break;
                        case 'ga_percentNewSessions':
                            $ga_sessions_rows = $all[0]['percentNewSessions'];
                            $seopress_ga_dashboard_widget_options_title = __('New Sessions', 'wp-seopress-pro');
                            break;
                        default:
                            $ga_sessions_rows = $all[0]['sessions'];
                            $seopress_ga_dashboard_widget_options_title = __('Sessions', 'wp-seopress-pro');
                    }

                    function seopress_ga_dashboard_get_sessions_labels($ga_date) {
                        $labels = [];
                        if ( ! empty($ga_date) && is_array($ga_date)) {
                            foreach ($ga_date as $key => $value) {
                                array_push($labels, date_i18n(get_option('date_format'), strtotime($value)));
                            }
                        }

                        return $labels;
                    }

                    function seopress_ga_dashboard_get_sessions_data($ga_sessions_rows) {
                        $data = [];
                        if ( ! empty($ga_sessions_rows) && is_array($ga_sessions_rows)) {
                            foreach ($ga_sessions_rows as $key => $value) {
                                array_push($data, $value);
                            }
                        }

                        return $data;
                    }
                    $ga_date = $all[0]['ga:date'];
                    $seopress_results_google_analytics_cache['sessions_graph_labels'] = seopress_ga_dashboard_get_sessions_labels($ga_date);
                    $seopress_results_google_analytics_cache['sessions_graph_data'] = seopress_ga_dashboard_get_sessions_data($ga_sessions_rows);
                    $seopress_results_google_analytics_cache['sessions_graph_title'] = $seopress_ga_dashboard_widget_options_title;
                }

                //Transient
                set_transient('seopress_results_google_analytics', $seopress_results_google_analytics_cache, 2 * HOUR_IN_SECONDS);
            }

            //Return
            $seopress_results_google_analytics_transient = get_transient('seopress_results_google_analytics');

            wp_send_json_success($seopress_results_google_analytics_transient);

        } catch (\Exception $e) {
            $error = $e->getMessage();
            wp_send_json(json_decode($error));
        }
    }

    exit();
}
/**
 * Request GA stats by CRON.
 *
 * @since 4.2
 *
 * @author Benjamin
 */
function seopress_request_google_analytics_cron() {
    seopress_request_google_analytics_fn(true);
}
add_action('seopress_google_analytics_cron', 'seopress_request_google_analytics_cron');

function seopress_request_google_analytics() {
    check_ajax_referer('seopress_request_google_analytics_nonce');
    if ((current_user_can(seopress_capability('manage_options', 'cron')) || seopress_advanced_security_ga_widget_check() === true) && is_admin()) {
        seopress_request_google_analytics_fn(false);
    }
}
add_action('wp_ajax_seopress_request_google_analytics', 'seopress_request_google_analytics');

///////////////////////////////////////////////////////////////////////////////////////////////////
//Request Matomo Analytics
///////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * Request Matomo stats.
 *
 * @since 6.0
 *
 * @author Benjamin
 */
function seopress_request_matomo_analytics_fn($clear = false) {
    if (function_exists('seopress_google_analytics_matomo_dashboard_widget_option') && seopress_google_analytics_matomo_dashboard_widget_option() === '1') {
        exit();
    }

    //Clear cache if CRON
    if (true === $clear) {
        delete_transient('seopress_results_matomo');
    }

    if (false === ($seopress_results_matomo_cache = get_transient('seopress_results_matomo'))) {
        $seopress_results_matomo_cache = [];

        $matomoID = seopress_get_service('GoogleAnalyticsOption')->getMatomoId() ? seopress_get_service('GoogleAnalyticsOption')->getMatomoId() : null;

        if (empty($matomoID)) {
            exit();
        }

        $siteID = seopress_get_service('GoogleAnalyticsOption')->getMatomoSiteId() ? seopress_get_service('GoogleAnalyticsOption')->getMatomoSiteId() : null;

        if (empty($siteID)) {
            exit();
        }

        $authToken = seopress_get_service('GoogleAnalyticsOption')->getMatomoAuthToken() ? seopress_get_service('GoogleAnalyticsOption')->getMatomoAuthToken() : null;

        if (empty($authToken)) {
            exit();
        }

        // get saved data
        if ( ! $widget_options = get_option('seopress_matomo_dashboard_widget_options')) {
            $widget_options = [];
        }

        // check if saved data contains content
        $seopress_matomo_dashboard_widget_options_period = isset($widget_options['period']) ? $widget_options['period'] : false;

        $seopress_matomo_dashboard_widget_options_type = isset($widget_options['type']) ? $widget_options['type'] : 'nb_visits';

        // custom content saved by control callback, modify output
        if ($seopress_matomo_dashboard_widget_options_period) {
            $period = $seopress_matomo_dashboard_widget_options_period;
        } else {
            $period = 'last30';
        }

        $url = 'https://' . $matomoID . '?module=API&method=API.getProcessedReport&idSite=' . $siteID . '&date=' . $period . '&period=day&apiModule=VisitsSummary&apiAction=get&format=json&token_auth=' . $authToken . '&filter_truncate=5&language=en';

        $args = [
            'blocking'    => true,
            'timeout'     => 10,
            'sslverify'   => false,
        ];

        $response = wp_remote_get($url, $args);

        //Check for error
        if (!is_wp_error($response)) {
            $response = wp_remote_retrieve_body($response);
            $response = json_decode($response, true);
        }

        switch ($seopress_matomo_dashboard_widget_options_type) {
            case 'nb_uniq_visitors':
                $widget_title = __('Unique visitors', 'wp-seopress-pro');
                break;
            case 'nb_visits':
                $widget_title = __('Visits', 'wp-seopress-pro');
                break;
            case 'max_actions':
                $widget_title = __('Maximum actions in one visit', 'wp-seopress-pro');
                break;
            case 'nb_actions_per_visit':
                $widget_title = __('Average actions per visit', 'wp-seopress-pro');
                break;
            case 'bounce_rate':
                $widget_title = __('Bounce Rate', 'wp-seopress-pro');
                break;
            case 'avg_time_on_site':
                $widget_title = __('Avg. Visit Duration (in seconds)', 'wp-seopress-pro');
                break;
            default:
                $widget_title = __('Unique visitors', 'wp-seopress-pro');
        }

        function seopress_matomo_get_sessions_labels($rows) {
            $labels = [];

            $rows = $rows['reportMetadata'];
            foreach ($rows as $key => $value) {
                $labels[] = date_i18n(get_option('date_format'), strtotime($key));
            }
            return $labels;
        }

        function seopress_matomo_get_sessions_data($rows, $seopress_matomo_dashboard_widget_options_type) {
            $data = [];
            $rows = array_values($rows['reportData']);
            foreach ($rows as $key => $value) {
                //Bounce rate: remove %
                if ($seopress_matomo_dashboard_widget_options_type === 'bounce_rate') {
                    $value[$seopress_matomo_dashboard_widget_options_type] = rtrim($value[$seopress_matomo_dashboard_widget_options_type], '%');
                }

                //Average time: convert to seconds
                if ($seopress_matomo_dashboard_widget_options_type === 'avg_time_on_site') {
                    $value[$seopress_matomo_dashboard_widget_options_type] = strtotime("1970-01-01 $value[$seopress_matomo_dashboard_widget_options_type] UTC");
                }

                $data[] = $value[$seopress_matomo_dashboard_widget_options_type];
            }
            return $data;
        }

        function seopress_timestamp_to_seconds($n) {
            return strtotime("1970-01-01 $n UTC");
        }

        function seopress_remove_pourcentage($n) {
            return rtrim($n, '%');
        }

        function seopress_matomo_get_all_data($rows) {
            $data = [];
            $rows = $rows['reportData'];

            //Unique Visitors
            $data['nb_uniq_visitors'] = array_sum(array_column($rows, 'nb_uniq_visitors'));

            //Visits
            $data['nb_visits'] = array_sum(array_column($rows, 'nb_visits'));

            //Max actions
            $data['max_actions'] = max(array_column($rows, 'max_actions'));

            //Actions per visit
            $data['nb_actions_per_visit'] = array_column($rows, 'nb_actions_per_visit');
            $count = count($data['nb_actions_per_visit']);
            if ($count > 1) {
                $data['nb_actions_per_visit'] = round(array_sum($data['nb_actions_per_visit']) / $count, 2);
            } else {
                $data['nb_actions_per_visit'] = $data['nb_actions_per_visit'][0];
            }

            //Bounce rate
            $data['bounce_rate'] = array_map('seopress_remove_pourcentage', array_column($rows, 'bounce_rate'));
            $count = count($data['bounce_rate']);
            if ($count > 1) {
                $data['bounce_rate'] = round(array_sum($data['bounce_rate']) / $count, 2);
            } else {
                $data['bounce_rate'] = $data['bounce_rate'][0];
            }

            //Avg. Visit Duration
            $data['avg_time_on_site'] = array_map('seopress_timestamp_to_seconds', array_column($rows, 'avg_time_on_site'));
            $count = count($data['avg_time_on_site']);
            if ($count > 1) {
                $data['avg_time_on_site'] = round(array_sum($data['avg_time_on_site']) / $count, 2);
            } else {
                $data['avg_time_on_site'] = $data['avg_time_on_site'][0];
            }

            return $data;
        }

        $response['sessions_graph_labels'] = seopress_matomo_get_sessions_labels($response);
        $response['sessions_graph_data'] = seopress_matomo_get_sessions_data($response, $seopress_matomo_dashboard_widget_options_type);
        $response['sessions_graph_title'] = $widget_title;
        $response['all'] = seopress_matomo_get_all_data($response);

        //Transient
        set_transient('seopress_results_matomo', $response, 2 * HOUR_IN_SECONDS);
    }
    //Return
    $seopress_results_matomo_transient = get_transient('seopress_results_matomo');

    wp_send_json_success($seopress_results_matomo_transient);
    exit();
}
/**
 * Request Matomo Analytics by CRON.
 *
 * @since 6.0
 * @param boolean Is is a CRON request?
 *
 * @author Benjamin
 */
function seopress_request_matomo_analytics_cron() {
    seopress_request_matomo_analytics_fn(true);
}
add_action('seopress_matomo_analytics_cron', 'seopress_request_matomo_analytics_cron');

function seopress_request_matomo_analytics() {
    check_ajax_referer('seopress_request_matomo_analytics_nonce');

    if ((current_user_can(seopress_capability('manage_options', 'cron')) || seopress_advanced_security_matomo_widget_check() === true) && is_admin()) {
        seopress_request_matomo_analytics_fn();
    }
}
add_action('wp_ajax_seopress_request_matomo_analytics', 'seopress_request_matomo_analytics');

Youez - 2016 - github.com/yon3zu
LinuXploit