sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
protected function createPackageFolder($packagePath)
{
$this->info('Create package folder.');
if (File::exists($packagePath)) {
$this->info('Package folder already exists. Skipping.');
return;
}
if (! File::makeDirectory($packagePath, 0755, true)) {
throw new RuntimeException('Cannot create package folder');
}
$this->info('Package folder was successfully created.');
} | Create package folder.
@param string $packagePath
@throws RuntimeException | entailment |
protected function removePackageFolder($packagePath)
{
$this->info('Remove package folder.');
if (File::exists($packagePath)) {
if (! File::deleteDirectory($packagePath)) {
throw new RuntimeException('Cannot remove package folder');
}
$this->info('Package folder was successfully removed.');
} else {
$this->info('Package folder does not exists. Skipping.');
}
} | Remove package folder.
@param $packagePath
@throws RuntimeException | entailment |
public function handle()
{
$vendor = $this->getVendor();
$package = $this->getPackage();
$vendorFolderName = $this->getVendorFolderName($vendor);
$packageFolderName = $this->getPackageFolderName($package);
$relPackagePath = "packages/$vendorFolderName/$packageFolderName";
$packagePath = base_path($relPackagePath);
try {
$this->createPackageFolder($packagePath);
$this->registerPackage($vendorFolderName, $packageFolderName, $relPackagePath);
$this->copySkeleton($packagePath, $vendor, $package, $vendorFolderName, $packageFolderName);
$this->initRepo($packagePath);
$this->composerUpdatePackage($vendorFolderName, $packageFolderName);
$this->composerDumpAutoload();
$this->info('Finished. Are you ready to write awesome package?');
} catch (Exception $e) {
$this->error($e->getMessage());
return -1;
}
return 0;
} | Execute the console command.
@return mixed | entailment |
public function levenshtein($first, $second)
{
$l = new \Atomescrochus\StringSimilarities\Levenshtein();
return $l->compare($first, $second);
} | Run a basic levenshtein comparison using PHP's built-in function
@param string $first First string to compare
@param string $second Second string to compare
@return string Returns the phrase passed in | entailment |
protected function askUser($question, $defaultValue = '')
{
if ($this->option('interactive')) {
return $this->ask($question, $defaultValue);
}
return $defaultValue;
} | Ask user.
@param $question
@param $defaultValue
@return string | entailment |
public function preProcess(PageLayoutView &$parentObject, &$drawItem, &$headerContent, &$itemContent, array &$row) {
if ($row['CType'] === 'pagelist_selected' || $row['CType'] === 'pagelist_sub' || $row['CType'] === 'pagelist_category') {
if ($row['CType'] === 'pagelist_selected') {
$itemContent = $parentObject->linkEditContent('<span style="display: block; margin-top: 0.3em;">Pagelist: selected '. $row['pages'] .'</span>', $row);
}
if ($row['CType'] === 'pagelist_sub') {
$itemContent = $parentObject->linkEditContent('<span style="display: block; margin-top: 0.3em;">Pagelist: subpages from '. $row['pages'] .'</span>', $row);
}
if ($row['CType'] === 'pagelist_category') {
$itemContent = $parentObject->linkEditContent('<span style="display: block; margin-top: 0.3em;">Pagelist: from category '. $row['selected_categories'] .'</span>', $row);
}
$itemContent .= '<ul style="margin: 0; padding: 0.2em 1.4em;">';
if ($row['CType'] === 'pagelist_sub') {
if ($row['tx_pagelist_orderby']) {
$itemContent .= '<li>' . $parentObject->linkEditContent($parentObject->renderText('Order by: ' . $row['tx_pagelist_orderby']), $row) . '</li>';
}
}
if ($row['CType'] === 'pagelist_sub' || $row['CType'] === 'pagelist_category') {
if ($row['tx_pagelist_startfrom']) {
$itemContent .= '<li>' . $parentObject->linkEditContent($parentObject->renderText('Start from: ' . $row['tx_pagelist_startfrom']), $row) . '</li>';
}
}
if ($row['CType'] === 'pagelist_sub' || $row['CType'] === 'pagelist_category') {
if ($row['tx_pagelist_limit']) {
$itemContent .= '<li>' . $parentObject->linkEditContent($parentObject->renderText('Items shown: ' . $row['tx_pagelist_limit']), $row) . '</li>';
}
}
if ($row['tx_pagelist_disableimages'] == 1) {
$itemContent .= '<li>' . $parentObject->linkEditContent('Images: disabled', $row) . '</li>';
}
if ($row['tx_pagelist_disableabstract'] == 1) {
$itemContent .= '<li>' . $parentObject->linkEditContent('Introduction: disabled', $row) . '</li>';
}
if ($row['tx_pagelist_paginate'] == 1) {
$itemContent .= '<li>' . $parentObject->linkEditContent('Pagination: enabled', $row) . '</li>';
}
if ($row['tx_pagelist_paginateitems'] > 1 && $row['tx_pagelist_paginate'] == 1) {
$itemContent .= '<li>' . $parentObject->linkEditContent($parentObject->renderText('Items per page: ' . $row['tx_pagelist_paginateitems']), $row) . '</li>';
}
if ($row['tx_pagelist_paginateitems'] == 0 && $row['tx_pagelist_paginate'] == 1) {
$itemContent .= '<li>' . $parentObject->linkEditContent('Items per page: TypoScript', $row) . '</li>';
}
if ($row['tx_pagelist_authors'] > 0) {
$itemContent .= '<li>' . $parentObject->linkEditContent('Author filter: active', $row) . '</li>';
}
$itemContent .= '</ul>';
$drawItem = FALSE;
}
} | Preprocesses the preview rendering of a content element of type "textmedia"
@param \TYPO3\CMS\Backend\View\PageLayoutView $parentObject Calling parent object
@param bool $drawItem Whether to draw the item using the default functionality
@param string $headerContent Header content
@param string $itemContent Item content
@param array $row Record row of tt_content
@return void | entailment |
public function run()
{
if(empty($this->options['id'])) {
$this->options['id'] = $this->id;
}
if($this->encodeLabel) {
$this->label = Html::encode($this->label);
}
$perPage = !empty($_GET[$this->pageSizeParam]) ? $_GET[$this->pageSizeParam] : $this->defaultPageSize;
$listHtml = Html::dropDownList($this->pageSizeParam, $perPage, $this->sizes, $this->options);
$labelHtml = Html::label($this->label, $this->options['id'], $this->labelOptions);
$output = str_replace(['{list}', '{label}'], [$listHtml, $labelHtml], $this->template);
return $output;
} | Runs the widget and render the output | entailment |
protected function registerPackage($vendor, $package, $relPackagePath)
{
$this->info('Register package in composer.json.');
$composerJson = $this->loadComposerJson();
if (! isset($composerJson['repositories'])) {
Arr::set($composerJson, 'repositories', []);
}
$filtered = array_filter($composerJson['repositories'], function ($repository) use ($relPackagePath) {
return $repository['type'] === 'path'
&& $repository['url'] === $relPackagePath;
});
if (count($filtered) === 0) {
$this->info('Register composer repository for package.');
$composerJson['repositories'][] = (object) [
'type' => 'path',
'url' => $relPackagePath,
];
} else {
$this->info('Composer repository for package is already registered.');
}
Arr::set($composerJson, "require.$vendor/$package", 'dev-master');
$this->saveComposerJson($composerJson);
$this->info('Package was successfully registered in composer.json.');
} | Register package in composer.json.
@param $vendor
@param $package
@param $relPackagePath
@throws RuntimeException | entailment |
protected function unregisterPackage($vendor, $package, $relPackagePath)
{
$this->info('Unregister package from composer.json.');
$composerJson = $this->loadComposerJson();
unset($composerJson['require']["$vendor\\$package\\"]);
$repositories = array_filter($composerJson['repositories'], function ($repository) use ($relPackagePath) {
return $repository['type'] !== 'path'
|| $repository['url'] !== $relPackagePath;
});
$composerJson['repositories'] = $repositories;
if (count($composerJson['repositories']) === 0) {
unset($composerJson['repositories']);
}
$this->saveComposerJson($composerJson);
$this->info('Package was successfully unregistered from composer.json.');
} | Unregister package from composer.json.
@param $vendor
@param $package
@throws FileNotFoundException
@throws RuntimeException | entailment |
protected function loadComposerJson()
{
$composerJsonPath = $this->getComposerJsonPath();
if (! File::exists($composerJsonPath)) {
throw new FileNotFoundException('composer.json does not exist');
}
$composerJsonContent = File::get($composerJsonPath);
$composerJson = json_decode($composerJsonContent, true);
if (! is_array($composerJson)) {
throw new RuntimeException("Invalid composer.json file [$composerJsonPath]");
}
return $composerJson;
} | Load and parse content of composer.json.
@return array
@throws FileNotFoundException
@throws RuntimeException | entailment |
protected function saveComposerJson($composerJson)
{
$newComposerJson = json_encode(
$composerJson,
JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES
);
$composerJsonPath = $this->getComposerJsonPath();
if (File::put($composerJsonPath, $newComposerJson) === false) {
throw new RuntimeException("Cannot write to composer.json [$composerJsonPath]");
}
} | @param array $composerJson
@throws RuntimeException | entailment |
public function handle()
{
$url = $this->argument('url');
try {
list($vendorFolderName, $packageFolderName) = $this->getVendorAndFolderName($url);
} catch (Exception $e) {
$this->error($e->getMessage());
return -1;
}
$vendor = $this->getVendor() ?: Str::title($vendorFolderName);
$package = $this->getPackage() ?: Str::studly($packageFolderName);
$relPackagePath = "packages/$vendorFolderName/$packageFolderName";
$packagePath = base_path($relPackagePath);
try {
$this->cloneRepo($url, $packagePath, $this->option('branch'));
$this->registerPackage($vendor, $package, $relPackagePath);
$this->composerUpdatePackage($vendorFolderName, $packageFolderName);
$this->composerDumpAutoload();
$this->info('Finished.');
} catch (Exception $e) {
$this->error($e->getMessage());
return -1;
}
return 0;
} | Execute the console command.
@return mixed | entailment |
protected function getVendorAndFolderName($url)
{
if (Str::contains($url, '@')) {
$vendorAndPackage = explode(':', $url);
$vendorAndPackage = explode('/', $vendorAndPackage[1]);
return [
$vendorAndPackage[0],
Str::replaceLast('.git', '', $vendorAndPackage[1]),
];
}
$urlParts = explode('/', $url);
return [$urlParts[3], $urlParts[4]];
} | Get vendor and package folder name.
@param $url
@return array | entailment |
public function hasMultilingualAttribute($name)
{
return in_array($name, $this->attributes) || array_key_exists($name, $this->_multilingualAttributes);
} | Whether an attribute exists
@param string $name the name of the attribute
@return boolean | entailment |
public function getMultilingualAttributeLabel($attribute)
{
$attributeLabels = $this->getMultilingualAttributeLabels();
return isset($attributeLabels[$attribute]) ? $attributeLabels[$attribute] : $attribute;
} | Return multilingual attribute label.
@param string $attribute
@return string | entailment |
public function beforeAction($event)
{
if (!Yii::$app->errorHandler->exception && count($this->languages) > 1) {
// Set language by GET request, session or cookie
if ($language = Yii::$app->getRequest()->get('language')) {
Yii::$app->language = $this->getLanguageCode($language);
Yii::$app->session->set('language', Yii::$app->language);
Yii::$app->response->cookies->add(new \yii\web\Cookie([
'name' => 'language',
'value' => Yii::$app->session->get('language'),
'expire' => time() + 31536000 // one year
]));
} elseif ($language = Yii::$app->session->get('language')) {
Yii::$app->language = $this->getLanguageCode($language);
} elseif (isset(Yii::$app->request->cookies['language'])) {
$language = Yii::$app->request->cookies['language']->value;
Yii::$app->language = $this->getLanguageCode($language);
}
Yii::$app->formatter->locale = Yii::$app->language;
}
return $event->isValid;
} | Tracks language parameter for multilingual controllers.
@param ActionEvent $event
@return bool
@throws MethodNotAllowedHttpException|InvalidConfigException when the request method is not allowed. | entailment |
protected function getLanguageCode($redirectLanguageCode)
{
$sourceLanguage = MultilingualHelper::getRedirectedLanguageCode($redirectLanguageCode, $this->languageRedirects);
if (!isset($this->languages[$sourceLanguage])) {
throw new NotFoundHttpException(Yii::t('yii', 'Page not found.'));
}
return $sourceLanguage;
} | Returns code of language by its redirect language code.
@param string $redirectLanguageCode
@return string
@throws NotFoundHttpException | entailment |
public function getStatus($id = null)
{
if ($this->isSuccess()) {
if (!$id) {
$result = $this->getResult();
return $result[0]['status'];
}
foreach ($this->getResult() as $row) {
if ($row['id'] == $id) {
return $row['status'];
}
}
}
return false;
} | Get the status of a lead. If no lead ID is given, it returns the status of the first lead returned.
@param $id
@return bool | entailment |
public function register()
{
$this->app->singleton('orchestra.imagine', function (Application $app) {
$manager = new ImagineManager($app);
$namespace = $this->hasPackageRepository() ? 'orchestra/imagine::' : 'orchestra.imagine';
$manager->setConfig($app->make('config')->get($namespace));
return $manager;
});
$this->registerCoreContainerAliases();
} | Register the service provider.
@return void | entailment |
protected function registerCoreContainerAliases(): void
{
$this->app->alias('orchestra.imagine', ImagineManager::class);
$this->app->bind(ImagineInterface::class, function (Application $app) {
return $app->make('orchestra.imagine')->driver();
});
} | Register the core class aliases in the container.
@return void | entailment |
public function handle(ImagineInterface $imagine)
{
$data = $this->getFilteredOptions($this->options);
$path = \rtrim($data['path'], '/');
$source = Str::replace('{filename}.{extension}', $data);
$destination = Str::replace($data['format'], $data);
$this->handleImageManipulation(
$imagine->open("{$path}/{$source}"), $data
)->save("{$path}/{$destination}");
} | Execute the job.
@param \Imagine\Image\ImagineInterface $imagine
@return void | entailment |
protected function getFilteredOptions(array $options)
{
$default = $this->getDefaultOptions();
$options = \array_merge($default, $options);
$uses = \array_unique(\array_merge([
'path', 'filename', 'extension', 'format',
], \array_keys($default)));
$data = Arr::only($options, $uses);
return $data;
} | Get filtered options.
@param array $options
@return array | entailment |
public function generateTableName($ownerTableName, $tableNameSuffix)
{
if (preg_match('/{{%(\w+)}}$/', $ownerTableName, $matches)) {
$ownerTableName = $matches[1];
}
return '{{%' . $ownerTableName . $tableNameSuffix . '}}';
} | Generate translation table name.
@param ActiveRecord $ownerTableName
@param string $tableNameSuffix
@return string | entailment |
public function getTranslations()
{
return $this->owner->hasMany($this->translationClassName, [$this->languageForeignKey => $this->_ownerPrimaryKey]);
} | Relation to model translations
@return ActiveQuery | entailment |
public function getTranslation($language = null)
{
$language = $language ?: $this->_currentLanguage;
return $this->owner->hasOne($this->translationClassName, [$this->languageForeignKey => $this->_ownerPrimaryKey])
->where([$this->languageField => $language]);
} | Relation to model translation
@param $language
@return ActiveQuery | entailment |
public function beforeValidate()
{
foreach ($this->attributes as $attribute) {
$this->setMultilingualAttribute($this->getAttributeName($attribute, $this->_currentLanguage), $this->getMultilingualAttribute($attribute));
}
} | Handle 'beforeValidate' event of the owner. | entailment |
public function afterFind()
{
/** @var ActiveRecord $owner */
$owner = $this->owner;
if ($owner->isRelationPopulated('translations') && $related = $owner->getRelatedRecords()['translations']) {
$translations = $this->indexByLanguage($related);
foreach ($this->_languageKeys as $language) {
foreach ($this->attributes as $attribute) {
foreach ($translations as $translation) {
if ($translation->{$this->languageField} == $language) {
$attributeName = $this->localizedPrefix . $attribute;
$this->setMultilingualAttribute($this->getAttributeName($attribute, $language), $translation->{$attributeName});
}
}
}
}
} else if ($owner->getAttribute($this->_ownerPrimaryKey) !== null) {
if (!$owner->isRelationPopulated('translation')) {
$owner->translation;
}
$translation = $owner->getRelatedRecords()['translation'];
if ($translation) {
foreach ($this->attributes as $attribute) {
$attribute_name = $this->localizedPrefix . $attribute;
$owner->setMultilingualAttribute($attribute, $translation->$attribute_name);
}
}
}
foreach ($this->attributes as $attribute) {
if ($owner->hasAttribute($attribute) && $this->getMultilingualAttribute($attribute)) {
$owner->setAttribute($attribute, $this->getMultilingualAttribute($attribute));
}
}
} | Handle 'afterFind' event of the owner. | entailment |
public function afterUpdate()
{
/** @var ActiveRecord $owner */
$owner = $this->owner;
if ($owner->isRelationPopulated('translations')) {
$translations = $this->indexByLanguage($owner->getRelatedRecords()['translations']);
$this->saveTranslations($translations);
}
} | Handle 'afterUpdate' event of the owner. | entailment |
protected function initTranslationClass()
{
if (!class_exists($this->translationClassName)) {
$namespace = substr($this->translationClassName, 0, strrpos($this->translationClassName, '\\'));
$translationClassName = $this->getShortClassName($this->translationClassName);
eval('
namespace ' . $namespace . ';
use yii\db\ActiveRecord;
class ' . $translationClassName . ' extends ActiveRecord
{
public static function tableName()
{
return \'' . $this->tableName . '\';
}
}');
}
} | Create dynamic translation model. | entailment |
public static function factory($config = array())
{
$default = array(
'url' => false,
'munchkin_id' => false,
'version' => 1,
'bulk' => false
);
$required = array('client_id', 'client_secret', 'version');
$config = Collection::fromConfig($config, $default, $required);
$url = $config->get('url');
if (!$url) {
$munchkin = $config->get('munchkin_id');
if (!$munchkin) {
throw new \Exception('Must provide either a URL or Munchkin code.');
}
$url = sprintf('https://%s.mktorest.com', $munchkin);
}
$grantType = new Credentials($url, $config->get('client_id'), $config->get('client_secret'));
$auth = new Oauth2Plugin($grantType);
if ($config->get('bulk') === true) {
$restUrl = sprintf('%s/bulk/v%d', rtrim($url, '/'), $config->get('version'));
} else {
$restUrl = sprintf('%s/rest/v%d', rtrim($url, '/'), $config->get('version'));
}
$client = new self($restUrl, $config);
$client->addSubscriber($auth);
$client->setDescription(ServiceDescription::factory(__DIR__ . '/service.json'));
$client->setDefaultOption('headers/Content-Type', 'application/json');
return $client;
} | {@inheritdoc} | entailment |
public function importLeadsCsv($args)
{
if (!is_readable($args['file'])) {
throw new \Exception('Cannot read file: ' . $args['file']);
}
if (empty($args['format'])) {
$args['format'] = 'csv';
}
return $this->getResult('importLeadsCsv', $args);
} | Import Leads via file upload
@param array $args - Must contain 'format' and 'file' keys
e.g. array( 'format' => 'csv', 'file' => '/full/path/to/filename.csv'
@link http://developers.marketo.com/documentation/rest/import-lead/
@return array
@throws \Exception | entailment |
public function getBulkUploadStatus($batchId)
{
if (empty($batchId) || !is_int($batchId)) {
throw new \Exception('Invalid $batchId provided in ' . __METHOD__);
}
return $this->getResult('getBulkUploadStatus', array('batchId' => $batchId));
} | Get status of an async Import Lead file upload
@param int $batchId
@link http://developers.marketo.com/documentation/rest/get-import-lead-status/
@return array | entailment |
public function getBulkUploadFailures($batchId)
{
if( empty($batchId) || !is_int($batchId) ) {
throw new \Exception('Invalid $batchId provided in ' . __METHOD__);
}
return $this->getResult('getBulkUploadFailures', array('batchId' => $batchId));
} | Get failed lead results from an Import Lead file upload
@param int $batchId
@link http://developers.marketo.com/documentation/rest/get-import-failure-file/
@return Guzzle\Http\Message\Response | entailment |
public function getBulkUploadWarnings($batchId)
{
if( empty($batchId) || !is_int($batchId) ) {
throw new \Exception('Invalid $batchId provided in ' . __METHOD__);
}
return $this->getResult('getBulkUploadWarnings', array('batchId' => $batchId));
} | Get warnings from Import Lead file upload
@param int $batchId
@link http://developers.marketo.com/documentation/rest/get-import-warning-file/
@return Guzzle\Http\Message\Response | entailment |
private function createOrUpdateLeadsCommand($action, $leads, $lookupField, $args, $returnRaw = false)
{
$args['input'] = $leads;
$args['action'] = $action;
if (isset($lookupField)) {
$args['lookupField'] = $lookupField;
}
return $this->getResult('createOrUpdateLeads', $args, false, $returnRaw);
} | Calls the CreateOrUpdateLeads command with the given action.
@param string $action
@param array $leads
@param string $lookupField
@param array $args
@see Client::createLeads()
@see Client::createOrUpdateLeads()
@see Client::updateLeads()
@see Client::createDuplicateLeads()
@link http://developers.marketo.com/documentation/rest/createupdate-leads/
@return CreateOrUpdateLeadsResponse | entailment |
public function createLeads($leads, $lookupField = null, $args = array())
{
return $this->createOrUpdateLeadsCommand('createOnly', $leads, $lookupField, $args);
} | Create the given leads.
@param array $leads
@param string $lookupField
@param array $args
@see Client::createOrUpdateLeadsCommand()
@link http://developers.marketo.com/documentation/rest/createupdate-leads/
@return CreateOrUpdateLeadsResponse | entailment |
public function createOrUpdateLeads($leads, $lookupField = null, $args = array())
{
return $this->createOrUpdateLeadsCommand('createOrUpdate', $leads, $lookupField, $args);
} | Update the given leads, or create them if they do not exist.
@param array $leads
@param string $lookupField
@param array $args
@see Client::createOrUpdateLeadsCommand()
@link http://developers.marketo.com/documentation/rest/createupdate-leads/
@return CreateOrUpdateLeadsResponse | entailment |
public function updateLeads($leads, $lookupField = null, $args = array())
{
return $this->createOrUpdateLeadsCommand('updateOnly', $leads, $lookupField, $args);
} | Update the given leads.
@param array $leads
@param string $lookupField
@param array $args
@see Client::createOrUpdateLeadsCommand()
@link http://developers.marketo.com/documentation/rest/createupdate-leads/
@return CreateOrUpdateLeadsResponse | entailment |
public function createDuplicateLeads($leads, $lookupField = null, $args = array())
{
return $this->createOrUpdateLeadsCommand('createDuplicate', $leads, $lookupField, $args);
} | Create duplicates of the given leads.
@param array $leads
@param string $lookupField
@param array $args
@see Client::createOrUpdateLeadsCommand()
@link http://developers.marketo.com/documentation/rest/createupdate-leads/
@return CreateOrUpdateLeadsResponse | entailment |
public function getLists($ids = null, $args = array(), $returnRaw = false)
{
if ($ids) {
$args['id'] = $ids;
}
return $this->getResult('getLists', $args, is_array($ids), $returnRaw);
} | Get multiple lists.
@param int|array $ids Filter by one or more IDs
@param array $args
@link http://developers.marketo.com/documentation/rest/get-multiple-lists/
@return GetListsResponse | entailment |
public function getList($id, $args = array(), $returnRaw = false)
{
$args['id'] = $id;
return $this->getResult('getList', $args, false, $returnRaw);
} | Get a list by ID.
@param int $id
@param array $args
@link http://developers.marketo.com/documentation/rest/get-list-by-id/
@return GetListResponse | entailment |
public function getLeadsByFilterType($filterType, $filterValues, $fields = array(), $nextPageToken = null, $returnRaw = false)
{
$args['filterType'] = $filterType;
$args['filterValues'] = $filterValues;
if ($nextPageToken) {
$args['nextPageToken'] = $nextPageToken;
}
if (count($fields)) {
$args['fields'] = implode(',', $fields);
}
return $this->getResult('getLeadsByFilterType', $args, false, $returnRaw);
} | Get multiple leads by filter type.
@param string $filterType One of the supported filter types, e.g. id, cookie or email. See Marketo's documentation for all types.
@param string $filterValues Comma separated list of filter values
@param array $fields Array of field names to be returned in the response
@param string $nextPageToken
@link http://developers.marketo.com/documentation/rest/get-multiple-leads-by-filter-type/
@return GetLeadsResponse | entailment |
public function getLeadByFilterType($filterType, $filterValue, $fields = array(), $returnRaw = false)
{
$args['filterType'] = $filterType;
$args['filterValues'] = $filterValue;
if (count($fields)) {
$args['fields'] = implode(',', $fields);
}
return $this->getResult('getLeadByFilterType', $args, false, $returnRaw);
} | Get a lead by filter type.
Convenient method which uses {@link http://developers.marketo.com/documentation/rest/get-multiple-leads-by-filter-type/}
internally and just returns the first lead if there is one.
@param string $filterType One of the supported filter types, e.g. id, cookie or email. See Marketo's documentation for all types.
@param string $filterValue The value to filter by
@param array $fields Array of field names to be returned in the response
@link http://developers.marketo.com/documentation/rest/get-multiple-leads-by-filter-type/
@return GetLeadResponse | entailment |
public function getLeadsByList($listId, $args = array(), $returnRaw = false)
{
$args['listId'] = $listId;
return $this->getResult('getLeadsByList', $args, false, $returnRaw);
} | Get multiple leads by list ID.
@param int $listId
@param array $args
@link http://developers.marketo.com/documentation/rest/get-multiple-leads-by-list-id/
@return GetLeadsResponse | entailment |
public function getLead($id, $fields = null, $args = array(), $returnRaw = false)
{
$args['id'] = $id;
if (is_array($fields)) {
$args['fields'] = implode(',', $fields);
}
return $this->getResult('getLead', $args, false, $returnRaw);
} | Get a lead by ID.
@param int $id
@param array $fields
@param array $args
@link http://developers.marketo.com/documentation/rest/get-lead-by-id/
@return GetLeadResponse | entailment |
public function isMemberOfList($listId, $id, $args = array(), $returnRaw = false)
{
$args['listId'] = $listId;
$args['id'] = $id;
return $this->getResult('isMemberOfList', $args, is_array($id), $returnRaw);
} | Check if a lead is a member of a list.
@param int $listId List ID
@param int|array $id Lead ID or an array of Lead IDs
@param array $args
@link http://developers.marketo.com/documentation/rest/member-of-list/
@return IsMemberOfListResponse | entailment |
public function getCampaign($id, $args = array(), $returnRaw = false)
{
$args['id'] = $id;
return $this->getResult('getCampaign', $args, false, $returnRaw);
} | Get a campaign by ID.
@param int $id
@param array $args
@link http://developers.marketo.com/documentation/rest/get-campaign-by-id/
@return GetCampaignResponse | entailment |
public function addLeadsToList($listId, $leads, $args = array(), $returnRaw = false)
{
$args['listId'] = $listId;
$args['id'] = (array) $leads;
return $this->getResult('addLeadsToList', $args, true, $returnRaw);
} | Add one or more leads to the specified list.
@param int $listId List ID
@param int|array $leads Either a single lead ID or an array of lead IDs
@param array $args
@link http://developers.marketo.com/documentation/rest/add-leads-to-list/
@return AddOrRemoveLeadsToListResponse | entailment |
public function deleteLead($leads, $args = array(), $returnRaw = false)
{
$args['id'] = (array) $leads;
return $this->getResult('deleteLead', $args, true, $returnRaw);
} | Delete one or more leads
@param int|array $leads Either a single lead ID or an array of lead IDs
@param array $args
@link http://developers.marketo.com/documentation/rest/delete-lead/
@return DeleteLeadResponse | entailment |
public function requestCampaign($id, $leads, $tokens = array(), $args = array(), $returnRaw = false)
{
$args['id'] = $id;
$args['input'] = array('leads' => array_map(function ($id) {
return array('id' => $id);
}, (array) $leads));
if (!empty($tokens)) {
$args['input']['tokens'] = $tokens;
}
return $this->getResult('requestCampaign', $args, false, $returnRaw);
} | Trigger a campaign for one or more leads.
@param int $id Campaign ID
@param int|array $leads Either a single lead ID or an array of lead IDs
@param array $tokens Key value array of tokens to send new values for.
@param array $args
@link http://developers.marketo.com/documentation/rest/request-campaign/
@return RequestCampaignResponse | entailment |
public function scheduleCampaign($id, \DateTime $runAt = NULL, $tokens = array(), $args = array(), $returnRaw = false)
{
$args['id'] = $id;
if (!empty($runAt)) {
$args['input']['runAt'] = $runAt->format('c');
}
if (!empty($tokens)) {
$args['input']['tokens'] = $tokens;
}
return $this->getResult('scheduleCampaign', $args, false, $returnRaw);
} | Schedule a campaign
@param int $id Campaign ID
@param DateTime $runAt The time to run the campaign. If not provided, campaign will be run in 5 minutes.
@param array $tokens Key value array of tokens to send new values for.
@param array $args
@link http://developers.marketo.com/documentation/rest/schedule-campaign/
@return ScheduleCampaignResponse | entailment |
public function associateLead($id, $cookie = null, $args = array(), $returnRaw = false)
{
$args['id'] = $id;
if (!empty($cookie)) {
$args['cookie'] = $cookie;
}
return $this->getResult('associateLead', $args, false, $returnRaw);
} | Associate a lead
@param int $id
@param string $cookie
@param array $args
@link http://developers.marketo.com/documentation/rest/associate-lead/
@return AssociateLeadResponse | entailment |
public function getPagingToken($sinceDatetime, $args = array(), $returnRaw = false)
{
$args['sinceDatetime'] = $sinceDatetime;
return $this->getResult('getPagingToken', $args, false, $returnRaw);
} | Get the paging token required for lead activity and changes
@param string $sinceDatetime String containing a datetime
@param array $args
@param bool $returnRaw
@return GetPagingToken
@link http://developers.marketo.com/documentation/rest/get-paging-token/ | entailment |
public function getLeadChanges($nextPageToken, $fields, $args = array(), $returnRaw = false)
{
$args['nextPageToken'] = $nextPageToken;
$args['fields'] = (array) $fields;
if (count($fields)) {
$args['fields'] = implode(',', $fields);
}
return $this->getResult('getLeadChanges', $args, true, $returnRaw);
} | Get lead changes
@param string $nextPageToken Next page token
@param string|array $fields
@param array $args
@param bool $returnRaw
@return GetLeadChanges
@link http://developers.marketo.com/documentation/rest/get-lead-changes/
@see getPagingToken | entailment |
public function updateEmailContent($emailId, $args = array(), $returnRaw = false)
{
$args['id'] = $emailId;
return $this->getResult('updateEmailContent', $args, false, $returnRaw);
} | Update an editable section in an email
@param int $emailId
@param string $htmlId
@param array $args
@link http://developers.marketo.com/documentation/asset-api/update-email-content-by-id/
@return Response | entailment |
public function updateEmailContentInEditableSection($emailId, $htmlId, $args = array(), $returnRaw = false)
{
$args['id'] = $emailId;
$args['htmlId'] = $htmlId;
return $this->getResult('updateEmailContentInEditableSection', $args, false, $returnRaw);
} | Update an editable section in an email
@param int $emailId
@param string $htmlId
@param array $args
@link http://developers.marketo.com/documentation/asset-api/update-email-content-in-editable-section/
@return UpdateEmailContentInEditableSectionResponse | entailment |
public function approveEmail($emailId, $args = array(), $returnRaw = false)
{
$args['id'] = $emailId;
return $this->getResult('approveEmailbyId', $args, false, $returnRaw);
} | Approve an email
@param int $emailId
@param string $htmlId
@param array $args
@link http://developers.marketo.com/documentation/asset-api/approve-email-by-id/
@return approveEmail | entailment |
private function getResult($command, $args, $fixArgs = false, $returnRaw = false)
{
$cmd = $this->getCommand($command, $args);
// Marketo expects parameter arrays in the format id=1&id=2, Guzzle formats them as id[0]=1&id[1]=2.
// Use a quick regex to fix it where necessary.
if ($fixArgs) {
$cmd->prepare();
$url = preg_replace('/id%5B([0-9]+)%5D/', 'id', $cmd->getRequest()->getUrl());
$cmd->getRequest()->setUrl($url);
}
$cmd->prepare();
if ($returnRaw) {
return $cmd->getResponse()->getBody(true);
}
return $cmd->getResult();
} | Internal helper method to actually perform command.
@param string $command
@param array $args
@param bool $fixArgs
@return Response | entailment |
public function getTokenData()
{
$client = new GuzzleClient($this->url);
$params = array(
'grant_type' => 'client_credentials',
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret
);
$request = $client->get('/identity/oauth/token', null, array('query' => $params));
$data = $request->send()->json();
if (!isset($data['access_token']) || !isset($data['expires_in'])) {
throw new \Exception('Invalid Marketo credentials response.');
}
return array(
'access_token' => $data['access_token'],
'expires_in' => $data['expires_in']
);
} | {@inheritdoc} | entailment |
public function localized($language = null)
{
if (!$language){
$language = Yii::$app->language;
}
if (!isset($this->with['translations'])) {
$this->with(['translation' => function ($query) use ($language) {
$query->where([$this->languageField => $language]);
}]);
}
return $this;
} | Scope for querying by languages.
@param $language
@param $abridge
@return $this | entailment |
public static function getLanguages($languages, $owner)
{
if (!$languages && isset(Yii::$app->params['languages'])) {
$languages = Yii::$app->params['languages'];
}
if (!is_array($languages) || empty($languages)) {
throw new InvalidConfigException('Please specify array of available languages in the '
. get_class($owner) . ' or in the application parameters');
}
return $languages;
} | Validates and returns list of languages.
@param array $languages
@param \yii\base\Object $owner
@return array
@throws InvalidConfigException | entailment |
public static function getLanguageRedirects($languageRedirects)
{
if (!$languageRedirects && isset(Yii::$app->params['languageRedirects'])) {
$languageRedirects = Yii::$app->params['languageRedirects'];
}
return $languageRedirects;
} | Validates and returns list of language redirects.
@param array $languageRedirects
@return array | entailment |
public static function getRedirectedLanguageCode($redirectLanguageCode, $redirects = null)
{
if (!$redirects && isset(Yii::$app->params['languageRedirects'])) {
$redirects = Yii::$app->params['languageRedirects'];
}
if (!is_array($redirects) || empty($redirects)) {
return $redirectLanguageCode;
}
$codes = array_flip($redirects);
return (isset($codes[$redirectLanguageCode])) ? $codes[$redirectLanguageCode] : $redirectLanguageCode;
} | Returns code of language by its redirect language code.
@param string $redirectLanguageCode
@param array $redirects
@return string | entailment |
public static function getDisplayLanguages($languages, $languageRedirects)
{
foreach ($languages as $key => $value) {
$key = (isset($languageRedirects[$key])) ? $languageRedirects[$key] : $key;
$redirects[$key] = $value;
}
return $redirects;
} | Returns list of languages with applied language redirects.
@param array $languages
@param array $languageRedirects
@return array | entailment |
public function shouldPrerenderPage(Request $request)
{
//if it contains _escaped_fragment_, show prerendered page
if (null !== $request->query->get('_escaped_fragment_')) {
return true;
}
// First, return false if User Agent is not a bot
if (!$this->isCrawler($request)) {
return false;
}
$uri = $request->getScheme().'://'.$request->getHost().$request->getRequestUri();
// Then, return false if URI string contains an ignored extension
if ($this->isIgnoredExtension($uri)) {
return false;
}
// Then, return true if it is whitelisted (only if whitelist contains data)
if (!empty($this->whitelistedUrls) && !$this->isWhitelisted($uri, $this->whitelistedUrls)) {
return false;
}
// Finally, return false if it is blacklisted (or the referer)
$referer = $request->headers->get('Referer');
$blacklistUrls = $this->blacklistedUrls;
if ($this->isBlacklisted($uri, $referer, $blacklistUrls)) {
return false;
}
return true;
} | Is this request should be a prerender request?
@param Request $request
@return bool | entailment |
public function isIgnoredExtension($uri)
{
foreach ($this->ignoredExtensions as $ignoredExtension) {
if (strpos($uri, $ignoredExtension) !== false) {
return true;
}
}
return false;
} | @param string $uri
@return bool | entailment |
public function isCrawler(Request $request)
{
$userAgent = strtolower($request->headers->get('User-Agent'));
foreach ($this->crawlerUserAgents as $crawlerUserAgent) {
if (strpos($userAgent, strtolower($crawlerUserAgent)) !== false) {
return true;
}
}
return false;
} | Check if the request is made from a crawler
@param Request $request
@return bool | entailment |
public function isWhitelisted($uri, array $whitelistUrls = null)
{
if (is_null($whitelistUrls)) {
$whitelistUrls = $this->whitelistedUrls;
}
foreach ($whitelistUrls as $whitelistUrl) {
$match = preg_match('`'.$whitelistUrl.'`i', $uri);
if ($match > 0) {
return true;
}
}
return false;
} | Check if the request is whitelisted
@param string $uri
@param array $whitelistUrls
@return bool | entailment |
public function isBlacklisted($uri, $referer, array $blacklistUrls = null)
{
if (is_null($blacklistUrls)) {
$blacklistUrls = $this->blacklistedUrls;
}
foreach ($blacklistUrls as $blacklistUrl) {
$pattern = '`'.$blacklistUrl.'`i';
$match = preg_match($pattern, $uri) + preg_match($pattern, $referer);
if ($match > 0) {
return true;
}
}
return false;
} | Check if the request is blacklisted
@param string $uri
@param string $referer
@param array $blacklistUrls
@return bool | entailment |
public function languageSwitcher($model, $view = null)
{
$languages = ($model->getBehavior('multilingual')) ? $languages = $model->getBehavior('multilingual')->languages : [];
return FormLanguageSwitcher::widget(['languages' => $languages, 'view' => $view]);
} | Renders form language switcher.
@param \yii\base\Model $model
@param string $view
@return string | entailment |
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('yucca_prerender');
// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.
$rootNode
->children()
->scalarNode('backend_url')
->defaultValue('http://service.prerender.io')
->info('url of the prerender backend')
->example('http://service.prerender.io')
->end()
->scalarNode('token')
->info('API Token on prerender.io')
->defaultValue('')
->end()
->scalarNode('force_scheme')
->defaultNull()
->info('replace scheme url of the prerender backend. https - true, http - false, current - null')
->example('null')
->end()
->arrayNode('crawler_user_agents')
->defaultValue($this->defaultCrawlerUserAgents)
->prototype('scalar')->end()
->info('which user agents are considered as crawlers')
->example('[googlebot,yahoo,bingbot,baiduspider]')
->end()
->arrayNode('ignored_extensions')
->defaultValue($this->defaultIgnoredExtensions)
->prototype('scalar')->end()
->info('extensions that are not forwarded to prerender backend')
->example('[.css,.js]')
->end()
->arrayNode('whitelist_urls')
->defaultValue(array())
->prototype('scalar')->end()
->info('whitelisted urls. Not routing keys, but urls')
->example('[]')
->end()
->arrayNode('blacklist_urls')
->defaultValue(array())
->prototype('scalar')->end()
->info('whitelisted urls. Not routing keys, but urls')
->example('[.css,.js]')
->end()
->end();
return $treeBuilder;
} | {@inheritDoc} | entailment |
protected function handleImageManipulation(ImageInterface $image, array $data): ImageInterface
{
$width = $data['width'];
$height = $data['height'];
if (isset($data['dimension'])) {
$width = $height = $data['dimension'];
}
return $image->resize(new Box($width, $height), $data['filter']);
} | Handle image manipulation.
@param \Imagine\Image\ImageInterface $image
@param array $data
@return \Imagine\Image\ImageInterface | entailment |
protected function handleImageManipulation(ImageInterface $image, array $data): ImageInterface
{
$width = $height = $data['dimension'];
return $image->thumbnail(new Box($width, $height), $data['mode'], $data['filter']);
} | Handle image manipulation.
@param \Imagine\Image\ImageInterface $image
@param array $data
@return \Imagine\Image\ImageInterface | entailment |
protected function updateArguments($method, $arguments, $field)
{
if ($method == 'widget' && isset($arguments[1]['options']['id'])) {
$arguments[1]['options']['id'] = MultilingualHelper::getAttributeName($arguments[1]['options']['id'], $field->language);
}
if (in_array($method, ['textInput', 'textarea', 'radio', 'checkbox', 'fileInput', 'hiddenInput', 'passwordInput']) && isset($arguments[0]['id'])) {
$arguments[0]['id'] = MultilingualHelper::getAttributeName($arguments[0]['id'], $field->language);
}
if (in_array($method, ['input', 'dropDownList', 'listBox', 'radioList', 'checkboxList']) && isset($arguments[1]['id'])) {
$arguments[1]['id'] = MultilingualHelper::getAttributeName($arguments[1]['id'], $field->language);
}
return $arguments;
} | Updates id for multilingual inputs with custom id.
@param string $method
@param array $arguments
@param mixed $field
@return array | entailment |
public function getStatus($id)
{
if ($this->isSuccess()) {
foreach ($this->getResult() as $row) {
if ($row['id'] == $id) {
return $row['status'];
}
}
}
return false;
} | Get the status of a lead.
@param $id
@return bool | entailment |
public function send($url, $token = '')
{
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_USERAGENT => 'Internal-UserAgent',
CURLOPT_HEADER => 1
));
if (!empty($token)) {
curl_setopt( $curl, CURLOPT_HTTPHEADER, array(
'X-Prerender-Token: ' . $token
) );
}
// Send the request & save response to $resp
$response = curl_exec($curl);
$headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $headerSize);
$body = substr($response, $headerSize);
// Check if any error occurred
$httpCode = null;
$error = curl_error($curl);
if (!curl_errno($curl)) {
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
}
// Close request to clear up some resources
curl_close($curl);
//Throw an error when not a 200
if (200 != $httpCode) {
throw new Exception('Request "'.$url.'" didn\'t run properly : '.$error, (int)$httpCode, null, $header, $body);
}
return $body;
} | @param $url
@param string $token
@return mixed
@throws Exception | entailment |
public function toArray()
{
$array = array();
foreach ($this as $key => $value) {
if ($value instanceof Enumerable) {
$array[$key] = $value->toArray();
} else {
$array[$key] = $value;
}
}
return $array;
} | {@inheritdoc} | entailment |
function nusoap_server($wsdl=false){
parent::nusoap_base();
// turn on debugging?
global $debug;
global $HTTP_SERVER_VARS;
if (isset($_SERVER)) {
$this->debug("_SERVER is defined:");
$this->appendDebug($this->varDump($_SERVER));
} elseif (isset($HTTP_SERVER_VARS)) {
$this->debug("HTTP_SERVER_VARS is defined:");
$this->appendDebug($this->varDump($HTTP_SERVER_VARS));
} else {
$this->debug("Neither _SERVER nor HTTP_SERVER_VARS is defined.");
}
if (isset($debug)) {
$this->debug("In nusoap_server, set debug_flag=$debug based on global flag");
$this->debug_flag = $debug;
} elseif (isset($_SERVER['QUERY_STRING'])) {
$qs = explode('&', $_SERVER['QUERY_STRING']);
foreach ($qs as $v) {
if (substr($v, 0, 6) == 'debug=') {
$this->debug("In nusoap_server, set debug_flag=" . substr($v, 6) . " based on query string #1");
$this->debug_flag = substr($v, 6);
}
}
} elseif (isset($HTTP_SERVER_VARS['QUERY_STRING'])) {
$qs = explode('&', $HTTP_SERVER_VARS['QUERY_STRING']);
foreach ($qs as $v) {
if (substr($v, 0, 6) == 'debug=') {
$this->debug("In nusoap_server, set debug_flag=" . substr($v, 6) . " based on query string #2");
$this->debug_flag = substr($v, 6);
}
}
}
// wsdl
if($wsdl){
$this->debug("In nusoap_server, WSDL is specified");
if (is_object($wsdl) && (get_class($wsdl) == 'wsdl')) {
$this->wsdl = $wsdl;
$this->externalWSDLURL = $this->wsdl->wsdl;
$this->debug('Use existing wsdl instance from ' . $this->externalWSDLURL);
} else {
$this->debug('Create wsdl from ' . $wsdl);
$this->wsdl = new wsdl($wsdl);
$this->externalWSDLURL = $wsdl;
}
$this->appendDebug($this->wsdl->getDebug());
$this->wsdl->clearDebug();
if($err = $this->wsdl->getError()){
die('WSDL ERROR: '.$err);
}
}
} | constructor
the optional parameter is a path to a WSDL file that you'd like to bind the server instance to.
@param mixed $wsdl file path or URL (string), or wsdl instance (object)
@access public | entailment |
function parse_http_headers() {
global $HTTP_SERVER_VARS;
$this->request = '';
$this->SOAPAction = '';
if(function_exists('getallheaders')){
$this->debug("In parse_http_headers, use getallheaders");
$headers = getallheaders();
foreach($headers as $k=>$v){
$k = strtolower($k);
$this->headers[$k] = $v;
$this->request .= "$k: $v\r\n";
$this->debug("$k: $v");
}
// get SOAPAction header
if(isset($this->headers['soapaction'])){
$this->SOAPAction = str_replace('"','',$this->headers['soapaction']);
}
// get the character encoding of the incoming request
if(isset($this->headers['content-type']) && strpos($this->headers['content-type'],'=')){
$enc = str_replace('"','',substr(strstr($this->headers["content-type"],'='),1));
if(preg_match('/^(ISO-8859-1|US-ASCII|UTF-8)$/i',$enc)){
$this->xml_encoding = strtoupper($enc);
} else {
$this->xml_encoding = 'US-ASCII';
}
} else {
// should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1
$this->xml_encoding = 'ISO-8859-1';
}
} elseif(isset($_SERVER) && is_array($_SERVER)){
$this->debug("In parse_http_headers, use _SERVER");
foreach ($_SERVER as $k => $v) {
if (substr($k, 0, 5) == 'HTTP_') {
$k = str_replace(' ', '-', strtolower(str_replace('_', ' ', substr($k, 5))));
} else {
$k = str_replace(' ', '-', strtolower(str_replace('_', ' ', $k)));
}
if ($k == 'soapaction') {
// get SOAPAction header
$k = 'SOAPAction';
$v = str_replace('"', '', $v);
$v = str_replace('\\', '', $v);
$this->SOAPAction = $v;
} else if ($k == 'content-type') {
// get the character encoding of the incoming request
if (strpos($v, '=')) {
$enc = substr(strstr($v, '='), 1);
$enc = str_replace('"', '', $enc);
$enc = str_replace('\\', '', $enc);
if (preg_match('/^(ISO-8859-1|US-ASCII|UTF-8)$/i',$enc)) {
$this->xml_encoding = strtoupper($enc);
} else {
$this->xml_encoding = 'US-ASCII';
}
} else {
// should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1
$this->xml_encoding = 'ISO-8859-1';
}
}
$this->headers[$k] = $v;
$this->request .= "$k: $v\r\n";
$this->debug("$k: $v");
}
} elseif (is_array($HTTP_SERVER_VARS)) {
$this->debug("In parse_http_headers, use HTTP_SERVER_VARS");
foreach ($HTTP_SERVER_VARS as $k => $v) {
if (substr($k, 0, 5) == 'HTTP_') {
$k = str_replace(' ', '-', strtolower(str_replace('_', ' ', substr($k, 5)))); $k = strtolower(substr($k, 5));
} else {
$k = str_replace(' ', '-', strtolower(str_replace('_', ' ', $k))); $k = strtolower($k);
}
if ($k == 'soapaction') {
// get SOAPAction header
$k = 'SOAPAction';
$v = str_replace('"', '', $v);
$v = str_replace('\\', '', $v);
$this->SOAPAction = $v;
} else if ($k == 'content-type') {
// get the character encoding of the incoming request
if (strpos($v, '=')) {
$enc = substr(strstr($v, '='), 1);
$enc = str_replace('"', '', $enc);
$enc = str_replace('\\', '', $enc);
if (preg_match('/^(ISO-8859-1|US-ASCII|UTF-8)$/i',$enc)) {
$this->xml_encoding = strtoupper($enc);
} else {
$this->xml_encoding = 'US-ASCII';
}
} else {
// should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1
$this->xml_encoding = 'ISO-8859-1';
}
}
$this->headers[$k] = $v;
$this->request .= "$k: $v\r\n";
$this->debug("$k: $v");
}
} else {
$this->debug("In parse_http_headers, HTTP headers not accessible");
$this->setError("HTTP headers not accessible");
}
} | parses HTTP request headers.
The following fields are set by this function (when successful)
headers
request
xml_encoding
SOAPAction
@access private | entailment |
function parse_request($data='') {
$this->debug('entering parse_request()');
$this->parse_http_headers();
$this->debug('got character encoding: '.$this->xml_encoding);
// uncompress if necessary
if (isset($this->headers['content-encoding']) && $this->headers['content-encoding'] != '') {
$this->debug('got content encoding: ' . $this->headers['content-encoding']);
if ($this->headers['content-encoding'] == 'deflate' || $this->headers['content-encoding'] == 'gzip') {
// if decoding works, use it. else assume data wasn't gzencoded
if (function_exists('gzuncompress')) {
if ($this->headers['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) {
$data = $degzdata;
} elseif ($this->headers['content-encoding'] == 'gzip' && $degzdata = gzinflate(substr($data, 10))) {
$data = $degzdata;
} else {
$this->fault('SOAP-ENV:Client', 'Errors occurred when trying to decode the data');
return;
}
} else {
$this->fault('SOAP-ENV:Client', 'This Server does not support compressed data');
return;
}
}
}
$this->request .= "\r\n".$data;
$data = $this->parseRequest($this->headers, $data);
$this->requestSOAP = $data;
$this->debug('leaving parse_request');
} | parses a request
The following fields are set by this function (when successful)
headers
request
xml_encoding
SOAPAction
request
requestSOAP
methodURI
methodname
methodparams
requestHeaders
document
This sets the fault field on error
@param string $data XML string
@access private | entailment |
function invoke_method() {
$this->debug('in invoke_method, methodname=' . $this->methodname . ' methodURI=' . $this->methodURI . ' SOAPAction=' . $this->SOAPAction);
//
// if you are debugging in this area of the code, your service uses a class to implement methods,
// you use SOAP RPC, and the client is .NET, please be aware of the following...
// when the .NET wsdl.exe utility generates a proxy, it will remove the '.' or '..' from the
// method name. that is fine for naming the .NET methods. it is not fine for properly constructing
// the XML request and reading the XML response. you need to add the RequestElementName and
// ResponseElementName to the System.Web.Services.Protocols.SoapRpcMethodAttribute that wsdl.exe
// generates for the method. these parameters are used to specify the correct XML element names
// for .NET to use, i.e. the names with the '.' in them.
//
$orig_methodname = $this->methodname;
if ($this->wsdl) {
if ($this->opData = $this->wsdl->getOperationData($this->methodname)) {
$this->debug('in invoke_method, found WSDL operation=' . $this->methodname);
$this->appendDebug('opData=' . $this->varDump($this->opData));
} elseif ($this->opData = $this->wsdl->getOperationDataForSoapAction($this->SOAPAction)) {
// Note: hopefully this case will only be used for doc/lit, since rpc services should have wrapper element
$this->debug('in invoke_method, found WSDL soapAction=' . $this->SOAPAction . ' for operation=' . $this->opData['name']);
$this->appendDebug('opData=' . $this->varDump($this->opData));
$this->methodname = $this->opData['name'];
} else {
$this->debug('in invoke_method, no WSDL for operation=' . $this->methodname);
$this->fault('SOAP-ENV:Client', "Operation '" . $this->methodname . "' is not defined in the WSDL for this service");
return;
}
} else {
$this->debug('in invoke_method, no WSDL to validate method');
}
// if a . is present in $this->methodname, we see if there is a class in scope,
// which could be referred to. We will also distinguish between two deliminators,
// to allow methods to be called a the class or an instance
if (strpos($this->methodname, '..') > 0) {
$delim = '..';
} else if (strpos($this->methodname, '.') > 0) {
$delim = '.';
} else {
$delim = '';
}
$this->debug("in invoke_method, delim=$delim");
$class = '';
$method = '';
if (strlen($delim) > 0 && substr_count($this->methodname, $delim) == 1) {
$try_class = substr($this->methodname, 0, strpos($this->methodname, $delim));
if (class_exists($try_class)) {
// get the class and method name
$class = $try_class;
$method = substr($this->methodname, strpos($this->methodname, $delim) + strlen($delim));
$this->debug("in invoke_method, class=$class method=$method delim=$delim");
} else {
$this->debug("in invoke_method, class=$try_class not found");
}
} else {
$try_class = '';
$this->debug("in invoke_method, no class to try");
}
// does method exist?
if ($class == '') {
if (!function_exists($this->methodname)) {
$this->debug("in invoke_method, function '$this->methodname' not found!");
$this->result = 'fault: method not found';
$this->fault('SOAP-ENV:Client',"method '$this->methodname'('$orig_methodname') not defined in service('$try_class' '$delim')");
return;
}
} else {
$method_to_compare = (substr(phpversion(), 0, 2) == '4.') ? strtolower($method) : $method;
if (!in_array($method_to_compare, get_class_methods($class))) {
$this->debug("in invoke_method, method '$this->methodname' not found in class '$class'!");
$this->result = 'fault: method not found';
$this->fault('SOAP-ENV:Client',"method '$this->methodname'/'$method_to_compare'('$orig_methodname') not defined in service/'$class'('$try_class' '$delim')");
return;
}
}
// evaluate message, getting back parameters
// verify that request parameters match the method's signature
if(! $this->verify_method($this->methodname,$this->methodparams)){
// debug
$this->debug('ERROR: request not verified against method signature');
$this->result = 'fault: request failed validation against method signature';
// return fault
$this->fault('SOAP-ENV:Client',"Operation '$this->methodname' not defined in service.");
return;
}
// if there are parameters to pass
$this->debug('in invoke_method, params:');
$this->appendDebug($this->varDump($this->methodparams));
$this->debug("in invoke_method, calling '$this->methodname'");
if (!function_exists('call_user_func_array')) {
if ($class == '') {
$this->debug('in invoke_method, calling function using eval()');
$funcCall = "\$this->methodreturn = $this->methodname(";
} else {
if ($delim == '..') {
$this->debug('in invoke_method, calling class method using eval()');
$funcCall = "\$this->methodreturn = ".$class."::".$method."(";
} else {
$this->debug('in invoke_method, calling instance method using eval()');
// generate unique instance name
$instname = "\$inst_".time();
$funcCall = $instname." = new ".$class."(); ";
$funcCall .= "\$this->methodreturn = ".$instname."->".$method."(";
}
}
if ($this->methodparams) {
foreach ($this->methodparams as $param) {
if (is_array($param) || is_object($param)) {
$this->fault('SOAP-ENV:Client', 'NuSOAP does not handle complexType parameters correctly when using eval; call_user_func_array must be available');
return;
}
$funcCall .= "\"$param\",";
}
$funcCall = substr($funcCall, 0, -1);
}
$funcCall .= ');';
$this->debug('in invoke_method, function call: '.$funcCall);
@eval($funcCall);
} else {
if ($class == '') {
$this->debug('in invoke_method, calling function using call_user_func_array()');
$call_arg = "$this->methodname"; // straight assignment changes $this->methodname to lower case after call_user_func_array()
} elseif ($delim == '..') {
$this->debug('in invoke_method, calling class method using call_user_func_array()');
$call_arg = array ($class, $method);
} else {
$this->debug('in invoke_method, calling instance method using call_user_func_array()');
$instance = new $class ();
$call_arg = array(&$instance, $method);
}
if (is_array($this->methodparams)) {
$this->methodreturn = call_user_func_array($call_arg, array_values($this->methodparams));
} else {
$this->methodreturn = call_user_func_array($call_arg, array());
}
}
$this->debug('in invoke_method, methodreturn:');
$this->appendDebug($this->varDump($this->methodreturn));
$this->debug("in invoke_method, called method $this->methodname, received data of type ".gettype($this->methodreturn));
} | invokes a PHP function for the requested SOAP method
The following fields are set by this function (when successful)
methodreturn
Note that the PHP function that is called may also set the following
fields to affect the response sent to the client
responseHeaders
outgoing_headers
This sets the fault field on error
@access private | entailment |
function serialize_return() {
$this->debug('Entering serialize_return methodname: ' . $this->methodname . ' methodURI: ' . $this->methodURI);
// if fault
if (isset($this->methodreturn) && is_object($this->methodreturn) && ((get_class($this->methodreturn) == 'soap_fault') || (get_class($this->methodreturn) == 'nusoap_fault'))) {
$this->debug('got a fault object from method');
$this->fault = $this->methodreturn;
return;
} elseif ($this->methodreturnisliteralxml) {
$return_val = $this->methodreturn;
// returned value(s)
} else {
$this->debug('got a(n) '.gettype($this->methodreturn).' from method');
$this->debug('serializing return value');
if($this->wsdl){
if (sizeof($this->opData['output']['parts']) > 1) {
$this->debug('more than one output part, so use the method return unchanged');
$opParams = $this->methodreturn;
} elseif (sizeof($this->opData['output']['parts']) == 1) {
$this->debug('exactly one output part, so wrap the method return in a simple array');
// TODO: verify that it is not already wrapped!
//foreach ($this->opData['output']['parts'] as $name => $type) {
// $this->debug('wrap in element named ' . $name);
//}
$opParams = array($this->methodreturn);
}
$return_val = $this->wsdl->serializeRPCParameters($this->methodname,'output',$opParams);
$this->appendDebug($this->wsdl->getDebug());
$this->wsdl->clearDebug();
if($errstr = $this->wsdl->getError()){
$this->debug('got wsdl error: '.$errstr);
$this->fault('SOAP-ENV:Server', 'unable to serialize result');
return;
}
} else {
if (isset($this->methodreturn)) {
$return_val = $this->serialize_val($this->methodreturn, 'return');
} else {
$return_val = '';
$this->debug('in absence of WSDL, assume void return for backward compatibility');
}
}
}
$this->debug('return value:');
$this->appendDebug($this->varDump($return_val));
$this->debug('serializing response');
if ($this->wsdl) {
$this->debug('have WSDL for serialization: style is ' . $this->opData['style']);
if ($this->opData['style'] == 'rpc') {
$this->debug('style is rpc for serialization: use is ' . $this->opData['output']['use']);
if ($this->opData['output']['use'] == 'literal') {
// http://www.ws-i.org/Profiles/BasicProfile-1.1-2004-08-24.html R2735 says rpc/literal accessor elements should not be in a namespace
if ($this->methodURI) {
$payload = '<ns1:'.$this->methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'</ns1:'.$this->methodname."Response>";
} else {
$payload = '<'.$this->methodname.'Response>'.$return_val.'</'.$this->methodname.'Response>';
}
} else {
if ($this->methodURI) {
$payload = '<ns1:'.$this->methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'</ns1:'.$this->methodname."Response>";
} else {
$payload = '<'.$this->methodname.'Response>'.$return_val.'</'.$this->methodname.'Response>';
}
}
} else {
$this->debug('style is not rpc for serialization: assume document');
$payload = $return_val;
}
} else {
$this->debug('do not have WSDL for serialization: assume rpc/encoded');
$payload = '<ns1:'.$this->methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'</ns1:'.$this->methodname."Response>";
}
$this->result = 'successful';
if($this->wsdl){
//if($this->debug_flag){
$this->appendDebug($this->wsdl->getDebug());
// }
if (isset($this->opData['output']['encodingStyle'])) {
$encodingStyle = $this->opData['output']['encodingStyle'];
} else {
$encodingStyle = '';
}
// Added: In case we use a WSDL, return a serialized env. WITH the usedNamespaces.
$this->responseSOAP = $this->serializeEnvelope($payload,$this->responseHeaders,$this->wsdl->usedNamespaces,$this->opData['style'],$this->opData['output']['use'],$encodingStyle);
} else {
$this->responseSOAP = $this->serializeEnvelope($payload,$this->responseHeaders);
}
$this->debug("Leaving serialize_return");
} | serializes the return value from a PHP function into a full SOAP Envelope
The following fields are set by this function (when successful)
responseSOAP
This sets the fault field on error
@access private | entailment |
function send_response() {
$this->debug('Enter send_response');
if ($this->fault) {
$payload = $this->fault->serialize();
$this->outgoing_headers[] = "HTTP/1.0 500 Internal Server Error";
$this->outgoing_headers[] = "Status: 500 Internal Server Error";
} else {
$payload = $this->responseSOAP;
// Some combinations of PHP+Web server allow the Status
// to come through as a header. Since OK is the default
// just do nothing.
// $this->outgoing_headers[] = "HTTP/1.0 200 OK";
// $this->outgoing_headers[] = "Status: 200 OK";
}
// add debug data if in debug mode
if(isset($this->debug_flag) && $this->debug_flag){
$payload .= $this->getDebugAsXMLComment();
}
$this->outgoing_headers[] = "Server: $this->title Server v$this->version";
preg_match('/\$Revisio' . 'n: ([^ ]+)/', $this->revision, $rev);
$this->outgoing_headers[] = "X-SOAP-Server: $this->title/$this->version (".$rev[1].")";
// Let the Web server decide about this
//$this->outgoing_headers[] = "Connection: Close\r\n";
$payload = $this->getHTTPBody($payload);
$type = $this->getHTTPContentType();
$charset = $this->getHTTPContentTypeCharset();
$this->outgoing_headers[] = "Content-Type: $type" . ($charset ? '; charset=' . $charset : '');
//begin code to compress payload - by John
// NOTE: there is no way to know whether the Web server will also compress
// this data.
if (strlen($payload) > 1024 && isset($this->headers) && isset($this->headers['accept-encoding'])) {
if (strstr($this->headers['accept-encoding'], 'gzip')) {
if (function_exists('gzencode')) {
if (isset($this->debug_flag) && $this->debug_flag) {
$payload .= "<!-- Content being gzipped -->";
}
$this->outgoing_headers[] = "Content-Encoding: gzip";
$payload = gzencode($payload);
} else {
if (isset($this->debug_flag) && $this->debug_flag) {
$payload .= "<!-- Content will not be gzipped: no gzencode -->";
}
}
} elseif (strstr($this->headers['accept-encoding'], 'deflate')) {
// Note: MSIE requires gzdeflate output (no Zlib header and checksum),
// instead of gzcompress output,
// which conflicts with HTTP 1.1 spec (http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.5)
if (function_exists('gzdeflate')) {
if (isset($this->debug_flag) && $this->debug_flag) {
$payload .= "<!-- Content being deflated -->";
}
$this->outgoing_headers[] = "Content-Encoding: deflate";
$payload = gzdeflate($payload);
} else {
if (isset($this->debug_flag) && $this->debug_flag) {
$payload .= "<!-- Content will not be deflated: no gzcompress -->";
}
}
}
}
//end code
$this->outgoing_headers[] = "Content-Length: ".strlen($payload);
reset($this->outgoing_headers);
foreach($this->outgoing_headers as $hdr){
header($hdr, false);
}
print $payload;
$this->response = join("\r\n",$this->outgoing_headers)."\r\n\r\n".$payload;
} | sends an HTTP response
The following fields are set by this function (when successful)
outgoing_headers
response
@access private | entailment |
function verify_method($operation,$request){
if(isset($this->wsdl) && is_object($this->wsdl)){
if($this->wsdl->getOperationData($operation)){
return true;
}
} elseif(isset($this->operations[$operation])){
return true;
}
return false;
} | takes the value that was created by parsing the request
and compares to the method's signature, if available.
@param string $operation The operation to be invoked
@param array $request The array of parameter values
@return boolean Whether the operation was found
@access private | entailment |
function fault($faultcode,$faultstring,$faultactor='',$faultdetail=''){
if ($faultdetail == '' && $this->debug_flag) {
$faultdetail = $this->getDebug();
}
$this->fault = new nusoap_fault($faultcode,$faultactor,$faultstring,$faultdetail);
$this->fault->soap_defencoding = $this->soap_defencoding;
} | Specify a fault to be returned to the client.
This also acts as a flag to the server that a fault has occured.
@param string $faultcode
@param string $faultstring
@param string $faultactor
@param string $faultdetail
@access public | entailment |
function getHTTPBody($soapmsg) {
if (count($this->responseAttachments) > 0) {
$params['content_type'] = 'multipart/related; type="text/xml"';
$mimeMessage = new Mail_mimePart('', $params);
unset($params);
$params['content_type'] = 'text/xml';
$params['encoding'] = '8bit';
$params['charset'] = $this->soap_defencoding;
$mimeMessage->addSubpart($soapmsg, $params);
foreach ($this->responseAttachments as $att) {
unset($params);
$params['content_type'] = $att['contenttype'];
$params['encoding'] = 'base64';
$params['disposition'] = 'attachment';
$params['dfilename'] = $att['filename'];
$params['cid'] = $att['cid'];
if ($att['data'] == '' && $att['filename'] <> '') {
if ($fd = fopen($att['filename'], 'rb')) {
$data = fread($fd, filesize($att['filename']));
fclose($fd);
} else {
$data = '';
}
$mimeMessage->addSubpart($data, $params);
} else {
$mimeMessage->addSubpart($att['data'], $params);
}
}
$output = $mimeMessage->encode();
$mimeHeaders = $output['headers'];
foreach ($mimeHeaders as $k => $v) {
$this->debug("MIME header $k: $v");
if (strtolower($k) == 'content-type') {
// PHP header() seems to strip leading whitespace starting
// the second line, so force everything to one line
$this->mimeContentType = str_replace("\r\n", " ", $v);
}
}
return $output['body'];
}
return parent::getHTTPBody($soapmsg);
} | gets the HTTP body for the current response.
@param string $soapmsg The SOAP payload
@return string The HTTP body, which includes the SOAP payload
@access private | entailment |
function soap_transport_http($url, $curl_options = NULL, $use_curl = false){
parent::nusoap_base();
$this->debug("ctor url=$url use_curl=$use_curl curl_options:");
$this->appendDebug($this->varDump($curl_options));
$this->setURL($url);
if (is_array($curl_options)) {
$this->ch_options = $curl_options;
}
$this->use_curl = $use_curl;
preg_match('/\$Revisio' . 'n: ([^ ]+)/', $this->revision, $rev);
$this->setHeader('User-Agent', $this->title.'/'.$this->version.' ('.$rev[1].')');
} | constructor
@param string $url The URL to which to connect
@param array $curl_options User-specified cURL options
@param boolean $use_curl Whether to try to force cURL use
@access public | entailment |
function io_method() {
if ($this->use_curl || ($this->scheme == 'https') || ($this->scheme == 'http' && $this->authtype == 'ntlm') || ($this->scheme == 'http' && is_array($this->proxy) && $this->proxy['authtype'] == 'ntlm'))
return 'curl';
if (($this->scheme == 'http' || $this->scheme == 'ssl') && $this->authtype != 'ntlm' && (!is_array($this->proxy) || $this->proxy['authtype'] != 'ntlm'))
return 'socket';
return 'unknown';
} | gets the I/O method to use
@return string I/O method to use (socket|curl|unknown)
@access private | entailment |
function send($data, $timeout=0, $response_timeout=30, $cookies=NULL) {
$this->debug('entered send() with data of length: '.strlen($data));
$this->tryagain = true;
$tries = 0;
while ($this->tryagain) {
$this->tryagain = false;
if ($tries++ < 2) {
// make connnection
if (!$this->connect($timeout, $response_timeout)){
return false;
}
// send request
if (!$this->sendRequest($data, $cookies)){
return false;
}
// get response
$respdata = $this->getResponse();
} else {
$this->setError("Too many tries to get an OK response ($this->response_status_line)");
}
}
$this->debug('end of send()');
return $respdata;
} | sends the SOAP request and gets the SOAP response via HTTP[S]
@param string $data message data
@param integer $timeout set connection timeout in seconds
@param integer $response_timeout set response timeout in seconds
@param array $cookies cookies to send
@return string data
@access public | entailment |
function setProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '', $proxyauthtype = 'basic') {
if ($proxyhost) {
$this->proxy = array(
'host' => $proxyhost,
'port' => $proxyport,
'username' => $proxyusername,
'password' => $proxypassword,
'authtype' => $proxyauthtype
);
if ($proxyusername != '' && $proxypassword != '' && $proxyauthtype = 'basic') {
$this->setHeader('Proxy-Authorization', ' Basic '.base64_encode($proxyusername.':'.$proxypassword));
}
} else {
$this->debug('remove proxy');
$proxy = null;
unsetHeader('Proxy-Authorization');
}
} | set proxy info here
@param string $proxyhost use an empty string to remove proxy
@param string $proxyport
@param string $proxyusername
@param string $proxypassword
@param string $proxyauthtype (basic|ntlm)
@access public | entailment |
function isSkippableCurlHeader(&$data) {
$skipHeaders = array( 'HTTP/1.1 100',
'HTTP/1.0 301',
'HTTP/1.1 301',
'HTTP/1.0 302',
'HTTP/1.1 302',
'HTTP/1.0 401',
'HTTP/1.1 401',
'HTTP/1.0 200 Connection established');
foreach ($skipHeaders as $hd) {
$prefix = substr($data, 0, strlen($hd));
if ($prefix == $hd) return true;
}
return false;
} | Test if the given string starts with a header that is to be skipped.
Skippable headers result from chunked transfer and proxy requests.
@param string $data The string to check.
@returns boolean Whether a skippable header was found.
@access private | entailment |
function parseCookie($cookie_str) {
$cookie_str = str_replace('; ', ';', $cookie_str) . ';';
$data = preg_split('/;/', $cookie_str);
$value_str = $data[0];
$cookie_param = 'domain=';
$start = strpos($cookie_str, $cookie_param);
if ($start > 0) {
$domain = substr($cookie_str, $start + strlen($cookie_param));
$domain = substr($domain, 0, strpos($domain, ';'));
} else {
$domain = '';
}
$cookie_param = 'expires=';
$start = strpos($cookie_str, $cookie_param);
if ($start > 0) {
$expires = substr($cookie_str, $start + strlen($cookie_param));
$expires = substr($expires, 0, strpos($expires, ';'));
} else {
$expires = '';
}
$cookie_param = 'path=';
$start = strpos($cookie_str, $cookie_param);
if ( $start > 0 ) {
$path = substr($cookie_str, $start + strlen($cookie_param));
$path = substr($path, 0, strpos($path, ';'));
} else {
$path = '/';
}
$cookie_param = ';secure;';
if (strpos($cookie_str, $cookie_param) !== FALSE) {
$secure = true;
} else {
$secure = false;
}
$sep_pos = strpos($value_str, '=');
if ($sep_pos) {
$name = substr($value_str, 0, $sep_pos);
$value = substr($value_str, $sep_pos + 1);
$cookie= array( 'name' => $name,
'value' => $value,
'domain' => $domain,
'path' => $path,
'expires' => $expires,
'secure' => $secure
);
return $cookie;
}
return false;
} | /*
TODO: allow a Set-Cookie string to be parsed into multiple cookies | entailment |
function getCookiesForRequest($cookies, $secure=false) {
$cookie_str = '';
if ((! is_null($cookies)) && (is_array($cookies))) {
foreach ($cookies as $cookie) {
if (! is_array($cookie)) {
continue;
}
$this->debug("check cookie for validity: ".$cookie['name'].'='.$cookie['value']);
if ((isset($cookie['expires'])) && (! empty($cookie['expires']))) {
if (strtotime($cookie['expires']) <= time()) {
$this->debug('cookie has expired');
continue;
}
}
if ((isset($cookie['domain'])) && (! empty($cookie['domain']))) {
$domain = preg_quote($cookie['domain']);
if (! preg_match("'.*$domain$'i", $this->host)) {
$this->debug('cookie has different domain');
continue;
}
}
if ((isset($cookie['path'])) && (! empty($cookie['path']))) {
$path = preg_quote($cookie['path']);
if (! preg_match("'^$path.*'i", $this->path)) {
$this->debug('cookie is for a different path');
continue;
}
}
if ((! $secure) && (isset($cookie['secure'])) && ($cookie['secure'])) {
$this->debug('cookie is secure, transport is not');
continue;
}
$cookie_str .= $cookie['name'] . '=' . $cookie['value'] . '; ';
$this->debug('add cookie to Cookie-String: ' . $cookie['name'] . '=' . $cookie['value']);
}
}
return $cookie_str;
} | sort out cookies for the current request
@param array $cookies array with all cookies
@param boolean $secure is the send-content secure or not?
@return string for Cookie-HTTP-Header
@access private | entailment |
public function generate()
{
$returnVar = $this->executeCommand($output);
if ($returnVar == 0)
{
$this->contents = $this->getPDFContents();
}
else
{
throw new PDFException($output);
}
$this->removeTmpFiles();
return $this;
} | Generates the PDF and save the PDF content for the further use
@return string
@throws PDFException | entailment |
public function save($fileName, AdapterInterface $adapter, $overwrite = false)
{
$fs = new Filesystem($adapter);
if ($overwrite == true)
{
$fs->put($fileName, $this->get());
}
else
{
$fs->write($fileName, $this->get());
}
return $this;
} | Saves the pdf content to the specified location
@param $fileName
@param AdapterInterface $adapter
@param bool $overwrite
@return $this | entailment |
public function removeTmpFiles()
{
if (file_exists($this->getHTMLPath()))
{
@unlink($this->getHTMLPath());
}
if (file_exists($this->getPDFPath()))
{
@unlink($this->getPDFPath());
}
} | Remove temporary HTML and PDF files | entailment |
public function executeCommand(&$output)
{
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("pipe", "w") // stderr is a pipe that the child will write to
);
$process = proc_open($this->cmd . ' ' . $this->getParams() . ' ' . $this->getInputSource() . ' ' . $this->getPDFPath(), $descriptorspec, $pipes);
$output = stream_get_contents($pipes[1]) . stream_get_contents($pipes[2]);
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
return proc_close($process);
} | Execute wkhtmltopdf command
@param array &$output
@return integer | entailment |
protected function getParams()
{
$result = "";
foreach ($this->params as $key => $value)
{
if (is_numeric($key))
{
$result .= '--' . $value;
}
else
{
$result .= '--' . $key . ' ' . '"' . $value . '"';
}
$result .= ' ';
}
return $result;
} | Gets the parameters defined by user
@return string | entailment |
protected function addParam($key, $value = null)
{
if (is_null($value))
{
$this->params[] = $key;
}
else
{
$this->params[$key] = $value;
}
} | Adds a wkhtmltopdf parameter
@param string $key
@param string $value | entailment |
protected function getInputSource()
{
if (!is_null($this->path))
{
return $this->path;
}
file_put_contents($this->getHTMLPath(), $this->htmlContent);
return $this->getHTMLPath();
} | Gets the Input source which can be an HTML file or a File path
@return string | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.