protected function decodeNewLineEncodedResponse($responseString, $requestQuery, array $forceArray = array())
    {
        // Splitting response body
        $parts = explode(chr(10), $responseString);

        // Getting the status
        $status = trim($parts[0]);

        $responseArray = [];

        // Valid answer?
        if (is_numeric($status)) {
            // Successful?
            if ($status != '0') {
                $responseArray['errorCode']    = $status;
                $responseArray['errorMessage'] = trim($parts[1]);
            } else {
                $responseArray['errorCode']    = $status;

                $partCount = count($parts);
                for ($i = 1; $i < $partCount; $i++) {
                    $tmp = preg_split('/[\s\t]+/', $parts[$i], 2);

                    $key   = trim($tmp[0]);
                    $value = trim($tmp[1]);

                    // if key already exists, open new array dimension
                    if (isset($responseArray[$key])) {
                        if (!is_array($responseArray[$key])) {
                            $tmpValue              = $responseArray[$key];
                            $responseArray[$key]   = array();
                            $responseArray[$key][] = $tmpValue;
                            $responseArray[$key][] = $value;
                        } else {
                            $responseArray[$key][] = $value;
                        }
                    } else {
                        // Just save
                        $responseArray[$key] = $value;
                    }
                }
            }
        } else {
            $responseArray['errorCode']    = '';
            $responseArray['errorMessage'] = trim($responseString);
        }

        foreach ($forceArray as $value) {
            if (isset($responseArray[$value]) && !is_array($responseArray[$value])) {
                $responseArray[$value] = array($responseArray[$value]);
            }
        }

        $responseArray['responseString'] = $responseString;
        $responseArray['requestQuery']   = $requestQuery;

        return $responseArray;
    }

Decodes a responseString, separated by new lines and returns an response array

@param string $responseString
@param string $requestQuery
@param array  $forceArray

@return array

Decodes a responseString separated by new lines and returns an response array


protected function decodeUrlEncodedResponse(
        $responseString,
        $requestQuery,
        array $notDecode = null,
        $forceArray = array()
    )
    {
        if (empty($notDecode)) {
            $responseString = urldecode($responseString);
        }

        if (!empty($forceArray)) {
            foreach ($forceArray as $param) {
                $responseString = str_replace($param.'=', $param.'[]=', $responseString);
            }
        }

        // Splitting response body
        $responseArray = [];
        parse_str($responseString, $responseArray);

        if (!empty($notDecode) && is_array($responseArray)) {
            foreach ($responseArray as $index => $value) {
                if (!in_array($index, $notDecode)) {
                    $value = urldecode($value);
                }

                $responseArray[$index] = $value;
            }
        }

        $responseArray['responseString'] = $responseString;
        $responseArray['requestQuery']   = $requestQuery;

        if (!isset($responseArray['errorCode'])) {
            $responseArray['errorCode'] = 99;
            $responseArray['errorMessage'] = $responseString;
        }

        return $responseArray;
    }

protected
function
decodeUrlEncodedResponse
(
$
responseString
,
$
requestQuery
,
array
$
notDecode
=
,
$
forceArray
=
array
(
)
)
{
if
(
empty
(
$
notDecode
)
)
{
$
responseString
=
urldecode
(
$
responseString
)
;
}
if
(
!
empty
(
$
forceArray
)
)
{
foreach
(
$
forceArray
as
$
param
)
{
$
responseString
=
str_replace
(
$
param
.
'='
,
$
param
.
'[]='
,
$
responseString
)
;
}
}
// Splitting response body
$
responseArray
=
[
]
;
parse_str
(
$
responseString
,
$
responseArray
)
;
if
(
!
empty
(
$
notDecode
)
&&
is_array
(
$
responseArray
)
)
{
foreach
(
$
responseArray
as
$
index
=>
$
value
)
{
if
(
!
in_array
(
$
index
,
$
notDecode
)
)
{
$
value
=
urldecode
(
$
value
)
;
}
$
responseArray
[
$
index
]
=
$
value
;
}
}
$
responseArray
[
'responseString'
]
=
$
responseString
;
$
responseArray
[
'requestQuery'
]
=
$
requestQuery
;
if
(
!
isset
(
$
responseArray
[
'errorCode'
]
)
)
{
$
responseArray
[
'errorCode'
]
=
99
;
$
responseArray
[
'errorMessage'
]
=
$
responseString
;
}
return
$
responseArray
;
}

Decodes a responseString, encoded in query-string-format and returns an response array

@param string   $responseString
@param string   $requestQuery
@param array    $notDecode
@param string[] $forceArray

@return mixed

Decodes a responseString encoded in query - string - format and returns an response array


public function fetchMails(ImapAdapter $imap, $search, $markProcessed = true, $assume = false, \Closure $callbackFunction = null)
    {
        $folder = 'INBOX';

        $imap->selectFolder($folder);
        $result = $imap->search(array($search));

        $messages = [];

        foreach ($result as $id) {
            $message = null;

            try {
                $message = $imap->getMessage($id);

                $messages[$id]['id']     = $id;
                $messages[$id]['folder'] = $folder;

                // Zend-mail sometimes got problems, with incorrect e-mails
                try {
                    $messages[$id]['subject'] = utf8_decode($message->getHeader('subject', 'string'));
                } catch (\Exception $e) {
                    $messages[$id]['subject'] = '-No subject-';
                }

                try {
                    $messages[$id]['received'] = strtotime($message->getHeader('date', 'string'));
                } catch (\Exception $e) {
                    $messages[$id]['received'] = '-No date-';
                }

                $messages[$id]['plainText']   = $this->getPlainText($message);
                $messages[$id]['attachments'] = $this->getAttachments($message);
                $messages[$id]['type']        = $this->getTypeOfMail($messages[$id]);

                if ($assume) {
                    $messages[$id]['orderNumber'] = $this->assumeOrderNumber($messages[$id]);
                    $messages[$id]['domainName']  = $this->assumeDomainName($messages[$id]);
                }

                $success = true;
                if (is_callable($callbackFunction)) {
                    $success = $callbackFunction($id, $messages[$id]);
                }
            } catch (ExceptionInterface $e) {
                // General decoding error -> removeMessage
                unset($messages[$id]);

                // Always mark as processed
                $success = true;
            }

            if ($markProcessed && $success) {
                $this->markProcessed($imap, $id, $message);
            }
        }

        return $messages;
    }

Fetches the mail recursively, through the folders.

@param ImapAdapter $imap             imap helper class
@param string      $search           imap-searchterm
@param bool        $markProcessed    Sets the flag as processed
@param bool        $assume           Assumes domainName / order-Number in the mail
@param \Closure    $callbackFunction callback

@return array

Fetches the mail recursively through the folders .


protected function markProcessed(ImapAdapter $imap, $id, Message $message = null)
    {
        $flags   = $message ? $message->getFlags() : [];
        $flags[] = self::PROCESSED_FLAG;

        try {
            $imap->setFlags($id, $flags);
        } catch (ExceptionInterface $e) {
            // Nothing to do
        }
    }

protected
function
markProcessed
(
ImapAdapter
$
imap
,
$
id
,
Message
$
message
=
)
{
$
flags
=
$
message
$
message
->
getFlags
(
)
:
[
]
;
$
flags
[
]
=
self
::
PROCESSED_FLAG
;
try
{
$
imap
->
setFlags
(
$
id
,
$
flags
)
;
}
catch
(
ExceptionInterface
$
e
)
{
// Nothing to do
}
}

Marks the mail with the processed flag

@param ImapAdapter $imap
@param integer     $id
@param Message     $message


protected function getTypeOfMail(array $mail)
    {
        foreach (self::$subjects as $key => $subject) {
            if (stristr($mail['subject'], $subject) !== false) {
                return $key;
            }
        }

        foreach (self::$bodies as $key => $body) {
            if (preg_match($body, $mail['plainText'])) {
                return $key;
            }
        }

        return null;
    }

protected function getTypeOfMail ( array $ mail ) { foreach ( self :: $ subjects as $ key => $ subject ) { if ( stristr ( $ mail [ 'subject' ] , $ subject ) !== false ) { return $ key ; } } foreach ( self :: $ bodies as $ key => $ body ) { if ( preg_match ( $ body , $ mail [ 'plainText' ] ) ) { return $ key ; } } return null ; }

Tries to find out, what Comodo wanna tell us...

@param array $mail

@return null|string

Tries to find out what Comodo wanna tell us ...


public function autoRefund(array $params)
    {
        if (false === isset($params['refundReasonCode'])) {
            $params['refundReasonCode'] = self::AUTO_REFUND_REASON_OTHER;
        }

        $response = $this
            ->communicationAdapter
            ->sendToApi(
                self::COMODO_AUTO_REFUND_URL,
                $params,
                CommunicationAdapter::RESPONSE_URL_ENCODED
            );

        if ($response['errorCode'] == 0) {
            return true;
        } else {
            throw $this->createException($response);
        }
    }

public function autoRefund ( array $ params ) { if ( false === isset ( $ params [ 'refundReasonCode' ] ) ) { $ params [ 'refundReasonCode' ] = self :: AUTO_REFUND_REASON_OTHER ; } $ response = $ this -> communicationAdapter -> sendToApi ( self :: COMODO_AUTO_REFUND_URL , $ params , CommunicationAdapter :: RESPONSE_URL_ENCODED ) ; if ( $ response [ 'errorCode' ] == 0 ) { return true ; } else { throw $ this -> createException ( $ response ) ; } }

Refunds a ordered certificate

@param array $params

@return bool

@throws AccountException
@throws ArgumentException
@throws CSRException
@throws RequestException
@throws UnknownApiException
@throws UnknownException


public function autoApplySSL(array $params)
    {
        // Two choices, we want url-encoded
        $params['responseFormat']    = CommunicationAdapter::RESPONSE_URL_ENCODED;
        $params['showCertificateID'] = 'Y';

        // Send request
        $arr = $this
            ->communicationAdapter
            ->sendToApi(self::COMODO_AUTO_APPLY_URL, $params, CommunicationAdapter::RESPONSE_URL_ENCODED);

        // Successful
        if ($arr['errorCode'] == 1 || $arr['errorCode'] == 0) {
            $result = new AutoApplyResult();

            if ($arr['errorCode'] == 0) {
                $paid = true;
            } else {
                $paid = false;
            }

            $result
                ->setPaid($paid)
                ->setCertificateID($arr['certificateID'])
                ->setExpectedDeliveryTime($arr['expectedDeliveryTime'])
                ->setOrderNumber($arr['orderNumber'])
                ->setTotalCost($arr['totalCost'])
                ->setRequestQuery($arr['requestQuery']);

            if (isset($arr['uniqueValue'])) {
                $result->setUniqueValue($arr['uniqueValue']);
            }

            return $result;
        } else {
            throw $this->createException($arr);
        }
    }

public
function
autoApplySSL
(
array
$
params
)
{
// Two choices, we want url-encoded
$
params
[
'responseFormat'
]
=
CommunicationAdapter
::
RESPONSE_URL_ENCODED
;
$
params
[
'showCertificateID'
]
=
'Y'
;
// Send request
$
arr
=
$
this
->
communicationAdapter
->
sendToApi
(
self
::
COMODO_AUTO_APPLY_URL
,
$
params
,
CommunicationAdapter
::
RESPONSE_URL_ENCODED
)
;
// Successful
if
(
$
arr
[
'errorCode'
]
==
1
||
$
arr
[
'errorCode'
]
==
0
)
{
$
result
=
new
AutoApplyResult
(
)
;
if
(
$
arr
[
'errorCode'
]
==
0
)
{
$
paid
=
true
;
}
else
{
$
paid
=
false
;
}
$
result
->
setPaid
(
$
paid
)
->
setCertificateID
(
$
arr
[
'certificateID'
]
)
->
setExpectedDeliveryTime
(
$
arr
[
'expectedDeliveryTime'
]
)
->
setOrderNumber
(
$
arr
[
'orderNumber'
]
)
->
setTotalCost
(
$
arr
[
'totalCost'
]
)
->
setRequestQuery
(
$
arr
[
'requestQuery'
]
)
;
if
(
isset
(
$
arr
[
'uniqueValue'
]
)
)
{
$
result
->
setUniqueValue
(
$
arr
[
'uniqueValue'
]
)
;
}
return
$
result
;
}
else
{
throw
$
this
->
createException
(
$
arr
)
;
}
}

