Parallels Plesk Panel API RPC Protocol Developer

Comments

class ApiRequestException Extends the standard Exception class. Visit http://www.php.net/manual/en/language.exceptions.php for details.
function domainsInfoRequest() Uses the DOM model to compose a request XML packet. Returns the resulting DOM object.
function curlInit() Initializes the CURL session with necessary options as follows:
CURLOPT_URL specifies the destination URL
CURLOPT_RETURNTRANSFER set to true means that the resulting output will be returned from the server in the form of a string.
CURLOPT_POST set to true means that the packet will be sent via HTTP POST.
CURLOPT_SSL_VERIFYPEER set to false stops CURL from verifying the peer’s certificate.
CURLOPT_SSL_VERIFYHOST set to false stops CURL from verifying the host.
CURLOPT_HTTPHEADER specifies an array of HTTP header fields to set.
Returns the handler of the URL session.
function sendRequest() Sends the HTTP packet by means of CURL and gets the pure XML response packet (without the HTTP header). Closes the CURL session and returns the resulting packet (a plain text with XML tags). To learn more about the CURL engine, visit http://www.php.net/manual/en/ref.curl.php.
function parseResponse() Gets the response packet (plain text) as a parameter. Parses the packet using SimpleXML and returns the SimpleXMLElement object in which the packet is structured as a tree. To learn more about the SimpleXML extension of PHP, visit http://www.php.net/manual/en/ref.simplexml.php.
function checkResponse() Gets the response packet of type SimpleXMLEelement and checks the result node. If this node holds ‘error’, then the function throws an exception with a string passed in the errtext node.

The main() function invokes these functions in the order they are considered. First it calls domainInfoRequest() to form a packet as follows:

<?xml version="1.0" encoding="UTF-8" ?>
<packet version="1.4.1.2">
<domain>
<get>
      <filter/>
      <dataset>
             <limits/>
             <prefs/>
             <user/>
             <hosting/>
             <stat/>
             <gen_info/>
      </dataset>
</get>
</domain>
</packet>

Then curlInit() is called to initialize CURL session with options. The sendRequest function sends a packet with the HTTP header as follows:

POST /enterprise/control/agent.php HTTP/1.1
Host: 10.58.32.100:8443
HTTP_AUTH_LOGIN: login
HTTP_AUTH_PASSWD: qwedsa
HTTP_PRETTY_PRINT: TRUE
Content-Length: 294
Content-Type: text/xml

The response XML packet received from Plesk server can look as follows:

<?xml version="1.0" encoding="UTF-8" ?>
<packet version="1.4.1.2">
<domain>
<get>
   <result>
      <status>ok</status>
      <id>1234</id>
      <value>
          <gen_info>
             <cr_date>1154513574</cr_date>
             <name>technolux.co.uk</name>
             <display_name>technolux</display_name>
             <status>64</status>
             <real_size>0</real_size>
             <client_id>4610</client_id>
             <dns_ip_address>123.123.123.121</dns_ip_address>
             <htype>none</htype>
          </gen_info>
      </value>
   </result>
</get>
</domain>
</packet>

Once the response packet is received and parsed with the parseResponse() function, the foreach iterator echoes the contents of the result node.

Code sample


<?php

/**
 * Reports error during API RPC request
 */
class ApiRequestException extends Exception {}

/**
 * Returns DOM object representing request for information about all available domains
 * @return DOMDocument
 */

function domainsInfoRequest()
{
      $xmldoc = new DomDocument('1.0', 'UTF-8');
      $xmldoc->formatOutput = true;

      // <packet>
      $packet = $xmldoc->createElement('packet');
      $packet->setAttribute('version', '1.4.1.2');
      $xmldoc->appendChild($packet);

      // <packet/domain>
      $domain = $xmldoc->createElement('domain');
      $packet->appendChild($domain);

      // <packet/domain/get>
      $get = $xmldoc->createElement('get');
      $domain->appendChild($get);

      // <packet/domain/get/filter>
      $filter = $xmldoc->createElement('filter');
      $get->appendChild($filter);

      // <packet/domain/get/dataset>
      $dataset = $xmldoc->createElement('dataset');
      $get->appendChild($dataset);

      // dataset elements
      $dataset->appendChild($xmldoc->createElement('limits'));
      $dataset->appendChild($xmldoc->createElement('prefs'));
      $dataset->appendChild($xmldoc->createElement('user'));
      $dataset->appendChild($xmldoc->createElement('hosting'));
      $dataset->appendChild($xmldoc->createElement('stat'));
      $dataset->appendChild($xmldoc->createElement('gen_info'));

      return $xmldoc;
}
/**
 * Prepares CURL to perform Plesk API request
 * @return resource
 */
