<?php

use Acms\Services\Facades\Storage;
use Acms\Services\Facades\Http;

class ACMS_POST_PingWeblogUpdate extends ACMS_POST
{
    public $isCacheDelete = false;

    public function post()
    {
        if (!sessionWithCompilation()) {
            die();
        }
        if (!IS_LICENSED) {
            die();
        }

        try {
            $tplPath = THEMES_DIR . 'system/rpc/weblog-updates-ping.xml';
            $tpl = Storage::get($tplPath);
        } catch (Exception $e) {
            return false;
        }
        $tpl = setGlobalVars($tpl);

        $siteName = ACMS_RAM::blogName(BID);
        $siteUrl = acmsLink(array('bid' => BID, 'protocol' => 'http'), false);
        $checkLink = acmsLink(array('bid' => BID, 'cid' => CID, 'eid' => EID, 'protocol' => 'http'), false);

        //------
        // ping
        if ($aryEndpoint = configArray('ping_weblog_updates_endpoint')) {
            $Tpl = new Template($tpl);
            $Tpl->add(null, array(
                'method' => 'ping',
                'siteName' => $siteName,
                'siteLink' => $siteUrl,
            ));
            $xml = $Tpl->get();

            foreach ($aryEndpoint as $endpoint) {
                try {
                    $req = \Http::init($endpoint, 'post');
                    $req->setRequestHeaders(array(
                        'Content-Type: text/xml',
                        'User-Agent: a-blog cms',
                    ));
                    $req->setPostData($xml);
                    $response = $req->send();
                    $response->getResponseBody();
                } catch (Exception $e) {
                }
            }
        }

        //--------------
        // extendedPing
        if ($aryEndpoint = configArray('ping_weblog_updates_extended_endpoint')) {
            $Tpl = new Template($tpl);
            if (CID) {
                $Tpl->add('cid');
                $Tpl->add('category');
            }
            $Tpl->add(null, array(
                'method' => 'extendedPing',
                'siteName' => $siteName,
                'siteLink' => $siteUrl,
                'checkLink' => $checkLink,
            ));
            $xml = $Tpl->get();

            foreach ($aryEndpoint as $endpoint) {
                try {
                    $req = Http::init($endpoint, 'post');
                    $req->setRequestHeaders(array(
                        'Content-Type: text/xml',
                        'User-Agent: a-blog cms',
                    ));
                    $req->setPostData($xml);
                    $response = $req->send();
                    $response->getResponseBody();
                } catch (Exception $e) {
                }
            }
        }

        return $this->Post;
    }
}