Function apply for a certificate

See documentation of params at https://secure.comodo.net/api/pdf/webhostreseller/sslcertificates/

@param array $params

@return AutoApplyResult
@throws Model\Exception\AccountException
@throws Model\Exception\ArgumentException
@throws Model\Exception\CSRException
@throws Model\Exception\RequestException
@throws Model\Exception\UnknownApiException
@throws Model\Exception\UnknownException


public function autoReplaceSSL(array $params)
    {
        // Two choices, we want url-encoded
        $params['responseFormat'] = CommunicationAdapter::RESPONSE_URL_ENCODED;

        // Send request
        $arr = $this
            ->communicationAdapter
            ->sendToApi(
                self::COMODO_AUTO_REPLACE_URL,
                $params,
                CommunicationAdapter::RESPONSE_URL_ENCODED
            );

        // Successful
        if ($arr['errorCode'] == 0) {
            $result = new AutoReplaceResult();

            $result
                ->setCertificateID($arr['certificateID'])
                ->setExpectedDeliveryTime($arr['expectedDeliveryTime']);

            if (isset($arr['uniqueValue'])) {
                $result->setUniqueValue($arr['uniqueValue']);
            }

            return $result;
        } else {
            throw $this->createException($arr);
        }
    }

public
function
autoReplaceSSL
(
array
$
params
)
{
// Two choices, we want url-encoded
$
params
[
'responseFormat'
]
=
CommunicationAdapter
::
RESPONSE_URL_ENCODED
;
// Send request
$
arr
=
$
this
->
communicationAdapter
->
sendToApi
(
self
::
COMODO_AUTO_REPLACE_URL
,
$
params
,
CommunicationAdapter
::
RESPONSE_URL_ENCODED
)
;
// Successful
if
(
$
arr
[
'errorCode'
]
==
0
)
{
$
result
=
new
AutoReplaceResult
(
)
;
$
result
->
setCertificateID
(
$
arr
[
'certificateID'
]
)
->
setExpectedDeliveryTime
(
$
arr
[
'expectedDeliveryTime'
]
)
;
if
(
isset
(
$
arr
[
'uniqueValue'
]
)
)
{
$
result
->
setUniqueValue
(
$
arr
[
'uniqueValue'
]
)
;
}
return
$
result
;
}
else
{
throw
$
this
->
createException
(
$
arr
)
;
}
}

Function update for a certificate

See documentation of params at https://secure.comodo.net/api/pdf/webhostreseller/sslcertificates/

@param array $params

@return AutoReplaceResult
@throws Model\Exception\AccountException
@throws Model\Exception\ArgumentException
@throws Model\Exception\CSRException
@throws Model\Exception\RequestException
@throws Model\Exception\UnknownApiException
@throws Model\Exception\UnknownException


public function autoRevokeSSL(array $params)
    {
        // Two choices, we want url-encoded
        $params['responseFormat'] = CommunicationAdapter::RESPONSE_URL_ENCODED;

        return $this->sendBooleanRequest(
            self::COMODO_AUTO_REVOKE_URL,
            $params,
            CommunicationAdapter::RESPONSE_URL_ENCODED
        );
    }

public
function
autoRevokeSSL
(
array
$
params
)
{
// Two choices, we want url-encoded
$
params
[
'responseFormat'
]
=
CommunicationAdapter
::
RESPONSE_URL_ENCODED
;
return
$
this
->
sendBooleanRequest
(
self
::
COMODO_AUTO_REVOKE_URL
,
$
params
,
CommunicationAdapter
::
RESPONSE_URL_ENCODED
)
;
}

Function to revoke order

See documentation of params at https://secure.comodo.net/api/pdf/webhostreseller/sslcertificates/

@param array $params

@return bool
@throws Model\Exception\AccountException
@throws Model\Exception\ArgumentException
@throws Model\Exception\RequestException
@throws Model\Exception\UnknownApiException
@throws Model\Exception\UnknownException


public function collectSsl(array $params)
    {
        // Not decode the following indexes
        $notDecode = array('caCertificate', 'certificate', 'netscapeCertificateSequence', 'zipFile');

        // Force threating as array
        $forceArray = array('caCertificate');

        // Two choices, we want url-encoded
        $params['responseFormat'] = CommunicationAdapter::RESPONSE_URL_ENCODED;

        // Send request
        $arr = $this
            ->communicationAdapter
            ->sendToApi(
                self::COMODO_COLLECT_SSL_URL,
                $params,
                CommunicationAdapter::RESPONSE_URL_ENCODED,
                $notDecode,
                $forceArray
            );

        // Successful
        if ($arr['errorCode'] >= 0) {
            $result = new CollectSslResult();

            $this->fill($result, $arr, array('notBefore', 'notAfter'));

            /*
             * Comodo does not provide these data, when not a EV certificate (Bug?). So we fill this manually to "not required".
             *
             * https://secure.comodo.net/api/pdf/webhostreseller/sslcertificates/CollectSSL%20v1.17.pdf
             */
            if (!isset($arr['evClickThroughStatus'])) {
                $result->setEvClickThroughStatus(-1);
            }

            if (!isset($arr['brandValStatus'])) {
                $result->setBrandValStatus(-1);
            }

            return $result;
        } else {
            throw $this->createException($arr);
        }
    }

Function to get details of a certificate

See documentation of params at https://secure.comodo.net/api/pdf/webhostreseller/sslcertificates/

@param array $params

@return CollectSslResult
@throws Model\Exception\AccountException
@throws Model\Exception\ArgumentException
@throws Model\Exception\CSRException
@throws Model\Exception\RequestException
@throws Model\Exception\UnknownApiException
@throws Model\Exception\UnknownException


public function getDCVEMailAddressList(array $params)
    {
        // Force threating as array
        $forceArray = array('whois_email', 'level2_email', 'level3_email');

        // Response is always new line encoded
        $responseArray = $this
            ->communicationAdapter
            ->sendToApi(
                self::COMODO_DCV_MAIL_URL,
                $params,
                CommunicationAdapter::RESPONSE_NEW_LINE,
                null,
                $forceArray
            );

        if ($responseArray['errorCode'] == 0) {
            $result = new GetDCVEMailAddressListResult();

            if (isset($responseArray['whois_email'][0]) && $responseArray['whois_email'][0] == 'none') {
                unset($responseArray['whois_email'][0]);
            }

            $result
                ->setDomainName($responseArray['domain_name'])
                ->setWhoisEmail($responseArray['whois_email'])
                ->setLevel2Emails($responseArray['level2_email'])
                ->setRequestQuery($responseArray['requestQuery']);

            if (isset($responseArray['level3_email'])) {
                $result->setLevel3Emails($responseArray['level3_email']);
            }

            return $result;
        } else {
            throw $this->createException($responseArray);
        }
    }

public
function
getDCVEMailAddressList
(
array
$
params
)
{
// Force threating as array
$
forceArray
=
array
(
'whois_email'
,
'level2_email'
,
'level3_email'
)
;
// Response is always new line encoded
$
responseArray
=
$
this
->
communicationAdapter
->
sendToApi
(
self
::
COMODO_DCV_MAIL_URL
,
$
params
,
CommunicationAdapter
::
RESPONSE_NEW_LINE
,
,
$
forceArray
)
;
if
(
$
responseArray
[
'errorCode'
]
==
0
)
{
$
result
=
new
GetDCVEMailAddressListResult
(
)
;
if
(
isset
(
$
responseArray
[
'whois_email'
]
[
0
]
)
&&
$
responseArray
[
'whois_email'
]
[
0
]
==
'none'
)
{
unset
(
$
responseArray
[
'whois_email'
]
[
0
]
)
;
}
$
result
->
setDomainName
(
$
responseArray
[
'domain_name'
]
)
->
setWhoisEmail
(
$
responseArray
[
'whois_email'
]
)
->
setLevel2Emails
(
$
responseArray
[
'level2_email'
]
)
->
setRequestQuery
(
$
responseArray
[
'requestQuery'
]
)
;
if
(
isset
(
$
responseArray
[
'level3_email'
]
)
)
{
$
result
->
setLevel3Emails
(
$
responseArray
[
'level3_email'
]
)
;
}
return
$
result
;
}
else
{
throw
$
this
->
createException
(
$
responseArray
)
;
}
}

Function to get the DCV e-mail address-list

See documentation of params at https://secure.comodo.net/api/pdf/webhostreseller/sslcertificates/

@param array $params

@return GetDCVEMailAddressListResult
@throws AccountException
@throws ArgumentException
@throws CSRException
@throws RequestException
@throws UnknownApiException
@throws UnknownException

Function to get the DCV e - mail address - list


public function sslChecker(array $params)
    {
        // Response is always new line encoded
        $responseArray = $this
            ->communicationAdapter
            ->sendToApi(
                self::COMODO_SSLCHECKER,
                $params,
                CommunicationAdapter::RESPONSE_URL_ENCODED
            );

        if ($responseArray['error_code'] == 0) {
            $result = new SslCheckerResult();

            $result
                ->setServerUrl($responseArray['server_url'])
                ->setServerDomainIsIDN($responseArray['server_domain_isIDN'])
                ->setServerDomainUtf8($responseArray['server_domain_utf8'])
                ->setServerDomainAce($responseArray['server_domain_ace'])
                ->setServerIp($responseArray['server_ip'])
                ->setServerPort($responseArray['server_port'])
                ->setServerSoftware($responseArray['server_software'])
                ->setCertNotBeforeFromUnixTimestamp($responseArray['cert_notBefore'])
                ->setCertNotAfterFromUnixTimestamp($responseArray['cert_notAfter'])
                ->setCertValidityNotBefore($responseArray['cert_validity_notBefore'])
                ->setCertValidityNotAfter($responseArray['cert_validity_notAfter'])
                ->setCertKeyAlgorithm($responseArray['cert_key_algorithm'])
                ->setCertKeySize($responseArray['cert_key_size'])
                ->setCertSubjectCN($responseArray['cert_subject_DN'])
                ->setCertSubjectCN($responseArray['cert_subject_CN'])
                ->setCertSubjectOU($responseArray['cert_subject_OU'])
                ->setCertSubjectOrganization($responseArray['cert_subject_O'])
                ->setCertSubjectStreetAddress1($responseArray['cert_subject_streetAddress_1'])
                ->setCertSubjectStreetAddress2($responseArray['cert_subject_streetAddress_2'])
                ->setCertSubjectStreetAddress3($responseArray['cert_subject_streetAddress_3'])
                ->setCertSubjectLocality($responseArray['cert_subject_L'])
                ->setCertSubjectState($responseArray['cert_subject_S'])
                ->setCertSubjectPostalCode($responseArray['cert_subject_postalCode'])
                ->setCertSubjectCountry($responseArray['cert_subject_C'])
                ->setCertIsMultiDomain($responseArray['cert_isMultiDomain'])
                ->setCertIsWildcard($responseArray['cert_isWildcard'])
                ->setCertIssuerDN($responseArray['cert_issuer_DN'])
                ->setCertIssuerCN($responseArray['cert_issuer_CN'])
                ->setCertIssuerOrganization($responseArray['cert_issuer_O'])
                ->setCertIssuerOrganization($responseArray['cert_issuer_C'])
                ->setCertIssuerBrand($responseArray['cert_issuer_brand'])
                ->setCertPolicyOID($responseArray['cert_policyOID'])
                ->setCertValidation($responseArray['cert_validation']);

            return $result;
        } else {
            throw $this->createException($responseArray);
        }
    }