function curlInit($host, $login, $password)
{
      $curl = curl_init();
      curl_setopt($curl, CURLOPT_URL, "https://{$host}:8443/enterprise/control/agent.php");
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($curl, CURLOPT_POST,           true);
      curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
      curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
      curl_setopt($curl, CURLOPT_HTTPHEADER,
             array("HTTP_AUTH_LOGIN: {$login}",
                    "HTTP_AUTH_PASSWD: {$password}",
                    "HTTP_PRETTY_PRINT: TRUE",
                    "Content-Type: text/xml")
      );

      return $curl;
}
/**
 * Performs a Plesk API request, returns raw API response text
 *
 * @return string
 * @throws ApiRequestException
 */
function sendRequest($curl, $packet)
{
      curl_setopt($curl, CURLOPT_POSTFIELDS, $packet);
      $result = curl_exec($curl);
      if (curl_errno($curl)) {
             $errmsg  = curl_error($curl);
             $errcode = curl_errno($curl);
             curl_close($curl);
             throw new ApiRequestException($errmsg, $errcode);
      }
      curl_close($curl);
      return $result;
}

/**
 * Looks if API responded with correct data
 *
 * @return SimpleXMLElement
 * @throws ApiRequestException
 */
function parseResponse($response_string)
{
      $xml = new SimpleXMLElement($response_string);
      if (!is_a($xml, 'SimpleXMLElement'))
             throw new ApiRequestException("Cannot parse server response: {$response_string}");
      return $xml;
}
/**
 * Check data in API response
 * @return void
 * @throws ApiRequestException
 */
function checkResponse(SimpleXMLElement $response)
{
      $resultNode = $response->domain->get->result;

      // check if request was successful
      if ('error' == (string)$resultNode->status)
             throw new ApiRequestException("Plesk API returned error: " . (string)$resultNode->result->errtext);
}

//
// int main()
//
$host = '10.58.32.100';
$login = 'admin';
$password = 'qwedsa';

$curl = curlInit($host, $login, $password);

try {

      $response = sendRequest($curl, domainsInfoRequest()->saveXML());
      $responseXml = parseResponse($response);
      checkResponse($responseXml);

} catch (ApiRequestException $e) {
      echo $e;
      die();
}

// Explore the result
foreach ($responseXml->xpath('/packet/domain/get/result') as $resultNode) {
      echo "Domain id: " . (string)$resultNode->id . " ";
      echo (string)$resultNode->data->gen_info->name . " (" . (string)$resultNode->data->gen_info->dns_ip_address . ")\n";
}

?>

Mysql AND(ve) ve OR(veya) Komutu

Veri tabanındaki verilere sorgular uygularken ve , veya gibi komutları kullanmamız gerekebilir. AND komutu “ve” anlamına gelmektedir, OR komutu “veya” anlamına gelmektedir.
Aynı anda iki olayın da gerçekleşmesini istiyorsak veya olayların aynı anda gerçekleşmesini istiyorsak; AND komutunu kullanmalıyız. Örneğin kitap tablosunda satışta olan ve onaylı olan kitapları göstermek isteyelim;
SELECT * FROM kitap WHERE onay=’1′ AND satis_durumu=’1′;

Onay 1 olan ve satis_durumu 1 olan verileri getir demiş olduk.

Or komutu ise veya manasına gelmektedir. satışta olan veya fiyatı 15 TL olan kitapları getirmek isteyelim.


SELECT * FROM kitap WHERE fiyat=’15’ OR satis_durumu=’1′;

fiyat 15 olan veya satis_durumu 1 olan verileri getir dedik. Tablomuzda kayıtlı olan kitabın fiyatı 15 Tl olsun ve satis_durumu 0 olsun; yinede sorgumuz bu veri satırını bize getirir. Çünkü OR (veya) komutunu kullandık.

Mysql Join Uygulaması

