<?php

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

/**
 * @file
 * Dynamically generated connection details for a Service Provider.
 * This file is used for cron based API 'Actions'
 * This is from UnlockBase, the API remote client enabled connection.
 * @link http://www.UnlockBase.com UnlockBase Client Remote API. @endlink
 */

/* Set this value to true if something goes wrong and you want to display error messages */
	
define('UNLOCKBASE_API_DEBUG_PROVIDERLIST_SUAPIPROVIDERNUM', false);
	
define('UNLOCKBASE_VARIABLE_ERROR_PROVIDERLIST_SUAPIPROVIDERNUM',    '_UnlockBaseError'    );
define('UNLOCKBASE_VARIABLE_ARRAY_PROVIDERLIST_SUAPIPROVIDERNUM',    '_UnlockBaseArray'    );
define('UNLOCKBASE_VARIABLE_POINTERS_PROVIDERLIST_SUAPIPROVIDERNUM', '_UnlockBasePointers' );

define("SUWP_UNLOCKBASE_URL_PROVIDERLIST_SUAPIPROVIDERNUM", $suwp_dhru_url);
define("SUWP_UNLOCKBASE_USERNAME_PROVIDERLIST_SUAPIPROVIDERNUM", $suwp_dhru_username);
define("SUWP_UNLOCKBASE_API_ACCESS_KEY_PROVIDERLIST_SUAPIPROVIDERNUM", $suwp_dhru_api_key);


if (!extension_loaded('curl')) {
  trigger_error('cURL extension not installed', E_USER_ERROR);
}

class StockunlocksUnlockBase_PROVIDERLIST_SUAPIPROVIDERNUM {
  /*
    mixed $this->CallAPI (string $Action, array $Parameters)
    Call the UnlockBase API.
    Returns the xml stream sent by the UnlockBase server
    Or false if an error occurs
  */