public
function
sslChecker
(
array
$
params
)
{
// Response is always new line encoded
$
responseArray
=
$
this
->
communicationAdapter
->
sendToApi
(
self
::
COMODO_SSLCHECKER
,
$
params
,
CommunicationAdapter
::
RESPONSE_URL_ENCODED
)
;
if
(
$
responseArray
[
'error_code'
]
==
0
)
{
$
result
=
new
SslCheckerResult
(
)
;
$
result
->
setServerUrl
(
$
responseArray
[
'server_url'
]
)
->
setServerDomainIsIDN
(
$
responseArray
[
'server_domain_isIDN'
]
)
->
setServerDomainUtf8
(
$
responseArray
[
'server_domain_utf8'
]
)
->
setServerDomainAce
(
$
responseArray
[
'server_domain_ace'
]
)
->
setServerIp
(
$
responseArray
[
'server_ip'
]
)
->
setServerPort
(
$
responseArray
[
'server_port'
]
)
->
setServerSoftware
(
$
responseArray
[
'server_software'
]
)
->
setCertNotBeforeFromUnixTimestamp
(
$
responseArray
[
'cert_notBefore'
]
)
->
setCertNotAfterFromUnixTimestamp
(
$
responseArray
[
'cert_notAfter'
]
)
->
setCertValidityNotBefore
(
$
responseArray
[
'cert_validity_notBefore'
]
)
->
setCertValidityNotAfter
(
$
responseArray
[
'cert_validity_notAfter'
]
)
->
setCertKeyAlgorithm
(
$
responseArray
[
'cert_key_algorithm'
]
)
->
setCertKeySize
(
$
responseArray
[
'cert_key_size'
]
)
->
setCertSubjectCN
(
$
responseArray
[
'cert_subject_DN'
]
)
->
setCertSubjectCN
(
$
responseArray
[
'cert_subject_CN'
]
)
->
setCertSubjectOU
(
$
responseArray
[
'cert_subject_OU'
]
)
->
setCertSubjectOrganization
(
$
responseArray
[
'cert_subject_O'
]
)
->
setCertSubjectStreetAddress1
(
$
responseArray
[
'cert_subject_streetAddress_1'
]
)
->
setCertSubjectStreetAddress2
(
$
responseArray
[
'cert_subject_streetAddress_2'
]
)
->
setCertSubjectStreetAddress3
(
$
responseArray
[
'cert_subject_streetAddress_3'
]
)
->
setCertSubjectLocality
(
$
responseArray
[
'cert_subject_L'
]
)
->
setCertSubjectState
(
$
responseArray
[
'cert_subject_S'
]
)
->
setCertSubjectPostalCode
(
$
responseArray
[
'cert_subject_postalCode'
]
)
->
setCertSubjectCountry
(
$
responseArray
[
'cert_subject_C'
]
)
->
setCertIsMultiDomain
(
$
responseArray
[
'cert_isMultiDomain'
]
)
->
setCertIsWildcard
(
$
responseArray
[
'cert_isWildcard'
]
)
->
setCertIssuerDN
(
$
responseArray
[
'cert_issuer_DN'
]
)
->
setCertIssuerCN
(
$
responseArray
[
'cert_issuer_CN'
]
)
->
setCertIssuerOrganization
(
$
responseArray
[
'cert_issuer_O'
]
)
->
setCertIssuerOrganization
(
$
responseArray
[
'cert_issuer_C'
]
)
->
setCertIssuerBrand
(
$
responseArray
[
'cert_issuer_brand'
]
)
->
setCertPolicyOID
(
$
responseArray
[
'cert_policyOID'
]
)
->
setCertValidation
(
$
responseArray
[
'cert_validation'
]
)
;
return
$
result
;
}
else
{
throw
$
this
->
createException
(
$
responseArray
)
;
}
}

Function to do a sslcheck

https://secure.comodo.net/api/pdf/latest/SSLChecker.pdf

@param array $params

@return GetMDCDomainDetailsResult

@throws Model\Exception\AccountException
@throws Model\Exception\ArgumentException
@throws Model\Exception\CSRException
@throws Model\Exception\RequestException
@throws Model\Exception\UnknownApiException
@throws Model\Exception\UnknownException


public function webHostReport(array $params) {

        if (empty($params['lastResultNo'])) {
            $params['lastResultNo'] = 10;
        }

        // Response is always new line encoded
        $responseArray = $this
            ->communicationAdapter
            ->sendToApi(
                self::COMODO_WEB_HOST_REPORT,
                $params,
                CommunicationAdapter::RESPONSE_URL_ENCODED
            );
        if ($responseArray['error_code'] == 0) {
            $result = new WebHostReportResult();
            $result->importEntries($responseArray);
            return $result;
        } else {
            throw $this->createException($responseArray);
        }
    }

public
function
webHostReport
(
array
$
params
)
{
if
(
empty
(
$
params
[
'lastResultNo'
]
)
)
{
$
params
[
'lastResultNo'
]
=
10
;
}
// Response is always new line encoded
$
responseArray
=
$
this
->
communicationAdapter
->
sendToApi
(
self
::
COMODO_WEB_HOST_REPORT
,
$
params
,
CommunicationAdapter
::
RESPONSE_URL_ENCODED
)
;
if
(
$
responseArray
[
'error_code'
]
==
0
)
{
$
result
=
new
WebHostReportResult
(
)
;
$
result
->
importEntries
(
$
responseArray
)
;
return
$
result
;
}
else
{
throw
$
this
->
createException
(
$
responseArray
)
;
}
}

Function to call WebHostReport api

https://secure.comodo.net/products/!WebHostReport

Details for params usage:
https://secure.comodo.net/api/pdf/latest/WebHostReport.pdf

@param array $params

@return WebHostReportResult

@throws Model\Exception\AccountException
@throws Model\Exception\ArgumentException
@throws Model\Exception\CSRException
@throws Model\Exception\RequestException
@throws Model\Exception\UnknownApiException
@throws Model\Exception\UnknownException


public function enterDCVCode(array $params)
    {
        // Check parameters
        if (!isset($params['dcvCode'])) {
            throw new ArgumentException(-3, 'Please provide an order-number', 'dcvCode', '');
        }

        if (!isset($params['orderNumber'])) {
            throw new ArgumentException(-3, 'Please provide an order-number', 'orderNumber', '');
        }

        // this is not a official request, so we need to use the website
        $responseString = $this
            ->communicationAdapter
            ->sendToWebsite(self::COMODO_DCV_CODE_URL, $params);

        // Decode answer from website
        if (stristr($responseString, 'You have entered the correct Domain Control Validation code') !== false) {
            return true;
        } elseif (stristr($responseString, 'the certificate has already been issued') !== false) {
            throw new ArgumentException(-104, 'The certificate has already been issued', 'certificate', $responseString);
        } elseif (stristr($responseString, 'Invalid Validation Code!') !== false) {
            throw new ArgumentException(-103, 'Invalid Validation Code', 'validation-code', $responseString);
        } else {
            throw new UnknownException(99, 'UnknownException', $responseString);
        }
    }

Function to enter the DCV code, coming from DCV E-Mail

@param array $params

@return bool
@throws Model\Exception\UnknownException
@throws Model\Exception\ArgumentException

Function to enter the DCV code coming from DCV E - Mail


protected function createException($responseArray)
    {
        if (is_array($responseArray) === false) {
            return new UnknownException(
                0,
                'Internal error',
                $responseArray['responseString']
            );
        }

        switch ($responseArray['errorCode']) {
            case -1: // Not using https:
            case -17: // Wrong HTTP-method
                return new RequestException(
                    $responseArray['errorCode'],
                    $responseArray['errorMessage'],
                    $responseArray['responseString']
                );

            case -2: // unrecognized argument
            case -3: // missing argument
            case -4: // invalid argument
            case -7: // invalid ISO Country
            case -18: // Name = Fully-Qualified Domain Name
            case -35: // Name = = IP
            case -19: // Name = = Accessible IP
                return new ArgumentException(
                    $responseArray['errorCode'],
                    $responseArray['errorMessage'],
                    ((isset($responseArray['errorItem'])) ? $responseArray['errorItem'] : null),
                    $responseArray['responseString']
                );

            case -16: // Permission denied
            case -15: // insufficient credits
                return new AccountException(
                    $responseArray['errorCode'],
                    $responseArray['errorMessage'],
                    $responseArray['responseString']
                );

            case -5: // contains wildcard
            case -6: // no wildcard, but must have
            case -8: // missing field
            case -9: // base64 decode exception
            case -10: // decode exception
            case -11: // unsupported algorithm
            case -12: // invalid signature
            case -13: // unsupported key size
            case -20: // Already rejected / Order relevated
            case -21: // Already revoked
            case -26: // current being issued
            case -40: // key compromised
                return new CSRException(
                    $responseArray['errorCode'],
                    $responseArray['errorMessage'],
                    $responseArray['responseString']
                );

            case -14:
                return new UnknownApiException(
                    $responseArray['errorCode'],
                    $responseArray['errorMessage'],
                    $responseArray['responseString']
                );

            default:
                return new UnknownException(
                    $responseArray['errorCode'],
                    $responseArray['errorMessage'],
                    $responseArray['responseString']
                );
        }
    }

protected
function
createException
(
$
responseArray
)
{
if
(
is_array
(
$
responseArray
)
===
false
)
{
return
new
UnknownException
(
0
,
'Internal error'
,
$
responseArray
[
'responseString'
]
)
;
}
switch
(
$
responseArray
[
'errorCode'
]
)
{
case
1
:
// Not using https:
case
17
:
// Wrong HTTP-method
return
new
RequestException
(
$
responseArray
[
'errorCode'
]
,
$
responseArray
[
'errorMessage'
]
,
$
responseArray
[
'responseString'
]
)
;
case
2
:
// unrecognized argument
case
3
:
// missing argument
case
4
:
// invalid argument
case
7
:
// invalid ISO Country
case
18
:
// Name = Fully-Qualified Domain Name
case
35
:
// Name = = IP
case
19
:
// Name = = Accessible IP
return
new
ArgumentException
(
$
responseArray
[
'errorCode'
]
,
$
responseArray
[
'errorMessage'
]
,
(
(
isset
(
$
responseArray
[
'errorItem'
]
)
)
$
responseArray
[
'errorItem'
]
:
)
,
$
responseArray
[
'responseString'
]
)
;
case
16
:
// Permission denied
case
15
:
// insufficient credits
return
new
AccountException
(
$
responseArray
[
'errorCode'
]
,
$
responseArray
[
'errorMessage'
]
,
$
responseArray
[
'responseString'
]
)
;
case
5
:
// contains wildcard
case
6
:
// no wildcard, but must have
case
8
:
// missing field
case
9
:
// base64 decode exception
case
10
:
// decode exception
case
11
:
// unsupported algorithm
case
12
:
// invalid signature
case
13
:
// unsupported key size
case
20
:
// Already rejected / Order relevated
case
21
:
// Already revoked
case
26
:
// current being issued
case
40
:
// key compromised
return
new
CSRException
(
$
responseArray
[
'errorCode'
]
,
$
responseArray
[
'errorMessage'
]
,
$
responseArray
[
'responseString'
]
)
;
case
14
:
return
new
UnknownApiException
(
$
responseArray
[
'errorCode'
]
,
$
responseArray
[
'errorMessage'
]
,
$
responseArray
[
'responseString'
]
)
;
default
:
return
new
UnknownException
(
$
responseArray
[
'errorCode'
]
,
$
responseArray
[
'errorMessage'
]
,
$
responseArray
[
'responseString'
]
)
;
}
}