Veri tabanı işlemlerinde bir tablodan çalışabileceğimiz gibi birden çok tablolardan veriler çekmemiz ve bu verilere belli kriterler uygulamamız gerekebilir. Uygulamalarımızda her defasında bir veriyi çekip kontorol etmek ve buna istenen kriterleri uygulamak büyük kapsamlı projelerde karmaşıklığa ve kodların yavaş çalışmasına neden olabilir.

Örnek olarak kitap tablomuz ve seçilen kitapların yer aldığı galeri tablomuz olsun. Galeri tablomuzda kitabın id si ne göre işlemler yapacağız.
Kitap tablomuzda: id, isim ve kapak sütunları yer alsın.
Galeri tablomuzda ise, id, kitap_id sutunları yer alsın.

Şimdi seçilen yani galeri tablosunda yer alan verilere göre kitapları vitrin bölümümüzde gösteren kodları yazalım.

SELECT kitap.id as  kid, kitap.isim, kitap.kapak, galeri.id as gid, galeri.kitap_id FROM kitap, galeri WHERE kitap.id=galeri.kitap_id

Yukarıdaki kod satır ; “kitap.id as kid” ile kitap tablosundaki id  sutununu kid olarak aldık,”kitap.isim” ile kitap tablosundaki isim sutununu almış olduk,”kitap.kapak” ile kitap tablosundaki kapak sutunundaki veriyi almış olduk(Kitap kapağının adının tutulmuş olduğu alan). Sıra galeri tablosundaki verileri almaya geldi. “galeri.id as gid” ile galeri tablosundaki id yi gid olarak almış olduk, “galeri.kitap_id” ile galeri tablosundaki kitap idlerinin tutulduğu bölümü çekmiş olduk. Daha sonra “WHERE kitap.id=galeri.kitap_id” ile kitap id si galeri tablosunda kitap_id sutununda yer alan yani galerimize eklenmiş olan verileri(kitapları) getir demiş olduk.
“as” kodu ile değişken tanımlamış oluyoruz.

Bu örnegimizi biraz daha geliştirerek satış içi olan ve galeride yer alan kitapları getirmek isteseydik.Satış içi olarak kitap tablomuzda durum sutununun yer aldığını farz edelim; ve durum=1 ise satış içi durum=0 ise satış dışı olsun kitabımız.
SELECT kitap.id as  kid, kitap.isim, kitap.kapak, galeri.id as gid, galeri.kitap_id FROM kitap, galeri WHERE kitap.id=galeri.kitap_id and kitap.durum=1

Yukarıdaki kod satırının en sonunda yer alan “and kitap.durum=1″ kodu ile ve kitap tablosunda durum ‘u 1 olan yani satış içi olan demiş olduk.

Mysql DATEDIFF Tarih Arası Hesaplama

Veri tabanımızda yer alan verilerin; kullanıcıların, kayıtlı olan stokların vb verilerin kaç gün önce eklendiğini veri tabanına hesaplıya biliriz. Veya üyenin kaç gün önce kayıt olduğu, en son kaç gün önce login olduğu vb işlemleride DATEDIFF(iki tarih arasını hesaplama) komutu aracılığı ile hesaplıya biliriz.

Örnek olarak kitap veri tabanımızda yer alan kitapların kaç gün önce veri tabanımıza kaydedildiğini hesaplıyalım.

SELECT DATEDIFF(NOW(),tarih) as gecen_gun FROM kitap;

[ad#satir]

Yukarıdaki kodlarda; NOW() şimdiki zamanı belirtiyor, tarih ise veri tabanımızdaki tarih sütunundan gelen tarih bilgisini belirtmektedir. Gelen sonuçları gecen_gun adıyla oluşturmuş olduğumuz sana bir sütunda göstermiş olduk.

Mysql İç İçe Select

Bazen bir sorgunun içinde başka bir sorgu yer alabilir, bu gibi durumlarda iç içe select yapısını kullanabiliriz.
Örnek olarak;

Kitap durum tablomuz olsun ve dışarıdaki kitaplarımız bulmak isteyelim. Dışarıdaki kitapların numaralarını ödünç tablosundan çekecek bir sorgu yazalım.

SELECT kitapno From odunc WHERE geldimi=0;

Bunu , kitaplar tablosundan karşılık gelen kitap numaralarını çekecek şekilde IN() komutu ile kullanalım.

SELECT * FROM kitap WHERE kitapno IN(SELECT kitapno FROM odunc WHERE geldimi='0');