sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function getProviderInfos($handle) { $record = $this->_getProviderRecordByHandle($handle); if($record) { return Oauth_ProviderInfosModel::populateModel($record); } else { $configProviderInfos = craft()->config->get('providerInfos', 'oauth'); if(isset($configProviderInfos[$handle])) { $attributes = []; if(isset($configProviderInfos[$handle]['clientId'])) { $attributes['clientId'] = $configProviderInfos[$handle]['clientId']; } if(isset($configProviderInfos[$handle]['clientSecret'])) { $attributes['clientSecret'] = $configProviderInfos[$handle]['clientSecret']; } return Oauth_ProviderInfosModel::populateModel($attributes); } } }
Get provider infos
entailment
public function getTokenById($id) { if ($id) { $record = Oauth_TokenRecord::model()->findById($id); if ($record) { $token = Oauth_TokenModel::populateModel($record); // will refresh token if needed try { if($this->_refreshToken($token)) { // save refreshed token $this->saveToken($token); } } catch(\Exception $e) { OauthPlugin::log("OAuth.Debug - Couldn't refresh token\r\n".$e->getMessage().'\r\n'.$e->getTraceAsString(), LogLevel::Error, true); } return $token; } } }
Get token by ID
entailment
public function getTokens() { $conditions = ''; $params = array(); $records = Oauth_TokenRecord::model()->findAll($conditions, $params); return Oauth_TokenModel::populateModels($records); }
Get tokens by provider
entailment
public function getTokensByProvider($providerHandle) { $conditions = 'providerHandle=:providerHandle'; $params = array(':providerHandle' => $providerHandle); $records = Oauth_TokenRecord::model()->findAll($conditions, $params); return Oauth_TokenModel::populateModels($records); }
Get tokens by provider
entailment
public function saveToken(Oauth_TokenModel &$model) { // is new ? $isNewToken = !$model->id; // populate record $record = $this->_getTokenRecordById($model->id); $record->providerHandle = strtolower($model->providerHandle); $record->pluginHandle = strtolower($model->pluginHandle); $record->accessToken = $model->accessToken; $record->secret = $model->secret; $record->endOfLife = $model->endOfLife; $record->refreshToken = $model->refreshToken; // save record if($record->save(false)) { // populate id if($isNewToken) { $model->id = $record->id; } return true; } else { return false; } }
Save token
entailment
public function deleteToken(Oauth_TokenModel $token) { if (!$token->id) { return false; } $record = Oauth_TokenRecord::model()->findById($token->id); if($record) { return $record->delete(); } return false; }
Delete token ID
entailment
public function deleteTokensByPlugin($pluginHandle) { $conditions = 'pluginHandle=:pluginHandle'; $params = array(':pluginHandle' => $pluginHandle); return Oauth_TokenRecord::model()->deleteAll($conditions, $params); }
Delete tokens by plugin
entailment
private function _getTokenRecordById($id = null) { if ($id) { $record = Oauth_TokenRecord::model()->findById($id); if (!$record) { throw new Exception(Craft::t('No oauth token exists with the ID “{id}”', array('id' => $id))); } } else { $record = new Oauth_TokenRecord(); } return $record; }
Get token record by ID
entailment
private function _refreshToken(Oauth_TokenModel $model) { $time = time(); // force refresh for testing // $time = time() + 3595; // google ttl // $time = time() + 50400005089; // facebook ttl $provider = craft()->oauth->getProvider($model->providerHandle); // Refreshing the token only applies to OAuth 2.0 providers if($provider && $provider->getOauthVersion() == 2) { // Has token expired ? if($time > $model->endOfLife) { $realToken = OauthHelper::getRealToken($model); $infos = $provider->getInfos(); $refreshToken = $model->refreshToken; $grant = new \League\OAuth2\Client\Grant\RefreshToken(); $newToken = $provider->getProvider()->getAccessToken($grant, ['refresh_token' => $refreshToken]); if($newToken) { $model->accessToken = $newToken->getToken(); $model->endOfLife = $newToken->getExpires(); $newRefreshToken = $newToken->getRefreshToken(); if(!empty($newRefreshToken)) { $model->refreshToken = $newToken->getRefreshToken(); } return true; } } } return false; }
Refresh token
entailment
public function _sessionClean() { craft()->httpSession->remove('oauth.handle'); craft()->httpSession->remove('oauth.referer'); craft()->httpSession->remove('oauth.authorizationOptions'); craft()->httpSession->remove('oauth.redirect'); craft()->httpSession->remove('oauth.response'); craft()->httpSession->remove('oauth.scope'); }
Clean session
entailment
private function _getProviderRecordByHandle($handle) { $providerRecord = Oauth_ProviderInfosRecord::model()->find( // conditions 'class=:provider', // params array( ':provider' => $handle ) ); if($providerRecord) { return $providerRecord; } return null; }
Get provider record by handle
entailment
private function _getProviderInfosRecordById($providerId = null) { if ($providerId) { $providerRecord = Oauth_ProviderInfosRecord::model()->findById($providerId); if (!$providerRecord) { throw new Exception(Craft::t('No oauth provider exists with the ID “{id}”', array('id' => $providerId))); } } else { $providerRecord = new Oauth_ProviderInfosRecord(); } return $providerRecord; }
Get provider infos record by ID
entailment
private function _loadProviders($fromRecord = false) { if($this->_providersLoaded) { return; } $providerSources = $this->_getProviders(); foreach($providerSources as $providerSource) { // handle $handle = $providerSource->getHandle(); // get provider record $record = $this->_getProviderRecordByHandle($providerSource->getHandle()); // create provider (from record if any) $providerInfos = Oauth_ProviderInfosModel::populateModel($record); // override provider infos from config $oauthConfig = craft()->config->get('providerInfos', 'oauth'); if($oauthConfig && !$fromRecord) { if(!empty($oauthConfig[$providerSource->getHandle()]['clientId'])) { $providerInfos->clientId = $oauthConfig[$providerSource->getHandle()]['clientId']; } if(!empty($oauthConfig[$providerSource->getHandle()]['clientSecret'])) { $providerInfos->clientSecret = $oauthConfig[$providerSource->getHandle()]['clientSecret']; } if(!empty($oauthConfig[$providerSource->getHandle()]['config'])) { $providerInfos->config = $oauthConfig[$providerSource->getHandle()]['config']; } } $providerSource->setInfos($providerInfos); if($providerSource->isConfigured()) { $this->_configuredProviders[$handle] = $providerSource; } // add to _allProviders array $this->_allProviders[$handle] = $providerSource; } // providers are now loaded $this->_providersLoaded = true; }
Loads the configured providers.
entailment
private function _getProviders() { require_once(CRAFT_PLUGINS_PATH.'oauth/vendor/autoload.php'); require_once(CRAFT_PLUGINS_PATH.'oauth/etc/providers/IOauth_Provider.php'); require_once(CRAFT_PLUGINS_PATH.'oauth/providers/BaseProvider.php'); // fetch all OAuth provider types $oauthProviderTypes = array(); foreach(craft()->plugins->call('getOauthProviders', [], true) as $pluginOAuthProviderTypes) { $oauthProviderTypes = array_merge($oauthProviderTypes, $pluginOAuthProviderTypes); } // instantiate providers $providers = []; foreach($oauthProviderTypes as $oauthProviderType) { $provider = $this->_createProvider($oauthProviderType); $providers[$provider->getHandle()] = $provider; } ksort($providers); return $providers; }
Get Providers
entailment
public function saveCampaign($name, $newName, $dateStart, $dateEnd, $discount){ // Sanity check if(!isset($name) || $name == '') throw new \Exception('Specificati numele campaniei'); if(!isset($newName) || $newName == '') throw new \Exception('Specificati noul nume al campaniei'); if(!isset($dateStart) || strtotime($dateStart) === false) throw new \Exception('Specificati o data de start valida'); if(!isset($dateEnd) || strtotime($dateEnd) === false) throw new \Exception('Specficati o data de sfarsit valida'); if(strtotime($dateStart) > strtotime($dateEnd)) throw new \Exception('Data de inceput trebuie sa fie mai mica sau egala cu data de sfarsit'); if(!isset($discount) || $discount == '' || !is_numeric($discount)) throw new \Exception('Specificati un discount valid'); // Set method and action $method = 'campaign'; $action = 'saveCampaign'; // Set data $data = array( 'numecampanie' => $name, 'CampaignData' => json_encode( array( 'numecampanie' => $newName, 'datastart' => $dateStart, 'dataend' => $dateEnd, 'reducere' => $discount ) ) ); // Send request and retrieve response $result = Dispatcher::send($method, $action, $data); return $result; }
[RO] Actualizeaza detaliile unei campanii si adauga un discount (https://github.com/celdotro/marketplace/wiki/Salvare-campanie) [EN] Updates the campaign details and adds a discount (https://github.com/celdotro/marketplace/wiki/Save-Campaign) @param $name @param $newName @param $dateStart @param $dateEnd @param $discount @return mixed @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function saveProduct($name, $model, $promoPrice, $start, $end){ // Sanity check if(!isset($name) || $name == '') throw new \Exception('Specificati numele campaniei'); if(!isset($model) && $model == '') throw new \Exception('Specificati modelul produsului'); if(!isset($promoPrice) && $promoPrice < 0) throw new \Exception('Specificati pretul promo al produslui'); // Set method and action $method = 'campaign'; $action = 'saveProduct'; // Set data $data = array( 'numecampanie' => $name, 'model' => $model, 'promo' => $promoPrice, 'start' => $start, 'end' => $end ); // Send request and retrieve response $result = Dispatcher::send($method, $action, $data); return $result; }
[RO] Actualizeaza un produs cu un pret promotional diferit de cel implicit al campaniei (https://github.com/celdotro/marketplace/wiki/Salvare-produs-in-campanie) [EN] Updates a product with a promotional price different than the campaign default (https://github.com/celdotro/marketplace/wiki/Save-Product-in-Campaign) @param $name @param $model @param $promoPrice @param $start @param $end @return mixed @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function addProduct($name, $model){ // Sanity check if(!isset($name) || $name == '') throw new \Exception('Specificati numele campaniei'); if(!isset($model) && $model == '') throw new \Exception('Specificati modelul produsului'); // Set method and action $method = 'campaign'; $action = 'addProduct'; // Set data $data = array( 'numecampanie' => $name, 'model' => $model, ); // Send request and retrieve response $result = Dispatcher::send($method, $action, $data); return $result; }
[RO] Adauga un produs unei campanii si ii aplica reducerea acestia (https://github.com/celdotro/marketplace/wiki/Adaugare-produs-in-campanie) [EN] Adds a product to a campaign and applies the campaign's discount (https://github.com/celdotro/marketplace/wiki/Add-Product-to-Campaign) @param $name @param $model @return mixed @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function setCampaignStoc($name, $stoc){ // Sanity check if(!isset($name) || $name == '') throw new \Exception('Specificati numele campaniei'); // Set method and action $method = 'campaign'; $action = 'setCampaignStoc'; // Set data $data = array( 'name' => $name, 'stoc' => $stoc, ); // Send request and retrieve response $result = Dispatcher::send($method, $action, $data); return $result; }
[RO] Returneaza informatiile aferente unei comenzi specificata prin parametru (https://github.com/celdotro/marketplace/wiki/Datele-comenzii) [EN] Returns all relevant informations for an order specified as a parameter (https://github.com/celdotro/marketplace/wiki/Order-data) @param $name @param $stoc @return mixed @throws \Exception
entailment
public function generateCoupons($campaignId, $couponsNumber){ // Sanity check if(empty($campaignId)) throw new \Exception('Specificati o campanie valida'); if(empty($couponsNumber)) throw new \Exception('Specificati un numar valid de cupoane'); // Set method and action $method = 'coupons'; $action = 'generateCoupons'; // Set data $data = array( 'campaignId' => $campaignId, 'couponsNumber' => $couponsNumber ); // Send request and retrieve response $result = Dispatcher::send($method, $action, $data); return $result; }
[RO] Generare cupon (https://github.com/celdotro/marketplace/wiki/Genereaza-cupon) [EN] Coupon generation (https://github.com/celdotro/marketplace/wiki/Generate-coupon) @param $campaignId @param $couponsNumber @return mixed @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function toggleCouponStatus($campaignId, $couponId, $status){ // Sanity check if(empty($campaignId)) throw new \Exception('Specificati o campanie valida'); if(empty($couponId)) throw new \Exception('Specificati un cupon valid'); if(is_null($status)) throw new \Exception('Specificati un status valid'); // Set method and action $method = 'coupons'; $action = 'toggleCouponStatus'; // Set data $data = array( 'campaignId' => $campaignId, 'couponId' => $couponId, 'status' => $status ); // Send request and retrieve response $result = Dispatcher::send($method, $action, $data); return $result; }
[RO] Schimbare status cupon (https://github.com/celdotro/marketplace/wiki/Schimbare-status-cupon) [EN] Change coupon status (https://github.com/celdotro/marketplace/wiki/Change-coupon-status) @param $campaignId @param $couponId @param $status @return mixed @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function actionIndex(array $variables = array()) { $providers = craft()->oauth->getProviders(false); $tokens = array(); foreach($providers as $provider) { $token = craft()->httpSession->get('oauth.console.token.'.$provider->getHandle()); if($token) { $tokens[$provider->getHandle()] = true; } } $variables['providers'] = $providers; $variables['tokens'] = $tokens; $this->renderTemplate('oauth/console/_index', $variables); }
Index @return null
entailment
public function actionProvider(array $variables = array()) { $handle = $variables['providerHandle']; // token $token = false; $tokenArray = craft()->httpSession->get('oauth.console.token.'.$handle); if($tokenArray) { $token = OauthHelper::arrayToToken($tokenArray); } // provider $provider = craft()->oauth->getProvider($handle); // render $variables['provider'] = $provider; $variables['token'] = $token; $this->renderTemplate('oauth/console/_provider', $variables); }
Provider @return null
entailment
public function actionConnect() { $referer = craft()->request->getUrlReferrer(); $providerHandle = craft()->request->getParam('provider'); craft()->httpSession->add('oauth.console.referer', $referer); craft()->httpSession->add('oauth.console.providerHandle', $providerHandle); craft()->httpSession->remove('oauth.console.token.'.$providerHandle); $this->redirect(UrlHelper::getActionUrl('oauth/console/connectStep2')); }
Connect @return null
entailment
public function actionConnectStep2() { $providerHandle = craft()->httpSession->get('oauth.console.providerHandle'); $referer = craft()->httpSession->get('oauth.console.referer'); // connect $provider = craft()->oauth->getProvider($providerHandle); if($response = craft()->oauth->connect(array( 'plugin' => 'oauth', 'provider' => $providerHandle ))) { if($response['success']) { // token $token = $response['token']; $tokenArray = OauthHelper::tokenToArray($token); // save token craft()->httpSession->add('oauth.console.token.'.$providerHandle, $tokenArray); // session notice craft()->userSession->setNotice(Craft::t("Connected.")); } else { craft()->userSession->setError(Craft::t($response['errorMsg'])); } } else { // session error craft()->userSession->setError(Craft::t("Couldn’t connect")); } // redirect $this->redirect($referer); }
Connect Step 2 @return null
entailment
public function actionDisconnect() { $providerHandle = craft()->request->getParam('provider'); // reset token craft()->httpSession->remove('oauth.console.token.'.$providerHandle); // set notice craft()->userSession->setNotice(Craft::t("Disconnected.")); // redirect $redirect = craft()->request->getUrlReferrer(); $this->redirect($redirect); }
Disconnect @return null
entailment
public function getOrderEmailList(){ // Set method and action $method = 'email'; $action = 'getOrderEmailList'; // Set data $data = array('params' => true); // Send request and retrieve response $result = Dispatcher::send($method, $action, $data); return $result; }
[RO] Returneaza o lista cu ID-uri si denumirea mesajelor predefinite pentru anumite actiuni legate de comanda (https://github.com/celdotro/marketplace/wiki/Listare-email-uri-predefinite-pentru-comenzi) [EN] Returns a list of IDs and names of predefined emails for actions related to an order (https://github.com/celdotro/marketplace/wiki/Get-client-emails-for-an-order) @return mixed @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function getClientEmailsForOrder($cmd){ // Sanity check if (is_null($cmd) || !is_numeric($cmd)) throw new \Exception('Specificati o comanda valida'); // Set method and action $method = 'email'; $action = 'getClientEmailsForOrder'; // Set data $data = array('cmd' => $cmd); // Send request and retrieve response $result = Dispatcher::send($method, $action, $data); return $result; }
[RO] Returneaza un graf cu conversatiile purtate prin intermediul email-ului cu clientii (https://github.com/celdotro/marketplace/wiki/Preia-email-urile-unui-client-pentru-o-comanda) [EN] Returns a graph with the conversations made through the email with the client (https://github.com/celdotro/marketplace/wiki/Get-client-emails-for-an-order) @param $cmd @return mixed @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function sendOrderEmail($cmd, $idEmail){ // Sanity check if (is_null($cmd) || !is_numeric($cmd)) throw new \Exception('Specificati o comanda valida'); if (is_null($idEmail) || !is_numeric($idEmail)) throw new \Exception('Specificati un ID valid de email'); // Set method and action $method = 'email'; $action = 'sendOrderEmail'; // Set data $data = array('cmd' => $cmd, 'idEmail' => $idEmail); // Send request and retrieve response $result = Dispatcher::send($method, $action, $data); return $result; }
[RO] Trimite clientului un email predefinit aferent unei comenzi (https://github.com/celdotro/marketplace/wiki/Trimitere-email-aferent-comenzii) [EN] Sends the client a predefined email related to an order (https://github.com/celdotro/marketplace/wiki/Send-predefined-order-email) @param $cmd @param $idEmail @return mixed @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function sendOrderCustomEmail($cmd, $subject, $body, $replyID = null){ // Sanity check if (is_null($cmd) || !is_numeric($cmd)) throw new \Exception('Specificati o comanda valida'); if (is_null($subject) || $subject == '') throw new \Exception('Specificati un subiect valid'); if (is_null($body) || $body == '') throw new \Exception('Specificati un continut valid'); // Set method and action $method = 'email'; $action = 'sendOrderCustomEmail'; // Set data $data = array('cmd' => $cmd, 'subject' => $subject, 'body' => $body); if(!is_null($replyID)) $data['replyID'] = $replyID; // Send request and retrieve response $result = Dispatcher::send($method, $action, $data); return $result; }
[RO] Trimite clientului un email personalizat aferent unei comenzi (https://github.com/celdotro/marketplace/wiki/Trimitere-email-personalizat-aferent-comenzii) [EN] Sends the client a custom email related to an order (https://github.com/celdotro/marketplace/wiki/Send-custom-order-email) @param $cmd @param $subject @param $body @param null $replyID @return mixed @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function notifyAWBRemoval($orders_id, $reason){ // Sanity check if (empty($orders_id) || !is_numeric($orders_id)) throw new \Exception('Specificati o comanda valida'); if (empty($reason)) throw new \Exception('Specificati un motiv valid'); // Set method and action $method = 'email'; $action = 'notifyAWBRemoval'; // Set data $data = array( 'orders_id' => $orders_id, 'reason' => $reason ); // Send request and retrieve response $result = Dispatcher::send($method, $action, $data); return $result; }
[RO] Trimite notificare de stergere a AWB-ului (https://github.com/celdotro/marketplace/wiki/Trimite-notificare-de-stergere-a-AWB-ului) [EN] Send AWB removal notification (https://github.com/celdotro/marketplace/wiki/Send-notification-for-AWB-removal) @param $orders_id @param $reason @return mixed @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function downloadOrderEmailAttachment($emailID, $attachmentNumber){ // Sanity check if (empty($emailID) || !is_numeric($emailID)) throw new \Exception('Specificati o comanda valida'); if(empty($attachmentNumber) || !is_numeric($attachmentNumber)) throw new \Exception('Speciificati un numar de atasament valid'); // Set method and action $method = 'email'; $action = 'downloadOrderEmailAttachment'; // Set data $data = array( 'emailID' => $emailID, 'attachmentNumber' => $attachmentNumber ); // Send request and retrieve response $result = Dispatcher::send($method, $action, $data); return $result; }
[RO] Descarca un atasament aferent email-ului unei comenzi si informatii relevante despre acesta (https://github.com/celdotro/marketplace/wiki/Descarca-atasamentul-email-ului-comenzii) [EN] Downloads an attachment belonging to an order's email and other relevant information regarding the attachment (https://github.com/celdotro/marketplace/wiki/Download-order-email-attachment) @param $emailID @param $attachmentNumber @return mixed @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function getOrdersContacts($minDate = null, $maxDate = null, $email = null, $name = null, $site = null, $raspuns = null){ // Set method and action $method = 'email'; $action = 'getOrdersContacts'; // Set data $data = array( 'minDate' => $minDate, 'maxDate' => $maxDate, 'email' => $email, 'name' => $name, 'site' => $site, 'raspuns' => $raspuns ); // Send request and retrieve response $result = Dispatcher::send($method, $action, $data); return $result; }
[RO] Preia mesajele comenzilor (https://github.com/celdotro/marketplace/wiki/Preia-mesajele-comenzilor) [EN] Retrieves orders messages (https://github.com/celdotro/marketplace/wiki/Get-orders-messages) @param null $minDate @param null $maxDate @param null $email @param null $name @param null $site @param null $raspuns @return mixed @throws \GuzzleHttp\Exception\GuzzleException
entailment
protected function defineAttributes() { $attributes = array( 'id' => AttributeType::Number, 'class' => array(AttributeType::String, 'required' => true), 'clientId' => array(AttributeType::String, 'required' => false), 'clientSecret' => array(AttributeType::String, 'required' => false), 'config' => array(AttributeType::Mixed) ); return $attributes; }
Define Attributes
entailment
public static function setUserDetails($username, $password, $class = null) { // Sanity check if (!isset($username) || is_null($username) || empty($username)) { throw new \Exception('Specificati un nume de utilizator valid'); } if (!isset($password) || is_null($password) || empty($password)) { throw new \Exception('Specificati o parola valida'); } // Set attributes self::$username = $username; self::$password = $password; if (is_null($class)) { $authProvider = new AuthProviderFile($username, $password); } else { $authProvider = new $class($username, $password); if (!($authProvider instanceof AuthProvider)) { throw new \Exception('Clasa specificata trebuie sa extinda celmarket\AuthProvider.'); } } Dispatcher::setProvider($authProvider); $authProvider::checkToken(); }
Set username and password @param $username @param $password @throws \Exception
entailment
public function initialize() { return !is_null($this->transactionRef) ? $this->getTransactionResource()->initialize($this->_requestPayload()) : new PaystackInvalidTransactionException( json_decode( json_encode( [ 'message' => 'Transaction Reference Not Generated.', ] ), false ) ); }
Initialize one time transaction to get payment url. @return \Exception|mixed|PaystackInvalidTransactionException
entailment
public function safeUp() { // unique index for 'userMapping' and 'provider' $tableName = 'oauth_tokens'; $tokensTable = $this->dbConnection->schema->getTable('{{'.$tableName.'}}'); if ($tokensTable) { $this->dropForeignKey($tableName, 'userId'); $this->dropIndex($tableName, 'userMapping, provider', true); $this->dropIndex($tableName, 'userId, provider', true); $this->dropIndex($tableName, 'namespace, provider', true); $this->addForeignKey($tableName, 'userId', 'users', 'id', 'CASCADE'); $this->createIndex($tableName, 'provider, userMapping, namespace', true); } return true; }
Any migration code in here is wrapped inside of a transaction. @return bool
entailment
public function listOrders($start, $limit, $options){ // Sanity check if(!isset($start) || !is_int($start)) throw new \Exception('$start trebuie sa fie de tip integer'); if(!isset($limit) || !is_int($limit)) throw new \Exception('$limit trebuie sa fie de tip integer'); if(!isset($options) || !is_array($options)) throw new \Exception('$options trebuie sa fie un array'); // Set method and action $method = 'orders'; $action = 'getOrders'; // Set data $data = array( 'start' => $start, 'limit' => $limit, 'filters' => json_encode($options), ); // Send request and retrieve response $result = Dispatcher::send($method, $action, $data); return $result; }
[RO] Listeaza comenzile unui client. Lista este scurtata folosind o pozitie de start si o limita. Nu suporta mai mult de 50 inregistrari. (https://github.com/celdotro/marketplace/wiki/Listare-comenzi) [EN] List orders for a customer. It is shrunk by using a start position and a limit. It can hold a maximum of 50 records. (https://github.com/celdotro/marketplace/wiki/List-orders) @param $start @param $limit @param $options @return mixed @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function verify($transactionRef) { $transactionData = $this->getTransactionResource()->verify($transactionRef); if ($transactionData instanceof \Exception) { throw $transactionData; } if ($transactionData['status'] == TransactionContract::TRANSACTION_STATUS_SUCCESS) { return [ 'authorization' => $transactionData['authorization'], 'customer' => $transactionData['customer'], 'amount' => $transactionData['amount'], 'plan' => $transactionData['plan'], ]; } return false; }
Verify Transaction. @param $transactionRef @throws \Exception @return array|bool
entailment
public function details($transactionId) { $transactionData = $this->getTransactionResource()->get($transactionId); if ($transactionData instanceof \Exception) { throw $transactionData; } return TransactionObject::make($transactionData); }
Get transaction details. @param $transactionId @throws \Exception|mixed @return \MAbiola\Paystack\Models\Transaction
entailment
public function allTransactions($page) { $transactions = []; $transactionData = $this->getTransactionResource()->getAll($page); if ($transactionData instanceof \Exception) { throw $transactionData; } foreach ($transactionData as $transaction) { $transactions[] = TransactionObject::make($transaction); } return $transactions; }
Get all transactions. per page. @param $page @throws \Exception|mixed @return array
entailment
protected function fix(\DOMNode $node, $value) { $fixed = $value; if ($node instanceof \DOMText) { $fixed = str_replace("\n", '', $fixed); $fixed = preg_replace('/\s+/u', ' ', $fixed); $fixed = str_replace('<', '&lt;', $fixed); $fixed = str_replace('>', '&gt;', $fixed); } return $fixed; }
Fix given value based on node type @param \DOMNode $node @param string $value @return string
entailment
protected function validation(\DOMNode $node, $value) { $boolean = Text::fullTrim($value) !== '' && !in_array($node->parentNode->localName, ['script', 'style', 'noscript', 'code']) && !is_numeric(Text::fullTrim($value)) && !preg_match('/^\d+%$/', Text::fullTrim($value)) && !Text::contains(Text::fullTrim($value), '[vc_') && !Text::contains(Text::fullTrim($value), '<?php'); if ($node instanceof \DOMText) { $boolean = $boolean && strpos($value, Parser::ATTRIBUTE_NO_TRANSLATE) === false; } return $boolean; }
Some default checks for our value depending on node type @param \DOMNode $node @param string $value @return bool
entailment
protected function replaceCallback(\DOMNode $node) { return function ($text) use ($node) { $attribute = ''; if ($node instanceof \DOMText) { $attribute = 'nodeValue'; } elseif ($node instanceof \DOMAttr) { $attribute = 'value'; } if ($attribute === '') { throw new ParserCrawlerAfterListenerException('No callback behavior set for this node type.'); } // reserved character in XML: & $text = str_replace('&amp;', '&', $text); $text = str_replace('&', '&amp;', $text); $text = str_replace('&lt;', '<', $text); $text = str_replace('&gt;', '>', $text); $node->$attribute = $text; }; }
Callback used to replace text with translated version @param \DOMNode $node @return callable
entailment
protected function type(\DOMNode $node) { $type = null; if ($node instanceof \DOMText) { $type = WordType::TEXT; } elseif ($node instanceof \DOMAttr) { $type = WordType::VALUE; } else { throw new ParserCrawlerAfterListenerException('No word type set for this kind of node.'); } return $type; }
Get the type of the word given by this kind of node @param \DOMNode $node @return string @throws ParserCrawlerAfterListenerException
entailment
public function importAWB($cmd, $awb, $idAdresaRidicare){ // Sanity check if(!isset($cmd) || !is_int($cmd)) throw new \Exception('Specificati comanda'); // Set method and action $method = 'orders'; $action = 'importAWB'; // Set data $data = array('orders_id' => $cmd, 'awb' => $awb, 'idAdresaRidicare' => $idAdresaRidicare); // Send request and retrieve response $result = Dispatcher::send($method, $action, $data); return $result; }
[RO] Seteaza un AWB pentru o comanda (https://github.com/celdotro/marketplace/wiki/Creare-AWB) [EN] Add an AWB for a specific order (https://github.com/celdotro/marketplace/wiki/AWB-Import) @param $cmd @param $awb @param $idAdresaRidicare @return mixed @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function setInputWords($words = null) { if ($words === null) { $this->inputWords = new WordCollection(); } else { $this->inputWords = $words; } return $this; }
Used to fill input words collection If $words is null, it would put an empty word collection @param WordCollection|null $words @return $this
entailment
public function setOutputWords($words = null) { if ($words === null) { $this->outputWords = new WordCollection(); } else { $this->outputWords = $words; } return $this; }
Used to fill output words collection If $words is null, it would put an empty word collection @param WordCollection|null $words @return $this
entailment
public function jsonSerialize() { return [ 'l_from' => $this->params['language_from'], 'l_to' => $this->params['language_to'], 'bot' => $this->params['bot'], 'title' => $this->params['title'], 'request_url' => $this->params['request_url'], 'words' => $this->inputWords->jsonSerialize() ]; }
{@inheritdoc}
entailment
public function safeUp() { $this->addColumnAfter('oauth_tokens', 'accessToken', array(ColumnType::Varchar, 'required' => false), 'pluginHandle'); $this->addColumnAfter('oauth_tokens', 'secret', array(ColumnType::Varchar, 'required' => false), 'accessToken'); $this->addColumnAfter('oauth_tokens', 'endOfLife', array(ColumnType::Varchar, 'required' => false), 'secret'); $this->addColumnAfter('oauth_tokens', 'refreshToken', array(ColumnType::Varchar, 'required' => false), 'endOfLife'); require_once(CRAFT_PLUGINS_PATH.'oauth/vendor/autoload.php'); $rows = craft()->db->createCommand() ->select('*') ->from('oauth_tokens') ->queryAll(); foreach($rows as $row) { $token = $row['encodedToken']; $token = @unserialize(base64_decode($token)); if($token && is_object($token)) { $attributes = array(); $attributes['accessToken'] = $token->getAccessToken(); if(method_exists($token, 'getAccessTokenSecret')) { $attributes['secret'] = $token->getAccessTokenSecret(); } $attributes['endOfLife'] = $token->getEndOfLife(); $attributes['refreshToken'] = $token->getRefreshToken(); $this->update('oauth_tokens', $attributes, 'id = :id', array(':id' => $row['id'])); } } OauthPlugin::log('Dropping the encodedToken column from the structures table...', LogLevel::Info, true); $this->dropColumn('oauth_tokens', 'encodedToken'); OauthPlugin::log('Done dropping the encodedToken column from the structures table.', LogLevel::Info, true); return true; }
Any migration code in here is wrapped inside of a transaction. @return bool
entailment
public function removeInvoice($ordersID){ // Sanity check if(!isset($ordersID) || !is_int($ordersID)) throw new \Exception('Specificati comanda'); // Set method and action $method = 'orders'; $action = 'removeInvoice'; // Set data $data = array('orders_id' => $ordersID); // Send request and retrieve response $result = Dispatcher::send($method, $action, $data); return $result; }
[RO] Sterge factura unei facturi (https://github.com/celdotro/marketplace/wiki/Stergere-factura) [EN] Deletes an order's invoice (https://github.com/celdotro/marketplace/wiki/Remove-Invoice) @param $ordersID @return mixed @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function loadFromServer() { $this ->setUrl(Server::fullUrl($_SERVER)) ->setBot(Server::detectBot($_SERVER)); }
Is used to load server data, you have to run it manually !
entailment
public function getImportHistory ($date_start = null, $date_stop = null, $import_type = NULL, $page = 0) { // Set method and action $method = 'admininfo'; $action = 'getImportHistory'; $data = array(); // Set data if (!is_null($date_start)) $data['data_start'] = $date_start; if (!is_null($date_stop)) $data['data_stop'] = $date_stop; if (!is_null($import_type)) $data['tip_import'] = $import_type; if (!is_null($page) && $page != 0) $data['page'] = $page; // Send request and retrieve response $result = Dispatcher::send($method, $action, $data); return $result; }
[RO] Returneaza date despre istoricul importurilor (https://github.com/celdotro/marketplace/wiki/Istoric-importuri) [EN] Returns data about import history (https://github.com/celdotro/marketplace/wiki/Import-history) @param null $date_start @param null $date_stop @param null $import_type @param int $page @return mixed @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function actionConnect() { $token = false; $success = false; $error = false; $errorMsg = false; // handle $providerHandle = craft()->httpSession->get('oauth.handle'); if(!$providerHandle) { $providerHandle = craft()->request->getParam('provider'); if($providerHandle) { craft()->httpSession->add('oauth.handle', $providerHandle); } else { throw new Exception("Couldn’t retrieve OAuth provider."); } } // session vars $scope = craft()->httpSession->get('oauth.scope'); $authorizationOptions = craft()->httpSession->get('oauth.authorizationOptions'); $referer = craft()->httpSession->get('oauth.referer'); OauthPlugin::log('OAuth Connect - Connect with `'.$providerHandle.'` OAuth provider'."\r\n". 'Session Data: '.print_r([ 'oauth.referer' => $referer, 'oauth.scope' => $scope, 'oauth.authorizationOptions' => $authorizationOptions ], true)."\r\n" , LogLevel::Info); try { // provider $provider = craft()->oauth->getProvider($providerHandle); // connect $tokenResponse = $provider->connect([ 'scope' => $scope, 'authorizationOptions' => $authorizationOptions, ]); // token if($tokenResponse) { $token = OauthHelper::realTokenToArray($tokenResponse); } else { throw new Exception("Error with token"); } $success = true; } catch(\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) { $error = true; $errorMsg = $e->getMessage(); if($errorMsg == 'invalid_client') { $errorMsg = Craft::t("Invalid OAuth client ID or secret."); } } catch(\Exception $e) { $error = true; $errorMsg = $e->getMessage(); } // build up response $response = array( 'error' => $error, 'errorMsg' => $errorMsg, 'success' => $success, 'token' => $token, ); OauthPlugin::log("OAuth Connect - Response\r\n". 'Session Data: '.print_r([ 'oauth.response' => $response, ], true)."\r\n" , LogLevel::Info); craft()->httpSession->add('oauth.response', $response); // redirect $this->redirect($referer); }
Connect @return null
entailment
protected static function doRegister($protocol, PathFactoryInterface $pathFactory, FactoryInterface $bufferFactory) { static::$protocol = $protocol; static::$pathFactory = $pathFactory; static::$bufferFactory = $bufferFactory; if (!stream_wrapper_register($protocol, get_called_class())) { throw new \RuntimeException(sprintf('The protocol "%s" is already registered with the runtime or it cannot be registered', $protocol)); } }
Registers the stream wrapper with the given protocol @param string $protocol The protocol (such as "vcs") @param PathFactoryInterface $pathFactory The path factory @param FactoryInterface $bufferFactory The buffer factory @throws \RuntimeException If $protocol is already registered
entailment
public static function unregister() { if (!static::$protocol) { return; } if (!stream_wrapper_unregister(static::$protocol)) { throw new \RuntimeException(sprintf('The protocol "%s" cannot be unregistered from the runtime', static::$protocol)); } static::$protocol = null; static::$pathFactory = null; static::$bufferFactory = null; }
Unregisters the stream wrapper
entailment
protected function getContextOptions($all = false) { if ($this->contextOptions === null) { $this->contextOptions = stream_context_get_options($this->context); } if (!$all && array_key_exists(self::$protocol, $this->contextOptions)) { return $this->contextOptions[self::$protocol]; } else if ($all) { return $this->contextOptions; } else { return array(); } }
Parses the passed stream context and returns the context options relevant for this stream wrapper @param boolean $all Return all options instead of just the relevant options @return array The context options
entailment
protected function getContextOption($option, $default = null) { $options = $this->getContextOptions(); if (array_key_exists($option, $options)) { return $options[$option]; } else { return $default; } }
Returns a context option - $default if option is not found @param string $option The option to retrieve @param mixed $default The default value if $option is not found @return mixed
entailment
protected function getContextParameters() { if ($this->contextParameters === null) { $this->contextParameters = stream_context_get_params($this->context); } return $this->contextParameters; }
Parses the passed stream context and returns the context parameters @return array The context parameters
entailment
protected function getContextParameter($parameter, $default = null) { $parameters = $this->getContextParameters(); if (array_key_exists($parameter, $parameters)) { return $parameters[$parameter]; } else { return $default; } }
Returns a context parameter - $default if parameter is not found @param string $parameter The parameter to retrieve @param mixed $default The default value if $parameter is not found @return mixed
entailment
public function dir_opendir($path, $options) { try { $path = $this->getPath($path); $repo = $path->getRepository(); $listing = $repo->listDirectory($path->getLocalPath(), $path->getRef()); $this->dirBuffer = new ArrayBuffer($listing); $this->path = $path; return true; } catch (\Exception $e) { trigger_error($e->getMessage(), E_USER_WARNING); return false; } }
streamWrapper::dir_opendir — Open directory handle @param string $path Specifies the URL that was passed to {@see opendir()}. @param integer $options Whether or not to enforce safe_mode (0x04). @return boolean Returns TRUE on success or FALSE on failure.
entailment
public function mkdir($path, $mode, $options) { try { $path = $this->getPath($path); if ($path->getRef() != 'HEAD') { throw new \Exception(sprintf( 'Cannot create a non-HEAD directory [%s#%s]', $path->getFullPath(), $path->getRef() )); } if (file_exists($path->getFullPath())) { throw new \Exception(sprintf('Path %s already exists', $path->getFullPath())); } $recursive = self::maskHasFlag($options, STREAM_MKDIR_RECURSIVE); $repo = $path->getRepository(); $commitMsg = $this->getContextOption('commitMsg', null); $author = $this->getContextOption('author', null); $repo->createDirectory($path->getLocalPath(), $commitMsg, $mode, $recursive, $author); return true; } catch (\Exception $e) { trigger_error($e->getMessage(), E_USER_WARNING); return false; } }
streamWrapper::mkdir — Create a directory @param string $path Directory which should be created. @param integer $mode The value passed to {@see mkdir()}. @param integer $options A bitwise mask of values, such as STREAM_MKDIR_RECURSIVE. @return boolean Returns TRUE on success or FALSE on failure.
entailment
public function rename($path_from, $path_to) { try { $pathFrom = $this->getPath($path_from); if ($pathFrom->getRef() != 'HEAD') { throw new \Exception(sprintf( 'Cannot rename a non-HEAD file [%s#%s]', $pathFrom->getFullPath(), $pathFrom->getRef() )); } if (!file_exists($pathFrom->getFullPath())) { throw new \Exception(sprintf('Path %s not found', $pathFrom->getFullPath())); } if (!is_file($pathFrom->getFullPath())) { throw new \Exception(sprintf('Path %s is not a file', $pathFrom->getFullPath())); } $pathTo = self::$pathFactory->parsePath($path_to); $pathTo = $pathTo['path']; if (strpos($pathTo, $pathFrom->getRepositoryPath()) !== 0) { throw new \Exception(sprintf('Cannot rename across repositories [%s -> %s]', $pathFrom->getFullPath(), $pathTo)); } $repo = $pathFrom->getRepository(); $commitMsg = $this->getContextOption('commitMsg', null); $author = $this->getContextOption('author', null); $repo->renameFile($pathFrom->getLocalPath(), $pathTo, $commitMsg, false, $author); return true; } catch (\Exception $e) { trigger_error($e->getMessage(), E_USER_WARNING); return false; } }
streamWrapper::rename — Renames a file or directory @param string $path_from The URL to the current file. @param string $path_to The URL which the $path_from should be renamed to. @return boolean Returns TRUE on success or FALSE on failure.
entailment
public function stream_close() { $this->fileBuffer->close(); $this->fileBuffer = null; $repo = $this->path->getRepository(); if ($repo->isDirty()) { $repo->add(array($this->path->getFullPath())); $commitMsg = $this->getContextOption('commitMsg', null); $author = $this->getContextOption('author', null); $repo->commit($commitMsg, array($this->path->getFullPath()), $author); } $this->path = null; }
streamWrapper::stream_close — Close an resource
entailment
public function stream_open($path, $mode, $options, &$opened_path) { try { $path = $this->getPath($path); $factory = $this->getBufferFactory(); $this->fileBuffer = $factory->createFileBuffer($path, $mode); $this->path = $path; if (self::maskHasFlag($options, STREAM_USE_PATH)) { $opened_path = $this->path->getUrl(); } return true; } catch (\Exception $e) { if (self::maskHasFlag($options, STREAM_REPORT_ERRORS)) { trigger_error($e->getMessage(), E_USER_WARNING); } return false; } }
streamWrapper::stream_open — Opens file or URL @param string $path Specifies the URL that was passed to the original function. @param string $mode The mode used to open the file, as detailed for fopen(). @param integer $options Holds additional flags set by the streams API. It can hold one or more of the following values OR'd together. STREAM_USE_PATH If path is relative, search for the resource using the include_path. STREAM_REPORT_ERRORS If this flag is set, you are responsible for raising errors using trigger_error() during opening of the stream. If this flag is not set, you should not raise any errors. @param string $opened_path If the path is opened successfully, and STREAM_USE_PATH is set in options, opened_path should be set to the full path of the file/resource that was actually opened. @return boolean Returns TRUE on success or FALSE on failure.
entailment
public function stream_read($count) { $buffer = $this->fileBuffer->read($count); if ($buffer === null) { return false; } return $buffer; }
streamWrapper::stream_read — Read from stream @param integer $count How many bytes of data from the current position should be returned. @return string If there are less than count bytes available, return as many as are available. If no more data is available, return either FALSE or an empty string.
entailment
public function unlink($path) { try { $path = $this->getPath($path); if ($path->getRef() != 'HEAD') { throw new \Exception(sprintf( 'Cannot unlink a non-HEAD file [%s#%s]', $path->getFullPath(), $path->getRef() )); } if (!file_exists($path->getFullPath())) { throw new \Exception(sprintf('Path %s not found', $path->getFullPath())); } if (!is_file($path->getFullPath())) { throw new \Exception(sprintf('Path %s is not a file', $path->getFullPath())); } $repo = $path->getRepository(); $commitMsg = $this->getContextOption('commitMsg', null); $author = $this->getContextOption('author', null); $repo->removeFile($path->getLocalPath(), $commitMsg, false, false, $author); return true; } catch (\Exception $e) { trigger_error($e->getMessage(), E_USER_WARNING); return false; } }
streamWrapper::unlink — Delete a file @param string $path The file URL which should be deleted. @return boolean Returns TRUE on success or FALSE on failure.
entailment
public function url_stat($path, $flags) { try { $path = $this->getPath($path); if ($path->getRef() == 'HEAD' && file_exists($path->getFullPath())) { return stat($path->getFullPath()); } else { $repo = $path->getRepository(); $info = $repo->getObjectInfo($path->getLocalPath(), $path->getRef()); $stat = array( 'ino' => 0, 'mode' => $info['mode'], 'nlink' => 0, 'uid' => 0, 'gid' => 0, 'rdev' => 0, 'size' => $info['size'], 'atime' => 0, 'mtime' => 0, 'ctime' => 0, 'blksize' => -1, 'blocks' => -1, ); return array_merge($stat, array_values($stat)); } } catch (\Exception $e) { if (!self::maskHasFlag($flags, STREAM_URL_STAT_QUIET)) { trigger_error($e->getMessage(), E_USER_WARNING); } return false; } }
streamWrapper::url_stat — Retrieve information about a file mode bit mask: S_IFMT 0170000 bit mask for the file type bit fields S_IFSOCK 0140000 socket S_IFLNK 0120000 symbolic link S_IFREG 0100000 regular file S_IFBLK 0060000 block device S_IFDIR 0040000 directory S_IFCHR 0020000 character device S_IFIFO 0010000 FIFO S_ISUID 0004000 set UID bit S_ISGID 0002000 set-group-ID bit (see below) S_ISVTX 0001000 sticky bit (see below) S_IRWXU 00700 mask for file owner permissions S_IRUSR 00400 owner has read permission S_IWUSR 00200 owner has write permission S_IXUSR 00100 owner has execute permission S_IRWXG 00070 mask for group permissions S_IRGRP 00040 group has read permission S_IWGRP 00020 group has write permission S_IXGRP 00010 group has execute permission S_IRWXO 00007 mask for permissions for others (not in group) S_IROTH 00004 others have read permission S_IWOTH 00002 others have write permission S_IXOTH 00001 others have execute permission @param string $path The file path or URL to stat. Note that in the case of a URL, it must be a :// delimited URL. Other URL forms are not supported. @param integer $flags Holds additional flags set by the streams API. It can hold one or more of the following values OR'd together. STREAM_URL_STAT_LINK For resources with the ability to link to other resource (such as an HTTP Location: forward, or a filesystem symlink). This flag specified that only information about the link itself should be returned, not the resource pointed to by the link. This flag is set in response to calls to lstat(), is_link(), or filetype(). STREAM_URL_STAT_QUIET If this flag is set, your wrapper should not raise any errors. If this flag is not set, you are responsible for reporting errors using the trigger_error() function during stating of the path. @return array Should return as many elements as stat() does. Unknown or unavailable values should be set to a rational value (usually 0).
entailment
protected static function maskHasFlag($mask, $flag) { $flag = (int)$flag; return ((int)$mask & $flag) === $flag; }
Checks if a bitmask has a specific flag set @param integer $mask The bitmask @param integer $flag The flag to check @return boolean
entailment
public static function open($repositoryPath, $svn = null) { $svn = Binary::ensure($svn); if (!is_string($repositoryPath)) { throw new \InvalidArgumentException(sprintf( '"%s" is not a valid path', $repositoryPath )); } $repositoryRoot = self::findRepositoryRoot($svn, $repositoryPath); if ($repositoryRoot === null) { throw new \InvalidArgumentException(sprintf( '"%s" is not a valid SVN repository', $repositoryPath )); } return new static($repositoryRoot, $svn); }
Opens a SVN repository on the file system @param string $repositoryPath The full path to the repository @param Binary|string|null $svn The SVN binary @return Repository @throws \RuntimeException If the path cannot be created @throws \InvalidArgumentException If the path is not valid or if it's not a valid SVN repository
entailment
public static function findRepositoryRoot(Binary $svn, $path) { $hasSvnDir = function($path) { $svnDir = $path.'/'.'.svn'; return file_exists($svnDir) && is_dir($svnDir); }; $pathWithSvnDir = FileSystem::bubble($path, $hasSvnDir); $root = $pathWithSvnDir; $parentDir = dirname($pathWithSvnDir); while ($hasSvnDir($parentDir) && strlen($root) > 1) { $root = dirname($root); $parentDir = dirname($parentDir); } return $root; }
Tries to find the root directory for a given repository path @param Binary $svn The SVN binary @param string $path The file system path @return string|null NULL if the root cannot be found, the root path otherwise
entailment
public function getCurrentCommit() { /** @var $result CallResult */ $result = $this->getSvn()->{'info'}($this->getRepositoryPath(), array( '--xml', '--revision' => 'HEAD' )); $result->assertSuccess(sprintf('Cannot get info for "%s"', $this->getRepositoryPath())); $xml = simplexml_load_string($result->getStdOut()); if (!$xml) { throw new \RuntimeException(sprintf('Cannot read info XML for "%s"', $this->getRepositoryPath())); } $commit = $xml->xpath('/info/entry/commit[@revision]'); if (empty($commit)) { throw new \RuntimeException(sprintf('Cannot read info XML for "%s"', $this->getRepositoryPath())); } $commit = reset($commit); return (string)($commit['revision']); }
Returns the current commit hash @return string @throws \RuntimeException
entailment
public function commit($commitMsg, array $file = null, $author = null, array $extraArgs = array()) { $author = $author ?: $this->getAuthor(); $args = array( '--message' => $commitMsg ); if ($author !== null) { $args['--username'] = $author; } if ($file !== null) { $args[] = '--'; $args = array_merge($args, $this->resolveLocalGlobPath($file)); } /** @var $result CallResult */ $result = $this->getSvn()->{'commit'}($this->getRepositoryPath(), $args); $result->assertSuccess(sprintf('Cannot commit to "%s"', $this->getRepositoryPath())); }
Commits the currently staged changes into the repository @param string $commitMsg The commit message @param array|null $file Restrict commit to the given files or NULL to commit all staged changes @param array $extraArgs Allow the user to pass extra args eg array('-i') @param string|null $author The author
entailment
public function reset() { /** @var $result CallResult */ $result = $this->getSvn()->{'revert'}($this->getRepositoryPath(), array( '--recursive', '--', '.' )); $result->assertSuccess(sprintf('Cannot reset "%s"', $this->getRepositoryPath())); $status = $this->getStatus(); foreach ($status as $item) { $file = $this->resolveFullPath($item['file']); if (@unlink($file) !== true || $item['status'] !== 'unversioned') { throw new \RuntimeException('Cannot delete file "'.$item['file'].'"'); } } }
Resets the working directory and/or the staging area and discards all changes @throws \RuntimeException
entailment
public function add(array $file = null, $force = false) { $args = array(); if ($force) { $args[] = '--force'; } if ($file !== null) { $status = $this->getStatus(); if (empty($status)) { return; } $files = $this->resolveLocalGlobPath($file); foreach ($this->getStatus() as $status) { if ( $status['status'] != 'unversioned' && in_array($status['file'], $files) ) { array_splice($files, array_search($status['file'], $files), 1); } } if (empty($files)) { return; } $args[] = '--parents'; $args[] = '--'; $args = array_merge($args, $files); } else { $toAdd = array(); $toRemove = array(); foreach ($this->getStatus() as $status) { if ($status['status'] == 'missing') { $toRemove[] = $this->resolveLocalPath($status['file']); } else if ($status['status'] == 'unversioned') { $toAdd[] = $this->resolveLocalPath($status['file']); } } if (!empty($toRemove)) { $this->remove($toRemove, false, $force); } if (empty($toAdd)) { return; } $args['--depth'] = 'infinity'; $args[] = '--'; $args = array_merge($args, $toAdd); } /** @var $result CallResult */ $result = $this->getSvn()->{'add'}($this->getRepositoryPath(), $args); $result->assertSuccess(sprintf('Cannot add "%s" to "%s"', ($file !== null) ? implode(', ', $file) : '*', $this->getRepositoryPath() )); }
Adds one or more files to the staging area @param array $file The file(s) to be added or NULL to add all new and/or changed files to the staging area @param boolean $force
entailment
public function remove(array $file, $recursive = false, $force = false) { $args = array(); if ($force) { $args[] = '--force'; } $args[] = '--'; $args = array_merge($args, $this->resolveLocalGlobPath($file)); /** @var $result CallResult */ $result = $this->getSvn()->{'delete'}($this->getRepositoryPath(), $args); $result->assertSuccess(sprintf('Cannot remove "%s" from "%s"', implode(', ', $file), $this->getRepositoryPath() )); }
Removes one or more files from the repository but does not commit the changes @param array $file The file(s) to be removed @param boolean $recursive True to recursively remove subdirectories @param boolean $force True to continue even though SVN reports a possible conflict
entailment
public function move($fromPath, $toPath, $force = false) { $args = array(); if ($force) { $args[] = '--force'; } $args[] = $this->resolveLocalPath($fromPath); $args[] = $this->resolveLocalPath($toPath); /** @var $result CallResult */ $result = $this->getSvn()->{'move'}($this->getRepositoryPath(), $args); $result->assertSuccess(sprintf('Cannot move "%s" to "%s" in "%s"', $fromPath, $toPath, $this->getRepositoryPath() )); }
Renames a file but does not commit the changes @param string $fromPath The source path @param string $toPath The destination path @param boolean $force True to continue even though SVN reports a possible conflict
entailment
public function writeFile($path, $data, $commitMsg = null, $fileMode = null, $dirMode = null, $recursive = true, $author = null ) { $file = $this->resolveFullPath($path); $fileMode = $fileMode ?: $this->getFileCreationMode(); $dirMode = $dirMode ?: $this->getDirectoryCreationMode(); $directory = dirname($file); if (!file_exists($directory) && !mkdir($directory, (int)$dirMode, $recursive)) { throw new \RuntimeException(sprintf('Cannot create "%s"', $directory)); } else if (!file_exists($file)) { if (!touch($file)) { throw new \RuntimeException(sprintf('Cannot create "%s"', $file)); } if (!chmod($file, (int)$fileMode)) { throw new \RuntimeException(sprintf('Cannot chmod "%s" to %d', $file, (int)$fileMode)); } } if (file_put_contents($file, $data) === false) { throw new \RuntimeException(sprintf('Cannot write to "%s"', $file)); } $this->add(array($file)); if ($commitMsg === null) { $commitMsg = sprintf('%s created or changed file "%s"', __CLASS__, $path); } $this->commit($commitMsg, null, $author); return $this->getCurrentCommit(); }
Writes data to a file and commit the changes immediately @param string $path The file path @param string|array $data The data to write to the file @param string|null $commitMsg The commit message used when committing the changes @param integer|null $fileMode The mode for creating the file @param integer|null $dirMode The mode for creating the intermediate directories @param boolean $recursive Create intermediate directories recursively if required @param string|null $author The author @return string The current commit hash @throws \RuntimeException If the file could not be written
entailment
public function createDirectory($path, $commitMsg = null, $dirMode = null, $recursive = true, $author = null) { $directory = $this->resolveFullPath($path); $dirMode = $dirMode ?: $this->getDirectoryCreationMode(); if (file_exists($directory) || !mkdir($directory, (int)$dirMode, $recursive)) { throw new \RuntimeException(sprintf('Cannot create "%s"', $directory)); } $this->add(array($this->resolveLocalPath($directory))); if ($commitMsg === null) { $commitMsg = sprintf('%s created directory "%s"', __CLASS__, $path); } $this->commit($commitMsg, null, $author); return $this->getCurrentCommit(); }
Writes data to a file and commit the changes immediately @param string $path The directory path @param string|null $commitMsg The commit message used when committing the changes @param integer|null $dirMode The mode for creating the intermediate directories @param boolean $recursive Create intermediate directories recursively if required @param string|null $author The author @return string The current commit hash @throws \RuntimeException If the directory could not be created
entailment
public function removeFile($path, $commitMsg = null, $recursive = false, $force = false, $author = null) { $this->remove(array($path), $recursive, $force); if ($commitMsg === null) { $commitMsg = sprintf('%s deleted file "%s"', __CLASS__, $path); } $this->commit($commitMsg, array($path), $author); return $this->getCurrentCommit(); }
Removes a file and commit the changes immediately @param string $path The file path @param string|null $commitMsg The commit message used when committing the changes @param boolean $recursive True to recursively remove subdirectories @param boolean $force True to continue even though SVN reports a possible conflict @param string|null $author The author @return string The current commit hash
entailment
public function renameFile($fromPath, $toPath, $commitMsg = null, $force = false, $author = null) { $this->move($fromPath, $toPath, $force); if ($commitMsg === null) { $commitMsg = sprintf('%s renamed/moved file "%s" to "%s"', __CLASS__, $fromPath, $toPath); } $this->commit($commitMsg, array($fromPath, $toPath), $author); return $this->getCurrentCommit(); }
Renames a file and commit the changes immediately @param string $fromPath The source path @param string $toPath The destination path @param string|null $commitMsg The commit message used when committing the changes @param boolean $force True to continue even though SVN reports a possible conflict @param string|null $author The author @return string The current commit hash
entailment
public function getLog($limit = null, $skip = null) { $arguments = array( '--xml', '--revision' => 'HEAD:0' ); $skip = ($skip === null) ? 0 : (int)$skip; if ($limit !== null) { $arguments['--limit'] = (int)($limit + $skip); } /** @var $result CallResult */ $result = $this->getSvn()->{'log'}($this->getRepositoryPath(), $arguments); $result->assertSuccess(sprintf('Cannot retrieve log from "%s"', $this->getRepositoryPath() )); $xml = simplexml_load_string($result->getStdOut()); if (!$xml) { throw new \RuntimeException(sprintf('Cannot read log XML for "%s"', $this->getRepositoryPath())); } $logEntries = new \ArrayIterator($xml->xpath('/log/logentry')); if ($limit !== null) { $logEntries = new \LimitIterator($logEntries, $skip, $limit); } $log = array(); foreach ($logEntries as $item) { $log[] = array( (string)$item['revision'], (string)$item->author, (string)$item->date, (string)$item->msg ); } return $log; }
Returns the current repository log @param integer|null $limit The maximum number of log entries returned @param integer|null $skip Number of log entries that are skipped from the beginning @return array @throws \RuntimeException
entailment
public function getObjectInfo($path, $ref = 'HEAD') { /** @var $result CallResult */ $result = $this->getSvn()->{'info'}($this->getRepositoryPath(), array( '--xml', '--revision' => $ref, $this->resolveLocalPath($path) )); $result->assertSuccess(sprintf('Cannot get info for "%s" at "%s" from "%s"', $path, $ref, $this->getRepositoryPath() )); $xml = simplexml_load_string($result->getStdOut()); if (!$xml) { throw new \RuntimeException(sprintf('Cannot read info XML for "%s" at "%s" from "%s"', $path, $ref, $this->getRepositoryPath() )); } $entry = $xml->xpath('/info/entry'); if (count($entry) !== 1) { throw new \RuntimeException(sprintf('Cannot read info XML for "%s" at "%s" from "%s"', $path, $ref, $this->getRepositoryPath() )); } $entry = reset($entry); $mode = 0; switch ((string)$entry['kind']) { case 'dir': $mode |= 0040000; break; case 'file': $mode |= 0100000; break; } return array( 'type' => (string)$entry['kind'], 'mode' => (int)$mode, 'size' => 0 ); }
Returns information about an object at a given version The information returned is an array with the following structure array( 'type' => blob|tree|commit, 'mode' => 0040000 for a tree, 0100000 for a blob, 0 otherwise, 'size' => the size ) @param string $path The path to the object @param string $ref The version ref @return array The object info @throws \RuntimeException
entailment
public function listDirectory($directory = '.', $ref = 'HEAD') { $directory = FileSystem::normalizeDirectorySeparator($directory); $directory = rtrim($directory, '/').'/'; $args = array( '--xml', '--revision' => $ref, $this->resolveLocalPath($directory) ); /** @var $result CallResult */ $result = $this->getSvn()->{'list'}($this->getRepositoryPath(), $args); $result->assertSuccess(sprintf('Cannot list directory "%s" at "%s" from "%s"', $directory, $ref, $this->getRepositoryPath() )); $xml = simplexml_load_string($result->getStdOut()); if (!$xml) { throw new \RuntimeException(sprintf('Cannot read list XML for "%s" at "%s" from "%s"', $directory, $ref, $this->getRepositoryPath() )); } $list = array(); foreach ($xml->xpath('/lists/list/entry') as $item) { $list[] = (string)$item->name; } return $list; }
List the directory at a given version @param string $directory The path ot the directory @param string $ref The version ref @return array @throws \RuntimeException
entailment
public function getStatus() { /** @var $result CallResult */ $result = $this->getSvn()->{'status'}($this->getRepositoryPath(), array( '--xml' )); $result->assertSuccess( sprintf('Cannot retrieve status from "%s"', $this->getRepositoryPath()) ); $xml = simplexml_load_string($result->getStdOut()); if (!$xml) { throw new \RuntimeException(sprintf('Cannot read status XML for "%s"', $this->getRepositoryPath())); } $status = array(); foreach ($xml->xpath('/status/target/entry') as $entry) { $status[] = array( 'file' => (string)$entry['path'], 'status' => (string)$entry->{'wc-status'}['item'] ); } return $status; }
Returns the current status of the working directory The returned array structure is array( 'file' => '...', 'status' => '...' ) @return array @throws \RuntimeException
entailment
public function getDiff(array $files = null) { $diffs = array(); if (is_null($files)) { $status = $this->getStatus(); foreach ($status as $entry) { if ($entry['status'] !== 'modified') { continue; } $files[] = $entry['file']; } asort($files); } $files = array_map(array($this, 'resolveLocalPath'), $files); foreach ($files as $file) { $result = $this->getSvn()->{'diff'}($this->getRepositoryPath(), $file); $result->assertSuccess(sprintf('Cannot show diff for "%s" from "%s"', $file, $this->getRepositoryPath() )); $diffs[$file] = $result->getStdOut(); } return $diffs; }
Returns the diff of a file @param array $files The path to the file @return string[]
entailment
protected function resolveLocalGlobPath(array $files) { $absoluteFiles = $this->resolveFullPath($files); $expandedFiles = array(); foreach ($absoluteFiles as $absoluteFile) { $globResult = glob($absoluteFile); if ( empty($globResult) && stripos($absoluteFile, '*') === false && !file_exists($absoluteFile) ) { $expandedFiles[] = $absoluteFile; } else { $expandedFiles = array_merge($expandedFiles, $globResult); } } return $this->resolveLocalPath($expandedFiles); }
Resolves an absolute path containing glob wildcards into a path relative to the repository path @param array $files The list of files @return array
entailment
public function setCwd($cwd) { if (empty($cwd)) { $cwd = null; } else { $cwd = (string)$cwd; } $this->cwd = $cwd; return $this; }
Sets the working directory for the call @param string|null $cwd The working directory in which the call will be executed @return Call
entailment
public function execute($stdIn = null) { $stdOut = fopen('php://temp', 'r'); $stdErr = fopen('php://temp', 'r'); $descriptorSpec = array( 0 => array("pipe", "r"), // stdin is a pipe that the child will read from 1 => $stdOut, // stdout is a temp file that the child will write to 2 => $stdErr // stderr is a temp file that the child will write to ); $pipes = array(); $process = proc_open( $this->getCmd(), $descriptorSpec, $pipes, $this->getCwd(), $this->getEnv() ); if (is_resource($process)) { if ($stdIn !== null) { fwrite($pipes[0], (string)$stdIn); } fclose($pipes[0]); $returnCode = proc_close($process); return new CallResult($this, $stdOut, $stdErr, $returnCode); } else { fclose($stdOut); fclose($stdErr); throw new \RuntimeException(sprintf('Cannot execute "%s"', $this->getCmd())); } }
Executes the call using the preconfigured command @param string|null $stdIn Content that will be piped to the command @return CallResult @throws \RuntimeException If the command cannot be executed
entailment
public function resolveRouteBinding($value) { $id = $this->getOptimus()->decode($value); return $this->where($this->getRouteKeyName(), '=', $id)->first(); }
Retrieve the model for a bound value. @param mixed $value @return \Illuminate\Database\Eloquent\Model|null
entailment
protected function getOptimus() { $connection = null; if (property_exists($this, 'optimusConnection')) { $connection = $this->optimusConnection; } return app('optimus')->connection($connection); }
Get the Optimus instance. @return \Cog\Laravel\Optimus\OptimusManager
entailment
private function isConfigured() : bool { if (!is_readable($this->settings['sp_key_file'])) { return false; } if (!is_readable($this->settings['sp_cert_file'])) { return false; } $key = file_get_contents($this->settings['sp_key_file']); if (!openssl_get_privatekey($key)) { return false; } $cert = file_get_contents($this->settings['sp_cert_file']); if (!openssl_get_publickey($cert)) { return false; } if (!SignatureUtils::certDNEquals($cert, $this->settings)) { return false; } return true; }
(i.e. the library has been configured correctly
entailment
private function configure() { $keyCert = SignatureUtils::generateKeyCert($this->settings); $dir = dirname($this->settings['sp_key_file']); if (!is_dir($dir)) { throw new \InvalidArgumentException('The directory you selected for sp_key_file does not exist. Please create ' . $dir); } $dir = dirname($this->settings['sp_cert_file']); if (!is_dir($dir)) { throw new \InvalidArgumentException('The directory you selected for sp_cert_file does not exist. Please create ' . $dir); } file_put_contents($this->settings['sp_key_file'], $keyCert['key']); file_put_contents($this->settings['sp_cert_file'], $keyCert['cert']); }
this function should be used with care because it requires write access to the filesystem, and invalidates the metadata
entailment
protected function preConfigure(Payment $payment) { if (!$payment->getTarget()) { $target = new Target(); $target->goid = $this->client->getGoId(); $target->type = TargetType::ACCOUNT; $payment->setTarget($target); } }
Add required target field @param Payment $payment @return void
entailment
public function createFileBuffer(PathInformationInterface $path, $mode) { $repo = $path->getRepository(); $buffer = $repo->showCommit($path->getArgument('ref')); return new StringBuffer($buffer, array(), 'r'); }
Returns the file stream to handle the requested path @param PathInformationInterface $path The path information @param string $mode The mode used to open the path @return FileBufferInterface The file buffer to handle the path
entailment
public function handle(Request $request, Closure $next) { $fields = array_slice(func_get_args(), 2); foreach ($fields as $field) { $hiddenField = '_'.$field; if ($request->has($hiddenField)) { $request->merge([$field => $this->formatDate($request->get($hiddenField))]); } } return $next($request); }
Handle an incoming request. @param \Illuminate\Http\Request $request @param \Closure $next @return mixed
entailment
public static function bubble($path, \Closure $comparator) { $found = null; $path = self::normalizeDirectorySeparator($path); $drive = null; if (preg_match('~^(\w:)(.+)~', $path, $parts)) { $drive = $parts[1]; $path = $parts[2]; } $pathParts = explode('/', $path); while (count($pathParts) > 0 && $found === null) { $path = implode('/', $pathParts); if ($comparator($path)) { $found = $path; } array_pop($pathParts); } if ($drive && $found) { $found = $drive.$found; } return $found; }
Bubbles up a path until $comparator returns true @param string $path The path @param \Closure $comparator The callback used inside when bubbling to determine a finding @return string|null The path that is found or NULL otherwise
entailment
protected function _camelizePlugin($plugin) { if (strpos($plugin, '/') === false) { return Inflector::camelize($plugin); } list($vendor, $plugin) = explode('/', $plugin, 2); return Inflector::camelize($vendor) . '/' . Inflector::camelize($plugin); }
Camelizes the previously underscored plugin route taking into account plugin vendors @param string $plugin Plugin name @return string
entailment
protected function _underscore($url) { foreach (['controller', 'plugin', 'action'] as $element) { if (!empty($url[$element])) { $url[$element] = Inflector::underscore($url[$element]); } } return $url; }
Helper method for creating underscore keys in a URL array. @param array $url An array of URL keys. @return array
entailment
public function read($count) { if ($this->isEof()) { return null; } $buffer = substr($this->buffer, $this->position, $count); $this->position += $count; return $buffer; }
Reads $count bytes from the buffer @param integer $count The number of bytes to read @return string|null
entailment
public function write($data) { $dataLength = strlen($data); $start = substr($this->buffer, 0, $this->position); $end = substr($this->buffer, $this->position + $dataLength); $this->buffer = $start.$data.$end; $this->length = strlen($this->buffer); $this->position += $dataLength; return $dataLength; }
Writes the given date into the buffer at the current pointer position @param string $data The data to write @return integer The number of bytes written
entailment