Function to create an exception for API errorcodes

@param array|mixed $responseArray

@return AccountException|ArgumentException|CSRException|RequestException|UnknownApiException|UnknownException

@SuppressWarnings(PHPMD.CyclomaticComplexity)


public function generate()
    {
        $title = $this->getTitle();
        $description = $this->getDescription();
        $keywords = $this->getKeywords();
        $canonical = $this->getCanonical();

        $html[] = "<title>$title</title>";

        if (! empty($description)) {
            $html[] = "<meta name='description' content='$description' />";
        }

        if (! empty($keywords)) {
            $html[] = "<meta name='keywords' content='$keywords' />";
        }

        if (! empty($canonical)) {
            $html[] = "<link rel='canonical' href='$canonical' />";
        }

        return implode(PHP_EOL, $html);
    }


public function setDescription($description)
    {
        $description = strip_tags($description);

        if (strlen($description) > $this->max_description_length) {
            $description = substr($description, 0, $this->max_description_length);
        }

        $this->description = $description;
    }

public function setDescription ( $ description ) { $ description = strip_tags ( $ description ) ; if ( strlen ( $ description ) > $ this -> max_description_length ) { $ description = substr ( $ description , 0 , $ this -> max_description_length ) ; } $ this -> description = $ description ; }

Set the Meta description.

@param string $description


public function reset()
    {
        $this->title = null;
        $this->description = null;
        $this->keywords = null;
        $this->canonical = null;
    }

public function reset ( ) { $ this -> title = null ; $ this -> description = null ; $ this -> keywords = null ; $ this -> canonical = null ; }

Reset the title and description fields.

@return void

Reset the title and description fields .


public function registerBindings()
    {
        // Register the sitemap.xml generator
        $this->app->singleton('calotype.seo.generators.sitemap', function ($app) {
            return new SitemapGenerator();
        });

        // Register the meta tags generator
        $this->app->singleton('calotype.seo.generators.meta', function ($app) {
            return new MetaGenerator($app['config']->get('calotype-seo::defaults'));
        });

        // Register the robots.txt generator
        $this->app->singleton('calotype.seo.generators.robots', function ($app) {
            return new RobotsGenerator();
        });

        // Register the open graph properties generator
        $this->app->singleton('calotype.seo.generators.opengraph', function ($app) {
            return new OpenGraphGenerator();
        });
    }


public function generate()
    {
        $html = array();

        foreach ($this->properties as $property => $value) {
            $html[] = strtr(static::OPENGRAPH_TAG, array(
                '[property]' => static::OPENGRAPH_PREFIX . $property,
                '[value]' => $value
            ));
        }

        return implode(PHP_EOL, $html);
    }

public function generate ( ) { $ html = array ( ) ; foreach ( $ this -> properties as $ property => $ value ) { $ html [ ] = strtr ( static :: OPENGRAPH_TAG , array ( '[property]' => static :: OPENGRAPH_PREFIX . $ property , '[value]' => $ value ) ) ; } return implode ( PHP_EOL , $ html ) ; }

Render the open graph tags.

@return string


public function addRaw(array $data)
    {
        $this->validateData($data);

        $data = $this->prepareData($data);

        $this->entries[] = $data;
    }

public function addRaw ( array $ data ) { $ this -> validateData ( $ data ) ; $ data = $ this -> prepareData ( $ data ) ; $ this -> entries [ ] = $ data ; }

Add a raw entry to the sitemap.

@param array $data


public function prepareData(array $data)
    {
        $data = $this->replaceAttributes($data);

        // Remove trailing slashes from the location
        if (array_key_exists('loc', $data)) {
            $data['loc'] = trim($data['loc'], '/');
        }

        return $data;
    }

Prepare the data.

@param  array $data

@return array


public function contains($url)
    {
        $url = trim($url, '/');

        foreach ($this->entries as $entry) {
            if ($entry['loc'] == $url) {
                return true;
            }
        }

        return false;
    }

public function contains ( $ url ) { $ url = trim ( $ url , '/' ) ; foreach ( $ this -> entries as $ entry ) { if ( $ entry [ 'loc' ] == $ url ) { return true ; } } return false ; }

Check if the sitemap contains an url.

@param string $url

@return boolean


protected function validateData($data)
    {
        $data = $this->replaceAttributes($data);

        foreach ($this->required as $required) {
            if (! array_key_exists($required, $data)) {
                $replacement = array_search($required, $this->replacements);

                if ($replacement !== false) {
                    $required = $replacement;
                }

                throw new \InvalidArgumentException("Required sitemap property [$required] is not present.");
            }
        }
    }

Validate the data for a sitemap entry.

@param array $data


public function fillIndex($index)
    {
        /** @param Command $value */
        $map = function ($value) use ($index) {
            if ($value->getIndex() === null) {
                $value->index($index);
            }
        };

        array_map($map, $this->commands);

        return $this;
    }

public
function
fillIndex
(
$
index
)
{
/** @param Command $value */
$
map
=
function
(
$
value
)
use
(
$
index
)
{
if
(
$
value
->
getIndex
(
)
===
)
{
$
value
->
index
(
$
index
)
;
}
}
;
array_map
(
$
map
,
$
this
->
commands
)
;
return
$
this
;
}

Fill all commands that don't have an index set

@param $index

@return $this

Fill all commands that don t have an index set


public function fillType($type)
    {

        /** @param Command $value */
        $map = function ($value) use ($type) {
            if ($value->getType() === null) {
                $value->type($type);
            }
        };

        array_map($map, $this->commands);

        return $this;
    }

public
function
fillType
(
$
type
)
{
/** @param Command $value */
$
map
=
function
(
$
value
)
use
(
$
type
)
{
if
(
$
value
->
getType
(
)
===
)
{
$
value
->
type
(
$
type
)
;
}
}
;
array_map
(
$
map
,
$
this
->
commands
)
;
return
$
this
;
}

Fill all commands that don't have a type set

@param $type

@return $this

Fill all commands that don t have a type set


public function index($index)
    {
        $this->params['index'] = array();
        $args                  = func_get_args();
        foreach ($args as $arg) {
            $this->params['index'][] = $arg;
        }

        return $this;
    }

public function index ( $ index ) { $ this -> params [ 'index' ] = array ( ) ; $ args = func_get_args ( ) ; foreach ( $ args as $ arg ) { $ this -> params [ 'index' ] [ ] = $ arg ; } return $ this ; }

Set the index to operate on

@param  string       $index     indices to operate on
@param  string       $index,... indices to operate on

@return IndexRequest


public function type($type)
    {
        $this->params['type'] = array();
        $args                 = func_get_args();
        foreach ($args as $arg) {
            $this->params['type'][] = $arg;
        }

        return $this;
    }

public function type ( $ type ) { $ this -> params [ 'type' ] = array ( ) ; $ args = func_get_args ( ) ; foreach ( $ args as $ arg ) { $ this -> params [ 'type' ] [ ] = $ arg ; } return $ this ; }

Set the type to operate on

@param  string       $type     indices to operate on
@param  string       $type,... indices to operate on

@return IndexRequest


public function settings($settings, $merge = true)
    {
        if ($settings instanceof \Sherlock\wrappers\IndexSettingsWrapper)
            $newSettings = $settings->toArray();
        else if (is_array($settings))
            $newSettings = $settings;
        else
            throw new \Sherlock\common\exceptions\BadMethodCallException("Unknown parameter provided to settings(). Must be array of settings or IndexSettingsWrapper.");

        if ($merge)
            $this->params['indexSettings'] = array_merge($this->params['indexSettings'], $newSettings);
        else
            $this->params['indexSettings'] = $newSettings;

        return $this;
    }

Set the index settings, used predominantly for index creation

@param  array|\sherlock\wrappers\IndexSettingsWrapper      $settings
@param  bool                                               $merge

@throws \Sherlock\common\exceptions\BadMethodCallException
@return IndexRequest

Set the index settings used predominantly for index creation


public function delete()
    {

        if (!isset($this->params['index']))
            throw new exceptions\RuntimeException("Index cannot be empty.");

        $index = implode(',', $this->params['index']);

        $command = new Command();
        $command->index($index)
            ->action('delete');

        $this->batch->clearCommands();
        $this->batch->addCommand($command);

        $ret = parent::execute();

        return $ret[0];
    }

public
function
delete
(
)
{
if
(
!
isset
(
$
this
->
params
[
'index'
]
)
)
throw
new
exceptions
\
RuntimeException
(
"Index cannot be empty."
)
;
$
index
=
implode
(
','
,
$
this
->
params
[
'index'
]
)
;
$
command
=
new
Command
(
)
;
$
command
->
index
(
$
index
)
->
action
(
'delete'
)
;
$
this
->
batch
->
clearCommands
(
)
;
$
this
->
batch
->
addCommand
(
$
command
)
;
$
ret
=
parent
::
execute
(
)
;
return
$
ret
[
0
]
;
}

Delete an index

@return \Sherlock\responses\IndexResponse
@throws exceptions\RuntimeException


public function create()
    {

        if (!isset($this->params['index']))
            throw new exceptions\RuntimeException("Index cannot be empty.");

        $index = implode(',', $this->params['index']);

        //Final JSON should be object properties, not an array.  So we need to iterate
        //through the array members and merge into an associative array.
        $mappings = array();
        foreach ($this->params['indexMappings'] as $type => $mapping) {
            $mappings = array_merge($mappings, array($type => $mapping));
        }
        $body = array(
            "settings" => $this->params['indexSettings'],
            "mappings" => $mappings
        );

        $command = new Command();
        $command->index($index)
            ->action('put')
            ->data(json_encode($body, JSON_FORCE_OBJECT));

        $this->batch->clearCommands();
        $this->batch->addCommand($command);

        /**
         * @var \Sherlock\responses\IndexResponse
         */
        $ret = parent::execute();

        //clear out mappings, settings
        $this->resetIndex();

        return $ret[0];
    }

Create an index

@return \Sherlock\responses\IndexResponse
@throws exceptions\RuntimeException


public function updateSettings()
    {

        if (!isset($this->params['index'])) {
                        throw new exceptions\RuntimeException("Index cannot be empty.");
        }

        $index = implode(',', $this->params['index']);

        $body = array("index" => $this->params['indexSettings']);

        $command = new Command();
        $command->index($index)
            ->id('_settings')
            ->action('put')
            ->data(json_encode($body, JSON_FORCE_OBJECT));

        $this->batch->clearCommands();
        $this->batch->addCommand($command);

        $ret = parent::execute();

        //clear out mappings, settings
        //$this->resetIndex();

        return $ret[0];

    }

public
function
updateSettings
(
)
{
if
(
!
isset
(
$
this
->
params
[
'index'
]
)
)
{
throw
new
exceptions
\
RuntimeException
(
"Index cannot be empty."
)
;
}
$
index
=
implode
(
','
,
$
this
->
params
[
'index'
]
)
;
$
body
=
array
(
"index"
=>
$
this
->
params
[
'indexSettings'
]
)
;
$
command
=
new
Command
(
)
;
$
command
->
index
(
$
index
)
->
id
(
'_settings'
)
->
action
(
'put'
)
->
data
(
json_encode
(
$
body
,
JSON_FORCE_OBJECT
)
)
;
$
this
->
batch
->
clearCommands
(
)
;
$
this
->
batch
->
addCommand
(
$
command
)
;
$
ret
=
parent
::
execute
(
)
;
//clear out mappings, settings
//$this->resetIndex();
return
$
ret
[
0
]
;
}

Update the settings of an index

@todo allow updating settings of all indices

@return \Sherlock\responses\IndexResponse
@throws exceptions\RuntimeException


