repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
firegento/firegento-magesetup2
Observer/AddProductAttributeVisibleCheckoutObserver.php
AddProductAttributeVisibleCheckoutObserver.execute
public function execute(\Magento\Framework\Event\Observer $observer) { /** @var \Magento\Framework\Data\Form $form */ $form = $observer->getEvent()->getData('form'); /** @var \Magento\Framework\Data\Form\Element\Fieldset $fieldset */ $fieldset = $form->getElement('front_fieldset'); $fieldset->addField( 'is_visible_on_checkout', 'select', [ 'name' => 'is_visible_on_checkout', 'label' => __('Visible in Checkout'), 'title' => __('Visible in Checkout'), 'values' => $this->yesNo->toOptionArray(), ] ); }
php
public function execute(\Magento\Framework\Event\Observer $observer) { /** @var \Magento\Framework\Data\Form $form */ $form = $observer->getEvent()->getData('form'); /** @var \Magento\Framework\Data\Form\Element\Fieldset $fieldset */ $fieldset = $form->getElement('front_fieldset'); $fieldset->addField( 'is_visible_on_checkout', 'select', [ 'name' => 'is_visible_on_checkout', 'label' => __('Visible in Checkout'), 'title' => __('Visible in Checkout'), 'values' => $this->yesNo->toOptionArray(), ] ); }
[ "public", "function", "execute", "(", "\\", "Magento", "\\", "Framework", "\\", "Event", "\\", "Observer", "$", "observer", ")", "{", "/** @var \\Magento\\Framework\\Data\\Form $form */", "$", "form", "=", "$", "observer", "->", "getEvent", "(", ")", "->", "getD...
lala @param \Magento\Framework\Event\Observer $observer @return void
[ "lala" ]
train
https://github.com/firegento/firegento-magesetup2/blob/d1727b581dd703f72babecab125b600446be06de/Observer/AddProductAttributeVisibleCheckoutObserver.php#L39-L57
firegento/firegento-magesetup2
Setup/UpgradeSchema.php
UpgradeSchema.upgrade
public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context) { $setup->startSetup(); if (version_compare($context->getVersion(), '2.0.1', '<')) { $setup->getConnection()->addColumn( $setup->getTable('catalog_eav_attribute'), 'is_visible_on_checkout', [ 'type' => \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, 'unsigned' => true, 'nullable' => false, 'default' => '0', 'comment' => 'Is Visible On Checkout' ] ); } $setup->endSetup(); }
php
public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context) { $setup->startSetup(); if (version_compare($context->getVersion(), '2.0.1', '<')) { $setup->getConnection()->addColumn( $setup->getTable('catalog_eav_attribute'), 'is_visible_on_checkout', [ 'type' => \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, 'unsigned' => true, 'nullable' => false, 'default' => '0', 'comment' => 'Is Visible On Checkout' ] ); } $setup->endSetup(); }
[ "public", "function", "upgrade", "(", "SchemaSetupInterface", "$", "setup", ",", "ModuleContextInterface", "$", "context", ")", "{", "$", "setup", "->", "startSetup", "(", ")", ";", "if", "(", "version_compare", "(", "$", "context", "->", "getVersion", "(", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/firegento/firegento-magesetup2/blob/d1727b581dd703f72babecab125b600446be06de/Setup/UpgradeSchema.php#L23-L42
firegento/firegento-magesetup2
Plugin/Email/Model/Source/Variables.php
Variables.afterGetData
public function afterGetData(\Magento\Email\Model\Source\Variables $subject, $result) { return array_merge($result, $this->getAdditionalConfigVariables()); }
php
public function afterGetData(\Magento\Email\Model\Source\Variables $subject, $result) { return array_merge($result, $this->getAdditionalConfigVariables()); }
[ "public", "function", "afterGetData", "(", "\\", "Magento", "\\", "Email", "\\", "Model", "\\", "Source", "\\", "Variables", "$", "subject", ",", "$", "result", ")", "{", "return", "array_merge", "(", "$", "result", ",", "$", "this", "->", "getAdditionalCo...
Return available config variables @param \Magento\Email\Model\Source\Variables $subject @param array $result @return array @codeCoverageIgnore
[ "Return", "available", "config", "variables" ]
train
https://github.com/firegento/firegento-magesetup2/blob/d1727b581dd703f72babecab125b600446be06de/Plugin/Email/Model/Source/Variables.php#L99-L102
firegento/firegento-magesetup2
Plugin/Email/Block/Adminhtml/Template/Edit/Form.php
Form.afterGetVariables
public function afterGetVariables(\Magento\Email\Block\Adminhtml\Template\Edit\Form $subject, $result) { $additionalConfigValues = $this->variables->getAdditionalConfigVariables(); $optionArray = []; foreach ($additionalConfigValues as $variable) { $optionArray[] = [ 'value' => '{{config path="' . $variable['value'] . '"}}', 'label' => $variable['label'], ]; } if ($optionArray) { $result[] = [ 'label' => __('Imprint'), 'value' => $optionArray, ]; } return $result; }
php
public function afterGetVariables(\Magento\Email\Block\Adminhtml\Template\Edit\Form $subject, $result) { $additionalConfigValues = $this->variables->getAdditionalConfigVariables(); $optionArray = []; foreach ($additionalConfigValues as $variable) { $optionArray[] = [ 'value' => '{{config path="' . $variable['value'] . '"}}', 'label' => $variable['label'], ]; } if ($optionArray) { $result[] = [ 'label' => __('Imprint'), 'value' => $optionArray, ]; } return $result; }
[ "public", "function", "afterGetVariables", "(", "\\", "Magento", "\\", "Email", "\\", "Block", "\\", "Adminhtml", "\\", "Template", "\\", "Edit", "\\", "Form", "$", "subject", ",", "$", "result", ")", "{", "$", "additionalConfigValues", "=", "$", "this", "...
Retrieve variables to insert into email @param \Magento\Email\Block\Adminhtml\Template\Edit\Form $subject @param array $result @return array
[ "Retrieve", "variables", "to", "insert", "into", "email" ]
train
https://github.com/firegento/firegento-magesetup2/blob/d1727b581dd703f72babecab125b600446be06de/Plugin/Email/Block/Adminhtml/Template/Edit/Form.php#L40-L57
firegento/firegento-magesetup2
Model/Setup/SubProcessor/SubProcessorPool.php
SubProcessorPool.get
public function get($subProcessorCode) { if (!isset($this->subProcessors[$subProcessorCode])) { throw new NotFoundException(__('SubProcessor %1 does not exist.', $subProcessorCode)); } return $this->subProcessors[$subProcessorCode]; }
php
public function get($subProcessorCode) { if (!isset($this->subProcessors[$subProcessorCode])) { throw new NotFoundException(__('SubProcessor %1 does not exist.', $subProcessorCode)); } return $this->subProcessors[$subProcessorCode]; }
[ "public", "function", "get", "(", "$", "subProcessorCode", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "subProcessors", "[", "$", "subProcessorCode", "]", ")", ")", "{", "throw", "new", "NotFoundException", "(", "__", "(", "'SubProcessor %1 ...
Retrieves operation @param string $subProcessorCode @return SubProcessorInterface @throws NotFoundException
[ "Retrieves", "operation" ]
train
https://github.com/firegento/firegento-magesetup2/blob/d1727b581dd703f72babecab125b600446be06de/Model/Setup/SubProcessor/SubProcessorPool.php#L47-L54
firegento/firegento-magesetup2
Model/Setup/SubProcessor/SubProcessorPool.php
SubProcessorPool.getSubProcessorCodes
public function getSubProcessorCodes() { $codes = []; foreach ($this->subProcessors->getIterator() as $code => $object) { $codes[] = $code; } return $codes; }
php
public function getSubProcessorCodes() { $codes = []; foreach ($this->subProcessors->getIterator() as $code => $object) { $codes[] = $code; } return $codes; }
[ "public", "function", "getSubProcessorCodes", "(", ")", "{", "$", "codes", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "subProcessors", "->", "getIterator", "(", ")", "as", "$", "code", "=>", "$", "object", ")", "{", "$", "codes", "[", "]"...
Retrieve the subprocessor codes @return array
[ "Retrieve", "the", "subprocessor", "codes" ]
train
https://github.com/firegento/firegento-magesetup2/blob/d1727b581dd703f72babecab125b600446be06de/Model/Setup/SubProcessor/SubProcessorPool.php#L61-L69
awssat/laravel-visits
src/Traits/Periods.php
Periods.periodsSync
protected function periodsSync() { foreach ($this->periods as $period) { $periodKey = $this->keys->period($period); if ($this->noExpiration($periodKey)) { $expireInSeconds = $this->newExpiration($period); $this->redis->incrby($periodKey . '_total', 0); $this->redis->zincrby($periodKey, 0, 0); $this->redis->expire($periodKey, $expireInSeconds); $this->redis->expire($periodKey . '_total', $expireInSeconds); } } }
php
protected function periodsSync() { foreach ($this->periods as $period) { $periodKey = $this->keys->period($period); if ($this->noExpiration($periodKey)) { $expireInSeconds = $this->newExpiration($period); $this->redis->incrby($periodKey . '_total', 0); $this->redis->zincrby($periodKey, 0, 0); $this->redis->expire($periodKey, $expireInSeconds); $this->redis->expire($periodKey . '_total', $expireInSeconds); } } }
[ "protected", "function", "periodsSync", "(", ")", "{", "foreach", "(", "$", "this", "->", "periods", "as", "$", "period", ")", "{", "$", "periodKey", "=", "$", "this", "->", "keys", "->", "period", "(", "$", "period", ")", ";", "if", "(", "$", "thi...
Sync periods times
[ "Sync", "periods", "times" ]
train
https://github.com/awssat/laravel-visits/blob/9d5fdbb84ba163bbf80e8c9c4c1cba9983dbece4/src/Traits/Periods.php#L13-L26
awssat/laravel-visits
src/Traits/Lists.php
Lists.top
public function top($limit = 5, $isLow = false) { $cacheKey = $this->keys->cache($limit, $isLow); $cachedList = $this->cachedList($limit, $cacheKey); $visitsIds = $this->getVisitsIds($limit, $this->keys->visits, $isLow); if($visitsIds === $cachedList->pluck($this->keys->primary)->toArray() && ! $this->fresh) { return $cachedList; } return $this->freshList($cacheKey, $visitsIds); }
php
public function top($limit = 5, $isLow = false) { $cacheKey = $this->keys->cache($limit, $isLow); $cachedList = $this->cachedList($limit, $cacheKey); $visitsIds = $this->getVisitsIds($limit, $this->keys->visits, $isLow); if($visitsIds === $cachedList->pluck($this->keys->primary)->toArray() && ! $this->fresh) { return $cachedList; } return $this->freshList($cacheKey, $visitsIds); }
[ "public", "function", "top", "(", "$", "limit", "=", "5", ",", "$", "isLow", "=", "false", ")", "{", "$", "cacheKey", "=", "$", "this", "->", "keys", "->", "cache", "(", "$", "limit", ",", "$", "isLow", ")", ";", "$", "cachedList", "=", "$", "t...
Fetch all time trending subjects. @param int $limit @param bool $isLow @return \Illuminate\Support\Collection|array
[ "Fetch", "all", "time", "trending", "subjects", "." ]
train
https://github.com/awssat/laravel-visits/blob/9d5fdbb84ba163bbf80e8c9c4c1cba9983dbece4/src/Traits/Lists.php#L14-L25
awssat/laravel-visits
src/Traits/Lists.php
Lists.countries
public function countries($limit = -1, $isLow = false) { $range = $isLow ? 'zrange' : 'zrevrange'; return $this->redis->$range($this->keys->visits . "_countries:{$this->keys->id}", 0, $limit, 'WITHSCORES'); }
php
public function countries($limit = -1, $isLow = false) { $range = $isLow ? 'zrange' : 'zrevrange'; return $this->redis->$range($this->keys->visits . "_countries:{$this->keys->id}", 0, $limit, 'WITHSCORES'); }
[ "public", "function", "countries", "(", "$", "limit", "=", "-", "1", ",", "$", "isLow", "=", "false", ")", "{", "$", "range", "=", "$", "isLow", "?", "'zrange'", ":", "'zrevrange'", ";", "return", "$", "this", "->", "redis", "->", "$", "range", "("...
Top/low countries @param int $limit @param bool $isLow @return mixed
[ "Top", "/", "low", "countries" ]
train
https://github.com/awssat/laravel-visits/blob/9d5fdbb84ba163bbf80e8c9c4c1cba9983dbece4/src/Traits/Lists.php#L35-L40
awssat/laravel-visits
src/Reset.php
Reset.factory
public function factory() { $this->visits(); $this->periods(); $this->ips(); $this->lists(); $this->allcountries(); $this->allrefs(); }
php
public function factory() { $this->visits(); $this->periods(); $this->ips(); $this->lists(); $this->allcountries(); $this->allrefs(); }
[ "public", "function", "factory", "(", ")", "{", "$", "this", "->", "visits", "(", ")", ";", "$", "this", "->", "periods", "(", ")", ";", "$", "this", "->", "ips", "(", ")", ";", "$", "this", "->", "lists", "(", ")", ";", "$", "this", "->", "a...
Reset everything
[ "Reset", "everything" ]
train
https://github.com/awssat/laravel-visits/blob/9d5fdbb84ba163bbf80e8c9c4c1cba9983dbece4/src/Reset.php#L34-L42
awssat/laravel-visits
src/Reset.php
Reset.visits
public function visits() { if ($this->keys->id) { $this->redis->zrem($this->keys->visits, $this->keys->id); $this->redis->del($this->keys->visits . "_countries:{$this->keys->id}"); $this->redis->del($this->keys->visits . "_referers:{$this->keys->id}"); foreach ($this->periods as $period => $days) { $this->redis->zrem($this->keys->period($period), $this->keys->id); } $this->ips(); } else { $this->redis->del($this->keys->visits); $this->redis->del($this->keys->visits . '_total'); } }
php
public function visits() { if ($this->keys->id) { $this->redis->zrem($this->keys->visits, $this->keys->id); $this->redis->del($this->keys->visits . "_countries:{$this->keys->id}"); $this->redis->del($this->keys->visits . "_referers:{$this->keys->id}"); foreach ($this->periods as $period => $days) { $this->redis->zrem($this->keys->period($period), $this->keys->id); } $this->ips(); } else { $this->redis->del($this->keys->visits); $this->redis->del($this->keys->visits . '_total'); } }
[ "public", "function", "visits", "(", ")", "{", "if", "(", "$", "this", "->", "keys", "->", "id", ")", "{", "$", "this", "->", "redis", "->", "zrem", "(", "$", "this", "->", "keys", "->", "visits", ",", "$", "this", "->", "keys", "->", "id", ")"...
reset all time visits
[ "reset", "all", "time", "visits" ]
train
https://github.com/awssat/laravel-visits/blob/9d5fdbb84ba163bbf80e8c9c4c1cba9983dbece4/src/Reset.php#L47-L64
awssat/laravel-visits
src/Reset.php
Reset.periods
public function periods() { foreach ($this->periods as $period => $days) { $periodKey = $this->keys->period($period); $this->redis->del($periodKey); $this->redis->del($periodKey . '_total'); } }
php
public function periods() { foreach ($this->periods as $period => $days) { $periodKey = $this->keys->period($period); $this->redis->del($periodKey); $this->redis->del($periodKey . '_total'); } }
[ "public", "function", "periods", "(", ")", "{", "foreach", "(", "$", "this", "->", "periods", "as", "$", "period", "=>", "$", "days", ")", "{", "$", "periodKey", "=", "$", "this", "->", "keys", "->", "period", "(", "$", "period", ")", ";", "$", "...
reset day,week counters
[ "reset", "day", "week", "counters" ]
train
https://github.com/awssat/laravel-visits/blob/9d5fdbb84ba163bbf80e8c9c4c1cba9983dbece4/src/Reset.php#L88-L95
awssat/laravel-visits
src/Reset.php
Reset.ips
public function ips($ips = '*') { $ips = $this->redis->keys($this->keys->ip($ips)); if (count($ips)) { $this->redis->del($ips); } }
php
public function ips($ips = '*') { $ips = $this->redis->keys($this->keys->ip($ips)); if (count($ips)) { $this->redis->del($ips); } }
[ "public", "function", "ips", "(", "$", "ips", "=", "'*'", ")", "{", "$", "ips", "=", "$", "this", "->", "redis", "->", "keys", "(", "$", "this", "->", "keys", "->", "ip", "(", "$", "ips", ")", ")", ";", "if", "(", "count", "(", "$", "ips", ...
reset ips protection @param string $ips
[ "reset", "ips", "protection" ]
train
https://github.com/awssat/laravel-visits/blob/9d5fdbb84ba163bbf80e8c9c4c1cba9983dbece4/src/Reset.php#L101-L108
awssat/laravel-visits
src/Reset.php
Reset.lists
public function lists() { $lists = $this->redis->keys($this->keys->cache()); if (count($lists)) { $this->redis->del($lists); } }
php
public function lists() { $lists = $this->redis->keys($this->keys->cache()); if (count($lists)) { $this->redis->del($lists); } }
[ "public", "function", "lists", "(", ")", "{", "$", "lists", "=", "$", "this", "->", "redis", "->", "keys", "(", "$", "this", "->", "keys", "->", "cache", "(", ")", ")", ";", "if", "(", "count", "(", "$", "lists", ")", ")", "{", "$", "this", "...
reset lists top/low
[ "reset", "lists", "top", "/", "low" ]
train
https://github.com/awssat/laravel-visits/blob/9d5fdbb84ba163bbf80e8c9c4c1cba9983dbece4/src/Reset.php#L113-L119
awssat/laravel-visits
src/VisitsServiceProvider.php
VisitsServiceProvider.boot
public function boot() { $this->publishes([ __DIR__ . '/config/visits.php' => config_path('visits.php'), ], 'config'); Carbon::macro('endOfxHours', function ($xhours) { if($xhours > 12) { throw new \Exception('12 is the maximum period in xHours feature'); } $hour = collect(range(1, 23 / $xhours)) ->map(function ($hour) use ($xhours) { return $hour * $xhours; })->first(function ($hour) { return $hour >= $this->hour; }); return $this->setTime($hour , 59, 59); }); }
php
public function boot() { $this->publishes([ __DIR__ . '/config/visits.php' => config_path('visits.php'), ], 'config'); Carbon::macro('endOfxHours', function ($xhours) { if($xhours > 12) { throw new \Exception('12 is the maximum period in xHours feature'); } $hour = collect(range(1, 23 / $xhours)) ->map(function ($hour) use ($xhours) { return $hour * $xhours; })->first(function ($hour) { return $hour >= $this->hour; }); return $this->setTime($hour , 59, 59); }); }
[ "public", "function", "boot", "(", ")", "{", "$", "this", "->", "publishes", "(", "[", "__DIR__", ".", "'/config/visits.php'", "=>", "config_path", "(", "'visits.php'", ")", ",", "]", ",", "'config'", ")", ";", "Carbon", "::", "macro", "(", "'endOfxHours'"...
Perform post-registration booting of services. @return void
[ "Perform", "post", "-", "registration", "booting", "of", "services", "." ]
train
https://github.com/awssat/laravel-visits/blob/9d5fdbb84ba163bbf80e8c9c4c1cba9983dbece4/src/VisitsServiceProvider.php#L15-L36
awssat/laravel-visits
src/Traits/Setters.php
Setters.period
public function period($period) { if (in_array($period, $this->periods)) { $this->keys->visits = $this->keys->period($period); } return $this; }
php
public function period($period) { if (in_array($period, $this->periods)) { $this->keys->visits = $this->keys->period($period); } return $this; }
[ "public", "function", "period", "(", "$", "period", ")", "{", "if", "(", "in_array", "(", "$", "period", ",", "$", "this", "->", "periods", ")", ")", "{", "$", "this", "->", "keys", "->", "visits", "=", "$", "this", "->", "keys", "->", "period", ...
Change period @param $period @return $this
[ "Change", "period" ]
train
https://github.com/awssat/laravel-visits/blob/9d5fdbb84ba163bbf80e8c9c4c1cba9983dbece4/src/Traits/Setters.php#L62-L69
h5p/h5p-php-library
h5p.classes.php
H5PValidator.isValidPackage
public function isValidPackage($skipContent = FALSE, $upgradeOnly = FALSE) { // Check dependencies, make sure Zip is present if (!class_exists('ZipArchive')) { $this->h5pF->setErrorMessage($this->h5pF->t('Your PHP version does not support ZipArchive.'), 'zip-archive-unsupported'); unlink($tmpPath); return FALSE; } if (!extension_loaded('mbstring')) { $this->h5pF->setErrorMessage($this->h5pF->t('The mbstring PHP extension is not loaded. H5P need this to function properly'), 'mbstring-unsupported'); unlink($tmpPath); return FALSE; } // Create a temporary dir to extract package in. $tmpDir = $this->h5pF->getUploadedH5pFolderPath(); $tmpPath = $this->h5pF->getUploadedH5pPath(); // Only allow files with the .h5p extension: if (strtolower(substr($tmpPath, -3)) !== 'h5p') { $this->h5pF->setErrorMessage($this->h5pF->t('The file you uploaded is not a valid HTML5 Package (It does not have the .h5p file extension)'), 'missing-h5p-extension'); unlink($tmpPath); return FALSE; } // Extract and then remove the package file. $zip = new ZipArchive; // Open the package if ($zip->open($tmpPath) !== TRUE) { $this->h5pF->setErrorMessage($this->h5pF->t('The file you uploaded is not a valid HTML5 Package (We are unable to unzip it)'), 'unable-to-unzip'); unlink($tmpPath); return FALSE; } if ($this->h5pC->disableFileCheck !== TRUE) { list($contentWhitelist, $contentRegExp) = $this->getWhitelistRegExp(FALSE); list($libraryWhitelist, $libraryRegExp) = $this->getWhitelistRegExp(TRUE); } $canInstall = $this->h5pC->mayUpdateLibraries(); $valid = TRUE; $libraries = array(); $totalSize = 0; $mainH5pExists = FALSE; $contentExists = FALSE; // Check for valid file types, JSON files + file sizes before continuing to unpack. for ($i = 0; $i < $zip->numFiles; $i++) { $fileStat = $zip->statIndex($i); if (!empty($this->h5pC->maxFileSize) && $fileStat['size'] > $this->h5pC->maxFileSize) { // Error file is too large $this->h5pF->setErrorMessage($this->h5pF->t('One of the files inside the package exceeds the maximum file size allowed. (%file %used > %max)', array('%file' => $fileStat['name'], '%used' => ($fileStat['size'] / 1048576) . ' MB', '%max' => ($this->h5pC->maxFileSize / 1048576) . ' MB')), 'file-size-too-large'); $valid = FALSE; } $totalSize += $fileStat['size']; $fileName = mb_strtolower($fileStat['name']); if (preg_match('/(^[\._]|\/[\._])/', $fileName) !== 0) { continue; // Skip any file or folder starting with a . or _ } elseif ($fileName === 'h5p.json') { $mainH5pExists = TRUE; } elseif ($fileName === 'content/content.json') { $contentExists = TRUE; } elseif (substr($fileName, 0, 8) === 'content/') { // This is a content file, check that the file type is allowed if ($skipContent === FALSE && $this->h5pC->disableFileCheck !== TRUE && !preg_match($contentRegExp, $fileName)) { $this->h5pF->setErrorMessage($this->h5pF->t('File "%filename" not allowed. Only files with the following extensions are allowed: %files-allowed.', array('%filename' => $fileStat['name'], '%files-allowed' => $contentWhitelist)), 'not-in-whitelist'); $valid = FALSE; } } elseif ($canInstall && strpos($fileName, '/') !== FALSE) { // This is a library file, check that the file type is allowed if ($this->h5pC->disableFileCheck !== TRUE && !preg_match($libraryRegExp, $fileName)) { $this->h5pF->setErrorMessage($this->h5pF->t('File "%filename" not allowed. Only files with the following extensions are allowed: %files-allowed.', array('%filename' => $fileStat['name'], '%files-allowed' => $libraryWhitelist)), 'not-in-whitelist'); $valid = FALSE; } // Further library validation happens after the files are extracted } } if (!empty($this->h5pC->maxTotalSize) && $totalSize > $this->h5pC->maxTotalSize) { // Error total size of the zip is too large $this->h5pF->setErrorMessage($this->h5pF->t('The total size of the unpacked files exceeds the maximum size allowed. (%used > %max)', array('%used' => ($totalSize / 1048576) . ' MB', '%max' => ($this->h5pC->maxTotalSize / 1048576) . ' MB')), 'total-size-too-large'); $valid = FALSE; } if ($skipContent === FALSE) { // Not skipping content, require two valid JSON files from the package if (!$contentExists) { $this->h5pF->setErrorMessage($this->h5pF->t('A valid content folder is missing'), 'invalid-content-folder'); $valid = FALSE; } else { $contentJsonData = $this->getJson($tmpPath, $zip, 'content/content.json'); // TODO: Is this case-senstivie? if ($contentJsonData === NULL) { return FALSE; // Breaking error when reading from the archive. } elseif ($contentJsonData === FALSE) { $valid = FALSE; // Validation error when parsing JSON } } if (!$mainH5pExists) { $this->h5pF->setErrorMessage($this->h5pF->t('A valid main h5p.json file is missing'), 'invalid-h5p-json-file'); $valid = FALSE; } else { $mainH5pData = $this->getJson($tmpPath, $zip, 'h5p.json', TRUE); if ($mainH5pData === NULL) { return FALSE; // Breaking error when reading from the archive. } elseif ($mainH5pData === FALSE) { $valid = FALSE; // Validation error when parsing JSON } elseif (!$this->isValidH5pData($mainH5pData, 'h5p.json', $this->h5pRequired, $this->h5pOptional)) { $this->h5pF->setErrorMessage($this->h5pF->t('The main h5p.json file is not valid'), 'invalid-h5p-json-file'); // Is this message a bit redundant? $valid = FALSE; } } } if (!$valid) { // If something has failed during the initial checks of the package // we will not unpack it or continue validation. $zip->close(); unlink($tmpPath); return FALSE; } // Extract the files from the package for ($i = 0; $i < $zip->numFiles; $i++) { $fileName = $zip->statIndex($i)['name']; if (preg_match('/(^[\._]|\/[\._])/', $fileName) !== 0) { continue; // Skip any file or folder starting with a . or _ } $isContentFile = (substr($fileName, 0, 8) === 'content/'); $isFolder = (strpos($fileName, '/') !== FALSE); if ($skipContent !== FALSE && $isContentFile) { continue; // Skipping any content files } if (!($isContentFile || ($canInstall && $isFolder))) { continue; // Not something we want to unpack } // Get file stream $fileStream = $zip->getStream($fileName); if (!$fileStream) { // This is a breaking error, there's no need to continue. (the rest of the files will fail as well) $this->h5pF->setErrorMessage($this->h5pF->t('Unable to read file from the package: %fileName', array('%fileName' => $fileName)), 'unable-to-read-package-file'); $zip->close(); unlink($path); H5PCore::deleteFileTree($tmpDir); return FALSE; } // Use file interface to allow overrides $this->h5pC->fs->saveFileFromZip($tmpDir, $fileName, $fileStream); // Clean up if (is_resource($fileStream)) { fclose($fileStream); } } // We're done with the zip file, clean up the stuff $zip->close(); unlink($tmpPath); if ($canInstall) { // Process and validate libraries using the unpacked library folders $files = scandir($tmpDir); foreach ($files as $file) { $filePath = $tmpDir . DIRECTORY_SEPARATOR . $file; if ($file === '.' || $file === '..' || $file === 'content' || !is_dir($filePath)) { continue; // Skip } $libraryH5PData = $this->getLibraryData($file, $filePath, $tmpDir); if ($libraryH5PData === FALSE) { $valid = FALSE; continue; // Failed, but continue validating the rest of the libraries } // Library's directory name must be: // - <machineName> // - or - // - <machineName>-<majorVersion>.<minorVersion> // where machineName, majorVersion and minorVersion is read from library.json if ($libraryH5PData['machineName'] !== $file && H5PCore::libraryToString($libraryH5PData, TRUE) !== $file) { $this->h5pF->setErrorMessage($this->h5pF->t('Library directory name must match machineName or machineName-majorVersion.minorVersion (from library.json). (Directory: %directoryName , machineName: %machineName, majorVersion: %majorVersion, minorVersion: %minorVersion)', array( '%directoryName' => $file, '%machineName' => $libraryH5PData['machineName'], '%majorVersion' => $libraryH5PData['majorVersion'], '%minorVersion' => $libraryH5PData['minorVersion'])), 'library-directory-name-mismatch'); $valid = FALSE; continue; // Failed, but continue validating the rest of the libraries } $libraryH5PData['uploadDirectory'] = $filePath; $libraries[H5PCore::libraryToString($libraryH5PData)] = $libraryH5PData; } } if ($valid) { if ($upgradeOnly) { // When upgrading, we only add the already installed libraries, and // the new dependent libraries $upgrades = array(); foreach ($libraries as $libString => &$library) { // Is this library already installed? if ($this->h5pF->getLibraryId($library['machineName']) !== FALSE) { $upgrades[$libString] = $library; } } while ($missingLibraries = $this->getMissingLibraries($upgrades)) { foreach ($missingLibraries as $libString => $missing) { $library = $libraries[$libString]; if ($library) { $upgrades[$libString] = $library; } } } $libraries = $upgrades; } $this->h5pC->librariesJsonData = $libraries; if ($skipContent === FALSE) { $this->h5pC->mainJsonData = $mainH5pData; $this->h5pC->contentJsonData = $contentJsonData; $libraries['mainH5pData'] = $mainH5pData; // Check for the dependencies in h5p.json as well as in the libraries } $missingLibraries = $this->getMissingLibraries($libraries); foreach ($missingLibraries as $libString => $missing) { if ($this->h5pC->getLibraryId($missing, $libString)) { unset($missingLibraries[$libString]); } } if (!empty($missingLibraries)) { // We still have missing libraries, check if our main library has an upgrade (BUT only if we has content) $mainDependency = NULL; if (!$skipContent && !empty($mainH5pData)) { foreach ($mainH5pData['preloadedDependencies'] as $dep) { if ($dep['machineName'] === $mainH5pData['mainLibrary']) { $mainDependency = $dep; } } } if ($skipContent || !$mainDependency || !$this->h5pF->libraryHasUpgrade(array( 'machineName' => $mainDependency['machineName'], 'majorVersion' => $mainDependency['majorVersion'], 'minorVersion' => $mainDependency['minorVersion'] ))) { foreach ($missingLibraries as $libString => $library) { $this->h5pF->setErrorMessage($this->h5pF->t('Missing required library @library', array('@library' => $libString)), 'missing-required-library'); $valid = FALSE; } if (!$this->h5pC->mayUpdateLibraries()) { $this->h5pF->setInfoMessage($this->h5pF->t("Note that the libraries may exist in the file you uploaded, but you're not allowed to upload new libraries. Contact the site administrator about this.")); $valid = FALSE; } } } } if (!$valid) { H5PCore::deleteFileTree($tmpDir); } return $valid; }
php
public function isValidPackage($skipContent = FALSE, $upgradeOnly = FALSE) { // Check dependencies, make sure Zip is present if (!class_exists('ZipArchive')) { $this->h5pF->setErrorMessage($this->h5pF->t('Your PHP version does not support ZipArchive.'), 'zip-archive-unsupported'); unlink($tmpPath); return FALSE; } if (!extension_loaded('mbstring')) { $this->h5pF->setErrorMessage($this->h5pF->t('The mbstring PHP extension is not loaded. H5P need this to function properly'), 'mbstring-unsupported'); unlink($tmpPath); return FALSE; } // Create a temporary dir to extract package in. $tmpDir = $this->h5pF->getUploadedH5pFolderPath(); $tmpPath = $this->h5pF->getUploadedH5pPath(); // Only allow files with the .h5p extension: if (strtolower(substr($tmpPath, -3)) !== 'h5p') { $this->h5pF->setErrorMessage($this->h5pF->t('The file you uploaded is not a valid HTML5 Package (It does not have the .h5p file extension)'), 'missing-h5p-extension'); unlink($tmpPath); return FALSE; } // Extract and then remove the package file. $zip = new ZipArchive; // Open the package if ($zip->open($tmpPath) !== TRUE) { $this->h5pF->setErrorMessage($this->h5pF->t('The file you uploaded is not a valid HTML5 Package (We are unable to unzip it)'), 'unable-to-unzip'); unlink($tmpPath); return FALSE; } if ($this->h5pC->disableFileCheck !== TRUE) { list($contentWhitelist, $contentRegExp) = $this->getWhitelistRegExp(FALSE); list($libraryWhitelist, $libraryRegExp) = $this->getWhitelistRegExp(TRUE); } $canInstall = $this->h5pC->mayUpdateLibraries(); $valid = TRUE; $libraries = array(); $totalSize = 0; $mainH5pExists = FALSE; $contentExists = FALSE; // Check for valid file types, JSON files + file sizes before continuing to unpack. for ($i = 0; $i < $zip->numFiles; $i++) { $fileStat = $zip->statIndex($i); if (!empty($this->h5pC->maxFileSize) && $fileStat['size'] > $this->h5pC->maxFileSize) { // Error file is too large $this->h5pF->setErrorMessage($this->h5pF->t('One of the files inside the package exceeds the maximum file size allowed. (%file %used > %max)', array('%file' => $fileStat['name'], '%used' => ($fileStat['size'] / 1048576) . ' MB', '%max' => ($this->h5pC->maxFileSize / 1048576) . ' MB')), 'file-size-too-large'); $valid = FALSE; } $totalSize += $fileStat['size']; $fileName = mb_strtolower($fileStat['name']); if (preg_match('/(^[\._]|\/[\._])/', $fileName) !== 0) { continue; // Skip any file or folder starting with a . or _ } elseif ($fileName === 'h5p.json') { $mainH5pExists = TRUE; } elseif ($fileName === 'content/content.json') { $contentExists = TRUE; } elseif (substr($fileName, 0, 8) === 'content/') { // This is a content file, check that the file type is allowed if ($skipContent === FALSE && $this->h5pC->disableFileCheck !== TRUE && !preg_match($contentRegExp, $fileName)) { $this->h5pF->setErrorMessage($this->h5pF->t('File "%filename" not allowed. Only files with the following extensions are allowed: %files-allowed.', array('%filename' => $fileStat['name'], '%files-allowed' => $contentWhitelist)), 'not-in-whitelist'); $valid = FALSE; } } elseif ($canInstall && strpos($fileName, '/') !== FALSE) { // This is a library file, check that the file type is allowed if ($this->h5pC->disableFileCheck !== TRUE && !preg_match($libraryRegExp, $fileName)) { $this->h5pF->setErrorMessage($this->h5pF->t('File "%filename" not allowed. Only files with the following extensions are allowed: %files-allowed.', array('%filename' => $fileStat['name'], '%files-allowed' => $libraryWhitelist)), 'not-in-whitelist'); $valid = FALSE; } // Further library validation happens after the files are extracted } } if (!empty($this->h5pC->maxTotalSize) && $totalSize > $this->h5pC->maxTotalSize) { // Error total size of the zip is too large $this->h5pF->setErrorMessage($this->h5pF->t('The total size of the unpacked files exceeds the maximum size allowed. (%used > %max)', array('%used' => ($totalSize / 1048576) . ' MB', '%max' => ($this->h5pC->maxTotalSize / 1048576) . ' MB')), 'total-size-too-large'); $valid = FALSE; } if ($skipContent === FALSE) { // Not skipping content, require two valid JSON files from the package if (!$contentExists) { $this->h5pF->setErrorMessage($this->h5pF->t('A valid content folder is missing'), 'invalid-content-folder'); $valid = FALSE; } else { $contentJsonData = $this->getJson($tmpPath, $zip, 'content/content.json'); // TODO: Is this case-senstivie? if ($contentJsonData === NULL) { return FALSE; // Breaking error when reading from the archive. } elseif ($contentJsonData === FALSE) { $valid = FALSE; // Validation error when parsing JSON } } if (!$mainH5pExists) { $this->h5pF->setErrorMessage($this->h5pF->t('A valid main h5p.json file is missing'), 'invalid-h5p-json-file'); $valid = FALSE; } else { $mainH5pData = $this->getJson($tmpPath, $zip, 'h5p.json', TRUE); if ($mainH5pData === NULL) { return FALSE; // Breaking error when reading from the archive. } elseif ($mainH5pData === FALSE) { $valid = FALSE; // Validation error when parsing JSON } elseif (!$this->isValidH5pData($mainH5pData, 'h5p.json', $this->h5pRequired, $this->h5pOptional)) { $this->h5pF->setErrorMessage($this->h5pF->t('The main h5p.json file is not valid'), 'invalid-h5p-json-file'); // Is this message a bit redundant? $valid = FALSE; } } } if (!$valid) { // If something has failed during the initial checks of the package // we will not unpack it or continue validation. $zip->close(); unlink($tmpPath); return FALSE; } // Extract the files from the package for ($i = 0; $i < $zip->numFiles; $i++) { $fileName = $zip->statIndex($i)['name']; if (preg_match('/(^[\._]|\/[\._])/', $fileName) !== 0) { continue; // Skip any file or folder starting with a . or _ } $isContentFile = (substr($fileName, 0, 8) === 'content/'); $isFolder = (strpos($fileName, '/') !== FALSE); if ($skipContent !== FALSE && $isContentFile) { continue; // Skipping any content files } if (!($isContentFile || ($canInstall && $isFolder))) { continue; // Not something we want to unpack } // Get file stream $fileStream = $zip->getStream($fileName); if (!$fileStream) { // This is a breaking error, there's no need to continue. (the rest of the files will fail as well) $this->h5pF->setErrorMessage($this->h5pF->t('Unable to read file from the package: %fileName', array('%fileName' => $fileName)), 'unable-to-read-package-file'); $zip->close(); unlink($path); H5PCore::deleteFileTree($tmpDir); return FALSE; } // Use file interface to allow overrides $this->h5pC->fs->saveFileFromZip($tmpDir, $fileName, $fileStream); // Clean up if (is_resource($fileStream)) { fclose($fileStream); } } // We're done with the zip file, clean up the stuff $zip->close(); unlink($tmpPath); if ($canInstall) { // Process and validate libraries using the unpacked library folders $files = scandir($tmpDir); foreach ($files as $file) { $filePath = $tmpDir . DIRECTORY_SEPARATOR . $file; if ($file === '.' || $file === '..' || $file === 'content' || !is_dir($filePath)) { continue; // Skip } $libraryH5PData = $this->getLibraryData($file, $filePath, $tmpDir); if ($libraryH5PData === FALSE) { $valid = FALSE; continue; // Failed, but continue validating the rest of the libraries } // Library's directory name must be: // - <machineName> // - or - // - <machineName>-<majorVersion>.<minorVersion> // where machineName, majorVersion and minorVersion is read from library.json if ($libraryH5PData['machineName'] !== $file && H5PCore::libraryToString($libraryH5PData, TRUE) !== $file) { $this->h5pF->setErrorMessage($this->h5pF->t('Library directory name must match machineName or machineName-majorVersion.minorVersion (from library.json). (Directory: %directoryName , machineName: %machineName, majorVersion: %majorVersion, minorVersion: %minorVersion)', array( '%directoryName' => $file, '%machineName' => $libraryH5PData['machineName'], '%majorVersion' => $libraryH5PData['majorVersion'], '%minorVersion' => $libraryH5PData['minorVersion'])), 'library-directory-name-mismatch'); $valid = FALSE; continue; // Failed, but continue validating the rest of the libraries } $libraryH5PData['uploadDirectory'] = $filePath; $libraries[H5PCore::libraryToString($libraryH5PData)] = $libraryH5PData; } } if ($valid) { if ($upgradeOnly) { // When upgrading, we only add the already installed libraries, and // the new dependent libraries $upgrades = array(); foreach ($libraries as $libString => &$library) { // Is this library already installed? if ($this->h5pF->getLibraryId($library['machineName']) !== FALSE) { $upgrades[$libString] = $library; } } while ($missingLibraries = $this->getMissingLibraries($upgrades)) { foreach ($missingLibraries as $libString => $missing) { $library = $libraries[$libString]; if ($library) { $upgrades[$libString] = $library; } } } $libraries = $upgrades; } $this->h5pC->librariesJsonData = $libraries; if ($skipContent === FALSE) { $this->h5pC->mainJsonData = $mainH5pData; $this->h5pC->contentJsonData = $contentJsonData; $libraries['mainH5pData'] = $mainH5pData; // Check for the dependencies in h5p.json as well as in the libraries } $missingLibraries = $this->getMissingLibraries($libraries); foreach ($missingLibraries as $libString => $missing) { if ($this->h5pC->getLibraryId($missing, $libString)) { unset($missingLibraries[$libString]); } } if (!empty($missingLibraries)) { // We still have missing libraries, check if our main library has an upgrade (BUT only if we has content) $mainDependency = NULL; if (!$skipContent && !empty($mainH5pData)) { foreach ($mainH5pData['preloadedDependencies'] as $dep) { if ($dep['machineName'] === $mainH5pData['mainLibrary']) { $mainDependency = $dep; } } } if ($skipContent || !$mainDependency || !$this->h5pF->libraryHasUpgrade(array( 'machineName' => $mainDependency['machineName'], 'majorVersion' => $mainDependency['majorVersion'], 'minorVersion' => $mainDependency['minorVersion'] ))) { foreach ($missingLibraries as $libString => $library) { $this->h5pF->setErrorMessage($this->h5pF->t('Missing required library @library', array('@library' => $libString)), 'missing-required-library'); $valid = FALSE; } if (!$this->h5pC->mayUpdateLibraries()) { $this->h5pF->setInfoMessage($this->h5pF->t("Note that the libraries may exist in the file you uploaded, but you're not allowed to upload new libraries. Contact the site administrator about this.")); $valid = FALSE; } } } } if (!$valid) { H5PCore::deleteFileTree($tmpDir); } return $valid; }
[ "public", "function", "isValidPackage", "(", "$", "skipContent", "=", "FALSE", ",", "$", "upgradeOnly", "=", "FALSE", ")", "{", "// Check dependencies, make sure Zip is present", "if", "(", "!", "class_exists", "(", "'ZipArchive'", ")", ")", "{", "$", "this", "-...
Validates a .h5p file @param bool $skipContent @param bool $upgradeOnly @return bool TRUE if the .h5p file is valid TRUE if the .h5p file is valid
[ "Validates", "a", ".", "h5p", "file" ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p.classes.php#L754-L1037
h5p/h5p-php-library
h5p.classes.php
H5PValidator.getJson
private function getJson($path, $zip, $file, $assoc = FALSE) { // Get stream $stream = $zip->getStream($file); if (!$stream) { // Breaking error, no need to continue validating. $this->h5pF->setErrorMessage($this->h5pF->t('Unable to read file from the package: %fileName', array('%fileName' => $file)), 'unable-to-read-package-file'); $zip->close(); unlink($path); return NULL; } // Read data $contents = ''; while (!feof($stream)) { $contents .= fread($stream, 2); } // Decode the data $json = json_decode($contents, $assoc); if ($json === NULL) { // JSON cannot be decoded or the recursion limit has been reached. $this->h5pF->setErrorMessage($this->h5pF->t('Unable to parse JSON from the package: %fileName', array('%fileName' => $file)), 'unable-to-parse-package'); return FALSE; } // All OK return $json; }
php
private function getJson($path, $zip, $file, $assoc = FALSE) { // Get stream $stream = $zip->getStream($file); if (!$stream) { // Breaking error, no need to continue validating. $this->h5pF->setErrorMessage($this->h5pF->t('Unable to read file from the package: %fileName', array('%fileName' => $file)), 'unable-to-read-package-file'); $zip->close(); unlink($path); return NULL; } // Read data $contents = ''; while (!feof($stream)) { $contents .= fread($stream, 2); } // Decode the data $json = json_decode($contents, $assoc); if ($json === NULL) { // JSON cannot be decoded or the recursion limit has been reached. $this->h5pF->setErrorMessage($this->h5pF->t('Unable to parse JSON from the package: %fileName', array('%fileName' => $file)), 'unable-to-parse-package'); return FALSE; } // All OK return $json; }
[ "private", "function", "getJson", "(", "$", "path", ",", "$", "zip", ",", "$", "file", ",", "$", "assoc", "=", "FALSE", ")", "{", "// Get stream", "$", "stream", "=", "$", "zip", "->", "getStream", "(", "$", "file", ")", ";", "if", "(", "!", "$",...
Help read JSON from the archive @param string $path @param ZipArchive $zip @param string $file @return mixed JSON content if valid, FALSE for invalid, NULL for breaking error.
[ "Help", "read", "JSON", "from", "the", "archive" ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p.classes.php#L1047-L1074
h5p/h5p-php-library
h5p.classes.php
H5PValidator.getWhitelistRegExp
private function getWhitelistRegExp($isLibrary) { $whitelist = $this->h5pF->getWhitelist($isLibrary, H5PCore::$defaultContentWhitelist, H5PCore::$defaultLibraryWhitelistExtras); return array($whitelist, '/\.(' . preg_replace('/ +/i', '|', preg_quote($whitelist)) . ')$/i'); }
php
private function getWhitelistRegExp($isLibrary) { $whitelist = $this->h5pF->getWhitelist($isLibrary, H5PCore::$defaultContentWhitelist, H5PCore::$defaultLibraryWhitelistExtras); return array($whitelist, '/\.(' . preg_replace('/ +/i', '|', preg_quote($whitelist)) . ')$/i'); }
[ "private", "function", "getWhitelistRegExp", "(", "$", "isLibrary", ")", "{", "$", "whitelist", "=", "$", "this", "->", "h5pF", "->", "getWhitelist", "(", "$", "isLibrary", ",", "H5PCore", "::", "$", "defaultContentWhitelist", ",", "H5PCore", "::", "$", "def...
Help retrieve file type regexp whitelist from plugin. @param bool $isLibrary Separate list with more allowed file types @return string RegExp
[ "Help", "retrieve", "file", "type", "regexp", "whitelist", "from", "plugin", "." ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p.classes.php#L1082-L1085
h5p/h5p-php-library
h5p.classes.php
H5PValidator.getLibraryData
public function getLibraryData($file, $filePath, $tmpDir) { if (preg_match('/^[\w0-9\-\.]{1,255}$/i', $file) === 0) { $this->h5pF->setErrorMessage($this->h5pF->t('Invalid library name: %name', array('%name' => $file)), 'invalid-library-name'); return FALSE; } $h5pData = $this->getJsonData($filePath . DIRECTORY_SEPARATOR . 'library.json'); if ($h5pData === FALSE) { $this->h5pF->setErrorMessage($this->h5pF->t('Could not find library.json file with valid json format for library %name', array('%name' => $file)), 'invalid-library-json-file'); return FALSE; } // validate json if a semantics file is provided $semanticsPath = $filePath . DIRECTORY_SEPARATOR . 'semantics.json'; if (file_exists($semanticsPath)) { $semantics = $this->getJsonData($semanticsPath, TRUE); if ($semantics === FALSE) { $this->h5pF->setErrorMessage($this->h5pF->t('Invalid semantics.json file has been included in the library %name', array('%name' => $file)), 'invalid-semantics-json-file'); return FALSE; } else { $h5pData['semantics'] = $semantics; } } // validate language folder if it exists $languagePath = $filePath . DIRECTORY_SEPARATOR . 'language'; if (is_dir($languagePath)) { $languageFiles = scandir($languagePath); foreach ($languageFiles as $languageFile) { if (in_array($languageFile, array('.', '..'))) { continue; } if (preg_match('/^(-?[a-z]+){1,7}\.json$/i', $languageFile) === 0) { $this->h5pF->setErrorMessage($this->h5pF->t('Invalid language file %file in library %library', array('%file' => $languageFile, '%library' => $file)), 'invalid-language-file'); return FALSE; } $languageJson = $this->getJsonData($languagePath . DIRECTORY_SEPARATOR . $languageFile, TRUE); if ($languageJson === FALSE) { $this->h5pF->setErrorMessage($this->h5pF->t('Invalid language file %languageFile has been included in the library %name', array('%languageFile' => $languageFile, '%name' => $file)), 'invalid-language-file'); return FALSE; } $parts = explode('.', $languageFile); // $parts[0] is the language code $h5pData['language'][$parts[0]] = $languageJson; } } // Check for icon: $h5pData['hasIcon'] = file_exists($filePath . DIRECTORY_SEPARATOR . 'icon.svg'); $validLibrary = $this->isValidH5pData($h5pData, $file, $this->libraryRequired, $this->libraryOptional); //$validLibrary = $this->h5pCV->validateContentFiles($filePath, TRUE) && $validLibrary; if (isset($h5pData['preloadedJs'])) { $validLibrary = $this->isExistingFiles($h5pData['preloadedJs'], $tmpDir, $file) && $validLibrary; } if (isset($h5pData['preloadedCss'])) { $validLibrary = $this->isExistingFiles($h5pData['preloadedCss'], $tmpDir, $file) && $validLibrary; } if ($validLibrary) { return $h5pData; } else { return FALSE; } }
php
public function getLibraryData($file, $filePath, $tmpDir) { if (preg_match('/^[\w0-9\-\.]{1,255}$/i', $file) === 0) { $this->h5pF->setErrorMessage($this->h5pF->t('Invalid library name: %name', array('%name' => $file)), 'invalid-library-name'); return FALSE; } $h5pData = $this->getJsonData($filePath . DIRECTORY_SEPARATOR . 'library.json'); if ($h5pData === FALSE) { $this->h5pF->setErrorMessage($this->h5pF->t('Could not find library.json file with valid json format for library %name', array('%name' => $file)), 'invalid-library-json-file'); return FALSE; } // validate json if a semantics file is provided $semanticsPath = $filePath . DIRECTORY_SEPARATOR . 'semantics.json'; if (file_exists($semanticsPath)) { $semantics = $this->getJsonData($semanticsPath, TRUE); if ($semantics === FALSE) { $this->h5pF->setErrorMessage($this->h5pF->t('Invalid semantics.json file has been included in the library %name', array('%name' => $file)), 'invalid-semantics-json-file'); return FALSE; } else { $h5pData['semantics'] = $semantics; } } // validate language folder if it exists $languagePath = $filePath . DIRECTORY_SEPARATOR . 'language'; if (is_dir($languagePath)) { $languageFiles = scandir($languagePath); foreach ($languageFiles as $languageFile) { if (in_array($languageFile, array('.', '..'))) { continue; } if (preg_match('/^(-?[a-z]+){1,7}\.json$/i', $languageFile) === 0) { $this->h5pF->setErrorMessage($this->h5pF->t('Invalid language file %file in library %library', array('%file' => $languageFile, '%library' => $file)), 'invalid-language-file'); return FALSE; } $languageJson = $this->getJsonData($languagePath . DIRECTORY_SEPARATOR . $languageFile, TRUE); if ($languageJson === FALSE) { $this->h5pF->setErrorMessage($this->h5pF->t('Invalid language file %languageFile has been included in the library %name', array('%languageFile' => $languageFile, '%name' => $file)), 'invalid-language-file'); return FALSE; } $parts = explode('.', $languageFile); // $parts[0] is the language code $h5pData['language'][$parts[0]] = $languageJson; } } // Check for icon: $h5pData['hasIcon'] = file_exists($filePath . DIRECTORY_SEPARATOR . 'icon.svg'); $validLibrary = $this->isValidH5pData($h5pData, $file, $this->libraryRequired, $this->libraryOptional); //$validLibrary = $this->h5pCV->validateContentFiles($filePath, TRUE) && $validLibrary; if (isset($h5pData['preloadedJs'])) { $validLibrary = $this->isExistingFiles($h5pData['preloadedJs'], $tmpDir, $file) && $validLibrary; } if (isset($h5pData['preloadedCss'])) { $validLibrary = $this->isExistingFiles($h5pData['preloadedCss'], $tmpDir, $file) && $validLibrary; } if ($validLibrary) { return $h5pData; } else { return FALSE; } }
[ "public", "function", "getLibraryData", "(", "$", "file", ",", "$", "filePath", ",", "$", "tmpDir", ")", "{", "if", "(", "preg_match", "(", "'/^[\\w0-9\\-\\.]{1,255}$/i'", ",", "$", "file", ")", "===", "0", ")", "{", "$", "this", "->", "h5pF", "->", "s...
Validates a H5P library @param string $file Name of the library folder @param string $filePath Path to the library folder @param string $tmpDir Path to the temporary upload directory @return boolean|array H5P data from library.json and semantics if the library is valid FALSE if the library isn't valid
[ "Validates", "a", "H5P", "library" ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p.classes.php#L1100-L1165
h5p/h5p-php-library
h5p.classes.php
H5PValidator.getMissingLibraries
private function getMissingLibraries($libraries) { $missing = array(); foreach ($libraries as $library) { if (isset($library['preloadedDependencies'])) { $missing = array_merge($missing, $this->getMissingDependencies($library['preloadedDependencies'], $libraries)); } if (isset($library['dynamicDependencies'])) { $missing = array_merge($missing, $this->getMissingDependencies($library['dynamicDependencies'], $libraries)); } if (isset($library['editorDependencies'])) { $missing = array_merge($missing, $this->getMissingDependencies($library['editorDependencies'], $libraries)); } } return $missing; }
php
private function getMissingLibraries($libraries) { $missing = array(); foreach ($libraries as $library) { if (isset($library['preloadedDependencies'])) { $missing = array_merge($missing, $this->getMissingDependencies($library['preloadedDependencies'], $libraries)); } if (isset($library['dynamicDependencies'])) { $missing = array_merge($missing, $this->getMissingDependencies($library['dynamicDependencies'], $libraries)); } if (isset($library['editorDependencies'])) { $missing = array_merge($missing, $this->getMissingDependencies($library['editorDependencies'], $libraries)); } } return $missing; }
[ "private", "function", "getMissingLibraries", "(", "$", "libraries", ")", "{", "$", "missing", "=", "array", "(", ")", ";", "foreach", "(", "$", "libraries", "as", "$", "library", ")", "{", "if", "(", "isset", "(", "$", "library", "[", "'preloadedDepende...
Use the dependency declarations to find any missing libraries @param array $libraries A multidimensional array of libraries keyed with machineName first and majorVersion second @return array A list of libraries that are missing keyed with machineName and holds objects with machineName, majorVersion and minorVersion properties
[ "Use", "the", "dependency", "declarations", "to", "find", "any", "missing", "libraries" ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p.classes.php#L1176-L1190
h5p/h5p-php-library
h5p.classes.php
H5PValidator.getMissingDependencies
private function getMissingDependencies($dependencies, $libraries) { $missing = array(); foreach ($dependencies as $dependency) { $libString = H5PCore::libraryToString($dependency); if (!isset($libraries[$libString])) { $missing[$libString] = $dependency; } } return $missing; }
php
private function getMissingDependencies($dependencies, $libraries) { $missing = array(); foreach ($dependencies as $dependency) { $libString = H5PCore::libraryToString($dependency); if (!isset($libraries[$libString])) { $missing[$libString] = $dependency; } } return $missing; }
[ "private", "function", "getMissingDependencies", "(", "$", "dependencies", ",", "$", "libraries", ")", "{", "$", "missing", "=", "array", "(", ")", ";", "foreach", "(", "$", "dependencies", "as", "$", "dependency", ")", "{", "$", "libString", "=", "H5PCore...
Helper function for getMissingLibraries, searches for dependency required libraries in the provided list of libraries @param array $dependencies A list of objects with machineName, majorVersion and minorVersion properties @param array $libraries An array of libraries keyed with machineName @return A list of libraries that are missing keyed with machineName and holds objects with machineName, majorVersion and minorVersion properties
[ "Helper", "function", "for", "getMissingLibraries", "searches", "for", "dependency", "required", "libraries", "in", "the", "provided", "list", "of", "libraries" ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p.classes.php#L1204-L1213
h5p/h5p-php-library
h5p.classes.php
H5PValidator.isExistingFiles
private function isExistingFiles($files, $tmpDir, $library) { foreach ($files as $file) { $path = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $file['path']); if (!file_exists($tmpDir . DIRECTORY_SEPARATOR . $library . DIRECTORY_SEPARATOR . $path)) { $this->h5pF->setErrorMessage($this->h5pF->t('The file "%file" is missing from library: "%name"', array('%file' => $path, '%name' => $library)), 'library-missing-file'); return FALSE; } } return TRUE; }
php
private function isExistingFiles($files, $tmpDir, $library) { foreach ($files as $file) { $path = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $file['path']); if (!file_exists($tmpDir . DIRECTORY_SEPARATOR . $library . DIRECTORY_SEPARATOR . $path)) { $this->h5pF->setErrorMessage($this->h5pF->t('The file "%file" is missing from library: "%name"', array('%file' => $path, '%name' => $library)), 'library-missing-file'); return FALSE; } } return TRUE; }
[ "private", "function", "isExistingFiles", "(", "$", "files", ",", "$", "tmpDir", ",", "$", "library", ")", "{", "foreach", "(", "$", "files", "as", "$", "file", ")", "{", "$", "path", "=", "str_replace", "(", "array", "(", "'/'", ",", "'\\\\'", ")", ...
Figure out if the provided file paths exists Triggers error messages if files doesn't exist @param array $files List of file paths relative to $tmpDir @param string $tmpDir Path to the directory where the $files are stored. @param string $library Name of the library we are processing @return boolean TRUE if all the files excists
[ "Figure", "out", "if", "the", "provided", "file", "paths", "exists" ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p.classes.php#L1229-L1238
h5p/h5p-php-library
h5p.classes.php
H5PValidator.isValidH5pData
private function isValidH5pData($h5pData, $library_name, $required, $optional) { $valid = $this->isValidRequiredH5pData($h5pData, $required, $library_name); $valid = $this->isValidOptionalH5pData($h5pData, $optional, $library_name) && $valid; // Check the library's required API version of Core. // If no requirement is set this implicitly means 1.0. if (isset($h5pData['coreApi']) && !empty($h5pData['coreApi'])) { if (($h5pData['coreApi']['majorVersion'] > H5PCore::$coreApi['majorVersion']) || ( ($h5pData['coreApi']['majorVersion'] == H5PCore::$coreApi['majorVersion']) && ($h5pData['coreApi']['minorVersion'] > H5PCore::$coreApi['minorVersion']) )) { $this->h5pF->setErrorMessage( $this->h5pF->t('The system was unable to install the <em>%component</em> component from the package, it requires a newer version of the H5P plugin. This site is currently running version %current, whereas the required version is %required or higher. You should consider upgrading and then try again.', array( '%component' => (isset($h5pData['title']) ? $h5pData['title'] : $library_name), '%current' => H5PCore::$coreApi['majorVersion'] . '.' . H5PCore::$coreApi['minorVersion'], '%required' => $h5pData['coreApi']['majorVersion'] . '.' . $h5pData['coreApi']['minorVersion'] ) ), 'api-version-unsupported' ); $valid = false; } } return $valid; }
php
private function isValidH5pData($h5pData, $library_name, $required, $optional) { $valid = $this->isValidRequiredH5pData($h5pData, $required, $library_name); $valid = $this->isValidOptionalH5pData($h5pData, $optional, $library_name) && $valid; // Check the library's required API version of Core. // If no requirement is set this implicitly means 1.0. if (isset($h5pData['coreApi']) && !empty($h5pData['coreApi'])) { if (($h5pData['coreApi']['majorVersion'] > H5PCore::$coreApi['majorVersion']) || ( ($h5pData['coreApi']['majorVersion'] == H5PCore::$coreApi['majorVersion']) && ($h5pData['coreApi']['minorVersion'] > H5PCore::$coreApi['minorVersion']) )) { $this->h5pF->setErrorMessage( $this->h5pF->t('The system was unable to install the <em>%component</em> component from the package, it requires a newer version of the H5P plugin. This site is currently running version %current, whereas the required version is %required or higher. You should consider upgrading and then try again.', array( '%component' => (isset($h5pData['title']) ? $h5pData['title'] : $library_name), '%current' => H5PCore::$coreApi['majorVersion'] . '.' . H5PCore::$coreApi['minorVersion'], '%required' => $h5pData['coreApi']['majorVersion'] . '.' . $h5pData['coreApi']['minorVersion'] ) ), 'api-version-unsupported' ); $valid = false; } } return $valid; }
[ "private", "function", "isValidH5pData", "(", "$", "h5pData", ",", "$", "library_name", ",", "$", "required", ",", "$", "optional", ")", "{", "$", "valid", "=", "$", "this", "->", "isValidRequiredH5pData", "(", "$", "h5pData", ",", "$", "required", ",", ...
Validates h5p.json and library.json data Error messages are triggered if the data isn't valid @param array $h5pData h5p data @param string $library_name Name of the library we are processing @param array $required Validation pattern for required properties @param array $optional Validation pattern for optional properties @return boolean TRUE if the $h5pData is valid
[ "Validates", "h5p", ".", "json", "and", "library", ".", "json", "data" ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p.classes.php#L1256-L1283
h5p/h5p-php-library
h5p.classes.php
H5PValidator.isValidOptionalH5pData
private function isValidOptionalH5pData($h5pData, $requirements, $library_name) { $valid = TRUE; foreach ($h5pData as $key => $value) { if (isset($requirements[$key])) { $valid = $this->isValidRequirement($value, $requirements[$key], $library_name, $key) && $valid; } // Else: ignore, a package can have parameters that this library doesn't care about, but that library // specific implementations does care about... } return $valid; }
php
private function isValidOptionalH5pData($h5pData, $requirements, $library_name) { $valid = TRUE; foreach ($h5pData as $key => $value) { if (isset($requirements[$key])) { $valid = $this->isValidRequirement($value, $requirements[$key], $library_name, $key) && $valid; } // Else: ignore, a package can have parameters that this library doesn't care about, but that library // specific implementations does care about... } return $valid; }
[ "private", "function", "isValidOptionalH5pData", "(", "$", "h5pData", ",", "$", "requirements", ",", "$", "library_name", ")", "{", "$", "valid", "=", "TRUE", ";", "foreach", "(", "$", "h5pData", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(...
Helper function for isValidH5pData Validates the optional part of the h5pData Triggers error messages @param array $h5pData h5p data @param array $requirements Validation pattern @param string $library_name Name of the library we are processing @return boolean TRUE if the optional part of the $h5pData is valid
[ "Helper", "function", "for", "isValidH5pData" ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p.classes.php#L1301-L1313
h5p/h5p-php-library
h5p.classes.php
H5PValidator.isValidRequirement
private function isValidRequirement($h5pData, $requirement, $library_name, $property_name) { $valid = TRUE; if (is_string($requirement)) { if ($requirement == 'boolean') { if (!is_bool($h5pData)) { $this->h5pF->setErrorMessage($this->h5pF->t("Invalid data provided for %property in %library. Boolean expected.", array('%property' => $property_name, '%library' => $library_name))); $valid = FALSE; } } else { // The requirement is a regexp, match it against the data if (is_string($h5pData) || is_int($h5pData)) { if (preg_match($requirement, $h5pData) === 0) { $this->h5pF->setErrorMessage($this->h5pF->t("Invalid data provided for %property in %library", array('%property' => $property_name, '%library' => $library_name))); $valid = FALSE; } } else { $this->h5pF->setErrorMessage($this->h5pF->t("Invalid data provided for %property in %library", array('%property' => $property_name, '%library' => $library_name))); $valid = FALSE; } } } elseif (is_array($requirement)) { // We have sub requirements if (is_array($h5pData)) { if (is_array(current($h5pData))) { foreach ($h5pData as $sub_h5pData) { $valid = $this->isValidRequiredH5pData($sub_h5pData, $requirement, $library_name) && $valid; } } else { $valid = $this->isValidRequiredH5pData($h5pData, $requirement, $library_name) && $valid; } } else { $this->h5pF->setErrorMessage($this->h5pF->t("Invalid data provided for %property in %library", array('%property' => $property_name, '%library' => $library_name))); $valid = FALSE; } } else { $this->h5pF->setErrorMessage($this->h5pF->t("Can't read the property %property in %library", array('%property' => $property_name, '%library' => $library_name))); $valid = FALSE; } return $valid; }
php
private function isValidRequirement($h5pData, $requirement, $library_name, $property_name) { $valid = TRUE; if (is_string($requirement)) { if ($requirement == 'boolean') { if (!is_bool($h5pData)) { $this->h5pF->setErrorMessage($this->h5pF->t("Invalid data provided for %property in %library. Boolean expected.", array('%property' => $property_name, '%library' => $library_name))); $valid = FALSE; } } else { // The requirement is a regexp, match it against the data if (is_string($h5pData) || is_int($h5pData)) { if (preg_match($requirement, $h5pData) === 0) { $this->h5pF->setErrorMessage($this->h5pF->t("Invalid data provided for %property in %library", array('%property' => $property_name, '%library' => $library_name))); $valid = FALSE; } } else { $this->h5pF->setErrorMessage($this->h5pF->t("Invalid data provided for %property in %library", array('%property' => $property_name, '%library' => $library_name))); $valid = FALSE; } } } elseif (is_array($requirement)) { // We have sub requirements if (is_array($h5pData)) { if (is_array(current($h5pData))) { foreach ($h5pData as $sub_h5pData) { $valid = $this->isValidRequiredH5pData($sub_h5pData, $requirement, $library_name) && $valid; } } else { $valid = $this->isValidRequiredH5pData($h5pData, $requirement, $library_name) && $valid; } } else { $this->h5pF->setErrorMessage($this->h5pF->t("Invalid data provided for %property in %library", array('%property' => $property_name, '%library' => $library_name))); $valid = FALSE; } } else { $this->h5pF->setErrorMessage($this->h5pF->t("Can't read the property %property in %library", array('%property' => $property_name, '%library' => $library_name))); $valid = FALSE; } return $valid; }
[ "private", "function", "isValidRequirement", "(", "$", "h5pData", ",", "$", "requirement", ",", "$", "library_name", ",", "$", "property_name", ")", "{", "$", "valid", "=", "TRUE", ";", "if", "(", "is_string", "(", "$", "requirement", ")", ")", "{", "if"...
Validate a requirement given as regexp or an array of requirements @param mixed $h5pData The data to be validated @param mixed $requirement The requirement the data is to be validated against, regexp or array of requirements @param string $library_name Name of the library we are validating(used in error messages) @param string $property_name Name of the property we are validating(used in error messages) @return boolean TRUE if valid, FALSE if invalid
[ "Validate", "a", "requirement", "given", "as", "regexp", "or", "an", "array", "of", "requirements" ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p.classes.php#L1329-L1375
h5p/h5p-php-library
h5p.classes.php
H5PValidator.isValidRequiredH5pData
private function isValidRequiredH5pData($h5pData, $requirements, $library_name) { $valid = TRUE; foreach ($requirements as $required => $requirement) { if (is_int($required)) { // We have an array of allowed options return $this->isValidH5pDataOptions($h5pData, $requirements, $library_name); } if (isset($h5pData[$required])) { $valid = $this->isValidRequirement($h5pData[$required], $requirement, $library_name, $required) && $valid; } else { $this->h5pF->setErrorMessage($this->h5pF->t('The required property %property is missing from %library', array('%property' => $required, '%library' => $library_name)), 'missing-required-property'); $valid = FALSE; } } return $valid; }
php
private function isValidRequiredH5pData($h5pData, $requirements, $library_name) { $valid = TRUE; foreach ($requirements as $required => $requirement) { if (is_int($required)) { // We have an array of allowed options return $this->isValidH5pDataOptions($h5pData, $requirements, $library_name); } if (isset($h5pData[$required])) { $valid = $this->isValidRequirement($h5pData[$required], $requirement, $library_name, $required) && $valid; } else { $this->h5pF->setErrorMessage($this->h5pF->t('The required property %property is missing from %library', array('%property' => $required, '%library' => $library_name)), 'missing-required-property'); $valid = FALSE; } } return $valid; }
[ "private", "function", "isValidRequiredH5pData", "(", "$", "h5pData", ",", "$", "requirements", ",", "$", "library_name", ")", "{", "$", "valid", "=", "TRUE", ";", "foreach", "(", "$", "requirements", "as", "$", "required", "=>", "$", "requirement", ")", "...
Validates the required h5p data in libraray.json and h5p.json @param mixed $h5pData Data to be validated @param array $requirements Array with regexp to validate the data against @param string $library_name Name of the library we are validating (used in error messages) @return boolean TRUE if all the required data exists and is valid, FALSE otherwise
[ "Validates", "the", "required", "h5p", "data", "in", "libraray", ".", "json", "and", "h5p", ".", "json" ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p.classes.php#L1389-L1405
h5p/h5p-php-library
h5p.classes.php
H5PValidator.isValidH5pDataOptions
private function isValidH5pDataOptions($selected, $allowed, $library_name) { $valid = TRUE; foreach ($selected as $value) { if (!in_array($value, $allowed)) { $this->h5pF->setErrorMessage($this->h5pF->t('Illegal option %option in %library', array('%option' => $value, '%library' => $library_name)), 'illegal-option-in-library'); $valid = FALSE; } } return $valid; }
php
private function isValidH5pDataOptions($selected, $allowed, $library_name) { $valid = TRUE; foreach ($selected as $value) { if (!in_array($value, $allowed)) { $this->h5pF->setErrorMessage($this->h5pF->t('Illegal option %option in %library', array('%option' => $value, '%library' => $library_name)), 'illegal-option-in-library'); $valid = FALSE; } } return $valid; }
[ "private", "function", "isValidH5pDataOptions", "(", "$", "selected", ",", "$", "allowed", ",", "$", "library_name", ")", "{", "$", "valid", "=", "TRUE", ";", "foreach", "(", "$", "selected", "as", "$", "value", ")", "{", "if", "(", "!", "in_array", "(...
Validates h5p data against a set of allowed values(options) @param array $selected The option(s) that has been specified @param array $allowed The allowed options @param string $library_name Name of the library we are validating (used in error messages) @return boolean TRUE if the specified data is valid, FALSE otherwise
[ "Validates", "h5p", "data", "against", "a", "set", "of", "allowed", "values", "(", "options", ")" ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p.classes.php#L1419-L1428
h5p/h5p-php-library
h5p.classes.php
H5PValidator.getJsonData
private function getJsonData($filePath, $return_as_string = FALSE) { $json = file_get_contents($filePath); if ($json === FALSE) { return FALSE; // Cannot read from file. } $jsonData = json_decode($json, TRUE); if ($jsonData === NULL) { return FALSE; // JSON cannot be decoded or the recursion limit has been reached. } return $return_as_string ? $json : $jsonData; }
php
private function getJsonData($filePath, $return_as_string = FALSE) { $json = file_get_contents($filePath); if ($json === FALSE) { return FALSE; // Cannot read from file. } $jsonData = json_decode($json, TRUE); if ($jsonData === NULL) { return FALSE; // JSON cannot be decoded or the recursion limit has been reached. } return $return_as_string ? $json : $jsonData; }
[ "private", "function", "getJsonData", "(", "$", "filePath", ",", "$", "return_as_string", "=", "FALSE", ")", "{", "$", "json", "=", "file_get_contents", "(", "$", "filePath", ")", ";", "if", "(", "$", "json", "===", "FALSE", ")", "{", "return", "FALSE", ...
Fetch json data from file @param string $filePath Path to the file holding the json string @param boolean $return_as_string If true the json data will be decoded in order to validate it, but will be returned as string @return mixed FALSE if the file can't be read or the contents can't be decoded string if the $return as string parameter is set array otherwise
[ "Fetch", "json", "data", "from", "file" ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p.classes.php#L1443-L1453
h5p/h5p-php-library
h5p.classes.php
H5PValidator.arrayCopy
private function arrayCopy(array $array) { $result = array(); foreach ($array as $key => $val) { if (is_array($val)) { $result[$key] = self::arrayCopy($val); } elseif (is_object($val)) { $result[$key] = clone $val; } else { $result[$key] = $val; } } return $result; }
php
private function arrayCopy(array $array) { $result = array(); foreach ($array as $key => $val) { if (is_array($val)) { $result[$key] = self::arrayCopy($val); } elseif (is_object($val)) { $result[$key] = clone $val; } else { $result[$key] = $val; } } return $result; }
[ "private", "function", "arrayCopy", "(", "array", "$", "array", ")", "{", "$", "result", "=", "array", "(", ")", ";", "foreach", "(", "$", "array", "as", "$", "key", "=>", "$", "val", ")", "{", "if", "(", "is_array", "(", "$", "val", ")", ")", ...
Helper function that copies an array @param array $array The array to be copied @return array Copy of $array. All objects are cloned
[ "Helper", "function", "that", "copies", "an", "array" ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p.classes.php#L1463-L1477
h5p/h5p-php-library
h5p.classes.php
H5PStorage.savePackage
public function savePackage($content = NULL, $contentMainId = NULL, $skipContent = FALSE, $options = array()) { if ($this->h5pC->mayUpdateLibraries()) { // Save the libraries we processed during validation $this->saveLibraries(); } if (!$skipContent) { $basePath = $this->h5pF->getUploadedH5pFolderPath(); $current_path = $basePath . DIRECTORY_SEPARATOR . 'content'; // Save content if ($content === NULL) { $content = array(); } if (!is_array($content)) { $content = array('id' => $content); } // Find main library version foreach ($this->h5pC->mainJsonData['preloadedDependencies'] as $dep) { if ($dep['machineName'] === $this->h5pC->mainJsonData['mainLibrary']) { $dep['libraryId'] = $this->h5pC->getLibraryId($dep); $content['library'] = $dep; break; } } $content['params'] = file_get_contents($current_path . DIRECTORY_SEPARATOR . 'content.json'); if (isset($options['disable'])) { $content['disable'] = $options['disable']; } $content['id'] = $this->h5pC->saveContent($content, $contentMainId); $this->contentId = $content['id']; try { // Save content folder contents $this->h5pC->fs->saveContent($current_path, $content); } catch (Exception $e) { $this->h5pF->setErrorMessage($e->getMessage(), 'save-content-failed'); } // Remove temp content folder H5PCore::deleteFileTree($basePath); } }
php
public function savePackage($content = NULL, $contentMainId = NULL, $skipContent = FALSE, $options = array()) { if ($this->h5pC->mayUpdateLibraries()) { // Save the libraries we processed during validation $this->saveLibraries(); } if (!$skipContent) { $basePath = $this->h5pF->getUploadedH5pFolderPath(); $current_path = $basePath . DIRECTORY_SEPARATOR . 'content'; // Save content if ($content === NULL) { $content = array(); } if (!is_array($content)) { $content = array('id' => $content); } // Find main library version foreach ($this->h5pC->mainJsonData['preloadedDependencies'] as $dep) { if ($dep['machineName'] === $this->h5pC->mainJsonData['mainLibrary']) { $dep['libraryId'] = $this->h5pC->getLibraryId($dep); $content['library'] = $dep; break; } } $content['params'] = file_get_contents($current_path . DIRECTORY_SEPARATOR . 'content.json'); if (isset($options['disable'])) { $content['disable'] = $options['disable']; } $content['id'] = $this->h5pC->saveContent($content, $contentMainId); $this->contentId = $content['id']; try { // Save content folder contents $this->h5pC->fs->saveContent($current_path, $content); } catch (Exception $e) { $this->h5pF->setErrorMessage($e->getMessage(), 'save-content-failed'); } // Remove temp content folder H5PCore::deleteFileTree($basePath); } }
[ "public", "function", "savePackage", "(", "$", "content", "=", "NULL", ",", "$", "contentMainId", "=", "NULL", ",", "$", "skipContent", "=", "FALSE", ",", "$", "options", "=", "array", "(", ")", ")", "{", "if", "(", "$", "this", "->", "h5pC", "->", ...
Saves a H5P file @param null $content @param int $contentMainId The main id for the content we are saving. This is used if the framework we're integrating with uses content id's and version id's @param bool $skipContent @param array $options @return bool TRUE if one or more libraries were updated TRUE if one or more libraries were updated FALSE otherwise
[ "Saves", "a", "H5P", "file" ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p.classes.php#L1515-L1561
h5p/h5p-php-library
h5p.classes.php
H5PStorage.saveLibraries
private function saveLibraries() { // Keep track of the number of libraries that have been saved $newOnes = 0; $oldOnes = 0; // Go through libraries that came with this package foreach ($this->h5pC->librariesJsonData as $libString => &$library) { // Find local library identifier $libraryId = $this->h5pC->getLibraryId($library, $libString); // Assume new library $new = TRUE; if ($libraryId) { // Found old library $library['libraryId'] = $libraryId; if ($this->h5pF->isPatchedLibrary($library)) { // This is a newer version than ours. Upgrade! $new = FALSE; } else { $library['saveDependencies'] = FALSE; // This is an older version, no need to save. continue; } } // Indicate that the dependencies of this library should be saved. $library['saveDependencies'] = TRUE; // Convert metadataSettings values to boolean & json_encode it before saving $library['metadataSettings'] = isset($library['metadataSettings']) ? H5PMetadata::boolifyAndEncodeSettings($library['metadataSettings']) : NULL; $this->h5pF->saveLibraryData($library, $new); // Save library folder $this->h5pC->fs->saveLibrary($library); // Remove cached assets that uses this library if ($this->h5pC->aggregateAssets && isset($library['libraryId'])) { $removedKeys = $this->h5pF->deleteCachedAssets($library['libraryId']); $this->h5pC->fs->deleteCachedAssets($removedKeys); } // Remove tmp folder H5PCore::deleteFileTree($library['uploadDirectory']); if ($new) { $newOnes++; } else { $oldOnes++; } } // Go through the libraries again to save dependencies. foreach ($this->h5pC->librariesJsonData as &$library) { if (!$library['saveDependencies']) { continue; } // TODO: Should the table be locked for this operation? // Remove any old dependencies $this->h5pF->deleteLibraryDependencies($library['libraryId']); // Insert the different new ones if (isset($library['preloadedDependencies'])) { $this->h5pF->saveLibraryDependencies($library['libraryId'], $library['preloadedDependencies'], 'preloaded'); } if (isset($library['dynamicDependencies'])) { $this->h5pF->saveLibraryDependencies($library['libraryId'], $library['dynamicDependencies'], 'dynamic'); } if (isset($library['editorDependencies'])) { $this->h5pF->saveLibraryDependencies($library['libraryId'], $library['editorDependencies'], 'editor'); } // Make sure libraries dependencies, parameter filtering and export files gets regenerated for all content who uses this library. $this->h5pF->clearFilteredParameters($library['libraryId']); } // Tell the user what we've done. if ($newOnes && $oldOnes) { if ($newOnes === 1) { if ($oldOnes === 1) { // Singular Singular $message = $this->h5pF->t('Added %new new H5P library and updated %old old one.', array('%new' => $newOnes, '%old' => $oldOnes)); } else { // Singular Plural $message = $this->h5pF->t('Added %new new H5P library and updated %old old ones.', array('%new' => $newOnes, '%old' => $oldOnes)); } } else { // Plural if ($oldOnes === 1) { // Plural Singular $message = $this->h5pF->t('Added %new new H5P libraries and updated %old old one.', array('%new' => $newOnes, '%old' => $oldOnes)); } else { // Plural Plural $message = $this->h5pF->t('Added %new new H5P libraries and updated %old old ones.', array('%new' => $newOnes, '%old' => $oldOnes)); } } } elseif ($newOnes) { if ($newOnes === 1) { // Singular $message = $this->h5pF->t('Added %new new H5P library.', array('%new' => $newOnes)); } else { // Plural $message = $this->h5pF->t('Added %new new H5P libraries.', array('%new' => $newOnes)); } } elseif ($oldOnes) { if ($oldOnes === 1) { // Singular $message = $this->h5pF->t('Updated %old H5P library.', array('%old' => $oldOnes)); } else { // Plural $message = $this->h5pF->t('Updated %old H5P libraries.', array('%old' => $oldOnes)); } } if (isset($message)) { $this->h5pF->setInfoMessage($message); } }
php
private function saveLibraries() { // Keep track of the number of libraries that have been saved $newOnes = 0; $oldOnes = 0; // Go through libraries that came with this package foreach ($this->h5pC->librariesJsonData as $libString => &$library) { // Find local library identifier $libraryId = $this->h5pC->getLibraryId($library, $libString); // Assume new library $new = TRUE; if ($libraryId) { // Found old library $library['libraryId'] = $libraryId; if ($this->h5pF->isPatchedLibrary($library)) { // This is a newer version than ours. Upgrade! $new = FALSE; } else { $library['saveDependencies'] = FALSE; // This is an older version, no need to save. continue; } } // Indicate that the dependencies of this library should be saved. $library['saveDependencies'] = TRUE; // Convert metadataSettings values to boolean & json_encode it before saving $library['metadataSettings'] = isset($library['metadataSettings']) ? H5PMetadata::boolifyAndEncodeSettings($library['metadataSettings']) : NULL; $this->h5pF->saveLibraryData($library, $new); // Save library folder $this->h5pC->fs->saveLibrary($library); // Remove cached assets that uses this library if ($this->h5pC->aggregateAssets && isset($library['libraryId'])) { $removedKeys = $this->h5pF->deleteCachedAssets($library['libraryId']); $this->h5pC->fs->deleteCachedAssets($removedKeys); } // Remove tmp folder H5PCore::deleteFileTree($library['uploadDirectory']); if ($new) { $newOnes++; } else { $oldOnes++; } } // Go through the libraries again to save dependencies. foreach ($this->h5pC->librariesJsonData as &$library) { if (!$library['saveDependencies']) { continue; } // TODO: Should the table be locked for this operation? // Remove any old dependencies $this->h5pF->deleteLibraryDependencies($library['libraryId']); // Insert the different new ones if (isset($library['preloadedDependencies'])) { $this->h5pF->saveLibraryDependencies($library['libraryId'], $library['preloadedDependencies'], 'preloaded'); } if (isset($library['dynamicDependencies'])) { $this->h5pF->saveLibraryDependencies($library['libraryId'], $library['dynamicDependencies'], 'dynamic'); } if (isset($library['editorDependencies'])) { $this->h5pF->saveLibraryDependencies($library['libraryId'], $library['editorDependencies'], 'editor'); } // Make sure libraries dependencies, parameter filtering and export files gets regenerated for all content who uses this library. $this->h5pF->clearFilteredParameters($library['libraryId']); } // Tell the user what we've done. if ($newOnes && $oldOnes) { if ($newOnes === 1) { if ($oldOnes === 1) { // Singular Singular $message = $this->h5pF->t('Added %new new H5P library and updated %old old one.', array('%new' => $newOnes, '%old' => $oldOnes)); } else { // Singular Plural $message = $this->h5pF->t('Added %new new H5P library and updated %old old ones.', array('%new' => $newOnes, '%old' => $oldOnes)); } } else { // Plural if ($oldOnes === 1) { // Plural Singular $message = $this->h5pF->t('Added %new new H5P libraries and updated %old old one.', array('%new' => $newOnes, '%old' => $oldOnes)); } else { // Plural Plural $message = $this->h5pF->t('Added %new new H5P libraries and updated %old old ones.', array('%new' => $newOnes, '%old' => $oldOnes)); } } } elseif ($newOnes) { if ($newOnes === 1) { // Singular $message = $this->h5pF->t('Added %new new H5P library.', array('%new' => $newOnes)); } else { // Plural $message = $this->h5pF->t('Added %new new H5P libraries.', array('%new' => $newOnes)); } } elseif ($oldOnes) { if ($oldOnes === 1) { // Singular $message = $this->h5pF->t('Updated %old H5P library.', array('%old' => $oldOnes)); } else { // Plural $message = $this->h5pF->t('Updated %old H5P libraries.', array('%old' => $oldOnes)); } } if (isset($message)) { $this->h5pF->setInfoMessage($message); } }
[ "private", "function", "saveLibraries", "(", ")", "{", "// Keep track of the number of libraries that have been saved", "$", "newOnes", "=", "0", ";", "$", "oldOnes", "=", "0", ";", "// Go through libraries that came with this package", "foreach", "(", "$", "this", "->", ...
Helps savePackage. @return int Number of libraries saved
[ "Helps", "savePackage", "." ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p.classes.php#L1568-L1699
h5p/h5p-php-library
h5p.classes.php
H5PStorage.deletePackage
public function deletePackage($content) { $this->h5pC->fs->deleteContent($content); $this->h5pC->fs->deleteExport(($content['slug'] ? $content['slug'] . '-' : '') . $content['id'] . '.h5p'); $this->h5pF->deleteContentData($content['id']); }
php
public function deletePackage($content) { $this->h5pC->fs->deleteContent($content); $this->h5pC->fs->deleteExport(($content['slug'] ? $content['slug'] . '-' : '') . $content['id'] . '.h5p'); $this->h5pF->deleteContentData($content['id']); }
[ "public", "function", "deletePackage", "(", "$", "content", ")", "{", "$", "this", "->", "h5pC", "->", "fs", "->", "deleteContent", "(", "$", "content", ")", ";", "$", "this", "->", "h5pC", "->", "fs", "->", "deleteExport", "(", "(", "$", "content", ...
Delete an H5P package @param $content
[ "Delete", "an", "H5P", "package" ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p.classes.php#L1706-L1710
h5p/h5p-php-library
h5p.classes.php
H5PStorage.copyPackage
public function copyPackage($contentId, $copyFromId, $contentMainId = NULL) { $this->h5pC->fs->cloneContent($copyFromId, $contentId); $this->h5pF->copyLibraryUsage($contentId, $copyFromId, $contentMainId); }
php
public function copyPackage($contentId, $copyFromId, $contentMainId = NULL) { $this->h5pC->fs->cloneContent($copyFromId, $contentId); $this->h5pF->copyLibraryUsage($contentId, $copyFromId, $contentMainId); }
[ "public", "function", "copyPackage", "(", "$", "contentId", ",", "$", "copyFromId", ",", "$", "contentMainId", "=", "NULL", ")", "{", "$", "this", "->", "h5pC", "->", "fs", "->", "cloneContent", "(", "$", "copyFromId", ",", "$", "contentId", ")", ";", ...
Copy/clone an H5P package May for instance be used if the content is being revisioned without uploading a new H5P package @param int $contentId The new content id @param int $copyFromId The content id of the content that should be cloned @param int $contentMainId The main id of the new content (used in frameworks that support revisioning)
[ "Copy", "/", "clone", "an", "H5P", "package" ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p.classes.php#L1725-L1728
h5p/h5p-php-library
h5p-development.class.php
H5PDevelopment.getFileContents
private function getFileContents($file) { if (file_exists($file) === FALSE) { return NULL; } $contents = file_get_contents($file); if ($contents === FALSE) { return NULL; } return $contents; }
php
private function getFileContents($file) { if (file_exists($file) === FALSE) { return NULL; } $contents = file_get_contents($file); if ($contents === FALSE) { return NULL; } return $contents; }
[ "private", "function", "getFileContents", "(", "$", "file", ")", "{", "if", "(", "file_exists", "(", "$", "file", ")", "===", "FALSE", ")", "{", "return", "NULL", ";", "}", "$", "contents", "=", "file_get_contents", "(", "$", "file", ")", ";", "if", ...
Get contents of file. @param string $file File path. @return mixed String on success or NULL on failure.
[ "Get", "contents", "of", "file", "." ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p-development.class.php#L42-L53
h5p/h5p-php-library
h5p-development.class.php
H5PDevelopment.findLibraries
private function findLibraries($path) { $this->libraries = array(); if (is_dir($path) === FALSE) { return; } $contents = scandir($path); for ($i = 0, $s = count($contents); $i < $s; $i++) { if ($contents[$i]{0} === '.') { continue; // Skip hidden stuff. } $libraryPath = $path . '/' . $contents[$i]; $libraryJSON = $this->getFileContents($libraryPath . '/library.json'); if ($libraryJSON === NULL) { continue; // No JSON file, skip. } $library = json_decode($libraryJSON, TRUE); if ($library === NULL) { continue; // Invalid JSON. } // TODO: Validate props? Not really needed, is it? this is a dev site. $library['libraryId'] = $this->h5pF->getLibraryId($library['machineName'], $library['majorVersion'], $library['minorVersion']); // Convert metadataSettings values to boolean & json_encode it before saving $library['metadataSettings'] = isset($library['metadataSettings']) ? H5PMetadata::boolifyAndEncodeSettings($library['metadataSettings']) : NULL; // Save/update library. $this->h5pF->saveLibraryData($library, $library['libraryId'] === FALSE); // Need to decode it again, since it is served from here. $library['metadataSettings'] = json_decode($library['metadataSettings']); $library['path'] = 'development/' . $contents[$i]; $this->libraries[H5PDevelopment::libraryToString($library['machineName'], $library['majorVersion'], $library['minorVersion'])] = $library; } // TODO: Should we remove libraries without files? Not really needed, but must be cleaned up some time, right? // Go trough libraries and insert dependencies. Missing deps. will just be ignored and not available. (I guess?!) $this->h5pF->lockDependencyStorage(); foreach ($this->libraries as $library) { $this->h5pF->deleteLibraryDependencies($library['libraryId']); // This isn't optimal, but without it we would get duplicate warnings. // TODO: You might get PDOExceptions if two or more requests does this at the same time!! $types = array('preloaded', 'dynamic', 'editor'); foreach ($types as $type) { if (isset($library[$type . 'Dependencies'])) { $this->h5pF->saveLibraryDependencies($library['libraryId'], $library[$type . 'Dependencies'], $type); } } } $this->h5pF->unlockDependencyStorage(); // TODO: Deps must be inserted into h5p_nodes_libraries as well... ? But only if they are used?! }
php
private function findLibraries($path) { $this->libraries = array(); if (is_dir($path) === FALSE) { return; } $contents = scandir($path); for ($i = 0, $s = count($contents); $i < $s; $i++) { if ($contents[$i]{0} === '.') { continue; // Skip hidden stuff. } $libraryPath = $path . '/' . $contents[$i]; $libraryJSON = $this->getFileContents($libraryPath . '/library.json'); if ($libraryJSON === NULL) { continue; // No JSON file, skip. } $library = json_decode($libraryJSON, TRUE); if ($library === NULL) { continue; // Invalid JSON. } // TODO: Validate props? Not really needed, is it? this is a dev site. $library['libraryId'] = $this->h5pF->getLibraryId($library['machineName'], $library['majorVersion'], $library['minorVersion']); // Convert metadataSettings values to boolean & json_encode it before saving $library['metadataSettings'] = isset($library['metadataSettings']) ? H5PMetadata::boolifyAndEncodeSettings($library['metadataSettings']) : NULL; // Save/update library. $this->h5pF->saveLibraryData($library, $library['libraryId'] === FALSE); // Need to decode it again, since it is served from here. $library['metadataSettings'] = json_decode($library['metadataSettings']); $library['path'] = 'development/' . $contents[$i]; $this->libraries[H5PDevelopment::libraryToString($library['machineName'], $library['majorVersion'], $library['minorVersion'])] = $library; } // TODO: Should we remove libraries without files? Not really needed, but must be cleaned up some time, right? // Go trough libraries and insert dependencies. Missing deps. will just be ignored and not available. (I guess?!) $this->h5pF->lockDependencyStorage(); foreach ($this->libraries as $library) { $this->h5pF->deleteLibraryDependencies($library['libraryId']); // This isn't optimal, but without it we would get duplicate warnings. // TODO: You might get PDOExceptions if two or more requests does this at the same time!! $types = array('preloaded', 'dynamic', 'editor'); foreach ($types as $type) { if (isset($library[$type . 'Dependencies'])) { $this->h5pF->saveLibraryDependencies($library['libraryId'], $library[$type . 'Dependencies'], $type); } } } $this->h5pF->unlockDependencyStorage(); // TODO: Deps must be inserted into h5p_nodes_libraries as well... ? But only if they are used?! }
[ "private", "function", "findLibraries", "(", "$", "path", ")", "{", "$", "this", "->", "libraries", "=", "array", "(", ")", ";", "if", "(", "is_dir", "(", "$", "path", ")", "===", "FALSE", ")", "{", "return", ";", "}", "$", "contents", "=", "scandi...
Scans development directory and find all libraries. @param string $path Libraries development folder
[ "Scans", "development", "directory", "and", "find", "all", "libraries", "." ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p-development.class.php#L60-L121
h5p/h5p-php-library
h5p-development.class.php
H5PDevelopment.getLibrary
public function getLibrary($name, $majorVersion, $minorVersion) { $library = H5PDevelopment::libraryToString($name, $majorVersion, $minorVersion); return isset($this->libraries[$library]) === TRUE ? $this->libraries[$library] : NULL; }
php
public function getLibrary($name, $majorVersion, $minorVersion) { $library = H5PDevelopment::libraryToString($name, $majorVersion, $minorVersion); return isset($this->libraries[$library]) === TRUE ? $this->libraries[$library] : NULL; }
[ "public", "function", "getLibrary", "(", "$", "name", ",", "$", "majorVersion", ",", "$", "minorVersion", ")", "{", "$", "library", "=", "H5PDevelopment", "::", "libraryToString", "(", "$", "name", ",", "$", "majorVersion", ",", "$", "minorVersion", ")", "...
Get library @param string $name of the library. @param int $majorVersion of the library. @param int $minorVersion of the library. @return array library.
[ "Get", "library" ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p-development.class.php#L138-L141
h5p/h5p-php-library
h5p-development.class.php
H5PDevelopment.getSemantics
public function getSemantics($name, $majorVersion, $minorVersion) { $library = H5PDevelopment::libraryToString($name, $majorVersion, $minorVersion); if (isset($this->libraries[$library]) === FALSE) { return NULL; } return $this->getFileContents($this->filesPath . $this->libraries[$library]['path'] . '/semantics.json'); }
php
public function getSemantics($name, $majorVersion, $minorVersion) { $library = H5PDevelopment::libraryToString($name, $majorVersion, $minorVersion); if (isset($this->libraries[$library]) === FALSE) { return NULL; } return $this->getFileContents($this->filesPath . $this->libraries[$library]['path'] . '/semantics.json'); }
[ "public", "function", "getSemantics", "(", "$", "name", ",", "$", "majorVersion", ",", "$", "minorVersion", ")", "{", "$", "library", "=", "H5PDevelopment", "::", "libraryToString", "(", "$", "name", ",", "$", "majorVersion", ",", "$", "minorVersion", ")", ...
Get semantics for the given library. @param string $name of the library. @param int $majorVersion of the library. @param int $minorVersion of the library. @return string Semantics
[ "Get", "semantics", "for", "the", "given", "library", "." ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p-development.class.php#L151-L157
h5p/h5p-php-library
h5p-default-storage.class.php
H5PDefaultStorage.saveLibrary
public function saveLibrary($library) { $dest = $this->path . '/libraries/' . \H5PCore::libraryToString($library, TRUE); // Make sure destination dir doesn't exist \H5PCore::deleteFileTree($dest); // Move library folder self::copyFileTree($library['uploadDirectory'], $dest); }
php
public function saveLibrary($library) { $dest = $this->path . '/libraries/' . \H5PCore::libraryToString($library, TRUE); // Make sure destination dir doesn't exist \H5PCore::deleteFileTree($dest); // Move library folder self::copyFileTree($library['uploadDirectory'], $dest); }
[ "public", "function", "saveLibrary", "(", "$", "library", ")", "{", "$", "dest", "=", "$", "this", "->", "path", ".", "'/libraries/'", ".", "\\", "H5PCore", "::", "libraryToString", "(", "$", "library", ",", "TRUE", ")", ";", "// Make sure destination dir do...
Store the library folder. @param array $library Library properties
[ "Store", "the", "library", "folder", "." ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p-default-storage.class.php#L41-L49
h5p/h5p-php-library
h5p-default-storage.class.php
H5PDefaultStorage.saveContent
public function saveContent($source, $content) { $dest = "{$this->path}/content/{$content['id']}"; // Remove any old content \H5PCore::deleteFileTree($dest); self::copyFileTree($source, $dest); }
php
public function saveContent($source, $content) { $dest = "{$this->path}/content/{$content['id']}"; // Remove any old content \H5PCore::deleteFileTree($dest); self::copyFileTree($source, $dest); }
[ "public", "function", "saveContent", "(", "$", "source", ",", "$", "content", ")", "{", "$", "dest", "=", "\"{$this->path}/content/{$content['id']}\"", ";", "// Remove any old content", "\\", "H5PCore", "::", "deleteFileTree", "(", "$", "dest", ")", ";", "self", ...
Store the content folder. @param string $source Path on file system to content directory. @param array $content Content properties
[ "Store", "the", "content", "folder", "." ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p-default-storage.class.php#L59-L66
h5p/h5p-php-library
h5p-default-storage.class.php
H5PDefaultStorage.cloneContent
public function cloneContent($id, $newId) { $path = $this->path . '/content/'; if (file_exists($path . $id)) { self::copyFileTree($path . $id, $path . $newId); } }
php
public function cloneContent($id, $newId) { $path = $this->path . '/content/'; if (file_exists($path . $id)) { self::copyFileTree($path . $id, $path . $newId); } }
[ "public", "function", "cloneContent", "(", "$", "id", ",", "$", "newId", ")", "{", "$", "path", "=", "$", "this", "->", "path", ".", "'/content/'", ";", "if", "(", "file_exists", "(", "$", "path", ".", "$", "id", ")", ")", "{", "self", "::", "cop...
Creates a stored copy of the content folder. @param string $id Identifier of content to clone. @param int $newId The cloned content's identifier
[ "Creates", "a", "stored", "copy", "of", "the", "content", "folder", "." ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p-default-storage.class.php#L86-L91
h5p/h5p-php-library
h5p-default-storage.class.php
H5PDefaultStorage.exportContent
public function exportContent($id, $target) { $source = "{$this->path}/content/{$id}"; if (file_exists($source)) { // Copy content folder if it exists self::copyFileTree($source, $target); } else { // No contnet folder, create emty dir for content.json self::dirReady($target); } }
php
public function exportContent($id, $target) { $source = "{$this->path}/content/{$id}"; if (file_exists($source)) { // Copy content folder if it exists self::copyFileTree($source, $target); } else { // No contnet folder, create emty dir for content.json self::dirReady($target); } }
[ "public", "function", "exportContent", "(", "$", "id", ",", "$", "target", ")", "{", "$", "source", "=", "\"{$this->path}/content/{$id}\"", ";", "if", "(", "file_exists", "(", "$", "source", ")", ")", "{", "// Copy content folder if it exists", "self", "::", "...
Fetch content folder and save in target directory. @param int $id Content identifier @param string $target Where the content folder will be saved
[ "Fetch", "content", "folder", "and", "save", "in", "target", "directory", "." ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p-default-storage.class.php#L113-L123
h5p/h5p-php-library
h5p-default-storage.class.php
H5PDefaultStorage.exportLibrary
public function exportLibrary($library, $target, $developmentPath=NULL) { $folder = \H5PCore::libraryToString($library, TRUE); $srcPath = ($developmentPath === NULL ? "/libraries/{$folder}" : $developmentPath); self::copyFileTree("{$this->path}{$srcPath}", "{$target}/{$folder}"); }
php
public function exportLibrary($library, $target, $developmentPath=NULL) { $folder = \H5PCore::libraryToString($library, TRUE); $srcPath = ($developmentPath === NULL ? "/libraries/{$folder}" : $developmentPath); self::copyFileTree("{$this->path}{$srcPath}", "{$target}/{$folder}"); }
[ "public", "function", "exportLibrary", "(", "$", "library", ",", "$", "target", ",", "$", "developmentPath", "=", "NULL", ")", "{", "$", "folder", "=", "\\", "H5PCore", "::", "libraryToString", "(", "$", "library", ",", "TRUE", ")", ";", "$", "srcPath", ...
Fetch library folder and save in target directory. @param array $library Library properties @param string $target Where the library folder will be saved @param string $developmentPath Folder that library resides in
[ "Fetch", "library", "folder", "and", "save", "in", "target", "directory", "." ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p-default-storage.class.php#L135-L139
h5p/h5p-php-library
h5p-default-storage.class.php
H5PDefaultStorage.saveExport
public function saveExport($source, $filename) { $this->deleteExport($filename); if (!self::dirReady("{$this->path}/exports")) { throw new Exception("Unable to create directory for H5P export file."); } if (!copy($source, "{$this->path}/exports/{$filename}")) { throw new Exception("Unable to save H5P export file."); } }
php
public function saveExport($source, $filename) { $this->deleteExport($filename); if (!self::dirReady("{$this->path}/exports")) { throw new Exception("Unable to create directory for H5P export file."); } if (!copy($source, "{$this->path}/exports/{$filename}")) { throw new Exception("Unable to save H5P export file."); } }
[ "public", "function", "saveExport", "(", "$", "source", ",", "$", "filename", ")", "{", "$", "this", "->", "deleteExport", "(", "$", "filename", ")", ";", "if", "(", "!", "self", "::", "dirReady", "(", "\"{$this->path}/exports\"", ")", ")", "{", "throw",...
Save export in file system @param string $source Path on file system to temporary export file. @param string $filename Name of export file. @throws Exception Unable to save the file
[ "Save", "export", "in", "file", "system" ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p-default-storage.class.php#L150-L160
h5p/h5p-php-library
h5p-default-storage.class.php
H5PDefaultStorage.cacheAssets
public function cacheAssets(&$files, $key) { foreach ($files as $type => $assets) { if (empty($assets)) { continue; // Skip no assets } $content = ''; foreach ($assets as $asset) { // Get content from asset file $assetContent = file_get_contents($this->path . $asset->path); $cssRelPath = preg_replace('/[^\/]+$/', '', $asset->path); // Get file content and concatenate if ($type === 'scripts') { $content .= $assetContent . ";\n"; } else { // Rewrite relative URLs used inside stylesheets $content .= preg_replace_callback( '/url\([\'"]?([^"\')]+)[\'"]?\)/i', function ($matches) use ($cssRelPath) { if (preg_match("/^(data:|([a-z0-9]+:)?\/)/i", $matches[1]) === 1) { return $matches[0]; // Not relative, skip } return 'url("../' . $cssRelPath . $matches[1] . '")'; }, $assetContent) . "\n"; } } self::dirReady("{$this->path}/cachedassets"); $ext = ($type === 'scripts' ? 'js' : 'css'); $outputfile = "/cachedassets/{$key}.{$ext}"; file_put_contents($this->path . $outputfile, $content); $files[$type] = array((object) array( 'path' => $outputfile, 'version' => '' )); } }
php
public function cacheAssets(&$files, $key) { foreach ($files as $type => $assets) { if (empty($assets)) { continue; // Skip no assets } $content = ''; foreach ($assets as $asset) { // Get content from asset file $assetContent = file_get_contents($this->path . $asset->path); $cssRelPath = preg_replace('/[^\/]+$/', '', $asset->path); // Get file content and concatenate if ($type === 'scripts') { $content .= $assetContent . ";\n"; } else { // Rewrite relative URLs used inside stylesheets $content .= preg_replace_callback( '/url\([\'"]?([^"\')]+)[\'"]?\)/i', function ($matches) use ($cssRelPath) { if (preg_match("/^(data:|([a-z0-9]+:)?\/)/i", $matches[1]) === 1) { return $matches[0]; // Not relative, skip } return 'url("../' . $cssRelPath . $matches[1] . '")'; }, $assetContent) . "\n"; } } self::dirReady("{$this->path}/cachedassets"); $ext = ($type === 'scripts' ? 'js' : 'css'); $outputfile = "/cachedassets/{$key}.{$ext}"; file_put_contents($this->path . $outputfile, $content); $files[$type] = array((object) array( 'path' => $outputfile, 'version' => '' )); } }
[ "public", "function", "cacheAssets", "(", "&", "$", "files", ",", "$", "key", ")", "{", "foreach", "(", "$", "files", "as", "$", "type", "=>", "$", "assets", ")", "{", "if", "(", "empty", "(", "$", "assets", ")", ")", "{", "continue", ";", "// Sk...
Will concatenate all JavaScrips and Stylesheets into two files in order to improve page performance. @param array $files A set of all the assets required for content to display @param string $key Hashed key for cached asset
[ "Will", "concatenate", "all", "JavaScrips", "and", "Stylesheets", "into", "two", "files", "in", "order", "to", "improve", "page", "performance", "." ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p-default-storage.class.php#L194-L233
h5p/h5p-php-library
h5p-default-storage.class.php
H5PDefaultStorage.getCachedAssets
public function getCachedAssets($key) { $files = array(); $js = "/cachedassets/{$key}.js"; if (file_exists($this->path . $js)) { $files['scripts'] = array((object) array( 'path' => $js, 'version' => '' )); } $css = "/cachedassets/{$key}.css"; if (file_exists($this->path . $css)) { $files['styles'] = array((object) array( 'path' => $css, 'version' => '' )); } return empty($files) ? NULL : $files; }
php
public function getCachedAssets($key) { $files = array(); $js = "/cachedassets/{$key}.js"; if (file_exists($this->path . $js)) { $files['scripts'] = array((object) array( 'path' => $js, 'version' => '' )); } $css = "/cachedassets/{$key}.css"; if (file_exists($this->path . $css)) { $files['styles'] = array((object) array( 'path' => $css, 'version' => '' )); } return empty($files) ? NULL : $files; }
[ "public", "function", "getCachedAssets", "(", "$", "key", ")", "{", "$", "files", "=", "array", "(", ")", ";", "$", "js", "=", "\"/cachedassets/{$key}.js\"", ";", "if", "(", "file_exists", "(", "$", "this", "->", "path", ".", "$", "js", ")", ")", "{"...
Will check if there are cache assets available for content. @param string $key Hashed key for cached asset @return array
[ "Will", "check", "if", "there", "are", "cache", "assets", "available", "for", "content", "." ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p-default-storage.class.php#L242-L262
h5p/h5p-php-library
h5p-default-storage.class.php
H5PDefaultStorage.deleteCachedAssets
public function deleteCachedAssets($keys) { foreach ($keys as $hash) { foreach (array('js', 'css') as $ext) { $path = "{$this->path}/cachedassets/{$hash}.{$ext}"; if (file_exists($path)) { unlink($path); } } } }
php
public function deleteCachedAssets($keys) { foreach ($keys as $hash) { foreach (array('js', 'css') as $ext) { $path = "{$this->path}/cachedassets/{$hash}.{$ext}"; if (file_exists($path)) { unlink($path); } } } }
[ "public", "function", "deleteCachedAssets", "(", "$", "keys", ")", "{", "foreach", "(", "$", "keys", "as", "$", "hash", ")", "{", "foreach", "(", "array", "(", "'js'", ",", "'css'", ")", "as", "$", "ext", ")", "{", "$", "path", "=", "\"{$this->path}/...
Remove the aggregated cache files. @param array $keys The hash keys of removed files
[ "Remove", "the", "aggregated", "cache", "files", "." ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p-default-storage.class.php#L270-L279
h5p/h5p-php-library
h5p-default-storage.class.php
H5PDefaultStorage.saveFile
public function saveFile($file, $contentId) { // Prepare directory if (empty($contentId)) { // Should be in editor tmp folder $path = $this->getEditorPath(); } else { // Should be in content folder $path = $this->path . '/content/' . $contentId; } $path .= '/' . $file->getType() . 's'; self::dirReady($path); // Add filename to path $path .= '/' . $file->getName(); copy($_FILES['file']['tmp_name'], $path); return $file; }
php
public function saveFile($file, $contentId) { // Prepare directory if (empty($contentId)) { // Should be in editor tmp folder $path = $this->getEditorPath(); } else { // Should be in content folder $path = $this->path . '/content/' . $contentId; } $path .= '/' . $file->getType() . 's'; self::dirReady($path); // Add filename to path $path .= '/' . $file->getName(); copy($_FILES['file']['tmp_name'], $path); return $file; }
[ "public", "function", "saveFile", "(", "$", "file", ",", "$", "contentId", ")", "{", "// Prepare directory", "if", "(", "empty", "(", "$", "contentId", ")", ")", "{", "// Should be in editor tmp folder", "$", "path", "=", "$", "this", "->", "getEditorPath", ...
Save files uploaded through the editor. The files must be marked as temporary until the content form is saved. @param \H5peditorFile $file @param int $contentid
[ "Save", "files", "uploaded", "through", "the", "editor", ".", "The", "files", "must", "be", "marked", "as", "temporary", "until", "the", "content", "form", "is", "saved", "." ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p-default-storage.class.php#L298-L317
h5p/h5p-php-library
h5p-default-storage.class.php
H5PDefaultStorage.cloneContentFile
public function cloneContentFile($file, $fromId, $toId) { // Determine source path if ($fromId === 'editor') { $sourcepath = $this->getEditorPath(); } else { $sourcepath = "{$this->path}/content/{$fromId}"; } $sourcepath .= '/' . $file; // Determine target path $filename = basename($file); $filedir = str_replace($filename, '', $file); $targetpath = "{$this->path}/content/{$toId}/{$filedir}"; // Make sure it's ready self::dirReady($targetpath); $targetpath .= $filename; // Check to see if source exist and if target doesn't if (!file_exists($sourcepath) || file_exists($targetpath)) { return; // Nothing to copy from or target already exists } copy($sourcepath, $targetpath); }
php
public function cloneContentFile($file, $fromId, $toId) { // Determine source path if ($fromId === 'editor') { $sourcepath = $this->getEditorPath(); } else { $sourcepath = "{$this->path}/content/{$fromId}"; } $sourcepath .= '/' . $file; // Determine target path $filename = basename($file); $filedir = str_replace($filename, '', $file); $targetpath = "{$this->path}/content/{$toId}/{$filedir}"; // Make sure it's ready self::dirReady($targetpath); $targetpath .= $filename; // Check to see if source exist and if target doesn't if (!file_exists($sourcepath) || file_exists($targetpath)) { return; // Nothing to copy from or target already exists } copy($sourcepath, $targetpath); }
[ "public", "function", "cloneContentFile", "(", "$", "file", ",", "$", "fromId", ",", "$", "toId", ")", "{", "// Determine source path", "if", "(", "$", "fromId", "===", "'editor'", ")", "{", "$", "sourcepath", "=", "$", "this", "->", "getEditorPath", "(", ...
Copy a file from another content or editor tmp dir. Used when copy pasting content in H5P Editor. @param string $file path + name @param string|int $fromid Content ID or 'editor' string @param int $toid Target Content ID
[ "Copy", "a", "file", "from", "another", "content", "or", "editor", "tmp", "dir", ".", "Used", "when", "copy", "pasting", "content", "in", "H5P", "Editor", "." ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p-default-storage.class.php#L327-L353
h5p/h5p-php-library
h5p-default-storage.class.php
H5PDefaultStorage.moveContentDirectory
public function moveContentDirectory($source, $contentId = NULL) { if ($source === NULL) { return NULL; } // TODO: Remove $contentId and never copy temporary files into content folder. JI-366 if ($contentId === NULL || $contentId == 0) { $target = $this->getEditorPath(); } else { // Use content folder $target = "{$this->path}/content/{$contentId}"; } $contentSource = $source . DIRECTORY_SEPARATOR . 'content'; $contentFiles = array_diff(scandir($contentSource), array('.','..', 'content.json')); foreach ($contentFiles as $file) { if (is_dir("{$contentSource}/{$file}")) { self::copyFileTree("{$contentSource}/{$file}", "{$target}/{$file}"); } else { copy("{$contentSource}/{$file}", "{$target}/{$file}"); } } // TODO: Return list of all files so that they can be marked as temporary. JI-366 }
php
public function moveContentDirectory($source, $contentId = NULL) { if ($source === NULL) { return NULL; } // TODO: Remove $contentId and never copy temporary files into content folder. JI-366 if ($contentId === NULL || $contentId == 0) { $target = $this->getEditorPath(); } else { // Use content folder $target = "{$this->path}/content/{$contentId}"; } $contentSource = $source . DIRECTORY_SEPARATOR . 'content'; $contentFiles = array_diff(scandir($contentSource), array('.','..', 'content.json')); foreach ($contentFiles as $file) { if (is_dir("{$contentSource}/{$file}")) { self::copyFileTree("{$contentSource}/{$file}", "{$target}/{$file}"); } else { copy("{$contentSource}/{$file}", "{$target}/{$file}"); } } // TODO: Return list of all files so that they can be marked as temporary. JI-366 }
[ "public", "function", "moveContentDirectory", "(", "$", "source", ",", "$", "contentId", "=", "NULL", ")", "{", "if", "(", "$", "source", "===", "NULL", ")", "{", "return", "NULL", ";", "}", "// TODO: Remove $contentId and never copy temporary files into content fol...
Copy a content from one directory to another. Defaults to cloning content from the current temporary upload folder to the editor path. @param string $source path to source directory @param string $contentId Id of contentarray
[ "Copy", "a", "content", "from", "one", "directory", "to", "another", ".", "Defaults", "to", "cloning", "content", "from", "the", "current", "temporary", "upload", "folder", "to", "the", "editor", "path", "." ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p-default-storage.class.php#L362-L388
h5p/h5p-php-library
h5p-default-storage.class.php
H5PDefaultStorage.removeContentFile
public function removeContentFile($file, $contentId) { $path = "{$this->path}/content/{$contentId}/{$file}"; if (file_exists($path)) { unlink($path); // Clean up any empty parent directories to avoid cluttering the file system $parts = explode('/', $path); while (array_pop($parts) !== NULL) { $dir = implode('/', $parts); if (is_dir($dir) && count(scandir($dir)) === 2) { // empty contains '.' and '..' rmdir($dir); // Remove empty parent } else { return; // Not empty } } } }
php
public function removeContentFile($file, $contentId) { $path = "{$this->path}/content/{$contentId}/{$file}"; if (file_exists($path)) { unlink($path); // Clean up any empty parent directories to avoid cluttering the file system $parts = explode('/', $path); while (array_pop($parts) !== NULL) { $dir = implode('/', $parts); if (is_dir($dir) && count(scandir($dir)) === 2) { // empty contains '.' and '..' rmdir($dir); // Remove empty parent } else { return; // Not empty } } } }
[ "public", "function", "removeContentFile", "(", "$", "file", ",", "$", "contentId", ")", "{", "$", "path", "=", "\"{$this->path}/content/{$contentId}/{$file}\"", ";", "if", "(", "file_exists", "(", "$", "path", ")", ")", "{", "unlink", "(", "$", "path", ")",...
Checks to see if content has the given file. Used when saving content. @param string $file path + name @param int $contentid @return string|int File ID or NULL if not found
[ "Checks", "to", "see", "if", "content", "has", "the", "given", "file", ".", "Used", "when", "saving", "content", "." ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p-default-storage.class.php#L411-L428
h5p/h5p-php-library
h5p-default-storage.class.php
H5PDefaultStorage.hasPresave
public function hasPresave($libraryFolder, $developmentPath = null) { $path = is_null($developmentPath) ? 'libraries' . DIRECTORY_SEPARATOR . $libraryFolder : $developmentPath; $filePath = realpath($this->path . DIRECTORY_SEPARATOR . $path . DIRECTORY_SEPARATOR . 'presave.js'); return file_exists($filePath); }
php
public function hasPresave($libraryFolder, $developmentPath = null) { $path = is_null($developmentPath) ? 'libraries' . DIRECTORY_SEPARATOR . $libraryFolder : $developmentPath; $filePath = realpath($this->path . DIRECTORY_SEPARATOR . $path . DIRECTORY_SEPARATOR . 'presave.js'); return file_exists($filePath); }
[ "public", "function", "hasPresave", "(", "$", "libraryFolder", ",", "$", "developmentPath", "=", "null", ")", "{", "$", "path", "=", "is_null", "(", "$", "developmentPath", ")", "?", "'libraries'", ".", "DIRECTORY_SEPARATOR", ".", "$", "libraryFolder", ":", ...
Check if the file presave.js exists in the root of the library @param string $libraryFolder @param string $developmentPath @return bool
[ "Check", "if", "the", "file", "presave", ".", "js", "exists", "in", "the", "root", "of", "the", "library" ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p-default-storage.class.php#L447-L451
h5p/h5p-php-library
h5p-default-storage.class.php
H5PDefaultStorage.getUpgradeScript
public function getUpgradeScript($machineName, $majorVersion, $minorVersion) { $upgrades = "/libraries/{$machineName}-{$majorVersion}.{$minorVersion}/upgrades.js"; if (file_exists($this->path . $upgrades)) { return $upgrades; } else { return NULL; } }
php
public function getUpgradeScript($machineName, $majorVersion, $minorVersion) { $upgrades = "/libraries/{$machineName}-{$majorVersion}.{$minorVersion}/upgrades.js"; if (file_exists($this->path . $upgrades)) { return $upgrades; } else { return NULL; } }
[ "public", "function", "getUpgradeScript", "(", "$", "machineName", ",", "$", "majorVersion", ",", "$", "minorVersion", ")", "{", "$", "upgrades", "=", "\"/libraries/{$machineName}-{$majorVersion}.{$minorVersion}/upgrades.js\"", ";", "if", "(", "file_exists", "(", "$", ...
Check if upgrades script exist for library. @param string $machineName @param int $majorVersion @param int $minorVersion @return string Relative path
[ "Check", "if", "upgrades", "script", "exist", "for", "library", "." ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p-default-storage.class.php#L461-L469
h5p/h5p-php-library
h5p-default-storage.class.php
H5PDefaultStorage.saveFileFromZip
public function saveFileFromZip($path, $file, $stream) { $filePath = $path . '/' . $file; // Make sure the directory exists first $matches = array(); preg_match('/(.+)\/[^\/]*$/', $filePath, $matches); self::dirReady($matches[1]); // Store in local storage folder return file_put_contents($filePath, $stream); }
php
public function saveFileFromZip($path, $file, $stream) { $filePath = $path . '/' . $file; // Make sure the directory exists first $matches = array(); preg_match('/(.+)\/[^\/]*$/', $filePath, $matches); self::dirReady($matches[1]); // Store in local storage folder return file_put_contents($filePath, $stream); }
[ "public", "function", "saveFileFromZip", "(", "$", "path", ",", "$", "file", ",", "$", "stream", ")", "{", "$", "filePath", "=", "$", "path", ".", "'/'", ".", "$", "file", ";", "// Make sure the directory exists first", "$", "matches", "=", "array", "(", ...
Store the given stream into the given file. @param string $path @param string $file @param resource $stream @return bool
[ "Store", "the", "given", "stream", "into", "the", "given", "file", "." ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p-default-storage.class.php#L479-L489
h5p/h5p-php-library
h5p-default-storage.class.php
H5PDefaultStorage.copyFileTree
private static function copyFileTree($source, $destination) { if (!self::dirReady($destination)) { throw new \Exception('unabletocopy'); } $ignoredFiles = self::getIgnoredFiles("{$source}/.h5pignore"); $dir = opendir($source); if ($dir === FALSE) { trigger_error('Unable to open directory ' . $source, E_USER_WARNING); throw new \Exception('unabletocopy'); } while (false !== ($file = readdir($dir))) { if (($file != '.') && ($file != '..') && $file != '.git' && $file != '.gitignore' && !in_array($file, $ignoredFiles)) { if (is_dir("{$source}/{$file}")) { self::copyFileTree("{$source}/{$file}", "{$destination}/{$file}"); } else { copy("{$source}/{$file}", "{$destination}/{$file}"); } } } closedir($dir); }
php
private static function copyFileTree($source, $destination) { if (!self::dirReady($destination)) { throw new \Exception('unabletocopy'); } $ignoredFiles = self::getIgnoredFiles("{$source}/.h5pignore"); $dir = opendir($source); if ($dir === FALSE) { trigger_error('Unable to open directory ' . $source, E_USER_WARNING); throw new \Exception('unabletocopy'); } while (false !== ($file = readdir($dir))) { if (($file != '.') && ($file != '..') && $file != '.git' && $file != '.gitignore' && !in_array($file, $ignoredFiles)) { if (is_dir("{$source}/{$file}")) { self::copyFileTree("{$source}/{$file}", "{$destination}/{$file}"); } else { copy("{$source}/{$file}", "{$destination}/{$file}"); } } } closedir($dir); }
[ "private", "static", "function", "copyFileTree", "(", "$", "source", ",", "$", "destination", ")", "{", "if", "(", "!", "self", "::", "dirReady", "(", "$", "destination", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "'unabletocopy'", ")", ";", ...
Recursive function for copying directories. @param string $source From path @param string $destination To path @return boolean Indicates if the directory existed. @throws Exception Unable to copy the file
[ "Recursive", "function", "for", "copying", "directories", "." ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p-default-storage.class.php#L503-L527
h5p/h5p-php-library
h5p-default-storage.class.php
H5PDefaultStorage.getIgnoredFiles
private static function getIgnoredFiles($file) { if (file_exists($file) === FALSE) { return array(); } $contents = file_get_contents($file); if ($contents === FALSE) { return array(); } return preg_split('/\s+/', $contents); }
php
private static function getIgnoredFiles($file) { if (file_exists($file) === FALSE) { return array(); } $contents = file_get_contents($file); if ($contents === FALSE) { return array(); } return preg_split('/\s+/', $contents); }
[ "private", "static", "function", "getIgnoredFiles", "(", "$", "file", ")", "{", "if", "(", "file_exists", "(", "$", "file", ")", "===", "FALSE", ")", "{", "return", "array", "(", ")", ";", "}", "$", "contents", "=", "file_get_contents", "(", "$", "file...
Retrieve array of file names from file. @param string $file @return array Array with files that should be ignored
[ "Retrieve", "array", "of", "file", "names", "from", "file", "." ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p-default-storage.class.php#L535-L546
h5p/h5p-php-library
h5p-default-storage.class.php
H5PDefaultStorage.dirReady
private static function dirReady($path) { if (!file_exists($path)) { $parent = preg_replace("/\/[^\/]+\/?$/", '', $path); if (!self::dirReady($parent)) { return FALSE; } mkdir($path, 0777, true); } if (!is_dir($path)) { trigger_error('Path is not a directory ' . $path, E_USER_WARNING); return FALSE; } if (!is_writable($path)) { trigger_error('Unable to write to ' . $path . ' – check directory permissions –', E_USER_WARNING); return FALSE; } return TRUE; }
php
private static function dirReady($path) { if (!file_exists($path)) { $parent = preg_replace("/\/[^\/]+\/?$/", '', $path); if (!self::dirReady($parent)) { return FALSE; } mkdir($path, 0777, true); } if (!is_dir($path)) { trigger_error('Path is not a directory ' . $path, E_USER_WARNING); return FALSE; } if (!is_writable($path)) { trigger_error('Unable to write to ' . $path . ' – check directory permissions –', E_USER_WARNING); return FALSE; } return TRUE; }
[ "private", "static", "function", "dirReady", "(", "$", "path", ")", "{", "if", "(", "!", "file_exists", "(", "$", "path", ")", ")", "{", "$", "parent", "=", "preg_replace", "(", "\"/\\/[^\\/]+\\/?$/\"", ",", "''", ",", "$", "path", ")", ";", "if", "(...
Recursive function that makes sure the specified directory exists and is writable. @param string $path @return bool
[ "Recursive", "function", "that", "makes", "sure", "the", "specified", "directory", "exists", "and", "is", "writable", "." ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p-default-storage.class.php#L555-L576
h5p/h5p-php-library
h5p-metadata.class.php
H5PMetadata.toJSON
public static function toJSON($content) { // Note: deliberatly creating JSON string "manually" to improve performance return '{"title":' . (isset($content->title) ? json_encode($content->title) : 'null') . ',"authors":' . (isset($content->authors) ? $content->authors : 'null') . ',"source":' . (isset($content->source) ? '"' . $content->source . '"' : 'null') . ',"license":' . (isset($content->license) ? '"' . $content->license . '"' : 'null') . ',"licenseVersion":' . (isset($content->license_version) ? '"' . $content->license_version . '"' : 'null') . ',"licenseExtras":' . (isset($content->license_extras) ? json_encode($content->license_extras) : 'null') . ',"yearFrom":' . (isset($content->year_from) ? $content->year_from : 'null') . ',"yearTo":' . (isset($content->year_to) ? $content->year_to : 'null') . ',"changes":' . (isset($content->changes) ? $content->changes : 'null') . ',"defaultLanguage":' . (isset($content->default_language) ? '"' . $content->default_language . '"' : 'null') . ',"authorComments":' . (isset($content->author_comments) ? json_encode($content->author_comments) : 'null') . '}'; }
php
public static function toJSON($content) { // Note: deliberatly creating JSON string "manually" to improve performance return '{"title":' . (isset($content->title) ? json_encode($content->title) : 'null') . ',"authors":' . (isset($content->authors) ? $content->authors : 'null') . ',"source":' . (isset($content->source) ? '"' . $content->source . '"' : 'null') . ',"license":' . (isset($content->license) ? '"' . $content->license . '"' : 'null') . ',"licenseVersion":' . (isset($content->license_version) ? '"' . $content->license_version . '"' : 'null') . ',"licenseExtras":' . (isset($content->license_extras) ? json_encode($content->license_extras) : 'null') . ',"yearFrom":' . (isset($content->year_from) ? $content->year_from : 'null') . ',"yearTo":' . (isset($content->year_to) ? $content->year_to : 'null') . ',"changes":' . (isset($content->changes) ? $content->changes : 'null') . ',"defaultLanguage":' . (isset($content->default_language) ? '"' . $content->default_language . '"' : 'null') . ',"authorComments":' . (isset($content->author_comments) ? json_encode($content->author_comments) : 'null') . '}'; }
[ "public", "static", "function", "toJSON", "(", "$", "content", ")", "{", "// Note: deliberatly creating JSON string \"manually\" to improve performance", "return", "'{\"title\":'", ".", "(", "isset", "(", "$", "content", "->", "title", ")", "?", "json_encode", "(", "$...
JSON encode metadata @param object $content @return string
[ "JSON", "encode", "metadata" ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p-metadata.class.php#L56-L70
h5p/h5p-php-library
h5p-metadata.class.php
H5PMetadata.toDBArray
public static function toDBArray($metadata, $include_title = true, $include_missing = true, &$types = array()) { $fields = array(); if (!is_array($metadata)) { $metadata = (array) $metadata; } foreach (self::$fields as $key => $config) { // Ignore title? if ($key === 'title' && !$include_title) { continue; } $exists = array_key_exists($key, $metadata); // Don't include missing fields if (!$include_missing && !$exists) { continue; } $value = $exists ? $metadata[$key] : null; // lowerCamelCase to snake_case $db_field_name = strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $key)); switch ($config['type']) { case 'text': if ($value !== null && strlen($value) > $config['maxLength']) { $value = mb_substr($value, 0, $config['maxLength']); } $types[] = '%s'; break; case 'int': $value = ($value !== null) ? intval($value) : null; $types[] = '%d'; break; case 'json': $value = ($value !== null) ? json_encode($value) : null; $types[] = '%s'; break; } $fields[$db_field_name] = $value; } return $fields; }
php
public static function toDBArray($metadata, $include_title = true, $include_missing = true, &$types = array()) { $fields = array(); if (!is_array($metadata)) { $metadata = (array) $metadata; } foreach (self::$fields as $key => $config) { // Ignore title? if ($key === 'title' && !$include_title) { continue; } $exists = array_key_exists($key, $metadata); // Don't include missing fields if (!$include_missing && !$exists) { continue; } $value = $exists ? $metadata[$key] : null; // lowerCamelCase to snake_case $db_field_name = strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $key)); switch ($config['type']) { case 'text': if ($value !== null && strlen($value) > $config['maxLength']) { $value = mb_substr($value, 0, $config['maxLength']); } $types[] = '%s'; break; case 'int': $value = ($value !== null) ? intval($value) : null; $types[] = '%d'; break; case 'json': $value = ($value !== null) ? json_encode($value) : null; $types[] = '%s'; break; } $fields[$db_field_name] = $value; } return $fields; }
[ "public", "static", "function", "toDBArray", "(", "$", "metadata", ",", "$", "include_title", "=", "true", ",", "$", "include_missing", "=", "true", ",", "&", "$", "types", "=", "array", "(", ")", ")", "{", "$", "fields", "=", "array", "(", ")", ";",...
Make the metadata into an associative array keyed by the property names @param mixed $metadata Array or object containing metadata @param bool $include_title @param bool $include_missing For metadata fields not being set, skip 'em. Relevant for content upgrade @param array $types @return array
[ "Make", "the", "metadata", "into", "an", "associative", "array", "keyed", "by", "the", "property", "names" ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p-metadata.class.php#L81-L130
h5p/h5p-php-library
h5p-metadata.class.php
H5PMetadata.boolifyAndEncodeSettings
public static function boolifyAndEncodeSettings($metadataSettings) { // Convert metadataSettings values to boolean if (isset($metadataSettings['disable'])) { $metadataSettings['disable'] = $metadataSettings['disable'] === 1; } if (isset($metadataSettings['disableExtraTitleField'])) { $metadataSettings['disableExtraTitleField'] = $metadataSettings['disableExtraTitleField'] === 1; } return json_encode($metadataSettings); }
php
public static function boolifyAndEncodeSettings($metadataSettings) { // Convert metadataSettings values to boolean if (isset($metadataSettings['disable'])) { $metadataSettings['disable'] = $metadataSettings['disable'] === 1; } if (isset($metadataSettings['disableExtraTitleField'])) { $metadataSettings['disableExtraTitleField'] = $metadataSettings['disableExtraTitleField'] === 1; } return json_encode($metadataSettings); }
[ "public", "static", "function", "boolifyAndEncodeSettings", "(", "$", "metadataSettings", ")", "{", "// Convert metadataSettings values to boolean", "if", "(", "isset", "(", "$", "metadataSettings", "[", "'disable'", "]", ")", ")", "{", "$", "metadataSettings", "[", ...
The metadataSettings field in libraryJson uses 1 for true and 0 for false. Here we are converting these to booleans, and also doing JSON encoding. This is invoked before the library data is beeing inserted/updated to DB. @param array $metadataSettings @return string
[ "The", "metadataSettings", "field", "in", "libraryJson", "uses", "1", "for", "true", "and", "0", "for", "false", ".", "Here", "we", "are", "converting", "these", "to", "booleans", "and", "also", "doing", "JSON", "encoding", ".", "This", "is", "invoked", "b...
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p-metadata.class.php#L140-L150
h5p/h5p-php-library
h5p-event-base.class.php
H5PEventBase.validLogLevel
private static function validLogLevel($type, $sub_type) { switch (self::$log_level) { default: case self::LOG_NONE: return FALSE; case self::LOG_ALL: return TRUE; // Log everything case self::LOG_ACTIONS: if (self::isAction($type, $sub_type)) { return TRUE; // Log actions } return FALSE; } }
php
private static function validLogLevel($type, $sub_type) { switch (self::$log_level) { default: case self::LOG_NONE: return FALSE; case self::LOG_ALL: return TRUE; // Log everything case self::LOG_ACTIONS: if (self::isAction($type, $sub_type)) { return TRUE; // Log actions } return FALSE; } }
[ "private", "static", "function", "validLogLevel", "(", "$", "type", ",", "$", "sub_type", ")", "{", "switch", "(", "self", "::", "$", "log_level", ")", "{", "default", ":", "case", "self", "::", "LOG_NONE", ":", "return", "FALSE", ";", "case", "self", ...
Determines if the event type should be saved/logged. @param string $type Name of event type @param string $sub_type Name of event sub type @return boolean
[ "Determines", "if", "the", "event", "type", "should", "be", "saved", "/", "logged", "." ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p-event-base.class.php#L87-L100
h5p/h5p-php-library
h5p-event-base.class.php
H5PEventBase.validStats
private static function validStats($type, $sub_type) { if ( ($type === 'content' && $sub_type === 'shortcode insert') || // Count number of shortcode inserts ($type === 'library' && $sub_type === NULL) || // Count number of times library is loaded in editor ($type === 'results' && $sub_type === 'content') ) { // Count number of times results page has been opened return TRUE; } elseif (self::isAction($type, $sub_type)) { // Count all actions return TRUE; } return FALSE; }
php
private static function validStats($type, $sub_type) { if ( ($type === 'content' && $sub_type === 'shortcode insert') || // Count number of shortcode inserts ($type === 'library' && $sub_type === NULL) || // Count number of times library is loaded in editor ($type === 'results' && $sub_type === 'content') ) { // Count number of times results page has been opened return TRUE; } elseif (self::isAction($type, $sub_type)) { // Count all actions return TRUE; } return FALSE; }
[ "private", "static", "function", "validStats", "(", "$", "type", ",", "$", "sub_type", ")", "{", "if", "(", "(", "$", "type", "===", "'content'", "&&", "$", "sub_type", "===", "'shortcode insert'", ")", "||", "// Count number of shortcode inserts", "(", "$", ...
Check if the event should be included in the statistics counter. @param string $type Name of event type @param string $sub_type Name of event sub type @return boolean
[ "Check", "if", "the", "event", "should", "be", "included", "in", "the", "statistics", "counter", "." ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p-event-base.class.php#L111-L121
h5p/h5p-php-library
h5p-event-base.class.php
H5PEventBase.isAction
private static function isAction($type, $sub_type) { if ( ($type === 'content' && in_array($sub_type, array('create', 'create upload', 'update', 'update upload', 'upgrade', 'delete'))) || ($type === 'library' && in_array($sub_type, array('create', 'update'))) ) { return TRUE; // Log actions } return FALSE; }
php
private static function isAction($type, $sub_type) { if ( ($type === 'content' && in_array($sub_type, array('create', 'create upload', 'update', 'update upload', 'upgrade', 'delete'))) || ($type === 'library' && in_array($sub_type, array('create', 'update'))) ) { return TRUE; // Log actions } return FALSE; }
[ "private", "static", "function", "isAction", "(", "$", "type", ",", "$", "sub_type", ")", "{", "if", "(", "(", "$", "type", "===", "'content'", "&&", "in_array", "(", "$", "sub_type", ",", "array", "(", "'create'", ",", "'create upload'", ",", "'update'"...
Check if event type is an action. @param string $type Name of event type @param string $sub_type Name of event sub type @return boolean
[ "Check", "if", "event", "type", "is", "an", "action", "." ]
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p-event-base.class.php#L132-L138
h5p/h5p-php-library
h5p-event-base.class.php
H5PEventBase.getDataArray
protected function getDataArray() { return array( 'created_at' => $this->time, 'type' => $this->type, 'sub_type' => empty($this->sub_type) ? '' : $this->sub_type, 'content_id' => empty($this->content_id) ? 0 : $this->content_id, 'content_title' => empty($this->content_title) ? '' : $this->content_title, 'library_name' => empty($this->library_name) ? '' : $this->library_name, 'library_version' => empty($this->library_version) ? '' : $this->library_version ); }
php
protected function getDataArray() { return array( 'created_at' => $this->time, 'type' => $this->type, 'sub_type' => empty($this->sub_type) ? '' : $this->sub_type, 'content_id' => empty($this->content_id) ? 0 : $this->content_id, 'content_title' => empty($this->content_title) ? '' : $this->content_title, 'library_name' => empty($this->library_name) ? '' : $this->library_name, 'library_version' => empty($this->library_version) ? '' : $this->library_version ); }
[ "protected", "function", "getDataArray", "(", ")", "{", "return", "array", "(", "'created_at'", "=>", "$", "this", "->", "time", ",", "'type'", "=>", "$", "this", "->", "type", ",", "'sub_type'", "=>", "empty", "(", "$", "this", "->", "sub_type", ")", ...
A helper which makes it easier for systems to save the data. Add all relevant properties to a assoc. array. There are no NULL values. Empty string or 0 is used instead. Used by both Drupal and WordPress. @return array with keyed values
[ "A", "helper", "which", "makes", "it", "easier", "for", "systems", "to", "save", "the", "data", ".", "Add", "all", "relevant", "properties", "to", "a", "assoc", ".", "array", ".", "There", "are", "no", "NULL", "values", ".", "Empty", "string", "or", "0...
train
https://github.com/h5p/h5p-php-library/blob/5d7b480c3b6ba41c2f27bdf06f93dfcd389cddd4/h5p-event-base.class.php#L148-L158
alchemy-fr/Phraseanet
lib/classes/patch/386alpha4a.php
patch_386alpha4a.apply
public function apply(base $appbox, Application $app) { $repo = $app['orm.em']->getRepository('Phraseanet:UsrList'); foreach ($app['orm.em']->getRepository('Phraseanet:User')->findDeleted() as $user) { foreach ($repo->findUserLists($user) as $list) { $app['orm.em']->remove($list); } $app['orm.em']->flush(); } return true; }
php
public function apply(base $appbox, Application $app) { $repo = $app['orm.em']->getRepository('Phraseanet:UsrList'); foreach ($app['orm.em']->getRepository('Phraseanet:User')->findDeleted() as $user) { foreach ($repo->findUserLists($user) as $list) { $app['orm.em']->remove($list); } $app['orm.em']->flush(); } return true; }
[ "public", "function", "apply", "(", "base", "$", "appbox", ",", "Application", "$", "app", ")", "{", "$", "repo", "=", "$", "app", "[", "'orm.em'", "]", "->", "getRepository", "(", "'Phraseanet:UsrList'", ")", ";", "foreach", "(", "$", "app", "[", "'or...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/386alpha4a.php#L59-L70
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Model/Repositories/FtpExportRepository.php
FtpExportRepository.findCrashedExports
public function findCrashedExports(\DateTime $before = null) { $qb = $this->createQueryBuilder('e'); $qb->where($qb->expr()->gte('e.crash', 'e.nbretry')); if (null !== $before) { $qb->andWhere($qb->expr()->lte('e.created', ':created')); $qb->setParameter(':created', $before); } return $qb->getQuery()->getResult(); }
php
public function findCrashedExports(\DateTime $before = null) { $qb = $this->createQueryBuilder('e'); $qb->where($qb->expr()->gte('e.crash', 'e.nbretry')); if (null !== $before) { $qb->andWhere($qb->expr()->lte('e.created', ':created')); $qb->setParameter(':created', $before); } return $qb->getQuery()->getResult(); }
[ "public", "function", "findCrashedExports", "(", "\\", "DateTime", "$", "before", "=", "null", ")", "{", "$", "qb", "=", "$", "this", "->", "createQueryBuilder", "(", "'e'", ")", ";", "$", "qb", "->", "where", "(", "$", "qb", "->", "expr", "(", ")", ...
Returns exports that crashed. If a date is provided, only exports created before this date are returned. @param \DateTime $before An optional date to search @return array
[ "Returns", "exports", "that", "crashed", ".", "If", "a", "date", "is", "provided", "only", "exports", "created", "before", "this", "date", "are", "returned", "." ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Model/Repositories/FtpExportRepository.php#L33-L44
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Command/Setup/XSendFileConfigurationDumper.php
XSendFileConfigurationDumper.doExecute
protected function doExecute(InputInterface $input, OutputInterface $output) { $output->writeln(''); if (!$this->container['phraseanet.xsendfile-factory']->isXSendFileModeEnabled()) { $output->writeln('XSendFile support is <error>disabled</error>, enable it to use this feature.'); $ret = 1; } else { $output->writeln('XSendFile support is <info>enabled</info>'); $ret = 0; } try { $configuration = $this->container['phraseanet.xsendfile-factory']->getMode(true, true)->getVirtualHostConfiguration(); $output->writeln('XSendFile configuration seems <info>OK</info>'); $output->writeln($configuration); } catch (RuntimeException $e) { $output->writeln('XSendFile configuration seems <error>invalid</error>'); $ret = 1; } $output->writeln(''); return $ret; }
php
protected function doExecute(InputInterface $input, OutputInterface $output) { $output->writeln(''); if (!$this->container['phraseanet.xsendfile-factory']->isXSendFileModeEnabled()) { $output->writeln('XSendFile support is <error>disabled</error>, enable it to use this feature.'); $ret = 1; } else { $output->writeln('XSendFile support is <info>enabled</info>'); $ret = 0; } try { $configuration = $this->container['phraseanet.xsendfile-factory']->getMode(true, true)->getVirtualHostConfiguration(); $output->writeln('XSendFile configuration seems <info>OK</info>'); $output->writeln($configuration); } catch (RuntimeException $e) { $output->writeln('XSendFile configuration seems <error>invalid</error>'); $ret = 1; } $output->writeln(''); return $ret; }
[ "protected", "function", "doExecute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "output", "->", "writeln", "(", "''", ")", ";", "if", "(", "!", "$", "this", "->", "container", "[", "'phraseanet.xsendfile-facto...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Command/Setup/XSendFileConfigurationDumper.php#L31-L57
alchemy-fr/Phraseanet
lib/classes/patch/390alpha13a.php
patch_390alpha13a.apply
public function apply(base $appbox, Application $app) { $em = $app['orm.em']; $sql = "SELECT date_modif, usr_id, base_id, en_cours, refuser FROM demand"; $rsm = new ResultSetMapping(); $rsm->addScalarResult('base_id','base_id'); $rsm->addScalarResult('en_cours','en_cours'); $rsm->addScalarResult('refuser','refuser'); $rsm->addScalarResult('usr_id', 'usr_id'); $rsm->addScalarResult('date_modif', 'date_modif'); $rs = $em->createNativeQuery($sql, $rsm)->getResult(); $n = 0; foreach ($rs as $row) { try { $user = $em->createQuery('SELECT PARTIAL u.{id} FROM Phraseanet:User u WHERE u.id = :id') ->setParameters(['id' => $row['usr_id']]) ->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true) ->getSingleResult(); } catch (NoResultException $e) { $app['monolog']->addInfo(sprintf( 'Patch %s : Registration for user (%s) could not be turn into doctrine entity as user could not be found.', $this->get_release(), $row['usr_id'] )); continue; } try { $collection = \collection::getByBaseId($app, $row['base_id']); } catch (\Exception $e) { $app['monolog']->addInfo(sprintf( 'Patch %s : Registration for user (%s) could not be turn into doctrine entity as base with id (%s) could not be found.', $this->get_release(), $row['usr_id'], $row['base_id'] )); continue; } $registration = new Registration(); $registration->setCollection($collection); $registration->setUser($user); $registration->setPending($row['en_cours']); $registration->setCreated(new \DateTime($row['date_modif'])); $registration->setRejected($row['refuser']); if ($n % 100 === 0) { $em->flush(); $em->clear(); } $n++; } $em->flush(); $em->clear(); }
php
public function apply(base $appbox, Application $app) { $em = $app['orm.em']; $sql = "SELECT date_modif, usr_id, base_id, en_cours, refuser FROM demand"; $rsm = new ResultSetMapping(); $rsm->addScalarResult('base_id','base_id'); $rsm->addScalarResult('en_cours','en_cours'); $rsm->addScalarResult('refuser','refuser'); $rsm->addScalarResult('usr_id', 'usr_id'); $rsm->addScalarResult('date_modif', 'date_modif'); $rs = $em->createNativeQuery($sql, $rsm)->getResult(); $n = 0; foreach ($rs as $row) { try { $user = $em->createQuery('SELECT PARTIAL u.{id} FROM Phraseanet:User u WHERE u.id = :id') ->setParameters(['id' => $row['usr_id']]) ->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true) ->getSingleResult(); } catch (NoResultException $e) { $app['monolog']->addInfo(sprintf( 'Patch %s : Registration for user (%s) could not be turn into doctrine entity as user could not be found.', $this->get_release(), $row['usr_id'] )); continue; } try { $collection = \collection::getByBaseId($app, $row['base_id']); } catch (\Exception $e) { $app['monolog']->addInfo(sprintf( 'Patch %s : Registration for user (%s) could not be turn into doctrine entity as base with id (%s) could not be found.', $this->get_release(), $row['usr_id'], $row['base_id'] )); continue; } $registration = new Registration(); $registration->setCollection($collection); $registration->setUser($user); $registration->setPending($row['en_cours']); $registration->setCreated(new \DateTime($row['date_modif'])); $registration->setRejected($row['refuser']); if ($n % 100 === 0) { $em->flush(); $em->clear(); } $n++; } $em->flush(); $em->clear(); }
[ "public", "function", "apply", "(", "base", "$", "appbox", ",", "Application", "$", "app", ")", "{", "$", "em", "=", "$", "app", "[", "'orm.em'", "]", ";", "$", "sql", "=", "\"SELECT date_modif, usr_id, base_id, en_cours, refuser\n FROM demand\"", "...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/390alpha13a.php#L61-L121
alchemy-fr/Phraseanet
lib/classes/patch/370alpha4a.php
patch_370alpha4a.apply
public function apply(base $databox, Application $app) { $sql = 'SELECT id, src FROM metadatas_structure'; $stmt = $databox->get_connection()->prepare($sql); $stmt->execute(); $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); $update = []; $tagDirname = new \Alchemy\Phrasea\Metadata\Tag\TfDirname(); $tagBasename = new \Alchemy\Phrasea\Metadata\Tag\TfBasename(); foreach ($rs as $row) { if (strpos(strtolower($row['src']), 'tf-parentdir') !== false) { $update[] = ['id' => $row['id'], 'src' => $tagDirname->getTagname()]; } if (strpos(strtolower($row['src']), 'tf-filename') !== false) { $update[] = ['id' => $row['id'], 'src' => $tagBasename->getTagname()]; } } $sql = 'UPDATE metadatas_structure SET src = :src WHERE id = :id'; $stmt = $databox->get_connection()->prepare($sql); foreach ($update as $row) { $stmt->execute([':src' => $row['src'], ':id' => $row['id']]); } $stmt->closeCursor(); return true; }
php
public function apply(base $databox, Application $app) { $sql = 'SELECT id, src FROM metadatas_structure'; $stmt = $databox->get_connection()->prepare($sql); $stmt->execute(); $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); $update = []; $tagDirname = new \Alchemy\Phrasea\Metadata\Tag\TfDirname(); $tagBasename = new \Alchemy\Phrasea\Metadata\Tag\TfBasename(); foreach ($rs as $row) { if (strpos(strtolower($row['src']), 'tf-parentdir') !== false) { $update[] = ['id' => $row['id'], 'src' => $tagDirname->getTagname()]; } if (strpos(strtolower($row['src']), 'tf-filename') !== false) { $update[] = ['id' => $row['id'], 'src' => $tagBasename->getTagname()]; } } $sql = 'UPDATE metadatas_structure SET src = :src WHERE id = :id'; $stmt = $databox->get_connection()->prepare($sql); foreach ($update as $row) { $stmt->execute([':src' => $row['src'], ':id' => $row['id']]); } $stmt->closeCursor(); return true; }
[ "public", "function", "apply", "(", "base", "$", "databox", ",", "Application", "$", "app", ")", "{", "$", "sql", "=", "'SELECT id, src FROM metadatas_structure'", ";", "$", "stmt", "=", "$", "databox", "->", "get_connection", "(", ")", "->", "prepare", "(",...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/370alpha4a.php#L49-L82
alchemy-fr/Phraseanet
lib/classes/patch/381alpha1b.php
patch_381alpha1b.apply
public function apply(base $databox, Application $app) { $sql = "SHOW INDEX FROM metadatas_structure WHERE KEY_NAME = 'sorter'"; $stmt = $databox->get_connection()->prepare($sql); $stmt->execute(); $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC); $stmt->closeCursor(); if (count($rows) === 0) { return true; } $sql = "DROP INDEX sorter ON metadatas_structure"; $stmt = $databox->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); return true; }
php
public function apply(base $databox, Application $app) { $sql = "SHOW INDEX FROM metadatas_structure WHERE KEY_NAME = 'sorter'"; $stmt = $databox->get_connection()->prepare($sql); $stmt->execute(); $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC); $stmt->closeCursor(); if (count($rows) === 0) { return true; } $sql = "DROP INDEX sorter ON metadatas_structure"; $stmt = $databox->get_connection()->prepare($sql); $stmt->execute(); $stmt->closeCursor(); return true; }
[ "public", "function", "apply", "(", "base", "$", "databox", ",", "Application", "$", "app", ")", "{", "$", "sql", "=", "\"SHOW INDEX FROM metadatas_structure WHERE KEY_NAME = 'sorter'\"", ";", "$", "stmt", "=", "$", "databox", "->", "get_connection", "(", ")", "...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/patch/381alpha1b.php#L49-L67
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Authentication/Provider/GooglePlus.php
GooglePlus.authenticate
public function authenticate(array $params = array()) { $params = array_merge(['providerId' => $this->getId()], $params); $this->client->setRedirectUri( $this->generator->generate( 'login_authentication_provider_callback', $params, UrlGenerator::ABSOLUTE_URL ) ); $state = $this->createState(); $this->session->set('google-plus.provider.state', $state); $this->client->setState($state); return new RedirectResponse($this->client->createAuthUrl()); }
php
public function authenticate(array $params = array()) { $params = array_merge(['providerId' => $this->getId()], $params); $this->client->setRedirectUri( $this->generator->generate( 'login_authentication_provider_callback', $params, UrlGenerator::ABSOLUTE_URL ) ); $state = $this->createState(); $this->session->set('google-plus.provider.state', $state); $this->client->setState($state); return new RedirectResponse($this->client->createAuthUrl()); }
[ "public", "function", "authenticate", "(", "array", "$", "params", "=", "array", "(", ")", ")", "{", "$", "params", "=", "array_merge", "(", "[", "'providerId'", "=>", "$", "this", "->", "getId", "(", ")", "]", ",", "$", "params", ")", ";", "$", "t...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Authentication/Provider/GooglePlus.php#L110-L128
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Authentication/Provider/GooglePlus.php
GooglePlus.logout
public function logout() { try { $this->client->revokeToken(); } catch (\Google_Exception $e) { throw new RuntimeException('Unable to logout from Google+', $e->getCode(), $e); } }
php
public function logout() { try { $this->client->revokeToken(); } catch (\Google_Exception $e) { throw new RuntimeException('Unable to logout from Google+', $e->getCode(), $e); } }
[ "public", "function", "logout", "(", ")", "{", "try", "{", "$", "this", "->", "client", "->", "revokeToken", "(", ")", ";", "}", "catch", "(", "\\", "Google_Exception", "$", "e", ")", "{", "throw", "new", "RuntimeException", "(", "'Unable to logout from Go...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Authentication/Provider/GooglePlus.php#L133-L140
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Authentication/Provider/GooglePlus.php
GooglePlus.onCallback
public function onCallback(Request $request) { if (!$this->session->has('google-plus.provider.state')) { throw new NotAuthenticatedException('No state value in session ; CSRF try ?'); } if ($request->query->get('state') !== $this->session->remove('google-plus.provider.state')) { throw new NotAuthenticatedException('Invalid state value ; CSRF try ?'); } try { $this->client->fetchAccessTokenWithAuthCode($request->query->get('code')); $token = @json_decode($this->client->getAccessToken(), true); if (JSON_ERROR_NONE !== json_last_error()) { throw new NotAuthenticatedException('Unable to parse Google+ JSON', json_last_error()); } $ticket = $this->client->verifyIdToken($token['id_token']); } catch (\Google_Exception $e) { throw new NotAuthenticatedException('Unable to authenticate through Google+', $e->getCode(), $e); } $this->session->set('google-plus.provider.token', $this->client->getAccessToken()); $this->session->set('google-plus.provider.id', $ticket['sub']); }
php
public function onCallback(Request $request) { if (!$this->session->has('google-plus.provider.state')) { throw new NotAuthenticatedException('No state value in session ; CSRF try ?'); } if ($request->query->get('state') !== $this->session->remove('google-plus.provider.state')) { throw new NotAuthenticatedException('Invalid state value ; CSRF try ?'); } try { $this->client->fetchAccessTokenWithAuthCode($request->query->get('code')); $token = @json_decode($this->client->getAccessToken(), true); if (JSON_ERROR_NONE !== json_last_error()) { throw new NotAuthenticatedException('Unable to parse Google+ JSON', json_last_error()); } $ticket = $this->client->verifyIdToken($token['id_token']); } catch (\Google_Exception $e) { throw new NotAuthenticatedException('Unable to authenticate through Google+', $e->getCode(), $e); } $this->session->set('google-plus.provider.token', $this->client->getAccessToken()); $this->session->set('google-plus.provider.id', $ticket['sub']); }
[ "public", "function", "onCallback", "(", "Request", "$", "request", ")", "{", "if", "(", "!", "$", "this", "->", "session", "->", "has", "(", "'google-plus.provider.state'", ")", ")", "{", "throw", "new", "NotAuthenticatedException", "(", "'No state value in ses...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Authentication/Provider/GooglePlus.php#L145-L172
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Authentication/Provider/GooglePlus.php
GooglePlus.getIdentity
public function getIdentity() { $identity = new Identity(); $accessToken = $this->client->getAccessToken(); $token = @json_decode($accessToken, true); if (JSON_ERROR_NONE !== json_last_error()) { throw new NotAuthenticatedException('Unable to parse Google+ JSON'); } try { if(is_array($ticket = $this->client->verifyIdToken($token['id_token']))){ $mapping = [ 'email' => Identity::PROPERTY_EMAIL, 'given_name' => Identity::PROPERTY_FIRSTNAME, 'family_name' => Identity::PROPERTY_LASTNAME, 'picture' => Identity::PROPERTY_IMAGEURL, 'sub' => Identity::PROPERTY_ID ]; foreach ($mapping as $src => $dest) { if (array_key_exists($src, $ticket)) { $identity->set($dest, $ticket[$src]); } } } else { throw new NotAuthenticatedException('Google + has not authenticated'); } } catch (\Google_Exception $e) { throw new NotAuthenticatedException('Google + has not authenticated'); } if(!$identity->has(Identity::PROPERTY_ID)) { throw new NotAuthenticatedException('Google + has not authenticated'); } return $identity; }
php
public function getIdentity() { $identity = new Identity(); $accessToken = $this->client->getAccessToken(); $token = @json_decode($accessToken, true); if (JSON_ERROR_NONE !== json_last_error()) { throw new NotAuthenticatedException('Unable to parse Google+ JSON'); } try { if(is_array($ticket = $this->client->verifyIdToken($token['id_token']))){ $mapping = [ 'email' => Identity::PROPERTY_EMAIL, 'given_name' => Identity::PROPERTY_FIRSTNAME, 'family_name' => Identity::PROPERTY_LASTNAME, 'picture' => Identity::PROPERTY_IMAGEURL, 'sub' => Identity::PROPERTY_ID ]; foreach ($mapping as $src => $dest) { if (array_key_exists($src, $ticket)) { $identity->set($dest, $ticket[$src]); } } } else { throw new NotAuthenticatedException('Google + has not authenticated'); } } catch (\Google_Exception $e) { throw new NotAuthenticatedException('Google + has not authenticated'); } if(!$identity->has(Identity::PROPERTY_ID)) { throw new NotAuthenticatedException('Google + has not authenticated'); } return $identity; }
[ "public", "function", "getIdentity", "(", ")", "{", "$", "identity", "=", "new", "Identity", "(", ")", ";", "$", "accessToken", "=", "$", "this", "->", "client", "->", "getAccessToken", "(", ")", ";", "$", "token", "=", "@", "json_decode", "(", "$", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Authentication/Provider/GooglePlus.php#L189-L228
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Authentication/Provider/GooglePlus.php
GooglePlus.create
public static function create(UrlGenerator $generator, SessionInterface $session, array $options) { $client = new \Google_Client(); $client->setApplicationName('Phraseanet'); $client->setClientId($options['client-id']); $client->setClientSecret($options['client-secret']); return new GooglePlus($generator, $session, $client, new Guzzle()); }
php
public static function create(UrlGenerator $generator, SessionInterface $session, array $options) { $client = new \Google_Client(); $client->setApplicationName('Phraseanet'); $client->setClientId($options['client-id']); $client->setClientSecret($options['client-secret']); return new GooglePlus($generator, $session, $client, new Guzzle()); }
[ "public", "static", "function", "create", "(", "UrlGenerator", "$", "generator", ",", "SessionInterface", "$", "session", ",", "array", "$", "options", ")", "{", "$", "client", "=", "new", "\\", "Google_Client", "(", ")", ";", "$", "client", "->", "setAppl...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Authentication/Provider/GooglePlus.php#L319-L328
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Admin/DataboxController.php
DataboxController.getDatabaseCGU
public function getDatabaseCGU($databox_id) { return $this->render('admin/databox/cgus.html.twig', [ 'languages' => $this->app['locales.available'], 'cgus' => $this->findDataboxById($databox_id)->get_cgus(), 'current_locale' => $this->app['locale'], ]); }
php
public function getDatabaseCGU($databox_id) { return $this->render('admin/databox/cgus.html.twig', [ 'languages' => $this->app['locales.available'], 'cgus' => $this->findDataboxById($databox_id)->get_cgus(), 'current_locale' => $this->app['locale'], ]); }
[ "public", "function", "getDatabaseCGU", "(", "$", "databox_id", ")", "{", "return", "$", "this", "->", "render", "(", "'admin/databox/cgus.html.twig'", ",", "[", "'languages'", "=>", "$", "this", "->", "app", "[", "'locales.available'", "]", ",", "'cgus'", "=>...
Get databox CGU's @param integer $databox_id The requested databox @return Response
[ "Get", "databox", "CGU", "s" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Admin/DataboxController.php#L62-L69
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Admin/DataboxController.php
DataboxController.deleteBase
public function deleteBase(Request $request, $databox_id) { $databox = null; $success = false; $msg = $this->app->trans('An error occured'); try { $databox = $this->findDataboxById($databox_id); if ($databox->get_record_amount() > 0) { $msg = $this->app->trans('admin::base: vider la base avant de la supprimer'); } else { $databox->unmount_databox(); $this->getApplicationBox()->write_databox_pic( $this->app['media-alchemyst'], $this->app['filesystem'], $databox, null, \databox::PIC_PDF ); $databox->delete(); $success = true; $msg = $this->app->trans('Successful removal'); } } catch (\Exception $e) { } if (!$databox) { $this->app->abort(404, $this->app->trans('admin::base: databox not found', ['databox_id' => $databox_id])); } if ('json' === $request->getRequestFormat()) { return $this->app->json([ 'success' => $success, 'msg' => $msg, 'sbas_id' => $databox->get_sbas_id() ]); } $params = [ 'databox_id' => $databox->get_sbas_id(), 'success' => (int) $success, ]; if ($databox->get_record_amount() > 0) { $params['error'] = 'databox-not-empty'; } return $this->app->redirectPath('admin_database', $params); }
php
public function deleteBase(Request $request, $databox_id) { $databox = null; $success = false; $msg = $this->app->trans('An error occured'); try { $databox = $this->findDataboxById($databox_id); if ($databox->get_record_amount() > 0) { $msg = $this->app->trans('admin::base: vider la base avant de la supprimer'); } else { $databox->unmount_databox(); $this->getApplicationBox()->write_databox_pic( $this->app['media-alchemyst'], $this->app['filesystem'], $databox, null, \databox::PIC_PDF ); $databox->delete(); $success = true; $msg = $this->app->trans('Successful removal'); } } catch (\Exception $e) { } if (!$databox) { $this->app->abort(404, $this->app->trans('admin::base: databox not found', ['databox_id' => $databox_id])); } if ('json' === $request->getRequestFormat()) { return $this->app->json([ 'success' => $success, 'msg' => $msg, 'sbas_id' => $databox->get_sbas_id() ]); } $params = [ 'databox_id' => $databox->get_sbas_id(), 'success' => (int) $success, ]; if ($databox->get_record_amount() > 0) { $params['error'] = 'databox-not-empty'; } return $this->app->redirectPath('admin_database', $params); }
[ "public", "function", "deleteBase", "(", "Request", "$", "request", ",", "$", "databox_id", ")", "{", "$", "databox", "=", "null", ";", "$", "success", "=", "false", ";", "$", "msg", "=", "$", "this", "->", "app", "->", "trans", "(", "'An error occured...
Delete a databox @param Request $request The current HTTP request @param integer $databox_id The requested databox @return JsonResponse|RedirectResponse
[ "Delete", "a", "databox" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Admin/DataboxController.php#L78-L126
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Admin/DataboxController.php
DataboxController.reindex
public function reindex(Request $request, $databox_id) { $success = false; try { $this->findDataboxById($databox_id)->reindex(); $success = true; } catch (\Exception $e) { } if ('json' === $request->getRequestFormat()) { return $this->app->json([ 'success' => $success, 'msg' => $success ? $this->app->trans('Successful update') : $this->app->trans('An error occured'), 'sbas_id' => $databox_id, ]); } return $this->app->redirectPath('admin_database', [ 'databox_id' => $databox_id, 'success' => (int) $success, ]); }
php
public function reindex(Request $request, $databox_id) { $success = false; try { $this->findDataboxById($databox_id)->reindex(); $success = true; } catch (\Exception $e) { } if ('json' === $request->getRequestFormat()) { return $this->app->json([ 'success' => $success, 'msg' => $success ? $this->app->trans('Successful update') : $this->app->trans('An error occured'), 'sbas_id' => $databox_id, ]); } return $this->app->redirectPath('admin_database', [ 'databox_id' => $databox_id, 'success' => (int) $success, ]); }
[ "public", "function", "reindex", "(", "Request", "$", "request", ",", "$", "databox_id", ")", "{", "$", "success", "=", "false", ";", "try", "{", "$", "this", "->", "findDataboxById", "(", "$", "databox_id", ")", "->", "reindex", "(", ")", ";", "$", ...
Reindex databox content @param Request $request The current HTTP request @param integer $databox_id The requested databox @return JsonResponse|RedirectResponse
[ "Reindex", "databox", "content" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Admin/DataboxController.php#L173-L196
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Admin/DataboxController.php
DataboxController.setIndexable
public function setIndexable(Request $request, $databox_id) { $success = false; try { $databox = $this->findDataboxById($databox_id); $indexable = !!$request->request->get('indexable', false); $this->getApplicationBox()->set_databox_indexable($databox, $indexable); $success = true; } catch (\Exception $e) { } if ('json' === $request->getRequestFormat()) { return $this->app->json([ 'success' => $success, 'msg' => $success ? $this->app->trans('Successful update') : $this->app->trans('An error occured'), 'sbas_id' => $databox_id, ]); } return $this->app->redirectPath('admin_database', [ 'databox_id' => $databox_id, 'success' => (int) $success, ]); }
php
public function setIndexable(Request $request, $databox_id) { $success = false; try { $databox = $this->findDataboxById($databox_id); $indexable = !!$request->request->get('indexable', false); $this->getApplicationBox()->set_databox_indexable($databox, $indexable); $success = true; } catch (\Exception $e) { } if ('json' === $request->getRequestFormat()) { return $this->app->json([ 'success' => $success, 'msg' => $success ? $this->app->trans('Successful update') : $this->app->trans('An error occured'), 'sbas_id' => $databox_id, ]); } return $this->app->redirectPath('admin_database', [ 'databox_id' => $databox_id, 'success' => (int) $success, ]); }
[ "public", "function", "setIndexable", "(", "Request", "$", "request", ",", "$", "databox_id", ")", "{", "$", "success", "=", "false", ";", "try", "{", "$", "databox", "=", "$", "this", "->", "findDataboxById", "(", "$", "databox_id", ")", ";", "$", "in...
Make a databox indexable @param Request $request The current HTTP request @param integer $databox_id The requested databox @return JsonResponse|RedirectResponse
[ "Make", "a", "databox", "indexable" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Admin/DataboxController.php#L205-L230
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Admin/DataboxController.php
DataboxController.updateDatabaseCGU
public function updateDatabaseCGU(Request $request, $databox_id) { $databox = $this->findDataboxById($databox_id); try { foreach ($request->request->get('TOU', []) as $loc => $terms) { $databox->update_cgus($loc, $terms, !!$request->request->get('valid', false)); } } catch (\Exception $e) { return $this->app->redirectPath('admin_database_display_cgus', [ 'databox_id' => $databox_id, 'success' => 0, ]); } return $this->app->redirectPath('admin_database_display_cgus', [ 'databox_id' => $databox_id, 'success' => 1, ]); }
php
public function updateDatabaseCGU(Request $request, $databox_id) { $databox = $this->findDataboxById($databox_id); try { foreach ($request->request->get('TOU', []) as $loc => $terms) { $databox->update_cgus($loc, $terms, !!$request->request->get('valid', false)); } } catch (\Exception $e) { return $this->app->redirectPath('admin_database_display_cgus', [ 'databox_id' => $databox_id, 'success' => 0, ]); } return $this->app->redirectPath('admin_database_display_cgus', [ 'databox_id' => $databox_id, 'success' => 1, ]); }
[ "public", "function", "updateDatabaseCGU", "(", "Request", "$", "request", ",", "$", "databox_id", ")", "{", "$", "databox", "=", "$", "this", "->", "findDataboxById", "(", "$", "databox_id", ")", ";", "try", "{", "foreach", "(", "$", "request", "->", "r...
Update databox CGU's @param Request $request The current HTTP request @param integer $databox_id The requested databox @return RedirectResponse
[ "Update", "databox", "CGU", "s" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Admin/DataboxController.php#L239-L258
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Admin/DataboxController.php
DataboxController.mountCollection
public function mountCollection(Request $request, $databox_id, $collection_id) { $connection = $this->getApplicationBox()->get_connection(); $connection->beginTransaction(); try { /** @var Authenticator $authenticator */ $authenticator = $this->app->getAuthenticator(); $baseId = \collection::mount_collection( $this->app, $this->findDataboxById($databox_id), $collection_id, $authenticator->getUser() ); $othCollSel = (int) $request->request->get("othcollsel") ?: null; if (null !== $othCollSel) { $query = $this->createUserQuery(); $n = 0; /** @var ACLProvider $aclProvider */ $aclProvider = $this->app['acl']; while ($n < $query->on_base_ids([$othCollSel])->get_total()) { $results = $query->limit($n, 50)->execute()->get_results(); foreach ($results as $user) { $aclProvider->get($user)->duplicate_right_from_bas($othCollSel, $baseId); } $n += 50; } } $connection->commit(); return $this->app->redirectPath('admin_database', [ 'databox_id' => $databox_id, 'mount' => 'ok', ]); } catch (\Exception $e) { $connection->rollBack(); return $this->app->redirectPath('admin_database', [ 'databox_id' => $databox_id, 'mount' => 'ko', ]); } }
php
public function mountCollection(Request $request, $databox_id, $collection_id) { $connection = $this->getApplicationBox()->get_connection(); $connection->beginTransaction(); try { /** @var Authenticator $authenticator */ $authenticator = $this->app->getAuthenticator(); $baseId = \collection::mount_collection( $this->app, $this->findDataboxById($databox_id), $collection_id, $authenticator->getUser() ); $othCollSel = (int) $request->request->get("othcollsel") ?: null; if (null !== $othCollSel) { $query = $this->createUserQuery(); $n = 0; /** @var ACLProvider $aclProvider */ $aclProvider = $this->app['acl']; while ($n < $query->on_base_ids([$othCollSel])->get_total()) { $results = $query->limit($n, 50)->execute()->get_results(); foreach ($results as $user) { $aclProvider->get($user)->duplicate_right_from_bas($othCollSel, $baseId); } $n += 50; } } $connection->commit(); return $this->app->redirectPath('admin_database', [ 'databox_id' => $databox_id, 'mount' => 'ok', ]); } catch (\Exception $e) { $connection->rollBack(); return $this->app->redirectPath('admin_database', [ 'databox_id' => $databox_id, 'mount' => 'ko', ]); } }
[ "public", "function", "mountCollection", "(", "Request", "$", "request", ",", "$", "databox_id", ",", "$", "collection_id", ")", "{", "$", "connection", "=", "$", "this", "->", "getApplicationBox", "(", ")", "->", "get_connection", "(", ")", ";", "$", "con...
Mount a collection on a databox @param Request $request The current HTTP request @param integer $databox_id The requested databox @param integer $collection_id The requested collection id @return RedirectResponse
[ "Mount", "a", "collection", "on", "a", "databox" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Admin/DataboxController.php#L268-L315
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Admin/DataboxController.php
DataboxController.sendLogoPdf
public function sendLogoPdf(Request $request, $databox_id) { try { if (null !== ($file = $request->files->get('newLogoPdf')) && $file->isValid()) { if ($file->getClientSize() < 65536) { $databox = $this->findDataboxById($databox_id); $this->getApplicationBox()->write_databox_pic( $this->app['media-alchemyst'], $this->app['filesystem'], $databox, $file, \databox::PIC_PDF ); unlink($file->getPathname()); return $this->app->redirectPath('admin_database', [ 'databox_id' => $databox_id, 'success' => '1', ]); } else { return $this->app->redirectPath('admin_database', [ 'databox_id' => $databox_id, 'success' => '0', 'error' => 'file-too-big', ]); } } else { return $this->app->redirectPath('admin_database', [ 'databox_id' => $databox_id, 'success' => '0', 'error' => 'file-invalid', ]); } } catch (\Exception $e) { return $this->app->redirectPath('admin_database', [ 'databox_id' => $databox_id, 'success' => '0', 'error' => 'file-error', ]); } }
php
public function sendLogoPdf(Request $request, $databox_id) { try { if (null !== ($file = $request->files->get('newLogoPdf')) && $file->isValid()) { if ($file->getClientSize() < 65536) { $databox = $this->findDataboxById($databox_id); $this->getApplicationBox()->write_databox_pic( $this->app['media-alchemyst'], $this->app['filesystem'], $databox, $file, \databox::PIC_PDF ); unlink($file->getPathname()); return $this->app->redirectPath('admin_database', [ 'databox_id' => $databox_id, 'success' => '1', ]); } else { return $this->app->redirectPath('admin_database', [ 'databox_id' => $databox_id, 'success' => '0', 'error' => 'file-too-big', ]); } } else { return $this->app->redirectPath('admin_database', [ 'databox_id' => $databox_id, 'success' => '0', 'error' => 'file-invalid', ]); } } catch (\Exception $e) { return $this->app->redirectPath('admin_database', [ 'databox_id' => $databox_id, 'success' => '0', 'error' => 'file-error', ]); } }
[ "public", "function", "sendLogoPdf", "(", "Request", "$", "request", ",", "$", "databox_id", ")", "{", "try", "{", "if", "(", "null", "!==", "(", "$", "file", "=", "$", "request", "->", "files", "->", "get", "(", "'newLogoPdf'", ")", ")", "&&", "$", ...
Set a new logo for a databox @param Request $request The current HTTP request @param integer $databox_id The requested databox @return RedirectResponse
[ "Set", "a", "new", "logo", "for", "a", "databox" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Admin/DataboxController.php#L324-L365
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Admin/DataboxController.php
DataboxController.deleteLogoPdf
public function deleteLogoPdf(Request $request, $databox_id) { $success = false; try { $this->getApplicationBox()->write_databox_pic( $this->app['media-alchemyst'], $this->app['filesystem'], $this->findDataboxById($databox_id), null, \databox::PIC_PDF ); $success = true; } catch (\Exception $e) { } if ('json' === $request->getRequestFormat()) { return $this->app->json([ 'success' => $success, 'msg' => $success ? $this->app->trans('Successful removal') : $this->app->trans('An error occured'), 'sbas_id' => $databox_id, ]); } // TODO: Check whether html call is still valid return $this->app->redirectPath('admin_database', [ 'databox_id' => $databox_id, 'error' => 'file-too-big', ]); }
php
public function deleteLogoPdf(Request $request, $databox_id) { $success = false; try { $this->getApplicationBox()->write_databox_pic( $this->app['media-alchemyst'], $this->app['filesystem'], $this->findDataboxById($databox_id), null, \databox::PIC_PDF ); $success = true; } catch (\Exception $e) { } if ('json' === $request->getRequestFormat()) { return $this->app->json([ 'success' => $success, 'msg' => $success ? $this->app->trans('Successful removal') : $this->app->trans('An error occured'), 'sbas_id' => $databox_id, ]); } // TODO: Check whether html call is still valid return $this->app->redirectPath('admin_database', [ 'databox_id' => $databox_id, 'error' => 'file-too-big', ]); }
[ "public", "function", "deleteLogoPdf", "(", "Request", "$", "request", ",", "$", "databox_id", ")", "{", "$", "success", "=", "false", ";", "try", "{", "$", "this", "->", "getApplicationBox", "(", ")", "->", "write_databox_pic", "(", "$", "this", "->", "...
Delete an existing logo for a databox @param Request $request The current HTTP request @param integer $databox_id The requested databox @return JsonResponse|RedirectResponse
[ "Delete", "an", "existing", "logo", "for", "a", "databox" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Admin/DataboxController.php#L374-L404
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Admin/DataboxController.php
DataboxController.clearLogs
public function clearLogs(Request $request, $databox_id) { $success = false; try { $this->findDataboxById($databox_id)->clear_logs(); $success = true; } catch (\Exception $e) { } if ('json' === $request->getRequestFormat()) { return $this->app->json([ 'success' => $success, 'msg' => $success ? $this->app->trans('Successful update') : $this->app->trans('An error occured'), 'sbas_id' => $databox_id, ]); } // TODO: Check whether html call is still valid return $this->app->redirectPath('admin_database', [ 'databox_id' => $databox_id, 'error' => 'file-too-big', ]); }
php
public function clearLogs(Request $request, $databox_id) { $success = false; try { $this->findDataboxById($databox_id)->clear_logs(); $success = true; } catch (\Exception $e) { } if ('json' === $request->getRequestFormat()) { return $this->app->json([ 'success' => $success, 'msg' => $success ? $this->app->trans('Successful update') : $this->app->trans('An error occured'), 'sbas_id' => $databox_id, ]); } // TODO: Check whether html call is still valid return $this->app->redirectPath('admin_database', [ 'databox_id' => $databox_id, 'error' => 'file-too-big', ]); }
[ "public", "function", "clearLogs", "(", "Request", "$", "request", ",", "$", "databox_id", ")", "{", "$", "success", "=", "false", ";", "try", "{", "$", "this", "->", "findDataboxById", "(", "$", "databox_id", ")", "->", "clear_logs", "(", ")", ";", "$...
Clear databox logs @param Request $request The current HTTP request @param integer $databox_id The requested databox @return JsonResponse|RedirectResponse
[ "Clear", "databox", "logs" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Admin/DataboxController.php#L413-L437
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Admin/DataboxController.php
DataboxController.changeViewName
public function changeViewName(Request $request, $databox_id) { if (null === $viewName = $request->request->get('viewname')) { $this->app->abort(400, $this->app->trans('Missing view name parameter')); } $success = false; try { $this->findDataboxById($databox_id)->set_viewname($viewName); $success = true; } catch (\Exception $e) { } if ('json' === $request->getRequestFormat()) { return $this->app->json([ 'success' => $success, 'msg' => $success ? $this->app->trans('Successful update') : $this->app->trans('An error occured'), 'sbas_id' => $databox_id, ]); } // TODO: Check whether html call is still valid return $this->app->redirectPath('admin_database', [ 'databox_id' => $databox_id, 'error' => 'file-too-big', ]); }
php
public function changeViewName(Request $request, $databox_id) { if (null === $viewName = $request->request->get('viewname')) { $this->app->abort(400, $this->app->trans('Missing view name parameter')); } $success = false; try { $this->findDataboxById($databox_id)->set_viewname($viewName); $success = true; } catch (\Exception $e) { } if ('json' === $request->getRequestFormat()) { return $this->app->json([ 'success' => $success, 'msg' => $success ? $this->app->trans('Successful update') : $this->app->trans('An error occured'), 'sbas_id' => $databox_id, ]); } // TODO: Check whether html call is still valid return $this->app->redirectPath('admin_database', [ 'databox_id' => $databox_id, 'error' => 'file-too-big', ]); }
[ "public", "function", "changeViewName", "(", "Request", "$", "request", ",", "$", "databox_id", ")", "{", "if", "(", "null", "===", "$", "viewName", "=", "$", "request", "->", "request", "->", "get", "(", "'viewname'", ")", ")", "{", "$", "this", "->",...
Change the name of a databox @param Request $request The current HTTP request @param integer $databox_id The requested databox @return JsonResponse|RedirectResponse
[ "Change", "the", "name", "of", "a", "databox" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Admin/DataboxController.php#L446-L474
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Admin/DataboxController.php
DataboxController.unmountDatabase
public function unmountDatabase(Request $request, $databox_id) { $success = false; try { $databox = $this->findDataboxById($databox_id); $databox->unmount_databox(); $success = true; } catch (\Exception $e) { } if ('json' === $request->getRequestFormat()) { $msg = $success ? $this->app->trans('The publication has been stopped') : $this->app->trans('An error occured'); return $this->app->json([ 'success' => $success, 'msg' => $msg, 'sbas_id' => $databox_id ]); } return $this->app->redirectPath('admin_databases', [ 'reload-tree' => 1, ]); }
php
public function unmountDatabase(Request $request, $databox_id) { $success = false; try { $databox = $this->findDataboxById($databox_id); $databox->unmount_databox(); $success = true; } catch (\Exception $e) { } if ('json' === $request->getRequestFormat()) { $msg = $success ? $this->app->trans('The publication has been stopped') : $this->app->trans('An error occured'); return $this->app->json([ 'success' => $success, 'msg' => $msg, 'sbas_id' => $databox_id ]); } return $this->app->redirectPath('admin_databases', [ 'reload-tree' => 1, ]); }
[ "public", "function", "unmountDatabase", "(", "Request", "$", "request", ",", "$", "databox_id", ")", "{", "$", "success", "=", "false", ";", "try", "{", "$", "databox", "=", "$", "this", "->", "findDataboxById", "(", "$", "databox_id", ")", ";", "$", ...
Unmount a databox @param Request $request The current HTTP request @param integer $databox_id The requested databox @return JsonResponse|RedirectResponse
[ "Unmount", "a", "databox" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Admin/DataboxController.php#L483-L510
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Admin/DataboxController.php
DataboxController.emptyDatabase
public function emptyDatabase(Request $request, $databox_id) { $msg = $this->app->trans('An error occurred'); $success = false; $taskCreated = false; try { $databox = $this->findDataboxById($databox_id); foreach ($databox->get_collections() as $collection) { if ($collection->get_record_amount() <= 500) { $collection->empty_collection(500); } else { /** @var TaskManipulator $taskManipulator */ $taskManipulator = $this->app['manipulator.task']; $taskManipulator->createEmptyCollectionJob($collection); } } $msg = $this->app->trans('Base empty successful'); $success = true; if ($taskCreated) { $msg = $this->app->trans('A task has been created, please run it to complete empty collection'); } } catch (\Exception $e) { } if ('json' === $request->getRequestFormat()) { return $this->app->json([ 'success' => $success, 'msg' => $msg, 'sbas_id' => $databox_id, ]); } // TODO: Can this method be called as HTML? return $this->app->redirectPath('admin_database', [ 'databox_id' => $databox_id, 'error' => 'file-too-big', ]); }
php
public function emptyDatabase(Request $request, $databox_id) { $msg = $this->app->trans('An error occurred'); $success = false; $taskCreated = false; try { $databox = $this->findDataboxById($databox_id); foreach ($databox->get_collections() as $collection) { if ($collection->get_record_amount() <= 500) { $collection->empty_collection(500); } else { /** @var TaskManipulator $taskManipulator */ $taskManipulator = $this->app['manipulator.task']; $taskManipulator->createEmptyCollectionJob($collection); } } $msg = $this->app->trans('Base empty successful'); $success = true; if ($taskCreated) { $msg = $this->app->trans('A task has been created, please run it to complete empty collection'); } } catch (\Exception $e) { } if ('json' === $request->getRequestFormat()) { return $this->app->json([ 'success' => $success, 'msg' => $msg, 'sbas_id' => $databox_id, ]); } // TODO: Can this method be called as HTML? return $this->app->redirectPath('admin_database', [ 'databox_id' => $databox_id, 'error' => 'file-too-big', ]); }
[ "public", "function", "emptyDatabase", "(", "Request", "$", "request", ",", "$", "databox_id", ")", "{", "$", "msg", "=", "$", "this", "->", "app", "->", "trans", "(", "'An error occurred'", ")", ";", "$", "success", "=", "false", ";", "$", "taskCreated"...
Empty a databox @param Request $request The current HTTP request @param integer $databox_id The requested databox @return JsonResponse|RedirectResponse
[ "Empty", "a", "databox" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Admin/DataboxController.php#L519-L561
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Admin/DataboxController.php
DataboxController.progressBarInfos
public function progressBarInfos(Request $request, $databox_id) { if (!$request->isXmlHttpRequest() || 'json' !== $request->getRequestFormat()) { $this->app->abort(400, $this->app->trans('Bad request format, only JSON is allowed')); } $appbox = $this->getApplicationBox(); $ret = [ 'success' => false, 'sbas_id' => null, 'msg' => $this->app->trans('An error occured'), 'indexable' => false, 'viewname' => null, 'printLogoURL' => null, 'counts' => null, ]; try { $databox = $this->findDataboxById($databox_id); $ret['sbas_id'] = $databox_id; $ret['indexable'] = $appbox->is_databox_indexable($databox); $ret['viewname'] = (($databox->get_dbname() == $databox->get_viewname()) ? $this->app->trans('admin::base: aucun alias') : $databox->get_viewname()); $ret['counts'] = $databox->get_counts(); if ($this->app['filesystem']->exists($this->app['root.path'] . '/config/minilogos/logopdf_' . $databox_id . '.jpg')) { $ret['printLogoURL'] = '/custom/minilogos/logopdf_' . $databox_id . '.jpg'; } $ret['success'] = true; $ret['msg'] = $this->app->trans('Successful update'); } catch (\Exception $e) { } return $this->app->json($ret); }
php
public function progressBarInfos(Request $request, $databox_id) { if (!$request->isXmlHttpRequest() || 'json' !== $request->getRequestFormat()) { $this->app->abort(400, $this->app->trans('Bad request format, only JSON is allowed')); } $appbox = $this->getApplicationBox(); $ret = [ 'success' => false, 'sbas_id' => null, 'msg' => $this->app->trans('An error occured'), 'indexable' => false, 'viewname' => null, 'printLogoURL' => null, 'counts' => null, ]; try { $databox = $this->findDataboxById($databox_id); $ret['sbas_id'] = $databox_id; $ret['indexable'] = $appbox->is_databox_indexable($databox); $ret['viewname'] = (($databox->get_dbname() == $databox->get_viewname()) ? $this->app->trans('admin::base: aucun alias') : $databox->get_viewname()); $ret['counts'] = $databox->get_counts(); if ($this->app['filesystem']->exists($this->app['root.path'] . '/config/minilogos/logopdf_' . $databox_id . '.jpg')) { $ret['printLogoURL'] = '/custom/minilogos/logopdf_' . $databox_id . '.jpg'; } $ret['success'] = true; $ret['msg'] = $this->app->trans('Successful update'); } catch (\Exception $e) { } return $this->app->json($ret); }
[ "public", "function", "progressBarInfos", "(", "Request", "$", "request", ",", "$", "databox_id", ")", "{", "if", "(", "!", "$", "request", "->", "isXmlHttpRequest", "(", ")", "||", "'json'", "!==", "$", "request", "->", "getRequestFormat", "(", ")", ")", ...
Get number of indexed items for a databox @param Request $request The current HTTP request @param integer $databox_id The requested databox @return JsonResponse
[ "Get", "number", "of", "indexed", "items", "for", "a", "databox" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Admin/DataboxController.php#L570-L608
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Admin/DataboxController.php
DataboxController.getReorder
public function getReorder($databox_id) { $acl = $this->getAclForUser(); return $this->render('admin/collection/reorder.html.twig', [ 'collections' => $acl->get_granted_base([], [$databox_id]), ]); }
php
public function getReorder($databox_id) { $acl = $this->getAclForUser(); return $this->render('admin/collection/reorder.html.twig', [ 'collections' => $acl->get_granted_base([], [$databox_id]), ]); }
[ "public", "function", "getReorder", "(", "$", "databox_id", ")", "{", "$", "acl", "=", "$", "this", "->", "getAclForUser", "(", ")", ";", "return", "$", "this", "->", "render", "(", "'admin/collection/reorder.html.twig'", ",", "[", "'collections'", "=>", "$"...
Display page for reorder collections on a databox @param integer $databox_id The requested databox @return Response
[ "Display", "page", "for", "reorder", "collections", "on", "a", "databox" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Admin/DataboxController.php#L616-L623
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Admin/DataboxController.php
DataboxController.setReorder
public function setReorder(Request $request, $databox_id) { try { foreach ($request->request->get('order', []) as $data) { $collection = \collection::getByBaseId($this->app, $data['id']); $collection->set_ord($data['offset']); } $success = true; } catch (\Exception $e) { $success = false; } if ('json' === $request->getRequestFormat()) { return $this->app->json([ 'success' => $success, 'msg' => $success ? $this->app->trans('Successful update') : $this->app->trans('An error occured'), 'sbas_id' => $databox_id, ]); } return $this->app->redirectPath('admin_database_display_collections_order', [ 'databox_id' => $databox_id, 'success' => (int) $success, ]); }
php
public function setReorder(Request $request, $databox_id) { try { foreach ($request->request->get('order', []) as $data) { $collection = \collection::getByBaseId($this->app, $data['id']); $collection->set_ord($data['offset']); } $success = true; } catch (\Exception $e) { $success = false; } if ('json' === $request->getRequestFormat()) { return $this->app->json([ 'success' => $success, 'msg' => $success ? $this->app->trans('Successful update') : $this->app->trans('An error occured'), 'sbas_id' => $databox_id, ]); } return $this->app->redirectPath('admin_database_display_collections_order', [ 'databox_id' => $databox_id, 'success' => (int) $success, ]); }
[ "public", "function", "setReorder", "(", "Request", "$", "request", ",", "$", "databox_id", ")", "{", "try", "{", "foreach", "(", "$", "request", "->", "request", "->", "get", "(", "'order'", ",", "[", "]", ")", "as", "$", "data", ")", "{", "$", "c...
Apply collection reorder changes @param Request $request The current HTTP request @param integer $databox_id The requested databox @return JsonResponse|RedirectResponse
[ "Apply", "collection", "reorder", "changes" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Admin/DataboxController.php#L632-L656
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Admin/DataboxController.php
DataboxController.createCollection
public function createCollection(Request $request, $databox_id) { if (($name = trim($request->request->get('name', ''))) === '') { return $this->app->redirectPath('admin_database_display_new_collection_form', [ 'databox_id' => $databox_id, 'error' => 'name', ]); } try { $databox = $this->findDataboxById($databox_id); $collection = \collection::create( $this->app, $databox, $this->getApplicationBox(), $name, $this->getAuthenticator()->getUser() ); if (($request->request->get('ccusrothercoll') === "on") && (null !== $othcollsel = $request->request->get('othcollsel'))) { $query = $this->createUserQuery(); $total = $query->on_base_ids([$othcollsel])->get_total(); $n = 0; while ($n < $total) { $results = $query->limit($n, 20)->execute()->get_results(); foreach ($results as $user) { $this->getAclForUser($user)->duplicate_right_from_bas($othcollsel, $collection->get_base_id()); } $n += 20; } } return $this->app->redirectPath('admin_display_collection', [ 'bas_id' => $collection->get_base_id(), 'success' => 1, 'reload-tree' => 1, ]); } catch (\Exception $e) { return $this->app->redirectPath('admin_database_submit_collection', [ 'databox_id' => $databox_id, 'error' => $e->getMessage(), ]); } }
php
public function createCollection(Request $request, $databox_id) { if (($name = trim($request->request->get('name', ''))) === '') { return $this->app->redirectPath('admin_database_display_new_collection_form', [ 'databox_id' => $databox_id, 'error' => 'name', ]); } try { $databox = $this->findDataboxById($databox_id); $collection = \collection::create( $this->app, $databox, $this->getApplicationBox(), $name, $this->getAuthenticator()->getUser() ); if (($request->request->get('ccusrothercoll') === "on") && (null !== $othcollsel = $request->request->get('othcollsel'))) { $query = $this->createUserQuery(); $total = $query->on_base_ids([$othcollsel])->get_total(); $n = 0; while ($n < $total) { $results = $query->limit($n, 20)->execute()->get_results(); foreach ($results as $user) { $this->getAclForUser($user)->duplicate_right_from_bas($othcollsel, $collection->get_base_id()); } $n += 20; } } return $this->app->redirectPath('admin_display_collection', [ 'bas_id' => $collection->get_base_id(), 'success' => 1, 'reload-tree' => 1, ]); } catch (\Exception $e) { return $this->app->redirectPath('admin_database_submit_collection', [ 'databox_id' => $databox_id, 'error' => $e->getMessage(), ]); } }
[ "public", "function", "createCollection", "(", "Request", "$", "request", ",", "$", "databox_id", ")", "{", "if", "(", "(", "$", "name", "=", "trim", "(", "$", "request", "->", "request", "->", "get", "(", "'name'", ",", "''", ")", ")", ")", "===", ...
Create a new collection @param Request $request The current HTTP request @param integer $databox_id The requested databox @return Response
[ "Create", "a", "new", "collection" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Admin/DataboxController.php#L675-L718
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Controller/Admin/DataboxController.php
DataboxController.getDetails
public function getDetails(Request $request, $databox_id) { $databox = $this->findDataboxById($databox_id); $details = []; $total = ['total_subdefs' => 0, 'total_size' => 0]; foreach ($databox->get_record_details($request->query->get('sort')) as $collName => $colDetails) { $details[$collName] = [ 'total_subdefs' => 0, 'total_size' => 0, 'medias' => [] ]; foreach ($colDetails as $subdefName => $subdefDetails) { $details[$collName]['total_subdefs'] += $subdefDetails['n']; $total['total_subdefs'] += $subdefDetails['n']; $details[$collName]['total_size'] += $subdefDetails['siz']; $total['total_size'] += $subdefDetails['siz']; $details[$collName]['medias'][] = [ 'subdef_name' => $subdefName, 'total_subdefs' => $subdefDetails['n'], 'total_size' => $subdefDetails['siz'], ]; } } return $this->render('admin/databox/details.html.twig', [ 'databox' => $databox, 'table' => $details, 'total' => $total ]); }
php
public function getDetails(Request $request, $databox_id) { $databox = $this->findDataboxById($databox_id); $details = []; $total = ['total_subdefs' => 0, 'total_size' => 0]; foreach ($databox->get_record_details($request->query->get('sort')) as $collName => $colDetails) { $details[$collName] = [ 'total_subdefs' => 0, 'total_size' => 0, 'medias' => [] ]; foreach ($colDetails as $subdefName => $subdefDetails) { $details[$collName]['total_subdefs'] += $subdefDetails['n']; $total['total_subdefs'] += $subdefDetails['n']; $details[$collName]['total_size'] += $subdefDetails['siz']; $total['total_size'] += $subdefDetails['siz']; $details[$collName]['medias'][] = [ 'subdef_name' => $subdefName, 'total_subdefs' => $subdefDetails['n'], 'total_size' => $subdefDetails['siz'], ]; } } return $this->render('admin/databox/details.html.twig', [ 'databox' => $databox, 'table' => $details, 'total' => $total ]); }
[ "public", "function", "getDetails", "(", "Request", "$", "request", ",", "$", "databox_id", ")", "{", "$", "databox", "=", "$", "this", "->", "findDataboxById", "(", "$", "databox_id", ")", ";", "$", "details", "=", "[", "]", ";", "$", "total", "=", ...
Display page to get some details on a appbox @param Request $request The current HTTP request @param integer $databox_id The requested databox @return Response
[ "Display", "page", "to", "get", "some", "details", "on", "a", "appbox" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Controller/Admin/DataboxController.php#L727-L760
alchemy-fr/Phraseanet
lib/classes/databox/field.php
databox_field.set_label
public function set_label($code, $value) { if (!array_key_exists($code, $this->labels)) { throw new InvalidArgumentException(sprintf('Code %s is not defined', $code)); } $this->labels[$code] = $value; return $this; }
php
public function set_label($code, $value) { if (!array_key_exists($code, $this->labels)) { throw new InvalidArgumentException(sprintf('Code %s is not defined', $code)); } $this->labels[$code] = $value; return $this; }
[ "public", "function", "set_label", "(", "$", "code", ",", "$", "value", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "code", ",", "$", "this", "->", "labels", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'...
Sets a localized label for the field. @param string $code @param null|string $value @return \databox_field @throws InvalidArgumentException
[ "Sets", "a", "localized", "label", "for", "the", "field", "." ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/databox/field.php#L413-L422
alchemy-fr/Phraseanet
lib/classes/databox/field.php
databox_field.get_label
public function get_label($code) { if (!array_key_exists($code, $this->labels)) { throw new InvalidArgumentException(sprintf('Code %s is not defined', $code)); } return isset($this->labels[$code]) && '' !== $this->labels[$code] ? $this->labels[$code] : $this->name; }
php
public function get_label($code) { if (!array_key_exists($code, $this->labels)) { throw new InvalidArgumentException(sprintf('Code %s is not defined', $code)); } return isset($this->labels[$code]) && '' !== $this->labels[$code] ? $this->labels[$code] : $this->name; }
[ "public", "function", "get_label", "(", "$", "code", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "code", ",", "$", "this", "->", "labels", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'Code %s is not defined'",...
Gets a localized label for the field. @param string $code @return string @throws InvalidArgumentException
[ "Gets", "a", "localized", "label", "for", "the", "field", "." ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/databox/field.php#L433-L440
alchemy-fr/Phraseanet
lib/classes/databox/field.php
databox_field.set_name
public function set_name($name) { $previous_name = $this->name; $name = self::generateName($name, $this->app['unicode']); if ($name === '') { throw new \Exception_InvalidArgument(); } $this->name = $name; if ($this->name !== $previous_name) { $this->renamed = true; } return $this; }
php
public function set_name($name) { $previous_name = $this->name; $name = self::generateName($name, $this->app['unicode']); if ($name === '') { throw new \Exception_InvalidArgument(); } $this->name = $name; if ($this->name !== $previous_name) { $this->renamed = true; } return $this; }
[ "public", "function", "set_name", "(", "$", "name", ")", "{", "$", "previous_name", "=", "$", "this", "->", "name", ";", "$", "name", "=", "self", "::", "generateName", "(", "$", "name", ",", "$", "this", "->", "app", "[", "'unicode'", "]", ")", ";...
@param string $name @return databox_field @throws Exception_InvalidArgument
[ "@param", "string", "$name", "@return", "databox_field" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/databox/field.php#L458-L475
alchemy-fr/Phraseanet
lib/classes/databox/field.php
databox_field.loadClassFromTagName
public static function loadClassFromTagName($tagName, $throwException = true) { $tagName = str_ireplace('/rdf:rdf/rdf:description/', '', $tagName); if ('' === trim($tagName)) { return new NoSource(); } try { return TagFactory::getFromTagname($tagName); } catch (TagUnknown $exception) { if ($throwException) { throw new NotFoundHttpException(sprintf("Tag %s not found", $tagName), $exception); } } return new NoSource($tagName); }
php
public static function loadClassFromTagName($tagName, $throwException = true) { $tagName = str_ireplace('/rdf:rdf/rdf:description/', '', $tagName); if ('' === trim($tagName)) { return new NoSource(); } try { return TagFactory::getFromTagname($tagName); } catch (TagUnknown $exception) { if ($throwException) { throw new NotFoundHttpException(sprintf("Tag %s not found", $tagName), $exception); } } return new NoSource($tagName); }
[ "public", "static", "function", "loadClassFromTagName", "(", "$", "tagName", ",", "$", "throwException", "=", "true", ")", "{", "$", "tagName", "=", "str_ireplace", "(", "'/rdf:rdf/rdf:description/'", ",", "''", ",", "$", "tagName", ")", ";", "if", "(", "''"...
Get a PHPExiftool Tag from tagName @param string $tagName @param bool $throwException @return object Makes phpstorm hangs \PHPExiftool\Driver\TagInterface
[ "Get", "a", "PHPExiftool", "Tag", "from", "tagName" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/classes/databox/field.php#L484-L501
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/Authentication/Provider/Linkedin.php
Linkedin.getIdentity
public function getIdentity() { $identity = new Identity(); try { $request = $this->client->get('https://api.linkedin.com/v1/people/~:(id,first-name,last-name,positions,industry,picture-url;secure=true,email-address)'); $request->getQuery() ->add('oauth2_access_token', $this->session->get('linkedin.provider.access_token')) ->add('format', 'json'); $response = $request->send(); } catch (GuzzleException $e) { throw new NotAuthenticatedException('Unable to fetch LinkedIn identity', $e->getCode(), $e); } if (200 !== $response->getStatusCode()) { throw new NotAuthenticatedException('Error while retrieving user info'); } $data = @json_decode($response->getBody(true), true); if (JSON_ERROR_NONE !== json_last_error()) { throw new NotAuthenticatedException('Unable to parse Linkedin JSON identity'); } if (0 < $data['positions']['_total']) { $position = array_pop($data['positions']['values']); $identity->set(Identity::PROPERTY_COMPANY, $position['company']['name']); } $identity->set(Identity::PROPERTY_EMAIL, $data['emailAddress']); $identity->set(Identity::PROPERTY_FIRSTNAME, $data['firstName']); $identity->set(Identity::PROPERTY_ID, $data['id']); $identity->set(Identity::PROPERTY_IMAGEURL, $data['pictureUrl']); $identity->set(Identity::PROPERTY_LASTNAME, $data['lastName']); return $identity; }
php
public function getIdentity() { $identity = new Identity(); try { $request = $this->client->get('https://api.linkedin.com/v1/people/~:(id,first-name,last-name,positions,industry,picture-url;secure=true,email-address)'); $request->getQuery() ->add('oauth2_access_token', $this->session->get('linkedin.provider.access_token')) ->add('format', 'json'); $response = $request->send(); } catch (GuzzleException $e) { throw new NotAuthenticatedException('Unable to fetch LinkedIn identity', $e->getCode(), $e); } if (200 !== $response->getStatusCode()) { throw new NotAuthenticatedException('Error while retrieving user info'); } $data = @json_decode($response->getBody(true), true); if (JSON_ERROR_NONE !== json_last_error()) { throw new NotAuthenticatedException('Unable to parse Linkedin JSON identity'); } if (0 < $data['positions']['_total']) { $position = array_pop($data['positions']['values']); $identity->set(Identity::PROPERTY_COMPANY, $position['company']['name']); } $identity->set(Identity::PROPERTY_EMAIL, $data['emailAddress']); $identity->set(Identity::PROPERTY_FIRSTNAME, $data['firstName']); $identity->set(Identity::PROPERTY_ID, $data['id']); $identity->set(Identity::PROPERTY_IMAGEURL, $data['pictureUrl']); $identity->set(Identity::PROPERTY_LASTNAME, $data['lastName']); return $identity; }
[ "public", "function", "getIdentity", "(", ")", "{", "$", "identity", "=", "new", "Identity", "(", ")", ";", "try", "{", "$", "request", "=", "$", "this", "->", "client", "->", "get", "(", "'https://api.linkedin.com/v1/people/~:(id,first-name,last-name,positions,in...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/Authentication/Provider/Linkedin.php#L192-L229
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/SearchEngine/Elastic/ElasticSearchEngine.php
ElasticSearchEngine.getStatus
public function getStatus() { $data = $this->client->info(); $version = $data['version']; unset($data['version']); foreach ($version as $prop => $value) { $data['version:'.$prop] = $value; } $ret = []; foreach ($data as $key => $value) { $ret[] = [$key, $value]; } return $ret; }
php
public function getStatus() { $data = $this->client->info(); $version = $data['version']; unset($data['version']); foreach ($version as $prop => $value) { $data['version:'.$prop] = $value; } $ret = []; foreach ($data as $key => $value) { $ret[] = [$key, $value]; } return $ret; }
[ "public", "function", "getStatus", "(", ")", "{", "$", "data", "=", "$", "this", "->", "client", "->", "info", "(", ")", ";", "$", "version", "=", "$", "data", "[", "'version'", "]", ";", "unset", "(", "$", "data", "[", "'version'", "]", ")", ";"...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/SearchEngine/Elastic/ElasticSearchEngine.php#L106-L123
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/SearchEngine/Elastic/ElasticSearchEngine.php
ElasticSearchEngine.getAvailableSort
public function getAvailableSort() { return [ SearchEngineOptions::SORT_RELEVANCE => $this->app->trans('pertinence'), SearchEngineOptions::SORT_CREATED_ON => $this->app->trans('date dajout'), SearchEngineOptions::SORT_UPDATED_ON => $this->app->trans('date de modification'), ]; }
php
public function getAvailableSort() { return [ SearchEngineOptions::SORT_RELEVANCE => $this->app->trans('pertinence'), SearchEngineOptions::SORT_CREATED_ON => $this->app->trans('date dajout'), SearchEngineOptions::SORT_UPDATED_ON => $this->app->trans('date de modification'), ]; }
[ "public", "function", "getAvailableSort", "(", ")", "{", "return", "[", "SearchEngineOptions", "::", "SORT_RELEVANCE", "=>", "$", "this", "->", "app", "->", "trans", "(", "'pertinence'", ")", ",", "SearchEngineOptions", "::", "SORT_CREATED_ON", "=>", "$", "this"...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/SearchEngine/Elastic/ElasticSearchEngine.php#L137-L144
alchemy-fr/Phraseanet
lib/Alchemy/Phrasea/SearchEngine/Elastic/ElasticSearchEngine.php
ElasticSearchEngine.getAvailableOrder
public function getAvailableOrder() { return [ SearchEngineOptions::SORT_MODE_DESC => $this->app->trans('descendant'), SearchEngineOptions::SORT_MODE_ASC => $this->app->trans('ascendant'), ]; }
php
public function getAvailableOrder() { return [ SearchEngineOptions::SORT_MODE_DESC => $this->app->trans('descendant'), SearchEngineOptions::SORT_MODE_ASC => $this->app->trans('ascendant'), ]; }
[ "public", "function", "getAvailableOrder", "(", ")", "{", "return", "[", "SearchEngineOptions", "::", "SORT_MODE_DESC", "=>", "$", "this", "->", "app", "->", "trans", "(", "'descendant'", ")", ",", "SearchEngineOptions", "::", "SORT_MODE_ASC", "=>", "$", "this",...
{@inheritdoc}
[ "{" ]
train
https://github.com/alchemy-fr/Phraseanet/blob/904b67192e276ab4706efb7b72df4910f9e00973/lib/Alchemy/Phrasea/SearchEngine/Elastic/ElasticSearchEngine.php#L173-L179