sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
protected function _inpath($path, $parent) {
$real_path = realpath($path);
$real_parent = realpath($parent);
if ($real_path && $real_parent) {
return $real_path === $real_parent || strpos($real_path, rtrim($real_parent, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR) === 0;
}
return false;
}
|
Return true if $path is children of $parent
@param string $path path to check
@param string $parent parent path
@return bool
@author Dmitry (dio) Levashov
|
entailment
|
protected function _stat($path) {
$stat = array();
if (!file_exists($path)) {
return $stat;
}
//Verifies the given path is the root or is inside the root. Prevents directory traveral.
if (!$this->aroot) {
// for Inheritance class ( not calling parent::configure() )
$this->aroot = realpath($this->root);
}
if (!$this->_inpath($path, $this->aroot)) {
return $stat;
}
if ($path != $this->root && is_link($path)) {
if (($target = $this->readlink($path)) == false
|| $target == $path) {
$stat['mime'] = 'symlink-broken';
$stat['read'] = false;
$stat['write'] = false;
$stat['size'] = 0;
return $stat;
}
$stat['alias'] = $this->_path($target);
$stat['target'] = $target;
$path = $target;
$lstat = lstat($path);
$size = sprintf('%u', $lstat['size']);
} else {
$size = sprintf('%u', @filesize($path));
}
$dir = is_dir($path);
$stat['mime'] = $dir ? 'directory' : $this->mimetype($path);
$stat['ts'] = filemtime($path);
//logical rights first
$stat['read'] = is_readable($path)? null : false;
$stat['write'] = is_writable($path)? null : false;
if (is_null($stat['read'])) {
$stat['size'] = $dir ? 0 : $size;
}
return $stat;
}
|
Return stat for given path.
Stat contains following fields:
- (int) size file size in b. required
- (int) ts file modification time in unix time. required
- (string) mime mimetype. required for folders, others - optionally
- (bool) read read permissions. required
- (bool) write write permissions. required
- (bool) locked is object locked. optionally
- (bool) hidden is object hidden. optionally
- (string) alias for symlinks - link target path relative to root path. optionally
- (string) target for symlinks - link target path. optionally
If file does not exists - returns empty array or false.
@param string $path file path
@return array|false
@author Dmitry (dio) Levashov
|
entailment
|
protected function _subdirs($path) {
if (($dir = dir($path))) {
$dir = dir($path);
while (($entry = $dir->read()) !== false) {
$p = $dir->path.DIRECTORY_SEPARATOR.$entry;
if ($entry != '.' && $entry != '..' && is_dir($p) && !$this->attr($p, 'hidden')) {
$dir->close();
return true;
}
}
$dir->close();
}
return false;
}
|
Return true if path is dir and has at least one childs directory
@param string $path dir path
@return bool
@author Dmitry (dio) Levashov
|
entailment
|
protected function _dimensions($path, $mime) {
clearstatcache();
return strpos($mime, 'image') === 0 && ($s = @getimagesize($path)) !== false
? $s[0].'x'.$s[1]
: false;
}
|
Return object width and height
Usualy used for images, but can be realize for video etc...
@param string $path file path
@param string $mime file mime type
@return string
@author Dmitry (dio) Levashov
|
entailment
|
protected function readlink($path) {
if (!($target = @readlink($path))) {
return false;
}
if (substr($target, 0, 1) != DIRECTORY_SEPARATOR) {
$target = dirname($path).DIRECTORY_SEPARATOR.$target;
}
if ($this->_inpath($target, $this->aroot)) {
$atarget = realpath($target);
return $this->_normpath($this->root.DIRECTORY_SEPARATOR.substr($atarget, strlen($this->aroot)+1));
}
return false;
}
|
Return symlink target file
@param string $path link path
@return string
@author Dmitry (dio) Levashov
|
entailment
|
protected function _scandir($path) {
$files = array();
foreach (scandir($path) as $name) {
if ($name != '.' && $name != '..') {
$files[] = $path.DIRECTORY_SEPARATOR.$name;
}
}
return $files;
}
|
Return files list in directory.
@param string $path dir path
@return array
@author Dmitry (dio) Levashov
|
entailment
|
protected function _mkdir($path, $name) {
$path = $path.DIRECTORY_SEPARATOR.$name;
if (@mkdir($path)) {
@chmod($path, $this->options['dirMode']);
return $path;
}
return false;
}
|
Create dir and return created dir path or false on failed
@param string $path parent dir path
@param string $name new directory name
@return string|bool
@author Dmitry (dio) Levashov
|
entailment
|
protected function _mkfile($path, $name) {
$path = $path.DIRECTORY_SEPARATOR.$name;
if (($fp = @fopen($path, 'w'))) {
@fclose($fp);
@chmod($path, $this->options['fileMode']);
return $path;
}
return false;
}
|
Create file and return it's path or false on failed
@param string $path parent dir path
@param string $name new file name
@return string|bool
@author Dmitry (dio) Levashov
|
entailment
|
protected function _move($source, $targetDir, $name) {
$target = $targetDir.DIRECTORY_SEPARATOR.$name;
return @rename($source, $target) ? $target : false;
}
|
Move file into another parent dir.
Return new file path or false.
@param string $source source file path
@param string $target target dir path
@param string $name file name
@return string|bool
@author Dmitry (dio) Levashov
|
entailment
|
protected function _save($fp, $dir, $name, $stat) {
$path = $dir.DIRECTORY_SEPARATOR.$name;
if (@file_put_contents($path, $fp, LOCK_EX) === false) {
return false;
}
@chmod($path, $this->options['fileMode']);
clearstatcache();
return $path;
}
|
Create new file and write into it from file pointer.
Return new file path or false on error.
@param resource $fp file pointer
@param string $dir target dir path
@param string $name file name
@param array $stat file stat (required by some virtual fs)
@return bool|string
@author Dmitry (dio) Levashov
|
entailment
|
protected function _filePutContents($path, $content) {
if (@file_put_contents($path, $content, LOCK_EX) !== false) {
clearstatcache();
return true;
}
return false;
}
|
Write a string to a file
@param string $path file path
@param string $content new file content
@return bool
@author Dmitry (dio) Levashov
|
entailment
|
protected function _unpack($path, $arc) {
$cwd = getcwd();
$dir = $this->_dirname($path);
chdir($dir);
$cmd = $arc['cmd'].' '.$arc['argc'].' '.escapeshellarg($this->_basename($path));
$this->procExec($cmd, $o, $c);
chdir($cwd);
}
|
Unpack archive
@param string $path archive path
@param array $arc archiver command and arguments (same as in $this->archivers)
@return void
@author Dmitry (dio) Levashov
@author Alexey Sukhotin
|
entailment
|
protected function _findSymlinks($path) {
if (is_link($path)) {
return true;
}
if (is_dir($path)) {
foreach (scandir($path) as $name) {
if ($name != '.' && $name != '..') {
$p = $path.DIRECTORY_SEPARATOR.$name;
if (is_link($p) || !$this->nameAccepted($name)) {
$this->setError(elFinder::ERROR_SAVE, $name);
return true;
}
if (is_dir($p) && $this->_findSymlinks($p)) {
return true;
} elseif (is_file($p)) {
$this->archiveSize += sprintf('%u', filesize($p));
}
}
}
} else {
$this->archiveSize += sprintf('%u', filesize($path));
}
return false;
}
|
Recursive symlinks search
@param string $path file/dir path
@return bool
@author Dmitry (dio) Levashov
|
entailment
|
protected function _extract($path, $arc) {
if ($this->quarantine) {
$dir = $this->quarantine.DIRECTORY_SEPARATOR.md5(basename($path).mt_rand());
$archive = $dir.DIRECTORY_SEPARATOR.basename($path);
if (!@mkdir($dir)) {
return false;
}
// insurance unexpected shutdown
register_shutdown_function(array($this, 'rmdirRecursive'), realpath($dir));
chmod($dir, 0777);
// copy in quarantine
if (!copy($path, $archive)) {
return false;
}
// extract in quarantine
$this->_unpack($archive, $arc);
unlink($archive);
// get files list
$ls = array();
foreach (scandir($dir) as $i => $name) {
if ($name != '.' && $name != '..') {
$ls[] = $name;
}
}
// no files - extract error ?
if (empty($ls)) {
return false;
}
$this->archiveSize = 0;
// find symlinks
$symlinks = $this->_findSymlinks($dir);
if ($symlinks) {
$this->delTree($dir);
return $this->setError(array_merge($this->error, array(elFinder::ERROR_ARC_SYMLINKS)));
}
// check max files size
if ($this->options['maxArcFilesSize'] > 0 && $this->options['maxArcFilesSize'] < $this->archiveSize) {
$this->delTree($dir);
return $this->setError(elFinder::ERROR_ARC_MAXSIZE);
}
// archive contains one item - extract in archive dir
$src = $dir.DIRECTORY_SEPARATOR.$ls[0];
if (count($ls) === 1 && is_file($src)) {
$name = $ls[0];
} else {
// for several files - create new directory
// create unique name for directory
$src = $dir;
$name = basename($path);
if (preg_match('/\.((tar\.(gz|bz|bz2|z|lzo))|cpio\.gz|ps\.gz|xcf\.(gz|bz2)|[a-z0-9]{1,4})$/i', $name, $m)) {
$name = substr($name, 0, strlen($name)-strlen($m[0]));
}
$test = dirname($path).DIRECTORY_SEPARATOR.$name;
if (file_exists($test) || is_link($test)) {
$name = $this->uniqueName(dirname($path), $name, '-', false);
}
}
$result = dirname($path).DIRECTORY_SEPARATOR.$name;
if (! @rename($src, $result)) {
$this->delTree($dir);
return false;
}
is_dir($dir) && $this->delTree($dir);
return file_exists($result) ? $result : false;
}
}
|
Extract files from archive
@param string $path archive path
@param array $arc archiver command and arguments (same as in $this->archivers)
@return true
@author Dmitry (dio) Levashov,
@author Alexey Sukhotin
|
entailment
|
protected function _archive($dir, $files, $name, $arc) {
$cwd = getcwd();
chdir($dir);
$files = array_map('escapeshellarg', $files);
$cmd = $arc['cmd'].' '.$arc['argc'].' '.escapeshellarg($name).' '.implode(' ', $files);
$this->procExec($cmd, $o, $c);
chdir($cwd);
$path = $dir.DIRECTORY_SEPARATOR.$name;
return file_exists($path) ? $path : false;
}
|
Create archive and return its path
@param string $dir target dir
@param array $files files names list
@param string $name archive name
@param array $arc archiver options
@return string|bool
@author Dmitry (dio) Levashov,
@author Alexey Sukhotin
|
entailment
|
public function settingsValidate(Event $event, array $data, ArrayObject $options)
{
if (!empty($options['entity']) && $options['entity']->has('name')) {
$validator = new Validator();
$this->trigger("Plugin.{$options['entity']->name}.settingsValidate", $data, $validator);
$errors = $validator->errors($data, $options['entity']->isNew());
if (!empty($errors)) {
foreach ($errors as $k => $v) {
$options['entity']->errors("settings:{$k}", $v);
}
}
}
}
|
Validates plugin settings before persisted in DB.
@param \Cake\Event\Event $event The event that was triggered
@param array $data Information to be validated
@param \ArrayObject $options Options given to pathEntity()
@return void
|
entailment
|
public function settingsDefaultValues(Event $event, Entity $plugin)
{
if ($plugin->has('name')) {
return (array)$this->trigger("Plugin.{$plugin->name}.settingsDefaults", $plugin)->result;
}
return [];
}
|
Here we set default values for plugin's settings.
Triggers the `Plugin.<PluginName>.settingsDefaults` event, event listeners
should catch the event and return an array as `key` => `value` with default
values.
@param \Cake\Event\Event $event The event that was triggered
@param \Cake\ORM\Entity $plugin The plugin entity where to put those values
@return array
|
entailment
|
public function beforeSave(Event $event, Entity $plugin, ArrayObject $options = null)
{
if ($plugin->isNew()) {
$max = $this->find()
->order(['ordering' => 'DESC'])
->limit(1)
->first();
$plugin->set('ordering', $max->ordering + 1);
}
}
|
Set plugin's load ordering to LAST if it's a new plugin being installed.
@param \Cake\Event\Event $event The event that was triggered
@param \Cake\ORM\Entity $plugin The Plugin entity being saved
@param \ArrayObject $options The options passed to the save method
@return void
|
entailment
|
public function afterSave(Event $event, Entity $plugin, ArrayObject $options = null)
{
snapshot();
$this->clearCache();
}
|
This method automatically regenerates system's snapshot.
@param \Cake\Event\Event $event The event that was triggered
@param \Cake\ORM\Entity $plugin The Plugin entity that was saved
@param \ArrayObject $options The options passed to the save method
@return void
|
entailment
|
public function offsetGet($index)
{
if (is_string($index) && isset($this->_keysMap[$index])) {
$index = $this->_keysMap[$index];
}
return parent::offsetGet($index);
}
|
Allows access fields by numeric index or by machine-name.
### Example:
```php
$fields => [
[0] => [
[name] => user-age,
[label] => User Age,
[value] => 22,
[extra] => null,
[metadata] => [ ... ]
],
[1] => [
[name] => user-phone,
[label] => User Phone,
[value] => null,
[extra] => null,
[metadata] => [ ... ]
]
];
$collection = new FieldCollection($fields);
if ($collection[1] === $collection['user-phone']) {
echo "SUCCESS";
}
// outputs: SUCCESS
```
@param int|string $index Numeric index or machine-name
@return mixed \Field\Model\Entity\Field on success or NULL on failure
|
entailment
|
public function sortByViewMode($viewMode, $dir = SORT_ASC)
{
$items = [];
$sorted = $this->sortBy(function ($field) use ($viewMode) {
if (isset($field->metadata->view_modes[$viewMode])) {
return $field->metadata->view_modes[$viewMode]['ordering'];
}
return 0;
}, $dir);
foreach ($sorted as $item) {
$items[] = $item;
}
return new FieldCollection($items);
}
|
Sorts the list of fields by view mode ordering.
Fields might have different orderings for each view mode.
@param string $viewMode View mode slug to use for sorting
@param int $dir either SORT_DESC or SORT_ASC
@return \Field\Collection\FieldCollection
|
entailment
|
public function beforeFind(Event $event, Query $query, ArrayObject $options, $primary)
{
$query->formatResults(function ($results) {
return $results->map(function ($revision) {
try {
if (isset($revision->data->content_type_id)) {
$contentType = TableRegistry::get('Content.ContentTypes')
->find()
->where(['id' => $revision->data->content_type_id])
->first();
$revision->data->set('content_type', $contentType);
}
} catch (\Exception $e) {
$revision->data->set('content_type', false);
}
return $revision;
});
});
return $query;
}
|
Attaches ContentType information to each content revision.
@param \Cake\Event\Event $event The event that was triggered
@param \Cake\ORM\Query $query The query object
@param \ArrayObject $options Additional options given as an array
@param bool $primary Whether this find is a primary query or not
@return Query
|
entailment
|
public static function parse($text, $context = null)
{
if (!static::$_enabled || strpos($text, '{') === false) {
return $text;
}
if ($context === null) {
$context = static::_getDefaultContext();
}
static::cache('context', $context);
$pattern = static::_regex();
return preg_replace_callback("/{$pattern}/s", 'static::_doShortcode', $text);
}
|
Look for shortcodes in the given $text.
@param string $text The content to parse
@param object $context The context for \Cake\Event\Event::$subject, if not
given an instance of this class will be used
@return string
|
entailment
|
public static function escape($text)
{
$tagregexp = implode('|', array_map('preg_quote', static::_list()));
preg_match_all('/(.?){(' . $tagregexp . ')\b(.*?)(?:(\/))?}(?:(.+?){\/\2})?(.?)/s', $text, $matches);
foreach ($matches[0] as $ht) {
$replace = str_replace_once('{', '{{', $ht);
$replace = str_replace_last('}', '}}', $replace);
$text = str_replace($ht, $replace, $text);
}
return $text;
}
|
Escapes all shortcodes from the given content.
@param string $text Text from which to escape shortcodes
@return string Content with all shortcodes escaped
|
entailment
|
protected static function _list()
{
if (empty(static::$_listeners)) {
$manager = EventDispatcher::instance('Shortcode')->eventManager();
static::$_listeners = listeners($manager);
}
return static::$_listeners;
}
|
Returns a list of all registered shortcodes.
@return array
|
entailment
|
protected static function _getDefaultContext()
{
if (!static::$_defaultContext) {
static::$_defaultContext = new View(Router::getRequest(), null, EventManager::instance(), []);
}
return static::$_defaultContext;
}
|
Gets default context to use.
@return \CMS\View\View
|
entailment
|
protected static function _doShortcode($m)
{
// allow {{foo}} syntax for escaping a tag
if ($m[1] == '{' && $m[6] == '}') {
return substr($m[0], 1, -1);
}
$tag = $m[2];
$atts = static::_parseAttributes($m[3]);
$listeners = EventDispatcher::instance('Shortcode')
->eventManager()
->listeners($tag);
if (!empty($listeners)) {
$options = [
'atts' => (array)$atts,
'content' => null,
'tag' => $tag
];
if (isset($m[5])) {
$options['content'] = $m[5];
}
$result = EventDispatcher::instance('Shortcode')
->triggerArray([$tag, static::cache('context')], $options)
->result;
return $m[1] . $result . $m[6];
}
return '';
}
|
Invokes shortcode lister method for the given shortcode.
@param array $m Shortcode as preg array
@return string
@author WordPress
|
entailment
|
public function main()
{
$this->loadModel('System.Plugins');
try {
$plugin = plugin($this->params['plugin']);
$existsInDb = (bool)$this->Plugins
->find()
->where(['name' => $this->params['plugin']])
->count();
} catch (\Exception $e) {
$plugin = $existsInDb = false;
}
if (!$plugin || !$existsInDb) {
$this->err(__d('installer', 'Plugin "{0}" was not found.', $this->params['plugin']));
return false;
}
if ($this->params['status'] === 'enable') {
return $this->_enable($plugin);
}
return $this->_disable($plugin);
}
|
Task main method.
@return bool
|
entailment
|
protected function _enable(PluginPackage $plugin)
{
$checker = new RuleChecker((array)$plugin->composer['require']);
if (!$checker->check()) {
$this->err(__d('installer', 'Plugin "{0}" cannot be enabled as some dependencies are disabled or not installed: {1}', $plugin->humanName, $checker->fail(true)));
return false;
}
// MENTAL NOTE: As plugin is disabled its listeners are not attached to the
// system, so we need to manually attach them in order to trigger callbacks.
if (!$this->params['no-callbacks']) {
$this->_attachListeners($plugin->name, "{$plugin->path}/");
$trigger = $this->_triggerBeforeEvents($plugin);
if (!$trigger) {
return false;
}
}
return $this->_finish($plugin);
}
|
Activates the given plugin.
@param \CMS\Core\Package\PluginPackage $plugin The plugin to enable
@return bool True on success
|
entailment
|
protected function _disable(PluginPackage $plugin)
{
$requiredBy = Plugin::checkReverseDependency($plugin->name);
if (!empty($requiredBy)) {
$names = [];
foreach ($requiredBy as $p) {
$names[] = $p->name();
}
$this->err(__d('installer', 'Plugin "{0}" cannot be disabled as it is required by: {1}', $plugin->humanName, implode(', ', $names)));
return false;
}
if (!$this->params['no-callbacks']) {
$trigger = $this->_triggerBeforeEvents($plugin);
if (!$trigger) {
return false;
}
}
return $this->_finish($plugin);
}
|
Disables the given plugin.
@param \CMS\Core\Package\PluginPackage $plugin The plugin to disable
@return bool True on success
|
entailment
|
protected function _finish(PluginPackage $plugin)
{
$pluginEntity = $this->Plugins
->find()
->where(['name' => $plugin->name])
->first();
$pluginEntity->set('status', $this->params['status'] === 'enable' ? true : false);
if (!$this->Plugins->save($pluginEntity)) {
if ($this->params['status'] === 'enable') {
$this->err(__d('installer', 'Plugin "{0}" could not be enabled due to an internal error.', $plugin->humanName));
} else {
$this->err(__d('installer', 'Plugin "{0}" could not be disabled due to an internal error.', $plugin->humanName));
}
return false;
}
snapshot();
if (!$this->params['no-callbacks']) {
$this->_triggerAfterEvents($plugin);
}
return true;
}
|
Finish this task.
@param \CMS\Core\Package\PluginPackage $plugin The plugin being managed
by this task
@return bool True on success
|
entailment
|
protected function _triggerBeforeEvents(PluginPackage $plugin)
{
$affix = ucwords($this->params['status']);
try {
$event = $this->trigger("Plugin.{$plugin->name}.before{$affix}");
if ($event->isStopped() || $event->result === false) {
$this->err(__d('installer', 'Task was explicitly rejected by the plugin.'));
return false;
}
} catch (\Exception $e) {
$this->err(__d('installer', 'Internal error, plugin did not respond to "before{0}" callback properly.', $affix));
return false;
}
return true;
}
|
Triggers plugin's "before<Enable|Disable>" events.
@param \CMS\Core\Package\PluginPackahe $plugin The plugin for which
trigger the events
@return bool True on success
|
entailment
|
protected function _triggerAfterEvents(PluginPackage $plugin)
{
$affix = ucwords($this->params['status']);
try {
$this->trigger("Plugin.{$plugin->name}.after{$affix}");
} catch (\Exception $e) {
$this->err(__d('installer', 'Plugin did not respond to "after{0}" callback properly.', $affix));
}
}
|
Triggers plugin's "after<Enable|Disable>" events.
@param \CMS\Core\Package\PluginPackahe $plugin The plugin for which
trigger the events
@return void
|
entailment
|
public static function cache($key = null, $value = null)
{
if ($key === null && $value === null) {
// read all
return static::$_cache;
} elseif ($key !== null && $value === null) {
// read key
if (isset(static::$_cache[$key])) {
return static::$_cache[$key];
}
return null;
}
if ($key !== null && $value !== null) {
// write key
static::$_cache[$key] = $value;
return $value;
} else {
// search key for given value
if (!empty(static::$_cache)) {
foreach (static::$_cache as $k => $v) {
if ($v === $value) {
return $k;
}
}
}
return null;
}
}
|
Reads, writes or search internal class's cache.
### Usages:
- When reading if no cache key is found NULL will be returned.
e.g. `$null = static::cache('invalid-key');`
- When writing, this method return the value that was written.
e.g. `$value = static::cache('key', 'value');`
- Set both arguments to NULL to read the whole cache content at the moment.
e.g. `$allCache = static::cache()`
- Set key to null and value to anything to find the first key holding the
given value. e.g. `$key = static::cache(null, 'search key for this value')`,
if no key for the given value is found NULL will be returned.
### Examples:
#### Writing cache:
```php
static::cache('user_name', 'John');
// returns 'John'
static::cache('user_last', 'Locke');
// returns 'Locke'
```
#### Reading cache:
```php
static::cache('user_name');
// returns: John
static::cache('unexisting_key');
// returns: null
static::cache();
// Reads the entire cache
// returns: ['user_name' => 'John', 'user_last' => 'Locke']
```
#### Searching keys:
```php
static::cache(null, 'Locke');
// returns: user_last
static::cache(null, 'Unexisting Value');
// returns: null
```
@param null|string $key Cache key to read or write, set both $key and $value
to get the whole cache information
@param mixed $value Values to write into the given $key, or null indicates
reading from cache
@return mixed
|
entailment
|
public static function dropCache($key = null)
{
if ($key !== null && isset(static::$_cache[$key])) {
unset(static::$_cache[$key]);
} else {
static::$_cache = [];
}
}
|
Drops the entire cache or a specific key.
## Usage:
```php
static::dropCache('user_cache'); // removes "user_cache" only
static::dropCache(); // removes every key
```
@param string|null $key Cache key to clear, if NULL the entire cache
will be erased.
@return void
|
entailment
|
public function main()
{
$options = (array)$this->params;
$destination = normalizePath("{$options['destination']}/");
if (is_string($options['tables'])) {
$options['tables'] = explode(',', $options['tables']);
}
if (is_string($options['no-data'])) {
$options['no-data'] = explode(',', $options['no-data']);
}
if (file_exists($destination)) {
$dst = new Folder($destination);
$dst->delete();
$this->out(__d('system', 'Removing existing directory: {0}', $destination), 1, Shell::VERBOSE);
} else {
new Folder($destination, true);
$this->out(__d('system', 'Creating directory: {0}', $destination), 1, Shell::VERBOSE);
}
$db = ConnectionManager::get('default');
$db->connect();
$schemaCollection = $db->schemaCollection();
$tables = $schemaCollection->listTables();
foreach ($tables as $table) {
if (!empty($options['tables']) && !in_array($table, $options['tables'])) {
$this->out(__d('system', 'Table "{0}" skipped', $table), 1, Shell::VERBOSE);
continue;
}
$Table = TableRegistry::get($table);
$Table->behaviors()->reset();
$fields = [
'_constraints' => [],
'_indexes' => [],
'_options' => (array)$Table->schema()->options(),
];
$columns = $Table->schema()->columns();
$records = [];
$primaryKeys = [];
foreach ($Table->schema()->indexes() as $indexName) {
$index = $Table->schema()->index($indexName);
if (!empty($index['columns'])) {
$fields['_indexes']["{$table}_{$indexName}_index"] = $index;
}
}
foreach ($columns as $column) {
$fields[$column] = $Table->schema()->column($column);
}
foreach ($Table->schema()->constraints() as $constraint) {
$constraintName = in_array($constraint, $columns) ? Inflector::underscore("{$table}_{$constraint}") : $constraint;
$fields['_constraints'][$constraintName] = $Table->schema()->constraint($constraint);
if (isset($fields['_constraints']['primary']['columns'])) {
$primaryKeys = $fields['_constraints']['primary']['columns'];
}
}
foreach ($fields as $column => $info) {
if (isset($info['length']) &&
in_array($column, $primaryKeys) &&
isset($info['autoIncrement']) &&
$info['autoIncrement'] === true
) {
unset($fields[$column]['length']);
}
}
// FIX: We need RAW data for time instead of Time Objects
$originalTypes = [];
foreach ($Table->schema()->columns() as $column) {
$type = $Table->schema()->columnType($column);
$originalTypes[$column] = $type;
if (in_array($type, ['date', 'datetime', 'time'])) {
$Table->schema()->columnType($column, 'string');
}
}
if ($options['mode'] === 'full') {
foreach ($Table->find('all') as $row) {
$row = $row->toArray();
if ($this->params['no-id'] && isset($row['id'])) {
unset($row['id']);
}
$records[] = $row;
}
}
$className = Inflector::camelize($table) . 'Fixture';
if ($options['fixture'] && in_array($className, ['AcosFixture', 'UsersFixture'])) {
$records = [];
}
// undo changes made by "FIX"
foreach ($originalTypes as $column => $type) {
$fields[$column]['type'] = $type;
}
if (empty($fields['_indexes'])) {
unset($fields['_indexes']);
}
$fields = $this->_arrayToString($fields);
$records = in_array($table, $options['no-data']) ? '[]' : $this->_arrayToString($records);
$fixture = $this->_classFileHeader($className);
$fixture .= "{\n";
$fixture .= "\n";
$fixture .= " /**\n";
$fixture .= " * Table name.\n";
$fixture .= " *\n";
$fixture .= " * @var string\n";
$fixture .= " */\n";
$fixture .= " public \$table = '{$table}';\n";
$fixture .= "\n";
$fixture .= " /**\n";
$fixture .= " * Table columns.\n";
$fixture .= " *\n";
$fixture .= " * @var array\n";
$fixture .= " */\n";
$fixture .= " public \$fields = {$fields};\n";
$fixture .= "\n";
$fixture .= " /**\n";
$fixture .= " * Table records.\n";
$fixture .= " *\n";
$fixture .= " * @var array\n";
$fixture .= " */\n";
$fixture .= " public \$records = {$records};\n";
$fixture .= "}\n";
$file = new File(normalizePath("{$destination}/{$className}.php"), true);
$file->write($fixture, 'w', true);
$this->out(__d('system', 'Table "{0}" exported!', $table), 1, Shell::VERBOSE);
}
$this->out(__d('system', 'Database exported to: {0}', $destination));
return true;
}
|
Export entire database to PHP fixtures.
By default, all generated PHP files will be placed in `/tmp/fixture/`
directory, this can be changed using the `--destination` argument.
@return bool
|
entailment
|
protected function _classFileHeader($className)
{
$header = <<<TEXT
<?php
/**
* Licensed under The GPL-3.0 License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @since 2.0.0
* @author Christopher Castro <[email protected]>
* @link http://www.quickappscms.org
* @license http://opensource.org/licenses/gpl-3.0.html GPL-3.0 License
*/
TEXT;
if ($this->params['fixture']) {
$header .= <<<TEXT
namespace CMS\Test\Fixture;
use Cake\TestSuite\Fixture\TestFixture;
TEXT;
}
$header .= $this->params['fixture'] ? "class {$className} extends TestFixture\n" : "\nclass {$className}\n";
return $header;
}
|
Returns correct class file header.
@param string $className The name of the class withing the file
@return string
|
entailment
|
protected function _arrayToString(array $var)
{
foreach ($var as $rowIndex => $row) {
foreach ($row as $k => $v) {
if (is_resource($var[$rowIndex][$k])) {
$var[$rowIndex][$k] = stream_get_contents($v);
}
}
}
$var = json_decode(str_replace(['(', ')'], ['(', ')'], json_encode($var)), true);
$var = var_export($var, true);
return str_replace(['array (', ')', '(', ')'], ['[', ']', '(', ')'], $var);
}
|
Converts an array to code-string representation.
@param array $var The array to convert
@return string
|
entailment
|
public function base_url($base_url = '', $preserve_query_string = true) {
// set the base URL
$base_url = ($base_url == '' ? $_SERVER['REQUEST_URI'] : $base_url);
// parse the URL
$parsed_url = parse_url($base_url);
// cache the "path" part of the URL (that is, everything *before* the "?")
$this->_properties['base_url'] = $parsed_url['path'];
// cache the "query" part of the URL (that is, everything *after* the "?")
$this->_properties['base_url_query'] = isset($parsed_url['query']) ? $parsed_url['query'] : '';
// store query string as an associative array
parse_str($this->_properties['base_url_query'], $this->_properties['base_url_query']);
// should query strings (other than those set in $base_url) be preserved?
$this->_properties['preserve_query_string'] = $preserve_query_string;
}
|
The base URL to be used when generating the navigation links.
This is helpful for the case when, for example, the URL where the records are paginated may have parameters that
are needed only once and need to be removed for any subsequent requests generated by pagination.
For example, suppose some records are paginated at <i>http://yourwebsite/mypage/</i>. When a record from the list
is updated, the URL could become something like <i>http://youwebsite/mypage/?action=updated</i>. Based on the
value of <i>action</i> a message would be shown to the user.
Because of the way this script works, the pagination links would become:
- <i>http://youwebsite/mypage/?action=updated&page=[page number]</i> when {@link method} is "get" and
{@link variable_name} is "page";
- <i>http://youwebsite/mypage/page[page number]/?action=updated</i> when {@link method} is "url" and
{@link variable_name} is "page").
Because of this, whenever the user would paginate, the message would be shown to him again and again because
<i>action</i> will be preserved in the URL!
The solution is to set the <i>base_url</i> to <i>http://youwebsite/mypage/</i> and in this way, regardless of
however will the URL be changed, the pagination links will always be in the form of
- <i>http://youwebsite/mypage/?page=[page number]</i> when {@link method} is "get" and {@link variable_name}
is "page";
- <i>http://youwebsite/mypage/page[page number]/</i> when {@link method} is "url" and {@link variable_name} is "page").
Of course, you may still have query strings in the value of the $base_url if you wish so, and these will be
preserved when paginating.
<samp>If you want to preserve the hash in the URL, make sure you load the zebra_pagination.js file!</samp>
@param string $base_url (Optional) The base URL to be used when generating the navigation
links
Defaults is whatever returned by
{@link http://www.php.net/manual/en/reserved.variables.server.php $_SERVER['REQUEST_URI']}
@param boolean $preserve_query_string (Optional) Indicates whether values in query strings, other than
those set in $base_url, should be preserved
Default is TRUE
@return void
|
entailment
|
public function css_classes($css_classes) {
// if argument is invalid
if (!is_array($css_classes) || empty($css_classes) || array_keys($css_classes) != array_filter(array_keys($css_classes), function($value) { return in_array($value, array('list', 'list_item', 'anchor'), true); }))
// stop execution
trigger_error('Invalid argument. Method <strong>classes()</strong> accepts as argument an associative array with one or more of the following keys: <em>list, list_item, anchor</em>' , E_USER_ERROR);
// merge values with the default ones
$this->_properties['css_classes'] = array_merge($this->_properties['css_classes'], $css_classes);
}
|
Sets the CSS class names to be applied to the unorderd list, list item and anchors that make up the HTML markup
of the pagination links.
@param array $css_classes An associative array with one or more or all of the following keys:
- <b>list</b>, for setting the CSS class name to be used for the unordered list (<kbd><ul></kbd>)
- <b>list_item</b>, for setting the CSS class name to be used for the list item (<kbd><li></kbd>)
- <b>anchor</b>, for setting the CSS class name to be used for the anchor (<kbd><a></kbd>)
The default generated HTML markup looks like below:
<code>
<div class="Zebra_Pagination">
<ul class="pagination">
<li class="page-item">
<a href="path/to/first/page/" class="page-link">1</a>
</li>
<li class="page-item">
<a href="path/to/second/page/" class="page-link">2</a>
</li>
...the other pages...
</ul>
</div>
</code>
Calling this method with the following argument...
<code>
$pagination->css_classes(array(
'list' => 'foo',
'list_item' => 'bar',
'anchor' => 'baz',
));
</code>
...would result in the following markup:
<code>
<div class="Zebra_Pagination">
<ul class="foo">
<li class="bar">
<a href="path/to/first/page/" class="baz">1</a>
</li>
<li class="bar">
<a href="path/to/second/page/" class="baz">2</a>
</li>
...the other pages...
</ul>
</div>
</code>
You can change only the CSS class names you want and the default CSS class names
will be used for the other ones.
Default values are:
<code>
$pagination->css_classes(array(
'list' => 'pagination',
'list_item' => 'page-item',
'anchor' => 'page-link',
));
</code>
These values make the resulting markup to be compatible with both the older version
3 of Twitter Bootstrap as well as the new version 4.
@return void
|
entailment
|
public function get_page() {
// unless page was not specifically set through the "set_page" method
if (!$this->_properties['page_set']) {
// if
if (
// page propagation is SEO friendly
$this->_properties['method'] == 'url' &&
// the current page is set in the URL
preg_match('/\b' . preg_quote($this->_properties['variable_name']) . '([0-9]+)\b/i', $_SERVER['REQUEST_URI'], $matches) > 0
)
// set the current page to whatever it is indicated in the URL
$this->set_page((int)$matches[1]);
// if page propagation is done through GET and the current page is set in $_GET
elseif (isset($_GET[$this->_properties['variable_name']]))
// set the current page to whatever it was set to
$this->set_page((int)$_GET[$this->_properties['variable_name']]);
}
// if showing records in reverse order we must know the total number of records and the number of records per page
// *before* calling the "get_page" method
if ($this->_properties['reverse'] && $this->_properties['records'] == '') trigger_error('When showing records in reverse order you must specify the total number of records (by calling the "records" method) *before* the first use of the "get_page" method!', E_USER_ERROR);
if ($this->_properties['reverse'] && $this->_properties['records_per_page'] == '') trigger_error('When showing records in reverse order you must specify the number of records per page (by calling the "records_per_page" method) *before* the first use of the "get_page" method!', E_USER_ERROR);
// get the total number of pages
$this->_properties['total_pages'] = $this->get_pages();
// if there are any pages
if ($this->_properties['total_pages'] > 0) {
// if current page is beyond the total number pages
/// make the current page be the last page
if ($this->_properties['page'] > $this->_properties['total_pages']) $this->_properties['page'] = $this->_properties['total_pages'];
// if current page is smaller than 1
// make the current page 1
elseif ($this->_properties['page'] < 1) $this->_properties['page'] = 1;
}
// if we're just starting and we have to display links in reverse order
// set the first to the last one rather then first
if (!$this->_properties['page_set'] && $this->_properties['reverse']) $this->set_page($this->_properties['total_pages']);
// return the current page
return $this->_properties['page'];
}
|
Returns the current page's number.
<code>
// echoes the current page
echo $pagination->get_page();
</code>
@return integer Returns the current page's number
|
entailment
|
public function render($return_output = false) {
// get some properties of the class
$this->get_page();
// if there is a single page, or no pages at all, don't display anything
if ($this->_properties['total_pages'] <= 1) return '';
// start building output
$output = '<div class="Zebra_Pagination"><ul' . ($this->_properties['css_classes']['list'] != '' ? ' class="' . trim($this->_properties['css_classes']['list']) . '"' : '') . '>';
// if we're showing records in reverse order
if ($this->_properties['reverse']) {
// if "next page" and "previous page" links are to be shown to the left of the links to individual pages
if ($this->_properties['navigation_position'] == 'left')
// first show next/previous and then page links
$output .= $this->_show_next() . $this->_show_previous() . $this->_show_pages();
// if "next page" and "previous page" links are to be shown to the right of the links to individual pages
elseif ($this->_properties['navigation_position'] == 'right')
$output .= $this->_show_pages() . $this->_show_next() . $this->_show_previous();
// if "next page" and "previous page" links are to be shown on the outside of the links to individual pages
else $output .= $this->_show_next() . $this->_show_pages() . $this->_show_previous();
// if we're showing records in natural order
} else {
// if "next page" and "previous page" links are to be shown to the left of the links to individual pages
if ($this->_properties['navigation_position'] == 'left')
// first show next/previous and then page links
$output .= $this->_show_previous() . $this->_show_next() . $this->_show_pages();
// if "next page" and "previous page" links are to be shown to the right of the links to individual pages
elseif ($this->_properties['navigation_position'] == 'right')
$output .= $this->_show_pages() . $this->_show_previous() . $this->_show_next();
// if "next page" and "previous page" links are to be shown on the outside of the links to individual pages
else $output .= $this->_show_previous() . $this->_show_pages() . $this->_show_next();
}
// finish generating the output
$output .= '</ul></div>';
// if $return_output is TRUE
// return the generated content
if ($return_output) return $output;
// if script gets this far, print generated content to the screen
echo $output;
}
|
Generates the output.
<i>Make sure your script references the CSS file unless you are using {@link http://getbootstrap.com/ Twitter Bootstrap}!</i>
<code>
// generate output but don't echo it
// and return it instead
$output = $pagination->render(true);
</code>
@param boolean $return_output (Optional) Setting this argument to TRUE will instruct the script to
return the generated output rather than outputting it to the screen.
Default is FALSE.
@return void
|
entailment
|
public function set_page($page) {
// set the current page
// make sure we save it as an integer
$this->_properties['page'] = (int)$page;
// if the number is lower than one
// make it '1'
if ($this->_properties['page'] < 1) $this->_properties['page'] = 1;
// set a flag so that the "get_page" method doesn't change this value
$this->_properties['page_set'] = true;
}
|
Sets the current page.
<code>
// sets the fifth page as the current page
$pagination->set_page(5);
</code>
@param integer $page The page's number.
A number lower than <b>1</b> will be interpreted as <b>1</b>, while a number
greater than the total number of pages will be interpreted as the last page.
@return void
|
entailment
|
private function _build_uri($page) {
// if page propagation method is through SEO friendly URLs
if ($this->_properties['method'] == 'url') {
// see if the current page is already set in the URL
if (preg_match('/\b' . $this->_properties['variable_name'] . '([0-9]+)\b/i', $this->_properties['base_url']) > 0) {
// build string
$url = str_replace('//', '/', preg_replace(
// replace the currently existing value
'/\b' . $this->_properties['variable_name'] . '([0-9]+)\b/i',
// if on the first page, remove it in order to avoid duplicate content
($page == 1 ? '' : $this->_properties['variable_name'] . $page),
$this->_properties['base_url']
));
// if the current page is not yet in the URL, set it, unless we're on the first page
// case in which we don't set it in order to avoid duplicate content
} else $url = rtrim($this->_properties['base_url'], '/') . '/' . ($this->_properties['variable_name'] . $page);
// handle trailing slash according to preferences
$url = rtrim($url, '/') . ($this->_properties['trailing_slash'] ? '/' : '');
// if values in the query string - other than those set through base_url() - are not to be preserved
// preserve only those set initially
if (!$this->_properties['preserve_query_string']) $query = implode('&', $this->_properties['base_url_query']);
// otherwise, get the current query string
else $query = $_SERVER['QUERY_STRING'];
// return the built string also appending the query string, if any
return $url . ($query != '' ? '?' . $query : '');
// if page propagation is to be done through GET
} else {
// if values in the query string - other than those set through base_url() - are not to be preserved
// preserve only those set initially
if (!$this->_properties['preserve_query_string']) $query = $this->_properties['base_url_query'];
// otherwise, get the current query string, if any, and transform it to an array
else parse_str($_SERVER['QUERY_STRING'], $query);
// if we are avoiding duplicate content and if not the first/last page (depending on whether the pagination links are shown in natural or reversed order)
if (!$this->_properties['avoid_duplicate_content'] || ($page != ($this->_properties['reverse'] ? $this->_properties['total_pages'] : 1)))
// add/update the page number
$query[$this->_properties['variable_name']] = $page;
// if we are avoiding duplicate content, don't use the "page" variable on the first/last page
elseif ($this->_properties['avoid_duplicate_content'] && $page == ($this->_properties['reverse'] ? $this->_properties['total_pages'] : 1))
unset($query[$this->_properties['variable_name']]);
// make sure the returned HTML is W3C compliant
return htmlspecialchars(html_entity_decode($this->_properties['base_url']) . (!empty($query) ? '?' . urldecode(http_build_query($query)) : ''));
}
}
|
Generate the link for the page given as argument.
@return void
|
entailment
|
private function _show_pages() {
$output = '';
// if the total number of pages is lesser than the number of selectable pages
if ($this->_properties['total_pages'] <= $this->_properties['selectable_pages'])
// iterate ascendingly or descendingly, depending on whether we're showing links in reverse order or not
for (
$i = ($this->_properties['reverse'] ? $this->_properties['total_pages'] : 1);
($this->_properties['reverse'] ? $i >= 1 : $i <= $this->_properties['total_pages']);
($this->_properties['reverse'] ? $i-- : $i++)
) {
// CSS classes to be applied to the list item, if any
$css_classes = isset($this->_properties['css_classes']['list_item']) && $this->_properties['css_classes']['list_item'] != '' ? array(trim($this->_properties['css_classes']['list_item'])) : array();
// if this the currently selected page, highlight it
if ($this->_properties['page'] == $i) $css_classes[] = 'active';
// generate markup
$output .= '<li' .
// add CSS classes to the list item, if necessary
(!empty($css_classes) ? ' class="' . implode(' ', $css_classes) . '"' : '') . '><a href="' . $this->_build_uri($i) . '"' .
// add CSS classes to the anchor, if necessary
(isset($this->_properties['css_classes']['anchor']) && $this->_properties['css_classes']['anchor'] != '' ? ' class="' . trim($this->_properties['css_classes']['anchor']) . '"' : '') . '>' .
// apply padding if required
($this->_properties['padding'] ? str_pad($i, strlen($this->_properties['total_pages']), '0', STR_PAD_LEFT) : $i) .
'</a></li>';
}
// if the total number of pages is greater than the number of selectable pages
else {
// CSS classes to be applied to the list item, if any
$css_classes = isset($this->_properties['css_classes']['list_item']) && $this->_properties['css_classes']['list_item'] != '' ? array(trim($this->_properties['css_classes']['list_item'])) : array();
// highlight if the page is currently selected
if ($this->_properties['page'] == ($this->_properties['reverse'] ? $this->_properties['total_pages'] : 1)) $css_classes[] = 'active';
// start with a link to the first or last page, depending if we're displaying links in reverse order or not
// generate markup
$output .= '<li' .
// add CSS classes to the list item, if necessary
(!empty($css_classes) ? ' class="' . implode(' ', $css_classes) . '"' : '') . '><a href="' . $this->_build_uri($this->_properties['reverse'] ? $this->_properties['total_pages'] : 1) . '"' .
// add CSS classes to the anchor, if necessary
(isset($this->_properties['css_classes']['anchor']) && $this->_properties['css_classes']['anchor'] != '' ? ' class="' . trim($this->_properties['css_classes']['anchor']) . '"' : '') . '>' .
// if padding is required
($this->_properties['padding'] ?
// apply padding
str_pad(($this->_properties['reverse'] ? $this->_properties['total_pages'] : 1), strlen($this->_properties['total_pages']), '0', STR_PAD_LEFT) :
// show the page number
($this->_properties['reverse'] ? $this->_properties['total_pages'] : 1)) .
'</a></li>';
// compute the number of adjacent pages to display to the left and right of the currently selected page so
// that the currently selected page is always centered
$adjacent = floor(($this->_properties['selectable_pages'] - 3) / 2);
// this number must be at least 1
if ($adjacent == 0) $adjacent = 1;
// find the page number after we need to show the first "..."
// (depending on whether we're showing links in reverse order or not)
$scroll_from = ($this->_properties['reverse'] ?
$this->_properties['total_pages'] - ($this->_properties['selectable_pages'] - $adjacent) + 1 :
$this->_properties['selectable_pages'] - $adjacent);
// get the page number from where we should start rendering
// if displaying links in natural order, then it's "2" because we have already rendered the first page
// if we're displaying links in reverse order, then it's total_pages - 1 because we have already rendered the last page
$starting_page = ($this->_properties['reverse'] ? $this->_properties['total_pages'] - 1 : 2);
// if the currently selected page is past the point from where we need to scroll,
if (
($this->_properties['reverse'] && $this->_properties['page'] <= $scroll_from) ||
(!$this->_properties['reverse'] && $this->_properties['page'] >= $scroll_from)
) {
// by default, the starting_page should be whatever the current page plus/minus $adjacent
// depending on whether we're showing links in reverse order or not
$starting_page = $this->_properties['page'] + ($this->_properties['reverse'] ? $adjacent : -$adjacent);
// but if that would mean displaying less navigation links than specified in $this->_properties['selectable_pages']
if (
($this->_properties['reverse'] && $starting_page < ($this->_properties['selectable_pages'] - 1)) ||
(!$this->_properties['reverse'] && $this->_properties['total_pages'] - $starting_page < ($this->_properties['selectable_pages'] - 2))
)
// adjust the value of $starting_page again
if ($this->_properties['reverse']) $starting_page = $this->_properties['selectable_pages'] - 1;
else $starting_page -= ($this->_properties['selectable_pages'] - 2) - ($this->_properties['total_pages'] - $starting_page);
// put the "..." after the link to the first/last page, depending on whether we're showing links in reverse order or not
$output .= '<li' .
// add CSS classes to the list item, if necessary
(isset($this->_properties['css_classes']['list_item']) && $this->_properties['css_classes']['list_item'] != '' ? ' class="' . $this->_properties['css_classes']['list_item'] . '"' : '') . '>' .
// add CSS classes to the span element, if necessary
'<span' . (isset($this->_properties['css_classes']['anchor']) && $this->_properties['css_classes']['anchor'] != '' ? ' class="' . trim($this->_properties['css_classes']['anchor']) . '"' : '') . '>' .
'…</span></li>';
}
// get the page number where we should stop rendering
// by default, this value is the sum of the starting page plus/minus (depending on whether we're showing links
// in reverse order or not) whatever the number of $this->_properties['selectable_pages'] minus 3 (first page,
// last page and current page)
$ending_page = $starting_page + (($this->_properties['reverse'] ? -1 : 1) * ($this->_properties['selectable_pages'] - 3));
// if we're showing links in natural order and ending page would be greater than the total number of pages minus 1
// (minus one because we don't take into account the very last page which we output automatically)
// adjust the ending page
if ($this->_properties['reverse'] && $ending_page < 2) $ending_page = 2;
// or, if we're showing links in reverse order, and ending page would be smaller than 2
// (2 because we don't take into account the very first page which we output automatically)
// adjust the ending page
elseif (!$this->_properties['reverse'] && $ending_page > $this->_properties['total_pages'] - 1) $ending_page = $this->_properties['total_pages'] - 1;
// render pagination links
for ($i = $starting_page; $this->_properties['reverse'] ? $i >= $ending_page : $i <= $ending_page; $this->_properties['reverse'] ? $i-- : $i++) {
// CSS classes to be applied to the list item, if any
$css_classes = isset($this->_properties['css_classes']['list_item']) && $this->_properties['css_classes']['list_item'] != '' ? array(trim($this->_properties['css_classes']['list_item'])) : array();
// highlight the currently selected page
if ($this->_properties['page'] == $i) $css_classes[] = 'active';
// generate markup
$output .= '<li' .
// add CSS classes to the list item, if necessary
(!empty($css_classes) ? ' class="' . implode(' ', $css_classes) . '"' : '') . '><a href="' . $this->_build_uri($i) . '"' .
// add CSS classes to the anchor, if necessary
(isset($this->_properties['css_classes']['anchor']) && $this->_properties['css_classes']['anchor'] != '' ? ' class="' . trim($this->_properties['css_classes']['anchor']) . '"' : '') . '>' .
// apply padding if required
($this->_properties['padding'] ? str_pad($i, strlen($this->_properties['total_pages']), '0', STR_PAD_LEFT) : $i) .
'</a></li>';
}
// if we have to, place another "..." at the end, before the link to the last/first page (depending on whether we're showing links in reverse order or not)
if (
($this->_properties['reverse'] && $ending_page > 2) ||
(!$this->_properties['reverse'] && $this->_properties['total_pages'] - $ending_page > 1)
)
// generate markup
$output .= '<li' .
// add CSS classes to the list item, if necessary
(isset($this->_properties['css_classes']['list_item']) && $this->_properties['css_classes']['list_item'] != '' ? ' class="' . $this->_properties['css_classes']['list_item'] . '"' : '') . '>' .
// add CSS classes to the span element, if necessary
'<span' . (isset($this->_properties['css_classes']['anchor']) && $this->_properties['css_classes']['anchor'] != '' ? ' class="' . trim($this->_properties['css_classes']['anchor']) . '"' : '') . '>' .
'…</span></li>';
// now we put a link to the last/first page (depending on whether we're showing links in reverse order or not)
// CSS classes to be applied to the list item, if any
$css_classes = isset($this->_properties['css_classes']['list_item']) && $this->_properties['css_classes']['list_item'] != '' ? array(trim($this->_properties['css_classes']['list_item'])) : array();
// highlight if the page is currently selected
if ($this->_properties['page'] == $i) $css_classes[] = 'active';
// generate markup
$output .= '<li' .
// add CSS classes to the list item, if necessary
(!empty($css_classes) ? ' class="' . implode(' ', $css_classes) . '"' : '') . '><a href="' . $this->_build_uri($this->_properties['reverse'] ? 1 : $this->_properties['total_pages']) . '"' .
// add CSS classes to the anchor, if necessary
(isset($this->_properties['css_classes']['anchor']) && $this->_properties['css_classes']['anchor'] != '' ? ' class="' . trim($this->_properties['css_classes']['anchor']) . '"' : '') . '>' .
// also, apply padding if necessary
($this->_properties['padding'] ? str_pad(($this->_properties['reverse'] ? 1 : $this->_properties['total_pages']), strlen($this->_properties['total_pages']), '0', STR_PAD_LEFT) : ($this->_properties['reverse'] ? 1 : $this->_properties['total_pages'])) .
'</a></li>';
}
// return the resulting string
return $output;
}
|
Generates the pagination links (minus "next" and "previous"), depending on whether the pagination links are shown
in natural or reversed order.
|
entailment
|
private function _show_previous() {
$output = '';
// if "always_show_navigation" is TRUE or
// if the number of total pages available is greater than the number of selectable pages
// it means we can show the "previous page" link
if ($this->_properties['always_show_navigation'] || $this->_properties['total_pages'] > $this->_properties['selectable_pages']) {
// CSS classes to be applied to the list item, if any
$css_classes = isset($this->_properties['css_classes']['list_item']) && $this->_properties['css_classes']['list_item'] != '' ? array(trim($this->_properties['css_classes']['list_item'])) : array();
// if we're on the first page, the link is disabled
if ($this->_properties['page'] == 1) $css_classes[] = 'disabled';
// generate markup
$output = '<li' .
// add CSS classes to the list item, if necessary
(!empty($css_classes) ? ' class="' . implode(' ', $css_classes) . '"' : '') . '><a href="' .
// the href is different if we're on the first page
($this->_properties['page'] == 1 ? 'javascript:void(0)' : $this->_build_uri($this->_properties['page'] - 1)) . '"' .
// add CSS classes to the anchor, if necessary
(isset($this->_properties['css_classes']['anchor']) && $this->_properties['css_classes']['anchor'] != '' ? ' class="' . trim($this->_properties['css_classes']['anchor']) . '"' : '') .
// good for SEO
// http://googlewebmastercentral.blogspot.de/2011/09/pagination-with-relnext-and-relprev.html
' rel="prev">' .
($this->_properties['reverse'] ? $this->_properties['next'] : $this->_properties['previous']) . '</a></li>';
}
// return the resulting string
return $output;
}
|
Generates the "previous page" link, depending on whether the pagination links are shown in natural or reversed order.
|
entailment
|
private function setToken(array $token)
{
if (is_a($this->container, '\\ArrayAccess')) {
$this->container['token'] = $token;
return;
}
$this->container->set('token', $token);
}
|
Helper method to set the token value in the container instance.
@param array $token The token from the incoming request.
@return void
|
entailment
|
private function formatScopes(array $scopes)
{
if (empty($scopes)) {
return [null]; //use at least 1 null scope
}
array_walk(
$scopes,
function (&$scope) {
if (is_array($scope)) {
$scope = implode(' ', $scope);
}
}
);
return $scopes;
}
|
Helper method to ensure given scopes are formatted properly.
@param array $scopes Scopes required for authorization.
@return array The formatted scopes array.
|
entailment
|
public function setPagination($nextURL = null, $previousURL = null, $firstURL = null, $lastURL = null)
{
if (empty($nextURL) && empty($previousURL) && empty($firstURL) && empty($lastURL))
throw new \LogicException('At least one URL must be specified for pagination to work.');
if (!empty($nextURL))
$this->setAtomLink($nextURL, 'next');
if (!empty($previousURL))
$this->setAtomLink($previousURL, 'previous');
if (!empty($firstURL))
$this->setAtomLink($firstURL, 'first');
if (!empty($lastURL))
$this->setAtomLink($lastURL, 'last');
return $this;
}
|
Set the URLs for feed pagination.
See RFC 5005, chapter 3. At least one page URL must be specified.
@param string $nextURL The URL to the next page of this feed. Optional.
@param string $previousURL The URL to the previous page of this feed. Optional.
@param string $firstURL The URL to the first page of this feed. Optional.
@param string $lastURL The URL to the last page of this feed. Optional.
@link http://tools.ietf.org/html/rfc5005#section-3
@return self
@throws \LogicException if none of the parameters are set.
|
entailment
|
public function addGenerator()
{
if ($this->version == Feed::ATOM)
$this->setChannelElement('atom:generator', 'FeedWriter', array('uri' => 'https://github.com/mibe/FeedWriter'));
else if ($this->version == Feed::RSS2)
$this->setChannelElement('generator', 'FeedWriter');
else
throw new InvalidOperationException('The generator element is not supported in RSS1 feeds.');
return $this;
}
|
Add a channel element indicating the program used to generate the feed.
@return self
@throws InvalidOperationException if this method is called on an RSS1 feed.
|
entailment
|
public function addNamespace($prefix, $uri)
{
if (empty($prefix))
throw new \InvalidArgumentException('The prefix may not be emtpy or NULL.');
if (empty($uri))
throw new \InvalidArgumentException('The uri may not be empty or NULL.');
$this->namespaces[$prefix] = $uri;
return $this;
}
|
Add a XML namespace to the internal list of namespaces. After that,
custom channel elements can be used properly to generate a valid feed.
@access public
@param string $prefix namespace prefix
@param string $uri namespace name (URI)
@return self
@link http://www.w3.org/TR/REC-xml-names/
@throws \InvalidArgumentException if the prefix or uri is empty or NULL.
|
entailment
|
public function setChannelElement($elementName, $content, array $attributes = null, $multiple = false)
{
if (empty($elementName))
throw new \InvalidArgumentException('The element name may not be empty or NULL.');
if (!is_string($elementName))
throw new \InvalidArgumentException('The element name must be a string.');
$entity['content'] = $content;
$entity['attributes'] = $attributes;
if ($multiple === TRUE)
$this->channels[$elementName][] = $entity;
else
$this->channels[$elementName] = $entity;
return $this;
}
|
Add a channel element to the feed.
@access public
@param string $elementName name of the channel tag
@param string $content content of the channel tag
@param array array of element attributes with attribute name as array key
@param bool TRUE if this element can appear multiple times
@return self
@throws \InvalidArgumentException if the element name is not a string, empty or NULL.
|
entailment
|
public function setChannelElementsFromArray(array $elementArray)
{
foreach ($elementArray as $elementName => $content) {
$this->setChannelElement($elementName, $content);
}
return $this;
}
|
Set multiple channel elements from an array. Array elements
should be 'channelName' => 'channelContent' format.
@access public
@param array array of channels
@return self
|
entailment
|
public function getMIMEType()
{
switch ($this->version) {
case Feed::RSS2 : $mimeType = "application/rss+xml";
break;
case Feed::RSS1 : $mimeType = "application/rdf+xml";
break;
case Feed::ATOM : $mimeType = "application/atom+xml";
break;
default : $mimeType = "text/xml";
}
return $mimeType;
}
|
Get the appropriate MIME type string for the current feed.
@access public
@return string The MIME type string.
|
entailment
|
public function printFeed($useGenericContentType = false)
{
if (!is_bool($useGenericContentType))
throw new \InvalidArgumentException('The useGenericContentType parameter must be boolean.');
$contentType = "text/xml";
if (!$useGenericContentType) {
$contentType = $this->getMIMEType();
}
// Generate the feed before setting the header, so Exceptions will be nicely visible.
$feed = $this->generateFeed();
header("Content-Type: " . $contentType . "; charset=" . $this->encoding);
echo $feed;
}
|
Print the actual RSS/ATOM file
Sets a Content-Type header and echoes the contents of the feed.
Should only be used in situations where direct output is desired;
if you need to pass a string around, use generateFeed() instead.
@access public
@param bool FALSE if the specific feed media type should be sent.
@return void
@throws \InvalidArgumentException if the useGenericContentType parameter is not boolean.
|
entailment
|
public function generateFeed()
{
if ($this->version != Feed::ATOM && !array_key_exists('link', $this->channels))
throw new InvalidOperationException('RSS1 & RSS2 feeds need a link element. Call the setLink method before this method.');
return $this->makeHeader()
. $this->makeChannels()
. $this->makeItems()
. $this->makeFooter();
}
|
Generate the feed.
@access public
@return string The complete feed XML.
@throws InvalidOperationException if the link element of the feed is not set.
|
entailment
|
public function addItem(Item $feedItem)
{
if ($feedItem->getVersion() != $this->version)
{
$msg = sprintf('Feed type mismatch: This instance can handle %s feeds only, but item for %s feeds given.', $this->version, $feedItem->getVersion());
throw new \InvalidArgumentException($msg);
}
$this->items[] = $feedItem;
return $this;
}
|
Add a FeedItem to the main class
@access public
@param Item $feedItem instance of Item class
@return self
@throws \InvalidArgumentException if the given item version mismatches.
|
entailment
|
public function setEncoding($encoding)
{
if (empty($encoding))
throw new \InvalidArgumentException('The encoding may not be empty or NULL.');
if (!is_string($encoding))
throw new \InvalidArgumentException('The encoding must be a string.');
$this->encoding = $encoding;
return $this;
}
|
Set the 'encoding' attribute in the XML prolog.
@access public
@param string $encoding value of 'encoding' attribute
@return self
@throws \InvalidArgumentException if the encoding is not a string, empty or NULL.
|
entailment
|
public function setDate($date)
{
if ($this->version == Feed::RSS1)
throw new InvalidOperationException('The publication date is not supported in RSS1 feeds.');
// The feeds have different date formats.
$format = $this->version == Feed::ATOM ? \DATE_ATOM : \DATE_RSS;
if ($date instanceof DateTime)
$date = $date->format($format);
else if(is_numeric($date) && $date >= 0)
$date = date($format, $date);
else if (is_string($date))
{
$timestamp = strtotime($date);
if ($timestamp === FALSE)
throw new \InvalidArgumentException('The given date was not parseable.');
$date = date($format, $timestamp);
}
else
throw new \InvalidArgumentException('The given date is not an instance of DateTime, a UNIX timestamp or a date string.');
if ($this->version == Feed::ATOM)
$this->setChannelElement('updated', $date);
else
$this->setChannelElement('lastBuildDate', $date);
return $this;
}
|
Set the date when the feed was lastly updated.
This adds the 'updated' element to the feed. The value of the date parameter
can be either an instance of the DateTime class, an integer containing a UNIX
timestamp or a string which is parseable by PHP's 'strtotime' function.
Not supported in RSS1 feeds.
@access public
@param DateTime|int|string Date which should be used.
@return self
@throws \InvalidArgumentException if the given date is not an instance of DateTime, a UNIX timestamp or a date string.
@throws InvalidOperationException if this method is called on an RSS1 feed.
|
entailment
|
public function setDescription($description)
{
if ($this->version != Feed::ATOM)
$this->setChannelElement('description', $description);
else
$this->setChannelElement('subtitle', $description);
return $this;
}
|
Set a phrase or sentence describing the feed.
@access public
@param string $description Description of the feed.
@return self
|
entailment
|
public function setLink($link)
{
if ($this->version == Feed::ATOM)
$this->setAtomLink($link);
else
$this->setChannelElement('link', $link);
return $this;
}
|
Set the 'link' channel element
@access public
@param string $link value of 'link' channel tag
@return self
|
entailment
|
public function setAtomLink($href, $rel = null, $type = null, $hreflang = null, $title = null, $length = null)
{
$data = array('href' => $href);
if ($rel != null) {
if (!is_string($rel) || empty($rel))
throw new \InvalidArgumentException('rel parameter must be a string and a valid relation identifier.');
$data['rel'] = $rel;
}
if ($type != null) {
// Regex used from RFC 4287, page 41
if (!is_string($type) || preg_match('/.+\/.+/', $type) != 1)
throw new \InvalidArgumentException('type parameter must be a string and a MIME type.');
$data['type'] = $type;
}
if ($hreflang != null) {
// Regex used from RFC 4287, page 41
if (!is_string($hreflang) || preg_match('/[A-Za-z]{1,8}(-[A-Za-z0-9]{1,8})*/', $hreflang) != 1)
throw new \InvalidArgumentException('hreflang parameter must be a string and a valid language code.');
$data['hreflang'] = $hreflang;
}
if ($title != null) {
if (!is_string($title) || empty($title))
throw new \InvalidArgumentException('title parameter must be a string and not empty.');
$data['title'] = $title;
}
if ($length != null) {
if (!is_int($length) || $length < 0)
throw new \InvalidArgumentException('length parameter must be a positive integer.');
$data['length'] = (string) $length;
}
// ATOM spec. has some restrictions on atom:link usage
// See RFC 4287, page 12 (4.1.1)
if ($this->version == Feed::ATOM) {
foreach ($this->channels as $key => $value) {
if ($key != 'atom:link')
continue;
// $value is an array , so check every element
foreach ($value as $linkItem) {
$attrib = $linkItem['attributes'];
// Only one link with relation alternate and same hreflang & type is allowed.
if (@$attrib['rel'] == 'alternate' && @$attrib['hreflang'] == $hreflang && @$attrib['type'] == $type)
throw new InvalidOperationException('The feed must not contain more than one link element with a'
. ' relation of "alternate" that has the same combination of type and hreflang attribute values.');
}
}
}
return $this->setChannelElement('atom:link', '', $data, true);
}
|
Set custom 'link' channel elements.
In ATOM feeds, only one link with alternate relation and the same combination of
type and hreflang values.
@access public
@param string $href URI of this link
@param string $rel relation type of the resource
@param string $type MIME type of the target resource
@param string $hreflang language of the resource
@param string $title human-readable information about the resource
@param int $length length of the resource in bytes
@link https://www.iana.org/assignments/link-relations/link-relations.xml
@link https://tools.ietf.org/html/rfc4287#section-4.2.7
@return self
@throws \InvalidArgumentException on multiple occasions.
@throws InvalidOperationException if the same link with the same attributes was already added to the feed.
|
entailment
|
public function setImage($url, $title = null, $link = null)
{
if (!is_string($url) || empty($url))
throw new \InvalidArgumentException('url parameter must be a string and may not be empty or NULL.');
// RSS feeds have support for a title & link element.
if ($this->version != Feed::ATOM)
{
if (!is_string($title) || empty($title))
throw new \InvalidArgumentException('title parameter must be a string and may not be empty or NULL.');
if (!is_string($link) || empty($link))
throw new \InvalidArgumentException('link parameter must be a string and may not be empty or NULL.');
$data = array('title'=>$title, 'link'=>$link, 'url'=>$url);
$name = 'image';
}
else
{
$name = 'logo';
$data = $url;
}
// Special handling for RSS1 again (since RSS1 is a bit strange...)
if ($this->version == Feed::RSS1)
{
$this->data['Image'] = $data;
return $this->setChannelElement($name, '', array('rdf:resource' => $url), false);
}
else
return $this->setChannelElement($name, $data);
}
|
Set the 'image' channel element
@access public
@param string $url URL of the image
@param string $title Title of the image. RSS only.
@param string $link Link target URL of the image. RSS only.
@return self
@throws \InvalidArgumentException if the url is invalid.
@throws \InvalidArgumentException if the title and link parameter are not a string or empty.
|
entailment
|
public function setChannelAbout($url)
{
if ($this->version != Feed::RSS1)
throw new InvalidOperationException("This method is only supported in RSS1 feeds.");
if (empty($url))
throw new \InvalidArgumentException('The about URL may not be empty or NULL.');
if (!is_string($url))
throw new \InvalidArgumentException('The about URL must be a string.');
$this->data['ChannelAbout'] = $url;
return $this;
}
|
Set the channel 'rdf:about' attribute, which is used in RSS1 feeds only.
@access public
@param string $url value of 'rdf:about' attribute of the channel element
@return self
@throws InvalidOperationException if this method is called and the feed is not of type RSS1.
@throws \InvalidArgumentException if the given URL is invalid.
|
entailment
|
public static function uuid($key = null, $prefix = '')
{
$key = ($key == null) ? uniqid(rand()) : $key;
$chars = md5($key);
$uuid = substr($chars,0,8) . '-';
$uuid .= substr($chars,8,4) . '-';
$uuid .= substr($chars,12,4) . '-';
$uuid .= substr($chars,16,4) . '-';
$uuid .= substr($chars,20,12);
return $prefix . $uuid;
}
|
Generate an UUID.
The UUID is based on an MD5 hash. If no key is given, a unique ID as the input
for the MD5 hash is generated.
@author Anis uddin Ahmad <[email protected]>
@access public
@param string $key optional key on which the UUID is generated
@param string $prefix an optional prefix
@return string the formatted UUID
|
entailment
|
public static function filterInvalidXMLChars($string, $replacement = '_') // default to '\x{FFFD}' ???
{
$result = preg_replace('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}\x{10000}-\x{10FFFF}]+/u', $replacement, $string);
// Did the PCRE replace failed because of bad UTF-8 data?
// If yes, try a non-multibyte regex and without the UTF-8 mode enabled.
if ($result == NULL && preg_last_error() == PREG_BAD_UTF8_ERROR)
$result = preg_replace('/[^\x09\x0a\x0d\x20-\xFF]+/', $replacement, $string);
// In case the regex replacing failed completely, return the whole unfiltered string.
if ($result == NULL)
$result = $string;
return $result;
}
|
Replace invalid XML characters.
@link http://www.phpwact.org/php/i18n/charsets#xml See utf8_for_xml() function
@link http://www.w3.org/TR/REC-xml/#charsets
@link https://github.com/mibe/FeedWriter/issues/30
@access public
@param string $string string which should be filtered
@param string $replacement replace invalid characters with this string
@return string the filtered string
|
entailment
|
private function getNamespacePrefixes()
{
$prefixes = array();
// Get all tag names from channel elements...
$tags = array_keys($this->channels);
// ... and now all names from feed items
foreach ($this->items as $item) {
foreach (array_keys($item->getElements()) as $key) {
if (!in_array($key, $tags)) {
$tags[] = $key;
}
}
}
// Look for prefixes in those tag names
foreach ($tags as $tag) {
$elements = explode(':', $tag);
if (count($elements) != 2)
continue;
$prefixes[] = $elements[0];
}
return array_unique($prefixes);
}
|
Returns all used XML namespace prefixes in this instance.
This includes all channel elements and feed items.
Unfortunately some namespace prefixes are not included,
because they are hardcoded, e.g. rdf.
@access private
@return array Array with namespace prefix as value.
|
entailment
|
private function makeHeader()
{
$out = '<?xml version="1.0" encoding="'.$this->encoding.'" ?>' . PHP_EOL;
$prefixes = $this->getNamespacePrefixes();
$attributes = array();
$tagName = '';
$defaultNamespace = '';
if ($this->version == Feed::RSS2) {
$tagName = 'rss';
$attributes['version'] = '2.0';
} elseif ($this->version == Feed::RSS1) {
$tagName = 'rdf:RDF';
$prefixes[] = 'rdf';
$defaultNamespace = $this->namespaces['rss1'];
} elseif ($this->version == Feed::ATOM) {
$tagName = 'feed';
$defaultNamespace = $this->namespaces['atom'];
// Ugly hack to remove the 'atom' value from the prefixes array.
$prefixes = array_flip($prefixes);
unset($prefixes['atom']);
$prefixes = array_flip($prefixes);
}
// Iterate through every namespace prefix and add it to the element attributes.
foreach ($prefixes as $prefix) {
if (!isset($this->namespaces[$prefix]))
throw new InvalidOperationException('Unknown XML namespace prefix: \'' . $prefix . '\'.'
. ' Use the addNamespace method to add support for this prefix.');
else
$attributes['xmlns:' . $prefix] = $this->namespaces[$prefix];
}
// Include default namepsace, if required
if (!empty($defaultNamespace))
$attributes['xmlns'] = $defaultNamespace;
$out .= $this->makeNode($tagName, '', $attributes, true);
return $out;
}
|
Returns the XML header and root element, depending on the feed type.
@access private
@return string The XML header of the feed.
@throws InvalidOperationException if an unknown XML namespace prefix is encountered.
|
entailment
|
private function makeFooter()
{
if ($this->version == Feed::RSS2) {
return '</channel>' . PHP_EOL . '</rss>';
} elseif ($this->version == Feed::RSS1) {
return '</rdf:RDF>';
} elseif ($this->version == Feed::ATOM) {
return '</feed>';
}
}
|
Closes the open tags at the end of file
@access private
@return string The XML footer of the feed.
|
entailment
|
private function makeNode($tagName, $tagContent, array $attributes = null, $omitEndTag = false)
{
$nodeText = '';
$attrText = '';
if ($attributes != null) {
foreach ($attributes as $key => $value) {
$value = self::filterInvalidXMLChars($value);
$value = htmlspecialchars($value);
$attrText .= " $key=\"$value\"";
}
}
$attrText .= (in_array($tagName, $this->CDATAEncoding) && $this->version == Feed::ATOM) ? ' type="html"' : '';
$nodeText .= "<{$tagName}{$attrText}>";
$nodeText .= (in_array($tagName, $this->CDATAEncoding)) ? '<![CDATA[' : '';
if (is_array($tagContent)) {
foreach ($tagContent as $key => $value) {
if (is_array($value)) {
$nodeText .= PHP_EOL;
foreach ($value as $subValue) {
$nodeText .= $this->makeNode($key, $subValue);
}
} else if (is_string($value)) {
$nodeText .= $this->makeNode($key, $value);
} else {
throw new \InvalidArgumentException("Unknown node-value type for $key");
}
}
} else {
$tagContent = self::filterInvalidXMLChars($tagContent);
$nodeText .= (in_array($tagName, $this->CDATAEncoding)) ? $this->sanitizeCDATA($tagContent) : htmlspecialchars($tagContent);
}
$nodeText .= (in_array($tagName, $this->CDATAEncoding)) ? ']]>' : '';
if (!$omitEndTag)
$nodeText .= "</$tagName>";
$nodeText .= PHP_EOL;
return $nodeText;
}
|
Creates a single node in XML format
@access private
@param string $tagName name of the tag
@param mixed $tagContent tag value as string or array of nested tags in 'tagName' => 'tagValue' format
@param array $attributes Attributes (if any) in 'attrName' => 'attrValue' format
@param bool $omitEndTag True if the end tag should be omitted. Defaults to false.
@return string formatted xml tag
@throws \InvalidArgumentException if the tagContent is not an array and not a string.
|
entailment
|
private function makeChannels()
{
$out = '';
//Start channel tag
switch ($this->version) {
case Feed::RSS2:
$out .= '<channel>' . PHP_EOL;
break;
case Feed::RSS1:
$out .= (isset($this->data['ChannelAbout']))? "<channel rdf:about=\"{$this->data['ChannelAbout']}\">" : "<channel rdf:about=\"{$this->channels['link']['content']}\">";
break;
}
//Print Items of channel
foreach ($this->channels as $key => $value) {
// In ATOM feeds, strip all ATOM namespace prefixes from the tag name. They are not needed here,
// because the ATOM namespace name is set as default namespace.
if ($this->version == Feed::ATOM && strncmp($key, 'atom', 4) == 0) {
$key = substr($key, 5);
}
// The channel element can occur multiple times, when the key 'content' is not in the array.
if (!array_key_exists('content', $value)) {
// If this is the case, iterate through the array with the multiple elements.
foreach ($value as $singleElement) {
$out .= $this->makeNode($key, $singleElement['content'], $singleElement['attributes']);
}
} else {
$out .= $this->makeNode($key, $value['content'], $value['attributes']);
}
}
if ($this->version == Feed::RSS1) {
//RSS 1.0 have special tag <rdf:Seq> with channel
$out .= "<items>" . PHP_EOL . "<rdf:Seq>" . PHP_EOL;
foreach ($this->items as $item) {
$thisItems = $item->getElements();
$out .= "<rdf:li resource=\"{$thisItems['link']['content']}\"/>" . PHP_EOL;
}
$out .= "</rdf:Seq>" . PHP_EOL . "</items>" . PHP_EOL . "</channel>" . PHP_EOL;
// An image has its own element after the channel elements.
if (array_key_exists('image', $this->data))
$out .= $this->makeNode('image', $this->data['Image'], array('rdf:about' => $this->data['Image']['url']));
} else if ($this->version == Feed::ATOM) {
// ATOM feeds have a unique feed ID. Use the title channel element as key.
$out .= $this->makeNode('id', Feed::uuid($this->channels['title']['content'], 'urn:uuid:'));
}
return $out;
}
|
Make the channels.
@access private
@return string The feed header as XML containing all the feed metadata.
|
entailment
|
private function makeItems()
{
$out = '';
foreach ($this->items as $item) {
$thisItems = $item->getElements();
// The argument is printed as rdf:about attribute of item in RSS 1.0
// We're using the link set in the item (which is mandatory) as the about attribute.
if ($this->version == Feed::RSS1)
$out .= $this->startItem($thisItems['link']['content']);
else
$out .= $this->startItem();
foreach ($thisItems as $feedItem) {
$name = $feedItem['name'];
// Strip all ATOM namespace prefixes from tags when feed is an ATOM feed.
// Not needed here, because the ATOM namespace name is used as default namespace.
if ($this->version == Feed::ATOM && strncmp($name, 'atom', 4) == 0)
$name = substr($name, 5);
$out .= $this->makeNode($name, $feedItem['content'], $feedItem['attributes']);
}
$out .= $this->endItem();
}
return $out;
}
|
Prints formatted feed items
@access private
@return string The XML of every feed item.
|
entailment
|
private function startItem($about = false)
{
$out = '';
if ($this->version == Feed::RSS2) {
$out .= '<item>' . PHP_EOL;
} elseif ($this->version == Feed::RSS1) {
if ($about) {
$out .= "<item rdf:about=\"$about\">" . PHP_EOL;
} else {
throw new InvalidOperationException("Missing data for about attribute. Call setChannelAbout method.");
}
} elseif ($this->version == Feed::ATOM) {
$out .= "<entry>" . PHP_EOL;
}
return $out;
}
|
Make the starting tag of channels
@access private
@param string $about The value of about attribute which is used for RSS 1.0 only.
@return string The starting XML tag of an feed item.
@throws InvalidOperationException if this object misses the data for the about attribute.
|
entailment
|
private function endItem()
{
if ($this->version == Feed::RSS2 || $this->version == Feed::RSS1) {
return '</item>' . PHP_EOL;
} elseif ($this->version == Feed::ATOM) {
return '</entry>' . PHP_EOL;
}
}
|
Closes feed item tag
@access private
@return string The ending XML tag of an feed item.
|
entailment
|
public function addElement($elementName, $content, array $attributes = null, $overwrite = FALSE, $allowMultiple = FALSE)
{
if (empty($elementName))
throw new \InvalidArgumentException('The element name may not be empty or NULL.');
if (!is_string($elementName))
throw new \InvalidArgumentException('The element name must be a string.');
$key = $elementName;
// return if element already exists & if overwriting is disabled
// & if multiple elements are not allowed.
if (isset($this->elements[$elementName]) && !$overwrite) {
if (!$allowMultiple)
return $this;
$key .= '-' . $this->cpt();
}
$this->elements[$key]['name'] = $elementName;
$this->elements[$key]['content'] = $content;
$this->elements[$key]['attributes'] = $attributes;
return $this;
}
|
Add an element to elements array
@access public
@param string $elementName The tag name of an element
@param string $content The content of tag
@param array $attributes Attributes (if any) in 'attrName' => 'attrValue' format
@param boolean $overwrite Specifies if an already existing element is overwritten.
@param boolean $allowMultiple Specifies if multiple elements of the same name are allowed.
@return self
@throws \InvalidArgumentException if the element name is not a string, empty or NULL.
|
entailment
|
public function getElements()
{
// ATOM feeds have some specific requirements...
if ($this->version == Feed::ATOM)
{
// Add an 'id' element, if it was not added by calling the setLink method.
// Use the value of the title element as key, since no link element was specified.
if (!array_key_exists('id', $this->elements))
$this->setId(Feed::uuid($this->elements['title']['content'], 'urn:uuid:'));
// Either a 'link' or 'content' element is needed.
if (!array_key_exists('content', $this->elements) && !array_key_exists('link', $this->elements))
throw new InvalidOperationException('ATOM feed entries need a link or a content element. Call the setLink or setContent method.');
}
// ...same with RSS1 feeds.
else if ($this->version == Feed::RSS1)
{
if (!array_key_exists('title', $this->elements))
throw new InvalidOperationException('RSS1 feed entries need a title element. Call the setTitle method.');
if (!array_key_exists('link', $this->elements))
throw new InvalidOperationException('RSS1 feed entries need a link element. Call the setLink method.');
}
return $this->elements;
}
|
Return the collection of elements in this feed item
@access public
@return array All elements of this item.
@throws InvalidOperationException on ATOM feeds if either a content or link element is missing.
@throws InvalidOperationException on RSS1 feeds if a title or link element is missing.
|
entailment
|
public function setDescription($description)
{
$tag = ($this->version == Feed::ATOM) ? 'summary' : 'description';
return $this->addElement($tag, $description);
}
|
Set the 'description' element of feed item
@access public
@param string $description The content of the 'description' or 'summary' element
@return self
|
entailment
|
public function setContent($content)
{
if ($this->version != Feed::ATOM)
throw new InvalidOperationException('The content element is supported in ATOM feeds only.');
return $this->addElement('content', $content, array('type' => 'html'));
}
|
Set the 'content' element of the feed item
For ATOM feeds only
@access public
@param string $content Content for the item (i.e., the body of a blog post).
@return self
@throws InvalidOperationException if this method is called on non-ATOM feeds.
|
entailment
|
public function setDate($date)
{
if (!is_numeric($date)) {
if ($date instanceof DateTime)
$date = $date->getTimestamp();
else {
$date = strtotime($date);
if ($date === FALSE)
throw new \InvalidArgumentException('The given date string was not parseable.');
}
} elseif ($date < 0)
throw new \InvalidArgumentException('The given date is not an UNIX timestamp.');
if ($this->version == Feed::ATOM) {
$tag = 'updated';
$value = date(\DATE_ATOM, $date);
} elseif ($this->version == Feed::RSS2) {
$tag = 'pubDate';
$value = date(\DATE_RSS, $date);
} else {
$tag = 'dc:date';
$value = date("Y-m-d", $date);
}
return $this->addElement($tag, $value);
}
|
Set the 'date' element of the feed item.
The value of the date parameter can be either an instance of the
DateTime class, an integer containing a UNIX timestamp or a string
which is parseable by PHP's 'strtotime' function.
@access public
@param DateTime|int|string $date Date which should be used.
@return self
@throws \InvalidArgumentException if the given date was not parseable.
|
entailment
|
public function setLink($link)
{
if ($this->version == Feed::RSS2 || $this->version == Feed::RSS1) {
$this->addElement('link', $link);
} else {
$this->addElement('link','',array('href'=>$link));
$this->setId(Feed::uuid($link,'urn:uuid:'));
}
return $this;
}
|
Set the 'link' element of feed item
@access public
@param string $link The content of 'link' element
@return self
|
entailment
|
public function addEnclosure($url, $length, $type, $multiple = TRUE)
{
if ($this->version == Feed::RSS1)
throw new InvalidOperationException('Media attachment is not supported in RSS1 feeds.');
// the length parameter should be set to 0 if it can't be determined
// see http://www.rssboard.org/rss-profile#element-channel-item-enclosure
if (!is_numeric($length) || $length < 0)
throw new \InvalidArgumentException('The length parameter must be an integer and greater or equals to zero.');
// Regex used from RFC 4287, page 41
if (!is_string($type) || preg_match('/.+\/.+/', $type) != 1)
throw new \InvalidArgumentException('type parameter must be a string and a MIME type.');
$attributes = array('length' => $length, 'type' => $type);
if ($this->version == Feed::RSS2) {
$attributes['url'] = $url;
$this->addElement('enclosure', '', $attributes, FALSE, $multiple);
} else {
$attributes['href'] = $url;
$attributes['rel'] = 'enclosure';
$this->addElement('atom:link', '', $attributes, FALSE, $multiple);
}
return $this;
}
|
Attach a external media to the feed item.
Not supported in RSS 1.0 feeds.
See RFC 4288 for syntactical correct MIME types.
Note that you should avoid the use of more than one enclosure in one item,
since some RSS aggregators don't support it.
@access public
@param string $url The URL of the media.
@param integer $length The length of the media.
@param string $type The MIME type attribute of the media.
@param boolean $multiple Specifies if multiple enclosures are allowed
@return self
@link https://tools.ietf.org/html/rfc4288
@throws \InvalidArgumentException if the length or type parameter is invalid.
@throws InvalidOperationException if this method is called on RSS1 feeds.
|
entailment
|
public function setAuthor($author, $email = null, $uri = null)
{
if ($this->version == Feed::RSS1)
throw new InvalidOperationException('The author element is not supported in RSS1 feeds.');
// Regex from RFC 4287 page 41
if ($email != null && preg_match('/.+@.+/', $email) != 1)
throw new \InvalidArgumentException('The email address is syntactically incorrect.');
if ($this->version == Feed::RSS2)
{
if ($email != null)
$author = $email . ' (' . $author . ')';
$this->addElement('author', $author);
}
else
{
$elements = array('name' => $author);
if ($email != null)
$elements['email'] = $email;
if ($uri != null)
$elements['uri'] = $uri;
$this->addElement('author', $elements);
}
return $this;
}
|
Set the 'author' element of feed item.
Not supported in RSS 1.0 feeds.
@access public
@param string $author The author of this item
@param string|null $email Optional email address of the author
@param string|null $uri Optional URI related to the author
@return self
@throws \InvalidArgumentException if the provided email address is syntactically incorrect.
@throws InvalidOperationException if this method is called on RSS1 feeds.
|
entailment
|
public function setId($id, $permaLink = false)
{
if ($this->version == Feed::RSS2) {
if (!is_bool($permaLink))
throw new \InvalidArgumentException('The permaLink parameter must be boolean.');
$permaLink = $permaLink ? 'true' : 'false';
$this->addElement('guid', $id, array('isPermaLink' => $permaLink));
} elseif ($this->version == Feed::ATOM) {
// Check if the given ID is an valid URI scheme (see RFC 4287 4.2.6)
// The list of valid schemes was generated from http://www.iana.org/assignments/uri-schemes
// by using only permanent or historical schemes.
$validSchemes = array('aaa', 'aaas', 'about', 'acap', 'acct', 'cap', 'cid', 'coap', 'coaps', 'crid', 'data', 'dav', 'dict', 'dns', 'example', 'fax', 'file', 'filesystem', 'ftp', 'geo', 'go', 'gopher', 'h323', 'http', 'https', 'iax', 'icap', 'im', 'imap', 'info', 'ipp', 'ipps', 'iris', 'iris.beep', 'iris.lwz', 'iris.xpc', 'iris.xpcs', 'jabber', 'ldap', 'mailserver', 'mailto', 'mid', 'modem', 'msrp', 'msrps', 'mtqp', 'mupdate', 'news', 'nfs', 'ni', 'nih', 'nntp', 'opaquelocktoken', 'pack', 'pkcs11', 'pop', 'pres', 'prospero', 'reload', 'rtsp', 'rtsps', 'rtspu', 'service', 'session', 'shttp', 'sieve', 'sip', 'sips', 'sms', 'snews', 'snmp', 'soap.beep', 'soap.beeps', 'stun', 'stuns', 'tag', 'tel', 'telnet', 'tftp', 'thismessage', 'tip', 'tn3270', 'turn', 'turns', 'tv', 'urn', 'vemmi', 'videotex', 'vnc', 'wais', 'ws', 'wss', 'xcon', 'xcon-userid', 'xmlrpc.beep', 'xmlrpc.beeps', 'xmpp', 'z39.50', 'z39.50r', 'z39.50s');
$found = FALSE;
$checkId = strtolower($id);
foreach($validSchemes as $scheme)
if (strrpos($checkId, $scheme . ':', -strlen($checkId)) !== FALSE)
{
$found = TRUE;
break;
}
if (!$found)
throw new \InvalidArgumentException("The ID must begin with an IANA-registered URI scheme.");
$this->addElement('id', $id, NULL, TRUE);
} else
throw new InvalidOperationException('A unique ID is not supported in RSS1 feeds.');
return $this;
}
|
Set the unique identifier of the feed item
On ATOM feeds, the identifier must begin with an valid URI scheme.
@access public
@param string $id The unique identifier of this item
@param boolean $permaLink The value of the 'isPermaLink' attribute in RSS 2 feeds.
@return self
@throws \InvalidArgumentException if the permaLink parameter is not boolean.
@throws InvalidOperationException if this method is called on RSS1 feeds.
|
entailment
|
public function shouldMinify($value)
{
if (preg_match('/skipmin/', $value)
|| preg_match('/<(pre|textarea)/', $value)
|| preg_match('/<script[^\??>]*>[^<\/script>]/', $value)
|| preg_match('/value=("|\')(.*)([ ]{2,})(.*)("|\')/', $value)
) {
return false;
} else {
return true;
}
}
|
We'll only compress a view if none of the following conditions are met.
1) <pre> or <textarea> tags
2) Embedded javascript (opening <script> tag not immediately followed
by </script>)
3) Value attribute that contains 2 or more adjacent spaces
@param string $value the contents of the view file
@return bool
|
entailment
|
protected function compileMinify($value)
{
if ($this->shouldMinify($value)) {
$replace = array(
'/<!--[^\[](.*?)[^\]]-->/s' => '',
"/<\?php/" => '<?php ',
"/\n([\S])/" => ' $1',
"/\r/" => '',
"/\n/" => '',
"/\t/" => ' ',
"/ +/" => ' ',
);
return preg_replace(
array_keys($replace), array_values($replace), $value
);
} else {
return $value;
}
}
|
Compress the HTML output before saving it
@param string $value the contents of the view file
@return string
|
entailment
|
public function reverseTransform($id)
{
if (empty($id)) {
return;
}
$object = $this->registry->getManagerForClass($this->class)->getRepository($this->class)->find($id);
if (null === $object) {
throw new TransformationFailedException(sprintf('Object from class %s with id "%s" not found', $this->class, $id));
}
return $object;
}
|
Transforms a string (id) to an object (object).
@param string $id
@throws TransformationFailedException if object (object) is not found
@return object|null
|
entailment
|
public function filterAutocomplete(GetFilterConditionEvent $event): void
{
$expr = $event->getFilterQuery()->getExpr();
$values = $event->getValues();
if ('' !== $values['value'] && null !== $values['value']) {
$paramName = str_replace('.', '_', $event->getField());
$event->setCondition(
$expr->eq($event->getField(), ':'.$paramName),
[$paramName => $values['value']]
);
}
}
|
Apply a filter for a filter_autcomplete type.
This method should work whih both ORM and DBAL query builder.
@param GetFilterConditionEvent $event
|
entailment
|
public function register()
{
$app = $this->app;
$app->view->getEngineResolver()->register(
'blade.php',
function () use ($app) {
$cachePath = storage_path() . '/views';
$compiler = new LaravelHtmlMinifyCompiler(
$app->make('config')->get('laravel-html-minify::config'),
$app['files'],
$cachePath
);
return new CompilerEngine($compiler);
}
);
$app->view->addExtension('blade.php', 'blade.php');
}
|
Register the service provider.
@return void
|
entailment
|
public function save_options() {
if ( ! filter_input( INPUT_POST, 'submit' ) ) {
return false;
}
if ( ! wp_verify_nonce( filter_input( INPUT_POST, '_wpnonce' ), 'update-permalink' ) ) {
return false;
}
if ( false === strpos( filter_input( INPUT_POST, '_wp_http_referer' ), 'options-permalink.php' ) ) {
return false;
}
$post_types = CPTP_Util::get_post_types();
foreach ( $post_types as $post_type ) :
$structure = trim( esc_attr( filter_input( INPUT_POST, $post_type . '_structure' ) ) ); // get setting.
// default permalink structure.
if ( ! $structure ) {
$structure = CPTP_DEFAULT_PERMALINK;
}
$structure = str_replace( '//', '/', '/' . $structure );// first "/"
// last "/".
$lastString = substr( trim( esc_attr( filter_input( INPUT_POST,'permalink_structure' ) ) ), - 1 );
$structure = rtrim( $structure, '/' );
if ( '/' === $lastString ) {
$structure = $structure . '/';
}
update_option( $post_type . '_structure', $structure );
endforeach;
$no_taxonomy_structure = ! filter_input( INPUT_POST, 'no_taxonomy_structure' );
$add_post_type_for_tax = filter_input( INPUT_POST, 'add_post_type_for_tax' );
update_option( 'no_taxonomy_structure', $no_taxonomy_structure );
update_option( 'add_post_type_for_tax', $add_post_type_for_tax );
update_option( 'cptp_permalink_checked', CPTP_VERSION );
}
|
Save Options.
@return bool
|
entailment
|
public function upgrader_process_complete( $wp_upgrader, $options ) {
if ( empty( $options['plugins'] ) ) {
return;
}
if ( ! is_array( $options['plugins'] ) ) {
return;
}
if ( 'update' === $options['action'] && 'plugin' === $options['type'] ) {
$plugin_path = plugin_basename( CPTP_PLUGIN_FILE );
if ( in_array( $plugin_path, $options['plugins'], true ) ) {
// for update code.
add_option( 'no_taxonomy_structure', false );
}
}
}
|
After update complete.
@since 3.0.0
@param object $wp_upgrader WP_Upgrader instance.
@param array $options Extra information about performed upgrade.
|
entailment
|
public function getarchives_where( $where, $r ) {
$this->get_archives_where_r = $r;
if ( isset( $r['post_type'] ) ) {
if ( ! in_array( $r['post_type'], CPTP_Util::get_post_types(), true ) ) {
return $where;
}
$post_type = get_post_type_object( $r['post_type'] );
if ( ! $post_type ) {
return $where;
}
if ( ! $post_type->has_archive ) {
return $where;
}
$where = str_replace( '\'post\'', '\'' . $r['post_type'] . '\'', $where );
}
if ( isset( $r['taxonomy'] ) && is_array( $r['taxonomy'] ) ) {
global $wpdb;
$where = $where . " AND $wpdb->term_taxonomy.taxonomy = '" . $r['taxonomy']['name'] . "' AND $wpdb->term_taxonomy.term_id = '" . $r['taxonomy']['termid'] . "'";
}
return $where;
}
|
Get archive where.
@param string $where SQL where.
@param array $r Argument in wp_get_archives.
@return mixed|string
|
entailment
|
public function getarchives_join( $join, $r ) {
global $wpdb;
$this->get_archives_where_r = $r;
if ( isset( $r['taxonomy'] ) && is_array( $r['taxonomy'] ) ) {
$join = $join . " INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)";
}
return $join;
}
|
Get_archive_join
@author Steve
@since 0.8
@version 1.0
@param string $join SQL JOIN.
@param array $r Argument in wp_get_archives.
@return string
|
entailment
|
public function get_archives_link( $html ) {
global $wp_rewrite;
if ( ! isset( $this->get_archives_where_r['post_type'] ) ) {
return $html;
}
if ( ! in_array( $this->get_archives_where_r['post_type'], CPTP_Util::get_post_types(), true ) ) {
return $html;
}
if ( 'post' === $this->get_archives_where_r['post_type'] ) {
return $html;
}
$post_type = get_post_type_object( $this->get_archives_where_r['post_type'] );
if ( ! $post_type ) {
return $html;
}
if ( ! $post_type->has_archive ) {
return $html;
}
$c = isset( $this->get_archives_where_r['taxonomy'] ) && is_array( $this->get_archives_where_r['taxonomy'] ) ? $this->get_archives_where_r['taxonomy'] : '';
$t = $this->get_archives_where_r['post_type'];
$this->get_archives_where_r['post_type'] = isset( $this->get_archives_where_r['post_type_slug'] ) ? $this->get_archives_where_r['post_type_slug'] : $t; // [steve] [*** bug fixing]
if ( isset( $this->get_archives_where_r['post_type'] ) && 'postbypost' !== $this->get_archives_where_r['type'] ) {
$blog_url = rtrim( home_url() ,'/' );
// remove front.
$front = substr( $wp_rewrite->front, 1 );
$html = str_replace( $front, '', $html );
$blog_url = preg_replace( '/https?:\/\//', '', $blog_url );
$ret_link = str_replace( $blog_url, $blog_url . '/%link_dir%', $html );
if ( empty( $c ) ) {
if ( isset( $post_type->rewrite['slug'] ) ) {
$link_dir = $post_type->rewrite['slug'];
} else {
$link_dir = $this->get_archives_where_r['post_type'];
}
} else {
$c['name'] = ( 'category' === $c['name'] && get_option( 'category_base' ) ) ? get_option( 'category_base' ) : $c['name'];
$link_dir = $post_type->rewrite['slug'] . '/' . $c['name'] . '/' . $c['termslug'];
}
if ( ! strstr( $html, '/date/' ) ) {
$link_dir = $link_dir . CPTP_Util::get_date_front( $post_type );
}
if ( $post_type->rewrite['with_front'] ) {
$link_dir = $front . $link_dir;
}
$ret_link = str_replace( '%link_dir%', $link_dir, $ret_link );
$ret_link = str_replace( '?post_type=' . $this->get_archives_where_r['post_type'], '', $ret_link );
} else {
$ret_link = $html;
}
$this->get_archives_where_r['post_type'] = $t;
return $ret_link;
}
|
Filter: get_arcihves_link
@version 2.2 03/27/14
@param string $html archive <li> html.
@return string
|
entailment
|
public function activate() {
foreach ( $this->modules as $module ) {
$module->activation_hook();
}
register_uninstall_hook( CPTP_PLUGIN_FILE, array( __CLASS__, 'uninstall' ) );
}
|
Activation Hooks
This function will browse initialized modules and execute their activation_hook methods.
It will also set the uninstall_hook to the cptp_uninstall function which behaves the same way as this one.
@since 2.0.0
|
entailment
|
public static function uninstall() {
$cptp = CPTP::get_instance();
foreach ( $cptp->modules as $module ) {
$module->uninstall_hook();
}
}
|
Uninstall Hooks
This function will browse initialized modules and execute their uninstall_hook methods.
@since 2.0.0
|
entailment
|
public static function get_post_types() {
$param = array(
'_builtin' => false,
'public' => true,
);
$post_type = get_post_types( $param );
return array_filter( $post_type, array( __CLASS__, 'is_rewrite_supported_by' ) );
}
|
Get filtered post type.
@return array
|
entailment
|
private static function is_rewrite_supported_by( $post_type ) {
$post_type_object = get_post_type_object( $post_type );
if ( false === $post_type_object->rewrite ) {
$support = false;
} else {
$support = true;
}
/**
* Filters support CPTP for custom post type.
*
* @since 3.2.0
*
* @param bool $support support CPTP.
*/
$support = apply_filters( "CPTP_is_rewrite_supported_by_${post_type}", $support );
/**
* Filters support CPTP for custom post type.
*
* @since 3.2.0
*
* @param bool $support support CPTP.
* @param string $post_type post type name.
*/
return apply_filters( 'CPTP_is_rewrite_supported', $support, $post_type );
}
|
Check post type support rewrite.
@param string $post_type post_type name.
@return bool
|
entailment
|
public static function get_taxonomies( $objects = false ) {
if ( $objects ) {
$output = 'objects';
} else {
$output = 'names';
}
return get_taxonomies( array(
'public' => true,
'_builtin' => false,
), $output );
}
|
Get taxonomies.
@param bool $objects object or name.
@return array
|
entailment
|
public static function get_taxonomy_parents_slug( $term, $taxonomy = 'category', $separator = '/', $nicename = false, $visited = array() ) {
$chain = '';
$parent = get_term( $term, $taxonomy );
if ( is_wp_error( $parent ) ) {
return $parent;
}
if ( $nicename ) {
$name = $parent->slug;
} else {
$name = $parent->name;
}
if ( $parent->parent && ( $parent->parent !== $parent->term_id ) && ! in_array( $parent->parent, $visited, true ) ) {
$visited[] = $parent->parent;
$chain .= CPTP_Util::get_taxonomy_parents_slug( $parent->parent, $taxonomy, $separator, $nicename, $visited );
}
$chain .= $name . $separator;
return $chain;
}
|
Get Custom Taxonomies parents slug.
@version 1.0
@param int|WP_Term|object $term Target term.
@param string $taxonomy Taxonomy name.
@param string $separator separater string.
@param bool $nicename use slug or name.
@param array $visited visited parent slug.
@return string
|
entailment
|
public static function get_taxonomy_parents( $term, $taxonomy = 'category', $link = false, $separator = '/', $nicename = false, $visited = array() ) {
$chain = '';
$parent = get_term( $term, $taxonomy );
if ( is_wp_error( $parent ) ) {
return $parent;
}
if ( $nicename ) {
$name = $parent->slug;
} else {
$name = $parent->name;
}
if ( $parent->parent && ( $parent->parent !== $parent->term_id ) && ! in_array( $parent->parent, $visited, true ) ) {
$visited[] = $parent->parent;
$chain .= CPTP_Util::get_taxonomy_parents( $parent->parent, $taxonomy, $link, $separator, $nicename, $visited );
}
if ( $link ) {
$chain .= '<a href="' . get_term_link( $parent->term_id, $taxonomy ) . '" title="' . esc_attr( sprintf( __( 'View all posts in %s' ), $parent->name ) ) . '">' . esc_html( $name ) . '</a>' . esc_html( $separator );
} else {
$chain .= $name . $separator;
}
return $chain;
}
|
Get Custom Taxonomies parents.
@deprecated
@param int|WP_Term|object $term term.
@param string $taxonomy taxonomy.
@param bool $link show link html.
@param string $separator separator string.
@param bool $nicename use slug or name.
@param array $visited visited term.
@return string
|
entailment
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.