Source for file httpclient.php

Documentation is available at httpclient.php

  1. <?php
  2. /**
  3.  * smsAPI_HTTPClient
  4.  *
  5.  * Copyright (c) 2010, ComVision
  6.  * All rights reserved.
  7.  *
  8.  * Redistribution and use in source and binary forms, with or without modification,
  9.  * are permitted provided that the following conditions are met:
  10.  *
  11.  *  - Redistributions of source code must retain the above copyright notice,
  12.  *    this list of conditions and the following disclaimer.
  13.  *  - Redistributions in binary form must reproduce the above copyright notice,
  14.  *    this list of conditions and the following disclaimer in the documentation and/or
  15.  *    other materials provided with the distribution.
  16.  *  - Neither the name of the smsAPI.pl nor the names of its contributors may be used to
  17.  *    endorse or promote products derived from this software without specific prior written permission.
  18.  *
  19.  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  20.  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  21.  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  22.  * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
  23.  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  24.  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
  25.  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  26.  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  27.  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28.  *
  29.  * @author ComVision <info@smsapi.pl>
  30.  * @copyright 2010 ComVision
  31.  * @license BSD-3
  32.  * @package smsapi
  33.  * @subpackage client\html
  34.  * @version 1.0 14.10.2010
  35.  */
  36.  
  37. /**
  38.  * Client smsAPI przez HTTP/HTTPS
  39.  *
  40.  * Przyklad:
  41.  * <code>
  42.  * require_once 'smsapi.php';
  43.  * //Instrukcja odpowiedziala za automatyczne wczytywanie class
  44.  * spl_autoload_register(array('smsAPI','__autoload'));
  45.  *
  46.  * try {
  47.  *
  48.  *    $smsapi = new smsAPI_HTTPClient('login', md5('password'));
  49.  *
  50.  *    $msg = $smsapi->new_sms();
  51.  *    $msg->add_to( 'xxxxxxxxx' );
  52.  *    $msg->message    = 'test';
  53.  *    $msg->eco        = TRUE;
  54.  *    $msg->flash        = FALSE;
  55.  *    $msg->test        = TRUE;
  56.  *
  57.  *     $result = $msg->send();
  58.  *     var_dump($result);
  59.  *
  60.  *     $smsapi->delete_sms( $result[0]->id );
  61.  * }
  62.  * catch ( smsAPI_Exception $e )
  63.  * {
  64.  *     echo $e->getMessage();
  65.  * }
  66.  * </code>
  67.  *
  68.  * @see http://www.smsapi.pl/spec/smsAPI.pdf
  69.  */
  70. {
  71.     /**
  72.      * Url do smsAPI
  73.      *
  74.      * @var string 
  75.      */
  76.     protected $url = null;
  77.     /**
  78.      * Sposob przesylania danych
  79.      *
  80.      * @see smsAPI_HTTPClient::METHOD_GET
  81.      * @see smsAPI_HTTPClient::METHOD_POST
  82.      * @var int 
  83.      */
  84.     protected $method = null;
  85.  
  86.     /**
  87.      * Dane klienta
  88.      *
  89.      * @var array 
  90.      */
  91.     protected $client;
  92.  
  93.     /**
  94.      * Przesylania danych metodą GET do smsAPI
  95.      */
  96.     const METHOD_GET    0;
  97.     /**
  98.      * Przesylania danych metodą POST do smsAPI
  99.      */
  100.     const METHOD_POST    1;
  101.  
  102.     /**
  103.      * Timeout
  104.      *
  105.      * @ignore
  106.      * @var float 
  107.      */
  108.     protected $timeout        1;
  109.  
  110.     /**
  111.      * Tablica opisu błędów
  112.      *
  113.      * @var array 
  114.      */
  115.     public static $errors array(
  116.         0    => 'Nieznany błąd',
  117.         11    => 'Zbyt długa lub brak wiadomości',
  118.         12    => 'Wiadomość zawiera ponad 160 znaków (gdy użyty parametr &single=1)',
  119.         13    => 'Nieprawidłowy numer odbiorcy',
  120.         14    => 'Nieprawidłowe pole nadawcy',
  121.         17    => 'Nie można wysłać FLASH ze znakami specjalnymi',
  122.         18    => 'Nieprawidłowa liczba parametrów',
  123.         19    => 'Za dużo wiadomości w jednym odwołaniu (maksymalnie 100)',
  124.         20    => 'Nieprawidłowa liczba parametrów IDX',
  125.         21    => 'Wiadomość MMS ma za duży rozmiar (maksymalnie 100kB)',
  126.         22    => 'Błędny format SMIL',
  127.         101    => 'Niepoprawne lub brak danych autoryzacji',
  128.         102    => 'Nieprawidłowy login lub hasło',
  129.         103    => 'Brak punków dla tego użytkownika',
  130.         104    => 'Brak szablonu',
  131.         105    => 'Błędny adres IP (włączony filtr IP dla interfejsu API)',
  132.         200    => 'Nieudana próba wysłania wiadomości',
  133.         300    => 'Nieprawidłowa wartość pola points (przy użyciu pola points jest wymagana wartość 1)',
  134.         301    => 'ID wiadomości nie istnieje',
  135.         400    => 'Nieprawidłowy ID statusu wiadomości',
  136.         999    => 'Wewnętrzny błąd systemu (prosimy zgłosić)'
  137.     );
  138.  
  139.     /**
  140.      * Inicializacjia
  141.      *
  142.      * Przyklad:
  143.      * <code>
  144.      * try {
  145.      *
  146.      *    $smsapi = new smsAPI_HTTPClient('login', md5('password'));
  147.      *
  148.      * }
  149.      * catch ( smsAPI_Exception $e )
  150.      * {
  151.      *     echo $e->getMessage();
  152.      * }
  153.      * </code>
  154.      *
  155.      * @uses smsAPI_HTTPClient::METHOD_GET
  156.      * @uses smsAPI_HTTPClient::METHOD_POST
  157.      * @param string    $username    Nazwa użytkownika w serwisie smsAPI
  158.      * @param string    $password    Hasło do Twojego konta w serwisie smsAPI zaszyfrowane w MD5
  159.      * @param int        $timeout    Timeout polączenia
  160.      * @param bool        $ssl        http lub https
  161.      * @param int        $method        Sposób przesyania danych do smsAPI
  162.      */
  163.     public function  __construct($username$password$timeout 0,$ssl true$method self::METHOD_POST)
  164.     {
  165.         $this->url = $ssl == TRUE 'https://ssl.smsapi.pl/send.do' 'http://api.smsapi.pl/send.do';
  166.         $this->method = $method;
  167.  
  168.         if!isset$username OR empty $username ) )
  169.             throw new smsAPI_Exception('Argument "username" is invalid');
  170.  
  171.         if!isset$password OR strlen$password != 32 )
  172.             throw new smsAPI_Exception('Argument "password" is invalid');
  173.  
  174.         $this->timeout    = (int)$timeout;
  175.  
  176.         $this->client = array(
  177.             
  178.             'username'    => $username,
  179.             'password'    => $password
  180.         );
  181.     }
  182.  
  183.     /**
  184.      * Utwórz nowa wiadomość
  185.      *
  186.      * Przyklad:
  187.      * <code>
  188.      * try {
  189.      *
  190.      *    $smsapi = new smsAPI_HTTPClient('login', md5('password'));
  191.      *
  192.      *    //Tworzenie wiadomości
  193.      *    $msg = $smsapi->new_sms();
  194.      *    $msg->add_to( 'xxxxxxxxx', 'xxxxxxxxx' );
  195.      *    $msg->message    = 'test message';
  196.      *    $msg->eco        = TRUE;
  197.      *    $msg->flash        = FALSE;
  198.      *
  199.      *    //Wysłanie wiadomości
  200.      *    $result = $msg->send();
  201.      *
  202.      *     var_dump($result);
  203.      *    //array
  204.      *    //  0 =>
  205.      *    //    object(stdClass)[3]
  206.      *    //      public 'id' => string '1010131304559538088' (length=19)
  207.      *    //      public 'points' => string '0.07' (length=1)
  208.      * }
  209.      * catch ( smsAPI_Exception $e )
  210.      * {
  211.      *     echo $e->getMessage();
  212.      * }
  213.      * </code>
  214.      *
  215.      * @param array $params 
  216.      * @return smsAPI_HTTP_SMS 
  217.      */
  218.     public function new_sms($params null)
  219.     {
  220.         return new smsAPI_HTTP_SMS($params$this);
  221.     }
  222.  
  223.     /**
  224.      * Wysyłanie pojedynczego SMS'a
  225.      *
  226.      * Przyklad:
  227.      * <code>
  228.      * //Tworzenie wiadomości
  229.      * $msg = new smsAPI_HTTP_SMS();
  230.      * $msg->add_to( 'xxxxxxxxx', 'xxxxxxxxx' );
  231.      * $msg->message    = 'test message';
  232.      * $msg->eco        = TRUE;
  233.      * $msg->flash        = FALSE;
  234.      *
  235.      * try {
  236.      *
  237.      *    $smsapi = new smsAPI_HTTPClient('login', md5('password'));
  238.      *
  239.      *    //Wysłanie wiadomości
  240.      *    $result = $smsapi->send_sms($msg);
  241.      * 
  242.      *     var_dump($result);
  243.      *    //array
  244.      *    //  0 =>
  245.      *    //    object(stdClass)[3]
  246.      *    //      public 'id' => string '1010131304559538088' (length=19)
  247.      *    //      public 'points' => string '0.07' (length=1)
  248.      * }
  249.      * catch ( smsAPI_Exception $e )
  250.      * {
  251.      *     echo $e->getMessage();
  252.      * }
  253.      * </code>
  254.      *
  255.      * @throws smsAPI_Exception
  256.      * @param smsAPI_HTTP_SMS $sms 
  257.      * @return stdClass(id,points) 
  258.      */
  259.     public function send_sms($sms)
  260.     {
  261.         if!($sms instanceof smsAPI_HTTP_SMS) )
  262.             throw new smsAPI_Exception('Invalid function argument'-18);
  263.  
  264.         $response $this->server_call$sms->_get_params() );
  265.  
  266.         $result array();
  267.  
  268.         foreach $response as $r )
  269.         {
  270.             $r trim($r);
  271.             ifempty ($r) )             continue;
  272.  
  273.             $r explode(':'$r);
  274.  
  275.             if!strcasecmp($r[0]'OK') )
  276.                 $tmp = (object)array'id' => $r[1]'points'    => $r[2);
  277.             else
  278.                 $tmp = (object)array'error' => (int)@$r[1);
  279.  
  280.             ifisset$r[3) ) $tmp->phone $r[3];
  281.  
  282.             $result[$tmp;
  283.         }
  284.  
  285.         return $result;
  286.     }
  287.  
  288.     /**
  289.      * Usuwanie zaplanowanej wiadomości
  290.      *
  291.      * Przyklad:
  292.      * <code>
  293.      * try {
  294.      *
  295.      *    $smsapi = new smsAPI_HTTPClient('login', md5('password'), true);
  296.      *
  297.      *    $smsapi->delete_sms('1010131304559538088');
  298.      * }
  299.      * catch ( smsAPI_Exception $e )
  300.      * {
  301.      *     echo $e->getMessage();
  302.      * }
  303.      * </code>
  304.      *
  305.      * @throws smsAPI_Exception
  306.      * @param string $id ID wiadomości w systemie smsAPI
  307.      * @return null 
  308.      */
  309.     public function delete_sms($id)
  310.     {
  311.         $result $this->server_callarray'sch_del'    => (string)$id ) );
  312.  
  313.         $result explode(':'$result[0]);
  314.  
  315.         if!strcasecmp($result[0]'ERROR') )
  316.         {
  317.             $code = (int)$result[1];
  318.             $msg = isset$code self::$errors[$codeself::$errors[0];
  319.             throw new smsAPI_Exception($msg$code );
  320.         }
  321.  
  322.         ifstrcasecmp($result[0]'OK') )
  323.             throw new smsAPI_Exception ('Unknown error'0);
  324.     }
  325.  
  326.     /**
  327.      * Sprawdzenie ilości punktów na koncie
  328.      *
  329.      * Przyklad
  330.      * <code>
  331.      * try {
  332.      *
  333.      *    $smsapi = new smsAPI_HTTPClient('login', md5('password'), true);
  334.      *
  335.      *    $result = $smsapi->get_points(true);
  336.      * }
  337.      * catch ( smsAPI_Exception $e )
  338.      * {
  339.      *     echo $e->getMessage();
  340.      * }
  341.      * </code>
  342.      *
  343.      * @param bool $details 
  344.      * @return stdClass(points,pro,eco) 
  345.      */
  346.     public function get_points($details false)
  347.     {
  348.         $response $this->server_call(array(
  349.             'points'    => 1,
  350.             'details'    => (bool)$details
  351.         ));
  352.  
  353.         $result new stdClass;
  354.         $result->points 0;
  355.  
  356.         $response[0explode(':'$response[0]);
  357.         
  358.         if!strcasecmp($response[0][0]'ERROR') )
  359.         {
  360.             $result->error trim(@$response[0][1]);
  361.         }
  362.         else
  363.         {
  364.             $result->points trim(@$response[0][1]);
  365.         
  366.             $count count($response);
  367.             if$count >= $result->pro trim(@$response[1]);
  368.             if$count >= $result->eco trim(@$response[2]);
  369.         }
  370.         
  371.         return $result;
  372.     }
  373.  
  374.     const CALL_AUTO        0;
  375.     const CALL_FOPEN    1;
  376.     const CALL_CURL        2;
  377.     
  378.     public static $call self::CALL_AUTO;
  379.  
  380.     protected function get_call()
  381.     {
  382.         ifin_array(self::$callarrayself::CALL_CURLself::CALL_FOPEN )) ) return self::$call;
  383.  
  384.         ifini_get('allow_url_fopen'== return self::CALL_FOPEN;
  385.         iffunction_exists('curl_init') ) return self::CALL_CURL;
  386.  
  387.         throw new smsAPI_Exception('allow_url_fopen is disabled and curl_init doesn\'t exists');
  388.     }
  389.  
  390.     /**
  391.      * Wywolanie zapytania do strony smsAPI.pl
  392.      *
  393.      * @uses smsAPI_HTTPClient::METHOD_GET
  394.      * @uses smsAPI_HTTPClient::METHOD_POST
  395.      * @throws smsAPI_Exception
  396.      * @param string $params 
  397.      * @return string 
  398.      */
  399.     protected function server_call($params)
  400.     {
  401.         $opts array(
  402.             'http'        => array(
  403.                 'method'    => ($this->method == self::METHOD_POST 'POST' 'GET'),
  404.                 'header'    => array(
  405.                     'user_agent'    =>    'SMSApi_HTTP_Client'
  406.                 )
  407.             )
  408.         );
  409.  
  410.         $url $this->url;
  411.         $data http_build_queryarray_merge(array)$params$this->client ) );
  412.  
  413.         switch$this->method )
  414.         {
  415.             case self::METHOD_GET:
  416.  
  417.                 $opts['http']['method']    'GET';
  418.                 $url .= '?' $data;
  419.                 break;
  420.  
  421.             case self::METHOD_POST:
  422.             default:
  423.  
  424.                 $opts['http']['method']        'POST';
  425.                 $opts['http']['header']        'Content-type: application/x-www-form-urlencoded';
  426.                 $opts['http']['content']    $data;
  427.                 break;
  428.         }
  429.  
  430.         if$this->timeout )
  431.         {
  432.             $opts['http']['timeout'$this->timeout;
  433.         }
  434.  
  435.         smsAPI::call_listners('server_call args'array'opts' => $opts'url' => $url ));
  436.  
  437.         switch$this->get_call() )
  438.         {
  439.             case self::CALL_FOPEN:
  440.                 $context stream_context_create($opts);
  441.                 $result file_get_contents($urlfalse$context);
  442.                 break;
  443.  
  444.             case self::CALL_CURL:
  445.                 $ch curl_init();
  446.                 @curl_setopt($chCURLOPT_URL$url);
  447.                 @curl_setopt($chCURLOPT_FOLLOWLOCATIONtrue);
  448.                 @curl_setopt($chCURLOPT_CRLFfalse);
  449.                 @curl_setopt($chCURLOPT_FRESH_CONNECTfalse);
  450.                 @curl_setopt($chCURLOPT_HEADERfalse);
  451.                 @curl_setopt($chCURLOPT_HEADERfalse);
  452.  
  453.                 if$this->method == self::METHOD_GET )
  454.                 {
  455.                     @curl_setopt($chCURLOPT_POSTfalse);
  456.                     @curl_setopt($chCURLOPT_HTTPGETtrue);
  457.                 }
  458.                 else
  459.                 {
  460.                     @curl_setopt($chCURLOPT_HTTPGETfalse);
  461.                     @curl_setopt($chCURLOPT_POSTtrue);
  462.                     @curl_setopt($chCURLOPT_POSTFIELDS$opts['http']['content']);
  463.                 }
  464.  
  465.                 @curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  466.                 ifisset$opts['http']['timeout') )
  467.                 {
  468.                     @curl_setopt($chCURLOPT_TIMEOUT$opts['http']['timeout']);
  469.                 }
  470.  
  471.                 $result @curl_exec($ch);
  472.  
  473.                 curl_close($ch);
  474.                 break;
  475.             default:
  476.                 throw new smsAPI_Exception('allow_url_fopen is disabled and curl_init doesn\'t exists');
  477.         }
  478.  
  479.         smsAPI::call_listners('server_call result'array'result' => $result ));
  480.  
  481.         if$result === false OR empty($result) )
  482.             throw new smsAPI_Exception('HTTP request failed'-200);
  483.  
  484.         $result trim($result" ;\n\t\r");
  485.         
  486.         $result explode(';'$result);
  487.  
  488.         ifempty($result) )
  489.             throw new smsAPI_Exception ('Empty result'0);
  490.  
  491.         return $result;
  492.     }
  493. }

Documentation generated on Thu, 27 Jan 2011 16:17:32 +0100 by phpDocumentor 1.4.3