public function execute()
    {

        if (!isset($this->params['uri'])) {
                        throw new exceptions\RuntimeException("URI is required for RawRequest");
        }

        if (!isset($this->params['method'])) {
                        throw new exceptions\RuntimeException("Method is required for RawRequest");
        }

        $command = new Command();
        $command->index($this->params['uri'])
            ->action($this->params['method']);

        if (isset($this->params['body'])) {
            $command->data($this->params['body']);
        }

        $this->batch->clearCommands();
        $this->batch->addCommand($command);

        $ret = parent::execute();

        return $ret[0];
    }

public
function
execute
(
)
{
if
(
!
isset
(
$
this
->
params
[
'uri'
]
)
)
{
throw
new
exceptions
\
RuntimeException
(
"URI is required for RawRequest"
)
;
}
if
(
!
isset
(
$
this
->
params
[
'method'
]
)
)
{
throw
new
exceptions
\
RuntimeException
(
"Method is required for RawRequest"
)
;
}
$
command
=
new
Command
(
)
;
$
command
->
index
(
$
this
->
params
[
'uri'
]
)
->
action
(
$
this
->
params
[
'method'
]
)
;
if
(
isset
(
$
this
->
params
[
'body'
]
)
)
{
$
command
->
data
(
$
this
->
params
[
'body'
]
)
;
}
$
this
->
batch
->
clearCommands
(
)
;
$
this
->
batch
->
addCommand
(
$
command
)
;
$
ret
=
parent
::
execute
(
)
;
return
$
ret
[
0
]
;
}

Execute the RawRequest

@throws \Sherlock\common\exceptions\RuntimeException
@return \Sherlock\responses\QueryResponse


public function toJSON()
    {
        $finalQuery = "";

        if (isset($this->params['body'])) {
            $finalQuery = json_encode($this->params['body']);
        }

        return $finalQuery;
    }

public function toJSON ( ) { $ finalQuery = "" ; if ( isset ( $ this -> params [ 'body' ] ) ) { $ finalQuery = json_encode ( $ this -> params [ 'body' ] ) ; } return $ finalQuery ; }

Return a JSON representation of the final search request

@return string


public function sort($value)
    {
        $args = func_get_args();

        //single param, array of sorts
        if (count($args) == 1 && is_array($args[0])) {
            $args = $args[0];
        }

        foreach ($args as $arg) {
            if ($arg instanceof \Sherlock\components\SortInterface) {
                $this->params['sort'][] = $arg->toArray();
            }
        }

        return $this;
    }

public
function
sort
(
$
value
)
{
$
args
=
func_get_args
(
)
;
//single param, array of sorts
if
(
count
(
$
args
)
==
1
&&
is_array
(
$
args
[
0
]
)
)
{
$
args
=
$
args
[
0
]
;
}
foreach
(
$
args
as
$
arg
)
{
if
(
$
arg
instanceof
\
Sherlock
\
components
\
SortInterface
)
{
$
this
->
params
[
'sort'
]
[
]
=
$
arg
->
toArray
(
)
;
}
}
return
$
this
;
}

Sets the query or queries that will be executed

@param  \Sherlock\components\SortInterface|array,... $value

@return SearchRequest


public function facets($facets)
    {
        $this->params['facets'] = array();
        if (is_array($facets)){
            $args = $facets;
        }else{
            $args = func_get_args();
        }
        foreach ($args as $arg) {
            if ($arg instanceof FacetInterface) {
                $this->params['facets'][] = $arg;
            }
        }

        return $this;
    }

public function facets ( $ facets ) { $ this -> params [ 'facets' ] = array ( ) ; if ( is_array ( $ facets ) ) { $ args = $ facets ; } else { $ args = func_get_args ( ) ; } foreach ( $ args as $ arg ) { if ( $ arg instanceof FacetInterface ) { $ this -> params [ 'facets' ] [ ] = $ arg ; } } return $ this ; }

Sets the facets to operate on

@param  FacetInterface $facets     types to query
@param  FacetInterface $facets,... types to query

@return SearchRequest


private function composeFinalQuery()
    {
        $finalQuery = array();

        if (isset($this->params['fields'])) {
            $finalQuery['fields'] = $this->params['fields'];
        }

        if (isset($this->params['query']) && $this->params['query'] instanceof components\QueryInterface) {
            $finalQuery['query'] = $this->params['query']->toArray();
        }

        if (isset($this->params['filter']) && $this->params['filter'] instanceof components\FilterInterface) {
            $finalQuery['filter'] = $this->params['filter']->toArray();
        }

        if (isset($this->params['facets'])) {
            $tFacets = array();
            foreach ($this->params['facets'] as $facet) {
                //@todo Investigate a better way of doing this
                //array_merge is supposedly slow when merging arrays of arrays
                if ($facet instanceof FacetInterface) {
                    $tFacets = array_merge($tFacets, $facet->toArray());
                }
            }
            $finalQuery['facets'] = $tFacets;
            unset($tFacets);
        }

        if (isset($this->params['highlight']) && $this->params['highlight'] instanceof components\HighlightInterface) {
            $finalQuery['highlight'] = $this->params['highlight']->toArray();
        }

        foreach (array('from', 'size', 'timeout', 'sort', 'min_score') as $key) {
            if (isset($this->params[$key])) {
                $finalQuery[$key] = $this->params[$key];
            }
        }

        $finalQuery = json_encode($finalQuery, true);

        return $finalQuery;
    }

Composes the final query, aggregating together the queries, filters, facets and associated parameters

@return string
@throws \Sherlock\common\exceptions\RuntimeException

Composes the final query aggregating together the queries filters facets and associated parameters


protected function convertParams($params)
    {
        $paramArray = array();
        foreach ($params as $param) {
            if (isset($this->params[$param]) === true) {
                $paramArray[$param] = $this->params[$param];
            }
        }

        return $paramArray;
    }

protected function convertParams ( $ params ) { $ paramArray = array ( ) ; foreach ( $ params as $ param ) { if ( isset ( $ this -> params [ $ param ] ) === true ) { $ paramArray [ $ param ] = $ this -> params [ $ param ] ; } } return $ paramArray ; }

Convert a parameter list into a composed parameter request array

@param array $params array of parameters to convert into assoc array

@return array


public function addNode($host, $port = 9200)
    {
        $this->settings['cluster']->addNode($host, $port, $this->settings['cluster.autodetect']);

        return $this;
    }

public function addNode ( $ host , $ port = 9200 ) { $ this -> settings [ 'cluster' ] -> addNode ( $ host , $ port , $ this -> settings [ 'cluster.autodetect' ] ) ; return $ this ; }

Add a new node to the ES cluster

@param  string                                     $host server host address (either IP or domain)
@param  int                                        $port ElasticSearch port (defaults to 9200)

@return \Sherlock\Sherlock
@throws common\exceptions\BadMethodCallException
@throws common\exceptions\InvalidArgumentException


public function must($value)
    {
        $args = $this->normalizeFuncArgs(func_get_args());

        foreach ($args as $arg) {
            if ($arg instanceof FilterInterface) {
                $this->params['must'][] = $arg->toArray();
            }
        }

        return $this;
    }

public function must ( $ value ) { $ args = $ this -> normalizeFuncArgs ( func_get_args ( ) ) ; foreach ( $ args as $ arg ) { if ( $ arg instanceof FilterInterface ) { $ this -> params [ 'must' ] [ ] = $ arg -> toArray ( ) ; } } return $ this ; }

Must clause of Bool

@param FilterInterface|array $value Single or array of FilterInterface objects

@return $this


public function document($id)
    {
        if (!$this->batch instanceof BatchCommand) {
                        throw new exceptions\RuntimeException("Cannot delete a document from an external BatchCommandInterface");
        }

        $command = new Command();
        $command->id($id)
            ->action('delete');

        //Only doing this because typehinting is wonky without it...
        if ($this->batch instanceof BatchCommand) {
            $this->batch->addCommand($command);
        }

        return $this;
    }

The document to delete

@param  null                                         $id

@throws \Sherlock\common\exceptions\RuntimeException
@return DeleteDocumentRequest


public function documents($values)
    {
        if ($values instanceof BatchCommandInterface) {
            $this->batch = $values;
        } elseif (is_array($values)) {

            $isBatch = true;
            $batch   = new BatchCommand();

            /**
             * @param mixed $value
             */
            $map = function ($value) use ($isBatch, $batch) {
                if (!$value instanceof Command) {
                    $isBatch = false;
                } else {
                    $batch->addCommand($value);
                }
            };

            array_map($map, $values);

            if (!$isBatch) {
                                throw new exceptions\BadMethodCallException("If an array is supplied, all elements must be a Command object.");
            }

            $this->batch = $batch;

        } else {
                        throw new exceptions\BadMethodCallException("Documents method only accepts arrays of Commands or BatchCommandInterface objects");
        }

        return $this;

    }

/**
             * @param mixed $value
             */

Accepts an array of Commands or a BatchCommand

@param array|BatchCommandInterface $values

@return $this
@throws \Sherlock\common\exceptions\BadMethodCallException


public function execute()
    {

        //if this is an internal Sherlock BatchCommand, make sure index/types/action are filled
        if ($this->batch instanceof BatchCommand) {
            $this->batch->fillIndex($this->params['index'][0])
                ->fillType($this->params['type'][0]);
        }

        return parent::execute();
    }

Perform the delete operation

@throws exceptions\RuntimeException
@return \Sherlock\responses\DeleteResponse


public function request($url, $method = "GET", $postData = null, $headers = null, $options = null)
    {
        $newRequest = new Request($url, $method);
        if ($postData) {
            $newRequest->setPostData($postData);
        }
        if ($headers) {
            $newRequest->setHeaders($headers);
        }
        if ($options) {
            $newRequest->setOptions($options);
        }

        return $this->add($newRequest);
    }

public function request ( $ url , $ method = "GET" , $ postData = null , $ headers = null , $ options = null ) { $ newRequest = new Request ( $ url , $ method ) ; if ( $ postData ) { $ newRequest -> setPostData ( $ postData ) ; } if ( $ headers ) { $ newRequest -> setHeaders ( $ headers ) ; } if ( $ options ) { $ newRequest -> setOptions ( $ options ) ; } return $ this -> add ( $ newRequest ) ; }

Create new Request and add it to the request queue

@param  string       $url
@param  string       $method
@param  array|string $postData
@param  array        $headers
@param  array        $options

@return RollingCurl


public function post($url, $postData = null, $headers = null, $options = null)
    {
        return $this->request($url, "POST", $postData, $headers, $options);
    }

public function post ( $ url , $ postData = null , $ headers = null , $ options = null ) { return $ this -> request ( $ url , "POST" , $ postData , $ headers , $ options ) ; }

Perform POST request

@param  string       $url
@param  array|string $postData
@param  array        $headers
@param  array        $options

@return RollingCurl


public function put($url, $putData = null, $headers = null, $options = null)
    {
        return $this->request($url, "PUT", $putData, $headers, $options);
    }

public function put ( $ url , $ putData = null , $ headers = null , $ options = null ) { return $ this -> request ( $ url , "PUT" , $ putData , $ headers , $ options ) ; }

Perform PUT request

@param  string      $url
@param  null        $putData
@param  array       $headers
@param  array       $options

@return RollingCurl


public function delete($url, $headers = null, $options = null)
    {
        return $this->request($url, "DELETE", null, $headers, $options);
    }

public function delete ( $ url , $ headers = null , $ options = null ) { return $ this -> request ( $ url , "DELETE" , null , $ headers , $ options ) ; }

Perform DELETE request

@param  string      $url
@param  array       $headers
@param  array       $options

@return RollingCurl