  function CallAPI ( $Action, $Parameters = array() )
  {
    if (is_string($Action))
    {
      if (is_array($Parameters))
      {
        /* Add the API Key and the Action to the parameters */
        $Parameters['Key'] = SUWP_UNLOCKBASE_API_ACCESS_KEY_PROVIDERLIST_SUAPIPROVIDERNUM;
        $Parameters['Action'] = $Action;

        /* Prepare the cURL session */
        $Ch = curl_init(SUWP_UNLOCKBASE_URL_PROVIDERLIST_SUAPIPROVIDERNUM);		
        curl_setopt($Ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($Ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($Ch, CURLOPT_HEADER, false);
        curl_setopt($Ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($Ch, CURLOPT_ENCODING, '');
        curl_setopt($Ch, CURLOPT_POST, true);
        curl_setopt($Ch, CURLOPT_POSTFIELDS, $this->BuildQuery($Parameters));
        
        /* Perform the session */
        $Data = curl_exec($Ch);
        
        if (UNLOCKBASE_API_DEBUG_PROVIDERLIST_SUAPIPROVIDERNUM && curl_errno($Ch) != CURLE_OK)
        {
          /* If an error occurred, report it in debug mode */
          trigger_error(curl_error($Ch), E_USER_WARNING);
        }
        
        /* Close the session */
        curl_close($Ch);
        
        /* Return the data, or false if an error occurred */
        return $Data;
      }
      else trigger_error('Parameters must be an array', E_USER_WARNING);
    }
    else trigger_error('Action must be a string', E_USER_WARNING);
    
    return false;
  }

  /*
    mixed $this->ParseXML (string $XML)
    Parse an XML stream from the UnlockBase API.
    Returns an associative array of the parsed XML string
    Or false if an error occurs
  */
  
  function ParseXML ( $XML )
  {
    if (! is_string($XML))
    {
      /* If the argument is not a string, report the error in debug mode & stop here */
      if (UNLOCKBASE_API_DEBUG_PROVIDERLIST_SUAPIPROVIDERNUM) trigger_error('Invalid argument supplied for $this->ParseXML()', E_USER_WARNING);
      return false;
    }

    /* Globalize variables */
    global ${UNLOCKBASE_VARIABLE_ERROR_PROVIDERLIST_SUAPIPROVIDERNUM}    ;
    global ${UNLOCKBASE_VARIABLE_ARRAY_PROVIDERLIST_SUAPIPROVIDERNUM}    ;
    global ${UNLOCKBASE_VARIABLE_POINTERS_PROVIDERLIST_SUAPIPROVIDERNUM} ;

    /* Initialize variables */
    ${UNLOCKBASE_VARIABLE_ERROR_PROVIDERLIST_SUAPIPROVIDERNUM}    = false   ;
    ${UNLOCKBASE_VARIABLE_ARRAY_PROVIDERLIST_SUAPIPROVIDERNUM}    = array() ;
    ${UNLOCKBASE_VARIABLE_POINTERS_PROVIDERLIST_SUAPIPROVIDERNUM} = array() ;

    /* Configure the parser */
    $Parser = xml_parser_create('UTF-8');
    xml_set_element_handler($Parser, array('StockunlocksUnlockBase_PROVIDERLIST_SUAPIPROVIDERNUM', 'XML_Start'), array('StockunlocksUnlockBase_PROVIDERLIST_SUAPIPROVIDERNUM', 'XML_End'));
    xml_set_character_data_handler($Parser, array('StockunlocksUnlockBase_PROVIDERLIST_SUAPIPROVIDERNUM', 'XML_CData'));
    xml_parser_set_option($Parser, XML_OPTION_CASE_FOLDING, 0);
    
    /* Start parsing, check the success of both parsing and analyzing */
    $Success = xml_parse($Parser, $XML, true) && ! ${UNLOCKBASE_VARIABLE_ERROR_PROVIDERLIST_SUAPIPROVIDERNUM};
    
    /* Report errors in debug mode */
    if (UNLOCKBASE_API_DEBUG_PROVIDERLIST_SUAPIPROVIDERNUM)
    {
      if (${UNLOCKBASE_VARIABLE_ERROR_PROVIDERLIST_SUAPIPROVIDERNUM})
      {
        /* The XML stream has not been recognized */
        trigger_error('Unrecognized XML format', E_USER_WARNING);
      }
      elseif (xml_get_error_code($Parser) != XML_ERROR_NONE)
      {
        /* A parser error occurred */
        trigger_error(xml_error_string(xml_get_error_code($Parser)), E_USER_WARNING);
      }
    }

    /* Free the parser */
    xml_parser_free($Parser);
    
    /* Get a reference to the result */
    $Array =& ${UNLOCKBASE_VARIABLE_ARRAY_PROVIDERLIST_SUAPIPROVIDERNUM};
    
    /* Unset global variables */
    unset ( $GLOBALS[UNLOCKBASE_VARIABLE_ERROR_PROVIDERLIST_SUAPIPROVIDERNUM] );
    unset ( $GLOBALS[UNLOCKBASE_VARIABLE_ARRAY_PROVIDERLIST_SUAPIPROVIDERNUM] );
    unset ( $GLOBALS[UNLOCKBASE_VARIABLE_POINTERS_PROVIDERLIST_SUAPIPROVIDERNUM] );

    /* Return the result */
    return ($Success ? $Array : false);
  }

  /*
    bool $this->CheckEmail (string $Email)
    Check the validity of an email address
    This function is *not* RFC 2822 compliant, but instead reflects today's email reality
    Returns true if the email address seems correct, false otherwise
  */
  
  function CheckEmail ( $Email )
  {
    return (bool) preg_match('/^[0-9a-z_\\-\\.]+@([0-9a-z][0-9a-z\\-]*[0-9a-z]\\.)+[a-z]{2,}$/i', $Email);
  }

  /*
    bool $this->CheckIMEI (string $IMEI, bool $Checksum)
    Check a 15-digit IMEI serial number.
    You are free to verify the checksum, or not;
    Bad checksums are 99% likely to provide unavailable unlock codes (exceptions exist, however)
    Returns true if the IMEI seems correct, false otherwise
  */
  
  function CheckIMEI ( $IMEI, $Checksum = true )
  {
    if (is_string($IMEI))
    {
      if (ereg('^[0-9]{15}$', $IMEI))
      {
        if (! $Checksum) return true;

        for ($i = 0, $Sum = 0; $i < 14; $i++)
        {
          $Tmp = $IMEI[$i] * ( ($i % 2) + 1 );
          $Sum += ($Tmp % 10) + intval($Tmp / 10);
        }
        
        return ( ( ( 10 - ( $Sum % 10 ) ) % 10 ) == $IMEI[14] );
      }
    }
    
    return false;
  }
  
  /*
    bool $this->CheckProviderID (string $ProviderID)
    Verify an Alcatel Provider ID
    Returns true if the Provider ID seems correct, false otherwise
  */
  
  function CheckProviderID ( $ProviderID )
  {
    return (is_string($ProviderID) && eregi('^[0-9a-z]{4,5}\\-[0-9a-z]{7}$', $ProviderID));
  }
  
  /*
    bool $this->CheckMEP_PRD (string $Type, string $String)
    Check a MEP/PRD number before submitting it to the API
    $Type is either 'MEP' or 'PRD'
    Returns true if the MEP/PRD seems correct, false otherwise
  */
  
  function CheckMEP_PRD( $Type, $String )
  {
    return ereg('^' . $Type . '\\-[0-9]{5}\\-[0-9]{3}$', $String);
  }

  /* Internal functions - do not care */
  
  function BuildQuery ( $Parameters )
  {
    if (function_exists('http_build_query'))
    { 
      /* PHP 5 */
      return http_build_query($Parameters);
    }
    else
    {
      /* PHP 4 */
      $Data = array();
      foreach ($Parameters as $Name => $Value) array_push($Data, urlencode($Name) . '=' . urlencode($Value));
      return implode('&', $Data);
    }
  }

  function XML_Start ( $Parser, $Name, $Attributes )
  {
    /* Globalize variables */
    global ${UNLOCKBASE_VARIABLE_ERROR_PROVIDERLIST_SUAPIPROVIDERNUM};
    global ${UNLOCKBASE_VARIABLE_ARRAY_PROVIDERLIST_SUAPIPROVIDERNUM};
    global ${UNLOCKBASE_VARIABLE_POINTERS_PROVIDERLIST_SUAPIPROVIDERNUM};
    
    /* Do nothing if an error occurred previously */
    if (${UNLOCKBASE_VARIABLE_ERROR_PROVIDERLIST_SUAPIPROVIDERNUM}) return;

    if (count( ${UNLOCKBASE_VARIABLE_POINTERS_PROVIDERLIST_SUAPIPROVIDERNUM} ) == 0)
    {
      /* Root Element : create the first pointer to the array */
      ${UNLOCKBASE_VARIABLE_POINTERS_PROVIDERLIST_SUAPIPROVIDERNUM}[] =& ${UNLOCKBASE_VARIABLE_ARRAY_PROVIDERLIST_SUAPIPROVIDERNUM};
    }
    else
    {
      /* Get the latest pointer */
      $Pointer =& ${UNLOCKBASE_VARIABLE_POINTERS_PROVIDERLIST_SUAPIPROVIDERNUM} [ count( ${UNLOCKBASE_VARIABLE_POINTERS_PROVIDERLIST_SUAPIPROVIDERNUM} ) -1 ];
      
      if (is_null($Pointer))
      {
        /* This is the first sub-tag with that name, create the new container array for it */
        $Pointer[] = array();
        
        /* Replace the latest pointer, point to the first item of the new container */
        ${UNLOCKBASE_VARIABLE_POINTERS_PROVIDERLIST_SUAPIPROVIDERNUM}[ count(${UNLOCKBASE_VARIABLE_POINTERS_PROVIDERLIST_SUAPIPROVIDERNUM}) -1 ] =& $Pointer[0];
        $Pointer =& $Pointer[0];
      }
      elseif (is_array($Pointer))
      {
        if (isset($Pointer[$Name]))
        {
          if (! is_array($Pointer[$Name]))
          {
            /* Unrecognized XML stream */
            ${UNLOCKBASE_VARIABLE_ERROR_PROVIDERLIST_SUAPIPROVIDERNUM} = true;
            return;
          }
          
          /* The tag is already known, add an item to the array and create a pointer to it */
          $Pointer[$Name][] = array();
          ${UNLOCKBASE_VARIABLE_POINTERS_PROVIDERLIST_SUAPIPROVIDERNUM}[] =& $Pointer[$Name][ count($Pointer[$Name]) -1 ];
          return;
        }
      }
      else
      {
        /* Unrecognized XML stream */
        ${UNLOCKBASE_VARIABLE_ERROR_PROVIDERLIST_SUAPIPROVIDERNUM} = true;
        return;
      }
      
      /* Set the default value and create a pointer to it */
      $Pointer[$Name] = NULL;
      ${UNLOCKBASE_VARIABLE_POINTERS_PROVIDERLIST_SUAPIPROVIDERNUM}[] =& $Pointer[$Name];
    }
  }
  
  function XML_End ( $Parser, $Name )
  {
    /* Globalize variables */
    global ${UNLOCKBASE_VARIABLE_ERROR_PROVIDERLIST_SUAPIPROVIDERNUM};
    global ${UNLOCKBASE_VARIABLE_POINTERS_PROVIDERLIST_SUAPIPROVIDERNUM};

    /* Do nothing if an error occurred previously */
    if (${UNLOCKBASE_VARIABLE_ERROR_PROVIDERLIST_SUAPIPROVIDERNUM}) return;

    /* Remove the latest pointer */
    array_pop( ${UNLOCKBASE_VARIABLE_POINTERS_PROVIDERLIST_SUAPIPROVIDERNUM} );
  }
  
  function XML_CData ( $Parser, $Data )
  {
    /* Ignore whitespaces */
    if (rtrim($Data) == '') return;

    /* Globalize variables */
    global ${UNLOCKBASE_VARIABLE_ERROR_PROVIDERLIST_SUAPIPROVIDERNUM};
    global ${UNLOCKBASE_VARIABLE_POINTERS_PROVIDERLIST_SUAPIPROVIDERNUM};

    /* Do nothing if an error occurred previously */
    if (${UNLOCKBASE_VARIABLE_ERROR_PROVIDERLIST_SUAPIPROVIDERNUM}) return;
    
    /* Get the latest pointer */
    $Pointer =& ${UNLOCKBASE_VARIABLE_POINTERS_PROVIDERLIST_SUAPIPROVIDERNUM} [ count( ${UNLOCKBASE_VARIABLE_POINTERS_PROVIDERLIST_SUAPIPROVIDERNUM} ) -1 ];
    
    if (is_array($Pointer))
    {
      /* Unrecognized XML stream, should be null or string here */
      ${UNLOCKBASE_VARIABLE_ERROR_PROVIDERLIST_SUAPIPROVIDERNUM} = true;
      return;
    }
    
    /* Append the character data */
    $Pointer .= $Data;
  }
}