public function execute()
    {

        $master = curl_multi_init();

        // start the first batch of requests
        $firstBatch = $this->getNextPendingRequests($this->getSimultaneousLimit());

        // what a silly "error"
        if (count($firstBatch) == 0) {
            return;
        }

        foreach ($firstBatch as $request) {
            // setup the curl request, queue it up, and put it in the active array
            $ch      = curl_init();
            $options = $this->prepareRequestOptions($request);
            curl_setopt_array($ch, $options);
            curl_multi_add_handle($master, $ch);
            $this->activeRequests[(string)$ch] = $request;
        }

        do {

            while (($execrun = curl_multi_exec($master, $running)) == CURLM_CALL_MULTI_PERFORM) {
                ;
            }

            if ($execrun != CURLM_OK) {
                // todo: throw exception
                break;
            }

            // a request was just completed -- find out which one
            while ($transfer = curl_multi_info_read($master)) {

                // get the request object back and put the curl response into it
                $key     = (string)$transfer['handle'];
                $request = $this->activeRequests[$key];
                $request->setResponseText(curl_multi_getcontent($transfer['handle']));
                $request->setResponseErrno(curl_errno($transfer['handle']));
                $request->setResponseError(curl_error($transfer['handle']));
                $request->setResponseInfo(curl_getinfo($transfer['handle']));

                // if there is a callback, run it
                if (is_callable($this->callback)) {
                    $callback = $this->callback;
                    $callback($request, $this);
                }

                // remove the request from the list of active requests
                unset($this->activeRequests[$key]);

                // move the request to the completed set
                $this->completedRequests[] = $request;

                // start a new request (it's important to do this before removing the old one)
                if ($nextRequest = $this->getNextPendingRequest()) {
                    // setup the curl request, queue it up, and put it in the active array
                    $ch      = curl_init();
                    $options = $this->prepareRequestOptions($nextRequest);
                    curl_setopt_array($ch, $options);
                    curl_multi_add_handle($master, $ch);
                    $this->activeRequests[(string)$ch] = $nextRequest;
                }

                // remove the curl handle that just completed
                curl_multi_remove_handle($master, $transfer['handle']);

            }

            if ($running) {
                curl_multi_select($master, $this->timeout);
            }

            // keep the loop going as long as multi_exec says it is running
        } while ($running);

        curl_multi_close($master);
    }


public function addOptions($options)
    {
        if (!is_array($options)) {
            throw new \InvalidArgumentException("options must be an array");
        }
        $this->options = $options + $this->options;

        return $this;
    }

public
function
addOptions
(
$
options
)
{
if
(
!
is_array
(
$
options
)
)
{
throw
new
\
InvalidArgumentException
(
"options must be an array"
)
;
}
$
this
->
options
=
$
options
+
$
this
->
options
;
return
$
this
;
}

Override and add options

@param  array                     $options

@throws \InvalidArgumentException
@return RollingCurl


public function onRequestExecute(RequestEvent $event)
    {
        $request = $event->getRequest();

        //Make sure we have some nodes to choose from
        if (count($this->nodes) === 0) {
            throw new RuntimeException("No nodes in cluster, request failed");
        }

        //Choose a random node
        $request->node = $this->nodes[array_rand($this->nodes)];

    }

Triggered just prior to a request being executed
Inject a random node into the Request object

@param  RequestEvent                $event

@throws exceptions\RuntimeException


private function autodetect_parseNodes()
    {
        foreach ($this->nodes as $node) {
            try {
                $client   = new Client('http://' . $node['host'] . ':' . $node['port']);
                $request  = $client->get('/_nodes/http');
                $response = $request->send()->json();

                foreach ($response['nodes'] as $newNode) {

                    //we don't want http-inaccessible nodes
                    if (!isset($newNode['http_address'])) {
                        continue;
                    }

                    preg_match('/inet\[\/([0-9\.]+):([0-9]+)\]/i', $newNode['http_address'], $match);

                    $tNode = array('host' => $match[1], 'port' => $match[2]);

                    //use host as key so that we don't add duplicates
                    $this->nodes[$match[1]] = $tNode;

                }

                //we have the complete node list, no need to keep checking
                break;

            } catch (\Guzzle\Http\Exception\BadResponseException $e) {
                //error with this node, continue onto the next one
            }
        }
    }

Autodetect the nodes in this cluster through Cluster State API


public function document($value, $id = null, $update = false)
    {
        if (!$this->batch instanceof BatchCommand) {
                        throw new exceptions\RuntimeException("Cannot add a new document to an external BatchCommandInterface");
        }

        $this->finalizeCurrentCommand();

        if (is_array($value)) {
            $this->params['doc'] = $value;

        } elseif (is_string($value)) {
            $this->params['doc'] = json_decode($value, true);
        }

        if ($id !== null) {
            $this->currentCommand->id($id)
                ->action('put');

            $this->params['update'] = $update;

        } else {
            $this->currentCommand->action('post');

            $this->params['update'] = false;
        }

        return $this;
    }

The document to index

@param  \string|\array $value
@param  null           $id
@param bool|null       $update

@throws \Sherlock\common\exceptions\RuntimeException
@return IndexDocumentRequest


public function execute()
    {

        /*
        foreach (array('index', 'type') as $key) {
            if (!isset($this->params[$key])) {
                                throw new exceptions\RuntimeException($key." cannot be empty.");
            }
        }

        foreach (array('index', 'type') as $key) {
            if (count($this->params[$key]) > 1) {
                                throw new exceptions\RuntimeException("Only one ".$key." may be inserted into at a time.");
            }
        }

        */

        $this->finalizeCurrentCommand();

        //if this is an internal Sherlock BatchCommand, make sure index/types/action are filled
        if ($this->batch instanceof BatchCommand) {
            if (isset($this->params['index'][0])) {
                $this->batch->fillIndex($this->params['index'][0]);
            }

            if (isset($this->params['type'][0])) {
                $this->batch->fillType($this->params['type'][0]);
            }

        }

        return parent::execute();
    }

Perform the indexing operation

@throws exceptions\RuntimeException
@return \Sherlock\responses\IndexResponse


private function finalizeCurrentCommand()
    {

        if ($this->batch instanceof BatchCommand && $this->currentCommand !== null) {

            if (isset($this->params['update']) && $this->params['update'] === true) {
                $this->currentCommand->action('post')->suffix('_update');

                if ($this->params['doc'] !== null) {
                    $data["doc"] = $this->params['doc'];
                }

                if ($this->params['updateScript'] !== null) {
                    $data["script"] = $this->params['updateScript'];
                }

                if ($this->params['updateParams'] !== null) {
                    $data["params"] = $this->params['updateParams'];
                }

                if ($this->params['updateUpsert'] !== null) {
                    $data["upsert"] = $this->params['updateUpsert'];
                }

                $this->currentCommand->data($data);

            } else {
                $this->currentCommand->data($this->params['doc']);
            }

            $this->batch->addCommand($this->currentCommand);

            $this->params['update'] = false;
        }

        $this->currentCommand = new Command();
    }

private function finalizeCurrentCommand ( ) { if ( $ this -> batch instanceof BatchCommand && $ this -> currentCommand !== null ) { if ( isset ( $ this -> params [ 'update' ] ) && $ this -> params [ 'update' ] === true ) { $ this -> currentCommand -> action ( 'post' ) -> suffix ( '_update' ) ; if ( $ this -> params [ 'doc' ] !== null ) { $ data [ "doc" ] = $ this -> params [ 'doc' ] ; } if ( $ this -> params [ 'updateScript' ] !== null ) { $ data [ "script" ] = $ this -> params [ 'updateScript' ] ; } if ( $ this -> params [ 'updateParams' ] !== null ) { $ data [ "params" ] = $ this -> params [ 'updateParams' ] ; } if ( $ this -> params [ 'updateUpsert' ] !== null ) { $ data [ "upsert" ] = $ this -> params [ 'updateUpsert' ] ; } $ this -> currentCommand -> data ( $ data ) ; } else { $ this -> currentCommand -> data ( $ this -> params [ 'doc' ] ) ; } $ this -> batch -> addCommand ( $ this -> currentCommand ) ; $ this -> params [ 'update' ] = false ; } $ this -> currentCommand = new Command ( ) ; }

This is all horribly terible and will be ripped out as soon as possible.

Basically, This class stores an intermediate Command that maintains state across
chained requests, which allows updates (scripts, params, etc) to affect it.

The command is finalized when a new document is added, or the request is executed.
Finalization means collapsing the doc field data into a param, as well as updating
the action/suffix as necessary.

This is all horribly terible and will be ripped out as soon as possible .


private function currentCommandCheck()
    {
        $this->params['update'] = true;
        if ($this->currentCommand === null) {
            $this->currentCommand = new Command();
        }

    }

private function currentCommandCheck ( ) { $ this -> params [ 'update' ] = true ; if ( $ this -> currentCommand === null ) { $ this -> currentCommand = new Command ( ) ; } }

Simple helper function to check if the current command is populated
If not, create a new one

Simple helper function to check if the current command is populated If not create a new one


public function getGallery(Model $Model, $object_id = null)
    {
        $Album = new Album();

        if (!$object_id) {
            $object_id = $Model->id;
        }

        return $Album->getAttachedAlbum($Model->alias, $object_id);
    }

public function getGallery ( Model $ Model , $ object_id = null ) { $ Album = new Album ( ) ; if ( ! $ object_id ) { $ object_id = $ Model -> id ; } return $ Album -> getAttachedAlbum ( $ Model -> alias , $ object_id ) ; }

Get model gallery
@param Model $Model
@return mixed


public function init($model = null, $model_id = null)
    {
        # If there is a Model and ModelID on parameters, get or create a folder for it
        if ($model && $model_id) {
            # Searching for folder that belongs to this particular $model and $model_id
            if (!$album = $this->getAttachedAlbum($model, $model_id)) {
                # If there is no Album , lets create one for it
                $album = $this->createInitAlbum($model, $model_id);
            }
        } else {
            # If there is no model on parameters, lets create a generic folder
            $album = $this->createInitAlbum(null, null);
        }

        return $album;
    }

Create an album record on database
@param $model
@param $model_id


private function createInitAlbum($model = null, $model_id = null)
    {
        $this->save(
            array(
                'Album' => array(
                    'model' => $model,
                    'model_id' => $model_id,
                    'status' => 'draft',
                    'tags' => '',
                    'title' => $this->generateAlbumName($model, $model_id)
                )
            )
        );
        return $this->read(null);
    }

private function createInitAlbum ( $ model = null , $ model_id = null ) { $ this -> save ( array ( 'Album' => array ( 'model' => $ model , 'model_id' => $ model_id , 'status' => 'draft' , 'tags' => '' , 'title' => $ this -> generateAlbumName ( $ model , $ model_id ) ) ) ) ; return $ this -> read ( null ) ; }

Save album with a random name in database
@param null $model
@param null $model_id
@return mixed


private function generateAlbumName($model = null, $model_id = null)
    {
        $name = 'Album - ' . rand(111, 999);

        if ($model && $model_id) {
            $name = Inflector::humanize('Album ' . $model . ' - ' . $model_id);
        }

        return $name;
    }

private
function
generateAlbumName
(
$
model
=
,
$
model_id
=
)
{
$
name
=
'Album - '
.
rand
(
111
,
999
)
;
if
(
$
model
&&
$
model_id
)
{
$
name
=
Inflector
::
humanize
(
'Album '
.
$
model
.
' - '
.
$
model_id
)
;
}
return
$
name
;
}

Generate a random album name
@param null $model
@param null $model_id
@return string


public function upload($model = null, $model_id = null)
    {
        ini_set("memory_limit", "10000M");

        if (isset($this->params['gallery_id']) && !empty($this->params['gallery_id'])) {
            $album = $this->Album->findById($this->params['gallery_id']);
        } else {
            # If the gallery doesnt exists, create a new one and redirect back to this page with the
            # gallery_id
            $album = $this->Album->init($model, $model_id);

            # Redirect back to this page with an album ID
            $this->redirect(
                array(
                    'action' => 'upload',
                    'gallery_id' => $album['Album']['id']
                )
            );
        }

        $files = $album['Picture'];

        $this->set(compact('model', 'model_id', 'album', 'files'));
    }

Create or find the requested album
@param null $model
@param null $model_id


public function afterDelete()
    {
      if( $this->pictureToDelete ) {

        $this->deleteVersions($this->pictureToDelete);

        $this->pictureToDelete = null;
      }
    }

public function afterDelete ( ) { if ( $ this -> pictureToDelete ) { $ this -> deleteVersions ( $ this -> pictureToDelete ) ; $ this -> pictureToDelete = null ; } }

Remove all versions of the picture from the storage after delete the
record from the database


public function getResizeToSize()
    {
        $width = $height = 0;

        if (Configure::check('GalleryOptions.Pictures.resize_to.0')) {
            $width = Configure::read('GalleryOptions.Pictures.resize_to.0');
        }

        if (Configure::check('GalleryOptions.Pictures.resize_to.1')) {
            $height = Configure::read('GalleryOptions.Pictures.resize_to.1');
        }

        $crop = Configure::read('GalleryOptions.Pictures.resize_to.2');
        $action = $crop ? "crop" : "";

        return array(
            'width' => $width,
            'height' => $height,
            'action' => $action
        );
    }

public function getResizeToSize ( ) { $ width = $ height = 0 ; if ( Configure :: check ( 'GalleryOptions.Pictures.resize_to.0' ) ) { $ width = Configure :: read ( 'GalleryOptions.Pictures.resize_to.0' ) ; } if ( Configure :: check ( 'GalleryOptions.Pictures.resize_to.1' ) ) { $ height = Configure :: read ( 'GalleryOptions.Pictures.resize_to.1' ) ; } $ crop = Configure :: read ( 'GalleryOptions.Pictures.resize_to.2' ) ; $ action = $ crop ? "crop" : "" ; return array ( 'width' => $ width , 'height' => $ height , 'action' => $ action ) ; }

Return configured main image resize attributes
@return array


public function addImageStyles($path)
    {
        # Styles configured in bootstrap.php
        $sizes = Configure::read('GalleryOptions.Pictures.styles');

        $links = array();

        if (count($sizes)) {
            $root_url = WWW_ROOT;
            $relative_url = Router::url('/');

            # Current filename
            $filename = end(explode("/", $path));

            foreach ($sizes as $sizename => $size) {
                # Filename with size prefix. E.g: small-filename.jpg
                $modified = $sizename . "-" . $filename;
                # Get final path replacing absolute URl to application relative URL
                $final_path = str_replace($root_url, $relative_url, str_replace($filename, $modified, $path));
                # Add to array
                $links[$sizename] = $final_path;
            }
        }

        return $links;
    }

Add image styles configured in bootstrap.php

@param $path
@param array $sizes
@return array

Add image styles configured in bootstrap . php


public function deleteVersions($id)
    {
        # Remove all versions of the picture
        $pictures = $this->find(
            'all',
            array(
                'conditions' => array(
                    'Picture.main_id' => $id
                )
            )
        );

        if (count($pictures)) {
            foreach ($pictures as $pic) {
                # Remove file
                if (unlink($pic['Picture']['path'])) {
                    # Remove from database
                    $this->delete($pic['Picture']['id'], array('callback' => false));
                }
            }
        }

        return true;
    }

public
function
deleteVersions
(
$
id
)
{
# Remove all versions of the picture
$
pictures
=
$
this
->
find
(
'all'
,
array
(
'conditions'
=>
array
(
'Picture.main_id'
=>
$
id
)
)
)
;
if
(
count
(
$
pictures
)
)
{
foreach
(
$
pictures
as
$
pic
)
{
# Remove file
if
(
unlink
(
$
pic
[
'Picture'
]
[
'path'
]
)
)
{
# Remove from database
$
this
->
delete
(
$
pic
[
'Picture'
]
[
'id'
]
,
array
(
'callback'
=>
false
)
)
;
}
}
}
return
true
;
}

Remove all versions from a picture from the database and from the server

@param $id


public function savePicture($album_id, $filename, $path, $main_id = null, $style = 'full')
    {
        $this->create();

        # Save the record in database
        $picture = array(
            'Picture' => array(
                'album_id' => $album_id,
                'name' => $filename,
                'path' => $path,
                'main_id' => $main_id,
                'style' => $style
            )
        );

        $this->save($picture);

        return $this->id;
    }

public
function
savePicture
(
$
album_id
,
$
filename
,
$
path
,
$
main_id
=
,
$
style
=
'full'
)
{
$
this
->
create
(
)
;
# Save the record in database
$
picture
=
array
(
'Picture'
=>
array
(
'album_id'
=>
$
album_id
,
'name'
=>
$
filename
,
'path'
=>
$
path
,
'main_id'
=>
$
main_id
,
'style'
=>
$
style
)
)
;
$
this
->
save
(
$
picture
)
;
return
$
this
->
id
;
}

Save picture information in database

@param $album_id
@param $filename
@param $filesize
@param $path
@param null $main_id
@param string $style
@return mixed


public function createExtraImages($styles, $filename, $tmp_name, $album_id, $main_id, $image_name)
    {
        $ext = pathinfo($filename, PATHINFO_EXTENSION);

        if (count($styles)) {
            foreach ($styles as $style_name => $style) {
                $width = $style[0];
                $height = $style[1];
                $crop = $style[2] ? "crop" : "";

                # eg: medium-1982318927313.jpg
                $custom_filename = $style_name . '-' . $image_name . '.' . $ext;

                $path = $this->generateFilePath($album_id, $custom_filename);

                try {
                    $this->uploadFile(
                        $path,
                        $album_id,
                        $style_name . '-' . $filename,
                        $tmp_name,
                        $width,
                        $height,
                        $crop,
                        true,
                        $main_id,
                        $style_name
                    );
                } catch (ForbiddenException $e) {
                    throw new ForbiddenException($e->getMessage());
                }
            }
        }
    }

public
function
createExtraImages
(
$
styles
,
$
filename
,
$
tmp_name
,
$
album_id
,
$
main_id
,
$
image_name
)
{
$
ext
=
pathinfo
(
$
filename
,
PATHINFO_EXTENSION
)
;
if
(
count
(
$
styles
)
)
{
foreach
(
$
styles
as
$
style_name
=>
$
style
)
{
$
width
=
$
style
[
0
]
;
$
height
=
$
style
[
1
]
;
$
crop
=
$
style
[
2
]
"crop"
:
""
;
# eg: medium-1982318927313.jpg
$
custom_filename
=
$
style_name
.
'-'
.
$
image_name
.
'.'
.
$
ext
;
$
path
=
$
this
->
generateFilePath
(
$
album_id
,
$
custom_filename
)
;
try
{
$
this
->
uploadFile
(
$
path
,
$
album_id
,
$
style_name
.
'-'
.
$
filename
,
$
tmp_name
,
$
width
,
$
height
,
$
crop
,
true
,
$
main_id
,
$
style_name
)
;
}
catch
(
ForbiddenException
$
e
)
{
throw
new
ForbiddenException
(
$
e
->
getMessage
(
)
)
;
}
}
}
}

Create extra images from a original one bases on
styles defined on bootstrap.php

@param $styles
@param $filename
@param $filesize
@param $tmp_name
@param $album_id
@param $main_id
@param $image_name
@throws ForbiddenException

Create extra images from a original one bases on styles defined on bootstrap . php


function Zebra_Image()
    {

        // set default values for properties
        $this->chmod_value = 0755;

        $this->error = 0;

        $this->jpeg_quality = 85;

        $this->png_compression = 9;

        $this->preserve_aspect_ratio = $this->preserve_time = $this->enlarge_smaller_images = true;

        $this->sharpen_images = false;

        $this->source_path = $this->target_path = '';

    }

function
Zebra_Image
(
)
{
// set default values for properties
$
this
->
chmod_value
=
0755
;
$
this
->
error
=
0
;
$
this
->
jpeg_quality
=
85
;
$
this
->
png_compression
=
9
;
$
this
->
preserve_aspect_ratio
=
$
this
->
preserve_time
=
$
this
->
enlarge_smaller_images
=
true
;
$
this
->
sharpen_images
=
false
;
$
this
->
source_path
=
$
this
->
target_path
=
''
;
}

Constructor of the class.

Initializes the class and the default properties

@return void


function _prepare_image($width, $height, $background_color = '#FFFFFF')
    {

        // create a blank image
        $identifier = imagecreatetruecolor((int)$width <= 0 ? 1 : (int)$width, (int)$height <= 0 ? 1 : (int)$height);

        // if we are creating a PNG image
        if ($this->target_type == 'png' && $background_color == -1) {

            // disable blending
            imagealphablending($identifier, false);

            // allocate a transparent color
            $transparent_color = imagecolorallocatealpha($identifier, 0, 0, 0, 127);

            // fill the image with the transparent color
            imagefill($identifier, 0, 0, $transparent_color);

            //save full alpha channel information
            imagesavealpha($identifier, true);

            // if source image is a transparent GIF
        } elseif ($this->target_type == 'gif' && $background_color == -1 && $this->source_transparent_color_index >= 0) {

            // allocate the source image's transparent color also to the new image resource
            $transparent_color = imagecolorallocate(
                $identifier,
                $this->source_transparent_color['red'],
                $this->source_transparent_color['green'],
                $this->source_transparent_color['blue']
            );

            // fill the background of the new image with transparent color
            imagefill($identifier, 0, 0, $transparent_color);

            // from now on, every pixel having the same RGB as the transparent color will be transparent
            imagecolortransparent($identifier, $transparent_color);

            // for other image types
        } else {

            // if transparent background color specified, revert to white
            if ($background_color == -1) {
                $background_color = '#FFFFFF';
            }

            // convert hex color to rgb
            $background_color = $this->_hex2rgb($background_color);

            // prepare the background color
            $background_color = imagecolorallocate(
                $identifier,
                $background_color['r'],
                $background_color['g'],
                $background_color['b']
            );

            // fill the image with the background color
            imagefill($identifier, 0, 0, $background_color);

        }

        // return the image's identifier
        return $identifier;

    }

Creates a blank image of given width, height and background color.

@param  integer $width Width of the new image.

@param  integer $height Height of the new image.

@param  string $background_color (Optional) The hexadecimal color of the background.

Can also be -1 case in which the script will try to create a transparent
image, if possible.

Default is "#FFFFFF".

@return                                 Returns the identifier of the newly created image.

@access private

Creates a blank image of given width height and background color .


public function configure()
    {
        $files_path = WWW_ROOT . 'files' . DS;
        if (!file_exists($files_path)) {
            mkdir($files_path, 0755);
        }
        $galleries_path = $files_path . 'gallery' . DS;
        if (!file_exists($galleries_path)) {
            mkdir($galleries_path, 0755);
        }

        $this->_configureDatabase();

        $this->Session->setFlash('Success! Gallery is now installed in your app.');

        $this->redirect(
            array(
                'controller' => 'gallery',
                'action' => 'index',
                'plugin' => 'gallery'
            )
        );

        $this->render(false, false);
    }

Configure galleries and create mysql tables


private function _configureDatabase()
    {
        try {
            $db = ConnectionManager::getDataSource('default');

            if (!$db->isConnected()) {
                throw new Exception("You need to connect to a MySQL Database to use this Plugin.");
            }

            /** Verify if the tables already exists */
            if (!$this->_checkTables($db->listSources())) {
                $this->_setupDatabase($db);
            }

            # Create config file
            $this->_createConfigFile();

            return;

        } catch (Exception $e) {
            $this->Session->setFlash($e->getMessage());
            $this->redirect('/');
        }
    }


private function _createConfigFile()
    {
        $destinationPath = App::pluginPath('Gallery') . 'config' . DS . 'config.php';

        if (!file_exists($destinationPath)) {
            $configFile = new File(App::pluginPath('Gallery') . 'config' . DS . 'config.php.install');

            $configFile->copy($destinationPath);
        }
    }

private function _createConfigFile ( ) { $ destinationPath = App :: pluginPath ( 'Gallery' ) . 'config' . DS . 'config.php' ; if ( ! file_exists ( $ destinationPath ) ) { $ configFile = new File ( App :: pluginPath ( 'Gallery' ) . 'config' . DS . 'config.php.install' ) ; $ configFile -> copy ( $ destinationPath ) ; } }

Create the config file copying the config.php.install file

Create the config file copying the config . php . install file


public function checkSummaries() {
		$need_summaries = array();

		foreach ( $this->service['operations'] as $method => $info ) {
			if ( ! isset( $info['summary'] ) ) {
				$need_summaries[] = $method;
			}
		}

		if ( ! empty( $need_summaries ) ) {

			echo PHP_EOL;
			echo 'Please set summaries for all operations to generate docs.' . PHP_EOL;
			echo 'The following operations are missing a \'summary\' value in service.php:' . PHP_EOL;

			foreach ( $need_summaries as $method ) {
				echo '	' . $method . PHP_EOL;
			}

			echo PHP_EOL;

			exit;

		}
	}

Verify that all service operations have summaries set before continuing


public function generate() {

		ob_start();

		foreach ( $this->service['operations'] as $method => $info ) {

			// Add method to info array for more convenient templates
			$info['method'] = $method;

			// Heading
			echo $this->template( $this->tmpl_heading, $info );

			// Code Block start
			echo $this->template( $this->tmpl_code_block_start, $info );

			if ( isset( $info['parameters'] ) ) {

				// Method call (with parameters) start
				echo $this->template( $this->tmpl_method_with_params_start, $info );

				// Parameters
				foreach ( $info['parameters'] as $param => $param_info ) {
					$param_info['param'] = $param;
					echo $this->template( $this->tmpl_method_parameter, $param_info );
				}

				// Method call end
				echo $this->template( $this->tmpl_method_with_params_end, $info );

			}else {

				// Method call (no parameters)
				echo $this->template( $this->tmpl_method_without_params, $info );

			}

			// Code Block end
			echo $this->template( $this->tmpl_code_block_end, $info );

		}

		$this->checkTestCoverage();

		$this->docs_markdown = ob_get_clean();

		return $this->docs_markdown;
	}

Output docs for each service operation in Markdown format.

Output docs for each service operation in Markdown format .


public function link($model = null, $model_id = null, $html_options = array())
    {
        return $this->_View->Html->link(
            __('Upload pictures'),
            array(
                'controller' => 'albums',
                'action' => 'upload',
                'plugin' => 'gallery',
                $model,
                $model_id
            ),
            $html_options
        );
    }

public
function
link
(
$
model
=
,
$
model_id
=
,
$
html_options
=
array
(
)
)
{
return
$
this
->
_View
->
Html
->
link
(
__
(
'Upload pictures'
)
,
array
(
'controller'
=>
'albums'
,
'action'
=>
'upload'
,
'plugin'
=>
'gallery'
,
$
model
,
$
model_id
)
,
$
html_options
)
;
}

Gallery link helper

This helper will create an link to a new or existing gallery

If no arguments are passed this will create a new gallery everytime the link are clicked.

When model & model_id arguments are passed, this will redirect to this specific gallery (it will also create a
new one if didn't exists)

Example:
<?php echo $this->Gallery->button('product', 1) ?>

@param null $model
@param null $model_id
@param array $html_options
@return string


public function showroom(
        $model = null,
        $model_id = null,
        $album_id = null,
        $style = 'medium',
        $html_options = array('jquery' => true, 'swipebox' => true))
    {

        $album = $this->getAlbum($model, $model_id, $album_id);

        if (!empty($album)) {
            # Load scripts for the showroom (jquery, bootstrap, swipebox)
            $this->_loadScripts($html_options);

            # Render the showroom
            $this->showroomTmpl($album, $style);
        } else {
            # Album doesn't exists
            $this->_noPhotosMessageTmpl();
        }

        return;
    }

Render a gallery with thumbnails

@example
<?php $this->Gallery->showroom('product', 10) ?>

@param null $model
@param null $model_id
@param null $album_id
@return string


public function showroomTmpl($album, $style = 'medium')
    {
        if (empty($album['Picture'])) {
            $this->_noPhotosMessageTmpl();
        } else {
            foreach ($album['Picture'] as $picture) {
                $this->_thumbnailTmpl($picture, $style);
            }
        }
    }

public function showroomTmpl ( $ album , $ style = 'medium' ) { if ( empty ( $ album [ 'Picture' ] ) ) { $ this -> _noPhotosMessageTmpl ( ) ; } else { foreach ( $ album [ 'Picture' ] as $ picture ) { $ this -> _thumbnailTmpl ( $ picture , $ style ) ; } } }

This method use a album object to loop in all pictures and
show them using a bootstrap html pattern.

@param $album

This method use a album object to loop in all pictures and show them using a bootstrap html pattern .


private function _loadScripts($scripts = array('jquery' => true, 'swipebox' => true))
    {
        if (!isset($scripts['jquery']) || (isset($scripts['jquery']) && $scripts['jquery'] == true)) {
            echo $this->_View->Html->script(
                'http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js',
                array('block' => 'script'));
        }

        if (!isset($scripts['swipebox']) || (isset($scripts['swipebox']) && $scripts['swipebox'] == true)) {
            echo $this->_View->Html->css(
                'https://cdnjs.cloudflare.com/ajax/libs/jquery.swipebox/1.3.0.2/css/swipebox.min.css',
                array('block' => 'css'));
            echo $this->_View->Html->script(array(
                'https://cdnjs.cloudflare.com/ajax/libs/jquery.swipebox/1.3.0.2/js/jquery.swipebox.min.js',
                'Gallery.interface'
            ),
                array('block' => 'script'));
        }
    }

Load scripts for using on showroom

@param bool $jquery


public function delete($id)
    {
        # Delete the picture and all its versions
        $this->Picture->delete($id);

        $this->render(false, false);
    }

Delete an image and all its versions from database
@param $id


public function sort()
    {
        if ($this->request->is('post')) {
            $order = explode(",", $_POST['order']);
            $i = 1;
            foreach ($order as $photo) {
                $this->Picture->read(null, $photo);
                $this->Picture->set('order', $i);
                $this->Picture->save();
                $i++;
            }
        }

        $this->render(false, false);
    }

public function sort ( ) { if ( $ this -> request -> is ( 'post' ) ) { $ order = explode ( "," , $ _POST [ 'order' ] ) ; $ i = 1 ; foreach ( $ order as $ photo ) { $ this -> Picture -> read ( null , $ photo ) ; $ this -> Picture -> set ( 'order' , $ i ) ; $ this -> Picture -> save ( ) ; $ i ++ ; } } $ this -> render ( false , false ) ; }


public function listChannelSections($parameters)
    {
        $this->apiUri   = $this->baseUri . '/channelSections';
        $this->filters  = [
            'channelId',
            'id',
        ];

        if (empty($parameters) || !isset($parameters['part'])) {
            throw new \InvalidArgumentException(
                'Missing the required "part" parameter.'
            );
        }

        $response = $this->callApi($parameters);

        return json_decode($response, true);
    }

Returns a list of channelSection resources that match the request criteria.

For more in-depth info check out the YouTube API documentation at
https://developers.google.com/youtube/v3/docs/channelSections/list.

@access  public
@param   array   $parameters An array of parameters to pass to the API.
@throws  \InvalidArgumentException
@return  array

Returns a list of channelSection resources that match the request criteria .


public function start()
    {
    	if (!$this->simulation) {
			$sockets = [];
			socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $sockets);
			$pid = getmypid();

			$this->pid = $this->forkThread([$this, 'onWorkerStart'], [$sockets[1], $pid]);
			$this->toChild = $sockets[0];
			socket_set_nonblock($this->toChild);
		}
    }

public function start ( ) { if ( ! $ this -> simulation ) { $ sockets = [ ] ; socket_create_pair ( AF_UNIX , SOCK_STREAM , 0 , $ sockets ) ; $ pid = getmypid ( ) ; $ this -> pid = $ this -> forkThread ( [ $ this , 'onWorkerStart' ] , [ $ sockets [ 1 ] , $ pid ] ) ; $ this -> toChild = $ sockets [ 0 ] ; socket_set_nonblock ( $ this -> toChild ) ; } }

Starts a worker and begins listening for incoming payload.
This method should not be invoked when new object is constructing
because a Worker can be cloned before starting working.
@throws \Exception

Starts a worker and begins listening for incoming payload . This method should not be invoked when new object is constructing because a Worker can be cloned before starting working .


public function stop($wait = false)
    {
    	if ($this->simulation) {
			$this->state = self::TERMINATED;
			return true;
		}

        if (!is_dir('/proc/'.$this->pid))
            return null;

        $this->state = self::TERMINATING;

        if (!posix_kill($this->pid, SIGTERM))
            return false;

        if ($wait) {
            pcntl_waitpid($this->pid, $status);
            $this->state = self::TERMINATED;
        } else {
            if (!is_dir('/proc/'.$this->pid))
                $this->state = self::TERMINATED;
        }
        return true;
    }

public function stop ( $ wait = false ) { if ( $ this -> simulation ) { $ this -> state = self :: TERMINATED ; return true ; } if ( ! is_dir ( '/proc/' . $ this -> pid ) ) return null ; $ this -> state = self :: TERMINATING ; if ( ! posix_kill ( $ this -> pid , SIGTERM ) ) return false ; if ( $ wait ) { pcntl_waitpid ( $ this -> pid , $ status ) ; $ this -> state = self :: TERMINATED ; } else { if ( ! is_dir ( '/proc/' . $ this -> pid ) ) $ this -> state = self :: TERMINATED ; } return true ; }

Stops a worker and ends the process
@param boolean $wait If true, this method will hold execution till the process end
@return boolean Null, if worker is not active. False, if signal can't be sent to worker.
True, if signal sent OR signal sent and worker terminated (if $wait = true).


public function kill($wait = false)
    {
		if ($this->simulation) {
			$this->state = self::TERMINATED;
			return true;
		}

        if (!is_dir('/proc/'.$this->pid))
            return null;

        $this->state = self::TERMINATING;

        if (!posix_kill($this->pid, SIGKILL))
            return false;

        if ($wait) {
            pcntl_waitpid($this->pid, $status);
            $this->state = self::TERMINATED;
        } else {
            if (!is_dir('/proc/'.$this->pid))
                $this->state = self::TERMINATED;
        }
        return true;
    }

public function kill ( $ wait = false ) { if ( $ this -> simulation ) { $ this -> state = self :: TERMINATED ; return true ; } if ( ! is_dir ( '/proc/' . $ this -> pid ) ) return null ; $ this -> state = self :: TERMINATING ; if ( ! posix_kill ( $ this -> pid , SIGKILL ) ) return false ; if ( $ wait ) { pcntl_waitpid ( $ this -> pid , $ status ) ; $ this -> state = self :: TERMINATED ; } else { if ( ! is_dir ( '/proc/' . $ this -> pid ) ) $ this -> state = self :: TERMINATED ; } return true ; }

Stops a worker and kills the process
@param boolean $wait If true, this method will hold execution till the process end
@return boolean Null, if worker is not active. False, if signal can't be sent to worker.
True, if signal sent OR signal sent and worker terminated (if $wait = true).