sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
protected function _setRegions($block = null) { $regions = plugin() ->filter(function ($plugin) { return $plugin->isTheme; }) ->map(function ($theme) use ($block) { $value = ''; if ($block !== null && $block->has('region')) { foreach ($block->region as $blockRegion) { if ($blockRegion->theme == $theme->name) { $value = $blockRegion->region; break; } } } return [ 'theme_machine_name' => $theme->name, 'theme_human_name' => $theme->humanName, 'description' => $theme->composer['description'], 'regions' => (array)$theme->composer['extra']['regions'], 'value' => $value, ]; }); $this->set('regions', $regions); }
Sets "regions" variable for later use in FormHelper. This variable is used to properly fill inputs in the "Theme Region" section of the add/edit form. @param null|\Block\Model\Entity\Block $block If a block entity is provided it will be used to guess which regions has been already selected in each theme, so we can properly show the selectbox in the form with the corrects options selected. @return void
entailment
protected function _patchEntity($block) { $this->loadModel('Block.Blocks'); $data = ['region' => []]; foreach ($this->request->data() as $column => $value) { if ($column == 'region') { foreach ($value as $theme => $region) { $tmp = ['theme' => $theme, 'region' => $region]; foreach ((array)$block->region as $blockRegion) { if ($blockRegion->theme == $theme) { $tmp['id'] = $blockRegion->id; break; } } $data[$column][] = $tmp; } } else { $data[$column] = $value; } } if ($block->isNew()) { $data['handler'] = 'Block\Widget\CustomBlockWidget'; $block->set('handler', 'Block\Widget\CustomBlockWidget'); } $validator = $block->isCustom() ? 'custom' : 'widget'; return $this->Blocks->patchEntity($block, $data, ['validate' => $validator, 'entity' => $block]); }
Prepares incoming data from Form's POST and patches the given entity. @param \Block\Model\Entity\Block $block BLock to patch with incoming POST data @return \Cake\Datasource\EntityInterface Patched entity
entailment
public function beforeFilter(Event $event) { $this->_controller = $event->subject(); $this->_controller->helpers['Breadcrumb'] = ['className' => 'Menu\View\Helper\BreadcrumbHelper']; }
Initializes BreadcrumbComponent for use in the controller. @param Event $event The event that was triggered @return void
entailment
public function push($crumbs = null, $url = null) { if ($crumbs === null && $url === null) { $MenuLinks = TableRegistry::get('Menu.MenuLinks'); $MenuLinks->removeBehavior('Tree'); $possibleMatches = $this->_urlChunk(); $found = $MenuLinks ->find() ->select(['id', 'menu_id']) ->where(['MenuLinks.url IN' => empty($possibleMatches) ? ['-1'] : $possibleMatches]) ->first(); $crumbs = []; if ($found) { $MenuLinks->addBehavior('Tree', ['scope' => ['menu_id' => $found->menu_id]]); $crumbs = $MenuLinks->find('path', ['for' => $found->id])->toArray(); } } elseif (is_string($crumbs) && strpos($crumbs, '/') !== false && $url === null) { $MenuLinks = TableRegistry::get('Menu.MenuLinks'); $MenuLinks->removeBehavior('Tree'); $found = $MenuLinks ->find() ->select(['id', 'menu_id']) ->where(['MenuLinks.url IN' => empty($crumbs) ? ['-1'] : $crumbs]) ->first(); $crumbs = []; if ($found) { $MenuLinks->addBehavior('Tree', ['scope' => ['menu_id' => $found->menu_id]]); $crumbs = $MenuLinks->find('path', ['for' => $found->id])->toArray(); } } if (is_array($crumbs) || is_string($crumbs)) { BreadcrumbRegistry::push($crumbs, $url); } return $this; }
Adds a new crumb to the stack. You can use this method without any argument, if you do, it will automatically try to guess the full breadcrumb path based on current URL (if current URL matches any URL in any of your menu links). ```php $this->Breadcrumb->push(); ``` Also, you can can pass a string as first argument representing an URL, if you do, it will try to find that URL in in any of your menus, and then generate its corresponding breadcrumb. ```php $this->Breadcrumb->push('/admin/some/url'); ``` @param array|string|null $crumbs Single crumb or an array of multiple crumbs to push at once. Or null for guess from current URL @param mixed $url If both $crumbs and $url are string values they will be used as `title` and `URL` respectively @return $this For method chaining @see \Menu\View\BreadcrumbRegistry::push()
entailment
protected function _urlChunk($url = null) { if (empty($url)) { $url = '/' . $this->_controller->request->url; } $cacheKey = 'urlChunk_' . md5($url); $cache = static::cache($cacheKey); if ($cache !== null) { return $cache; } $parsedURL = Router::parse($url); $out = [$url]; $passArguments = []; if (!empty($parsedURL['?'])) { unset($parsedURL['?']); } if (!empty($parsedURL['pass'])) { $passArguments = $parsedURL['pass']; $parsedURL['pass'] = null; $parsedURL = array_merge($parsedURL, $passArguments); } // "/controller_name/index" -> "/controller" if ($parsedURL['action'] === 'index') { $parsedURL['action'] = null; $out[] = Router::url($parsedURL); } // "/plugin_name/plugin_name/action_name" -> "/plugin_name/action_name" if (!empty($parsedURL['plugin']) && strtolower($parsedURL['controller']) === strtolower($parsedURL['plugin']) ) { $parsedURL['plugin'] = null; $out[] = Router::url($parsedURL); } foreach (array_reverse($passArguments) as $pass) { unset($parsedURL[array_search($pass, $parsedURL)]); $out[] = Router::url($parsedURL); } $out = array_map(function ($value) { if (str_starts_with($value, $this->_controller->request->base)) { return str_replace_once($this->_controller->request->base, '', $value); } return $value; }, $out); return static::cache($cacheKey, array_unique($out)); }
Returns possible URL combinations for the given URL or current request's URL. ### Example: For the given URL, `/admin/content/manage/index/arg1/arg2?get1=v1&get2=v2` where: - `/admin`: Prefix. - `/content`: Plugin name. - `/manage`: Controller name. - `/index`: Controller's action. - `/arg1` and `/arg2`: Action's arguments. - `get1` and `get2`: GET arguments. The following array will be returned by this method: ```php [ "/admin/content/content/index/arg1/arg2?get1=v1&get2=v2", "/admin/content/content/arg1/arg2", "/admin/content/arg1/arg2", "/admin/content/arg1", "/admin/content", ] ``` @param string|null $url The URL to chunk as string value, set to null will use current request URL. @return array
entailment
public static function formatter($view, $field) { switch ($field->viewModeSettings['formatter']) { case 'link': $out = $view->element('Field.FileField/display_link', compact('field')); break; case 'table': $out = $view->element('Field.FileField/display_table', compact('field')); break; case 'url': default: $out = $view->element('Field.FileField/display_url', compact('field')); break; } return $out; }
Renders the given custom field. @param \Cake\View\View $view Instance of view class @param \Field\Model\Entity\Field $field The field to be rendered @return string HTML code
entailment
public static function fileIcon($mime, $iconsDirectory = false) { if (!$iconsDirectory) { $iconsDirectory = Plugin::path('Field') . 'webroot/img/file-icons/'; } // If there's an icon matching the exact mimetype, go for it. $dashedMime = strtr($mime, ['/' => '-']); if (is_readable("{$iconsDirectory}{$dashedMime}.png")) { return "{$dashedMime}.png"; } // For a few mimetypes, we can "manually" map to a generic icon. $genericMime = (string)static::fileIconMap($mime); if ($genericMime && is_readable("{$iconsDirectory}{$genericMime}.png")) { return "{$genericMime}.png"; } // Use generic icons for each category that provides such icons. if (preg_match('/^(audio|image|text|video)\//', $mime, $matches)) { if (is_readable("{$iconsDirectory}{$matches[1]}-x-generic.png")) { return "{$matches[1]}-x-generic.png"; } } if (is_readable("{$iconsDirectory}/application-octet-stream.png")) { return 'application-octet-stream.png'; } return false; }
Creates a path to the icon for a file mime. @param string $mime File mime type @param mixed $iconsDirectory A path to a directory of icons to be used for files. Defaults to built-in icons directory (Field/webroot/img/file-icons/) @return mixed A string for the icon file name, or false if an appropriate icon could not be found
entailment
public static function fileIconMap($mime) { foreach (FileIconMap::$map as $icon => $mimeList) { if (in_array($mime, $mimeList)) { return $icon; } } return false; }
Determine the generic icon MIME package based on a file's MIME type. @param string $mime File mime type @return string The generic icon MIME package expected for this file
entailment
public static function ext($fileName) { if (strpos($fileName, '.') === false) { return ''; } return strtolower( substr( $fileName, strrpos($fileName, '.') + 1, strlen($fileName) ) ); }
Get file extension. @param string $fileName File name, including its extension. e.g.: `my-file.docx` @return string File extension without the ending DOT and lowercased, e.g. `pdf`, `jpg`, `png`, etc. If no extension is found an empty string will be returned
entailment
public function getOptionParser() { $parser = parent::getOptionParser(); $parser ->description(__d('eav', 'Select target table')) ->addOption('use', [ 'short' => 'u', 'help' => __d('eav', 'The table alias name. e.g. "User.Users".'), ]) ->addOption('action', [ 'short' => 'a', 'help' => __d('eav', 'Indicates what you want to do, drop an existing column or add a new one.'), 'default' => 'add', 'choices' => ['add', 'drop'], ]) ->addOption('name', [ 'short' => 'n', 'help' => __d('eav', 'Name of the column to be added or dropped'), ]) ->addOption('type', [ 'short' => 't', 'help' => __d('eav', 'Type of information for the column being added.'), 'default' => 'string', 'choices' => EavToolbox::$types, ]) ->addOption('bundle', [ 'short' => 'b', 'help' => __d('eav', 'Indicates the column belongs to a bundle name within the table.'), 'default' => null, ]) ->addOption('searchable', [ 'short' => 's', 'help' => __d('eav', 'Whether the column being created can be used in SQL WHERE clauses.'), 'boolean' => true, 'default' => true, ]) ->addOption('overwrite', [ 'short' => 'o', 'help' => __d('eav', 'Overwrite column definition if already exists. An exception will be raised when overwrite is disabled and column already exists.'), 'boolean' => true, ]); return $parser; }
Gets the option parser instance and configures it. @return \Cake\Console\ConsoleOptionParser
entailment
public function main() { $options = (array)$this->params; if (empty($options['use'])) { $this->err(__d('eav', 'You must indicate a table alias name using the "--use" option. Example: "Articles.Users"')); return false; } try { $table = TableRegistry::get($options['use']); } catch (\Exception $ex) { $table = false; } if (!$table) { $this->err(__d('eav', 'The specified table does not exists.')); return false; } elseif (!$table->behaviors()->has('Eav')) { $this->err(__d('eav', 'The specified table is not using EAV behavior.')); return false; } elseif (empty($options['name'])) { $this->err(__d('eav', 'You must indicate a table column.')); return false; } elseif (!preg_match('/^[a-z\d\-_]+$/', $options['name'])) { $this->err(__d('eav', 'Invalid column name, please use only lowercase letters, numbers, "-" and "_", e.g.: "user_age".')); return false; } $meta = [ 'type' => $options['type'], 'bundle' => (empty($options['bundle']) ? null : (string)$options['bundle']), 'searchable' => $options['searchable'], 'overwrite' => $options['overwrite'], ]; if ($options['action'] == 'drop') { return $table->dropColumn($options['name'], $meta['bundle']); } try { $errors = $table->addColumn($options['name'], $meta); if (!empty($errors)) { foreach ($errors as $message) { $this->err($message); } return false; } return true; } catch (FatalErrorException $ex) { $this->err($ex->getMessage()); return false; } }
Adds or drops the specified column. @return bool
entailment
public static function match($version, $constraints = null) { if (is_string($version) && empty($version)) { return false; } if (empty($constraints) || $version == $constraints) { return true; } $parser = new VersionParser(); $modifierRegex = '[\-\@]dev(\#\w+)?'; $constraints = preg_replace('{' . $modifierRegex . '$}i', '', $constraints); $version = $parser->normalize($version); $version = preg_replace('{' . $modifierRegex . '$}i', '', $version); if (empty($constraints) || $version == $constraints) { return true; } try { $pkgConstraint = new VersionConstraint('==', $version); $constraintObjects = $parser->parseConstraints($constraints); return $constraintObjects->matches($pkgConstraint); } catch (\Exception $ex) { return false; } }
Check whether a version matches the given constraint. ### Example: ```php Constraint::match('1.2.6', '>=1.1'); // returns true ``` @param string $version The version to check against (e.g. v4.2.6) @param string $constraints A string representing a dependency constraints, for instance, `>7.0 || 1.2` @return bool True if compatible, false otherwise @see https://getcomposer.org/doc/01-basic-usage.md#package-versions
entailment
public function toPHP($value, Driver $driver) { if ($this->_isSerialized($value)) { $value = unserialize($value); } return $value; }
Deserialize the stored information if it was serialized before. @param string $value The serialized element to deserialize @param \Cake\Database\Driver $driver Database connection driver @return mixed
entailment
public function toDatabase($value, Driver $driver) { if (is_array($value) || is_object($value)) { return serialize($value); } return (string)$value; }
Serializes (if it can) the information to be stored in DB. Arrays and object are serialized, any other type of information will be stored as plain text. @param mixed $value Array or object to be serialized, any other type will not be serialized @param \Cake\Database\Driver $driver Database connection driver @return string
entailment
public function shortcodeBlock(Event $event, array $atts, $content, $tag) { $out = ''; if (isset($atts[0])) { $id = intval($atts[0]); try { $block = TableRegistry::get('Block.Blocks')->get($id); $out = $event->subject()->render($block); } catch (\Exception $ex) { $out = !Configure::read('debug') ? '' : "<!-- block #{$id} not found -->"; } } return $out; }
Implements the "block" shortcode. {block 1 /} @param \Cake\Event\Event $event The event that was fired @param array $atts An associative array of attributes, or an empty string if no attributes are given @param string $content The enclosed content (if the shortcode is used in its enclosing form) @param string $tag The shortcode name @return string
entailment
public function edit(View $view) { $handler = $this->get('metadata')->get('handler'); if (class_exists($handler)) { $handler = new $handler(); return $handler->edit($this, $view); } return ''; }
Renders field in edit mode. @return string
entailment
public function fieldAttached() { $handler = $this->get('metadata')->get('handler'); if (class_exists($handler)) { $handler = new $handler(); return $handler->fieldAttached($this); } return true; }
Triggers entity's fieldAttached callback. @return void
entailment
public function beforeFind(array $options, $primary) { $handler = $this->get('metadata')->get('handler'); if (class_exists($handler)) { $handler = new $handler(); return $handler->beforeFind($this, $options, $primary); } return true; }
Triggers entity's beforeFind callback. Returning NULL will remove the entity from resulting collection, returning FALSE will halt the entire find operation. @param array $options Options given to Query::find() @param bool $primary Whether this find comes from a primary find query or not @return bool|null
entailment
public function validate(Validator $validator) { $handler = $this->get('metadata')->get('handler'); if (class_exists($handler)) { $handler = new $handler(); return $handler->validate($this, $validator); } }
Triggers entity's validate callback. @param \Cake\Validation\Validator $validator The validator object to be altered. @return bool|null
entailment
public function beforeSave($post) { $handler = $this->get('metadata')->get('handler'); if (class_exists($handler)) { $handler = new $handler(); return $handler->beforeSave($this, $post); } return true; }
Triggers entity's beforeSave callback. Returning FALSE will halt the save operation. @param mixed $post Post data received for this particular Field @return bool
entailment
public function afterSave() { $handler = $this->get('metadata')->get('handler'); if (class_exists($handler)) { $handler = new $handler(); return $handler->afterSave($this); } }
Triggers entity's afterSave callback. @return void
entailment
public function beforeDelete() { $handler = $this->get('metadata')->get('handler'); if (class_exists($handler)) { $handler = new $handler(); return $handler->beforeDelete($this); } return true; }
Triggers entity's beforeDelete callback. Returning FALSE will halt the delete operation. @return bool
entailment
public function index() { $this->loadModel('User.Acos'); $roles = $this->Acos->Roles->find()->all(); $this->title(__d('user', 'User Roles List')); $this->set(compact('roles')); $this->Breadcrumb ->push('/admin/user/manage') ->push(__d('user', 'Roles'), ['plugin' => 'User', 'controller' => 'roles', 'action' => 'index']); }
Shows a list of all available roles. @return void
entailment
public function add() { $this->loadModel('User.Roles'); $role = $this->Roles->newEntity(); if ($this->request->data()) { $role = $this->Roles->patchEntity($role, $this->request->data(), ['fieldList' => 'name']); if ($this->Roles->save($role)) { $this->Flash->success(__d('user', 'Role successfully created.')); } else { $this->Flash->danger(__d('user', 'Role could not be created.')); } } $this->title(__d('user', 'Define New Role')); $this->set(compact('role')); $this->Breadcrumb ->push('/admin/user/manage') ->push(__d('user', 'Roles'), ['plugin' => 'User', 'controller' => 'roles', 'action' => 'index']) ->push(__d('user', 'Add new role'), ''); }
Add a new role. @return void
entailment
public function edit($id) { $this->loadModel('User.Roles'); $role = $this->Roles->get($id); if ($this->request->data()) { if (empty($this->request->data['regenerate_slug'])) { $this->Roles->behaviors()->Sluggable->config(['on' => 'create']); } $role = $this->Roles->patchEntity($role, $this->request->data(), ['fieldList' => 'name']); if ($this->Roles->save($role)) { $this->Flash->success(__d('user', 'Role successfully updated.')); } else { $this->Flash->danger(__d('user', 'Role could not be updated.')); } } $this->title(__d('user', 'Editing User Role')); $this->set(compact('role')); $this->Breadcrumb ->push('/admin/user/manage') ->push(__d('user', 'Roles'), ['plugin' => 'User', 'controller' => 'roles', 'action' => 'index']) ->push(__d('user', 'Edit role'), ''); }
Edits the given role. @param int $id Role ID @return void
entailment
public function delete($id) { $this->loadModel('User.Roles'); $role = $this->Roles->get($id); if (!in_array($role->id, [ROLE_ID_ADMINISTRATOR, ROLE_ID_AUTHENTICATED, ROLE_ID_ANONYMOUS])) { if ($this->Roles->delete($role)) { $this->Flash->success(__d('user', 'Role was successfully removed!')); } else { $this->Flash->danger(__d('user', 'Role could not be removed')); } } else { $this->Flash->danger(__d('user', 'This role cannot be deleted!')); } $this->title(__d('user', 'Remove User Role')); $this->redirect($this->referer()); }
Removes the given role. @param int $id Role ID @return void Redirects to previous page
entailment
public function beforeFilter(Event $event) { $requestParams = $event->subject()->request->params; if (!isset($this->_manageTable) || empty($this->_manageTable)) { throw new ForbiddenException(__d('comment', 'CommentUIControllerTrait: The property $_manageTable was not found or is empty.')); } elseif (!($this instanceof \Cake\Controller\Controller)) { throw new ForbiddenException(__d('comment', 'CommentUIControllerTrait: This trait must be used on instances of Cake\Controller\Controller.')); } elseif (!isset($requestParams['prefix']) || strtolower($requestParams['prefix']) !== 'admin') { throw new ForbiddenException(__d('comment', 'CommentUIControllerTrait: This trait must be used on backend-controllers only.')); } elseif (!method_exists($this, '_inResponseTo')) { throw new ForbiddenException(__d('comment', 'CommentUIControllerTrait: This trait needs you to implement the "_inResponseTo()" method.')); } $this->_manageTable = Inflector::underscore($this->_manageTable); $this->helpers[] = 'Time'; $this->helpers[] = 'Paginator'; $this->paginate['limit'] = 10; $this->loadComponent('Paginator'); $this->loadComponent('Comment.Comment'); $this->Comment->initialize([]); }
Validation rules. @param \Cake\Event\Event $event The event instance. @return void @throws \Cake\Network\Exception\ForbiddenException When - $_manageTable is not defined. - trait is used in non-controller classes. - the controller is not a backend controller. - the "_inResponseTo()" is not implemented.
entailment
public function beforeRender(Event $event) { $plugin = (string)Inflector::camelize($event->subject()->request->params['plugin']); $controller = Inflector::camelize($event->subject()->request->params['controller']); $action = Inflector::underscore($event->subject()->request->params['action']); $prefix = ''; if (!empty($event->subject()->request->params['prefix'])) { $prefix = Inflector::camelize($event->subject()->request->params['prefix']) . '/'; } $templatePath = Plugin::classPath($plugin) . "Template/{$prefix}{$controller}/{$action}.ctp"; if (!is_readable($templatePath)) { $alternativeTemplatePath = Plugin::classPath('Comment') . 'Template/CommentUI'; if (is_readable("{$alternativeTemplatePath}/{$action}.ctp")) { $this->plugin = 'Comment'; $this->viewBuilder()->templatePath('CommentUI'); } } parent::beforeRender($event); }
Fallback for template location when extending Comment UI API. If controller tries to render an unexisting template under its Template directory, then we try to find that view under `Comment/Template/CommentUI` directory. ### Example: Suppose you are using this trait to manage comments attached to `Persons` entities. You would probably have a `Person` plugin and a `clean` controller as follow: // http://example.com/admin/person/comments_manager Person\Controller\CommentsManagerController::index() The above controller action will try to render `/plugins/Person/Template/CommentsManager/index.ctp`. But if does not exists then `<QuickAppsCorePath>/plugins/Comment/Template/CommentUI/index.ctp` will be used instead. Of course you may create your own template and skip this fallback functionality. @param \Cake\Event\Event $event the event instance. @return void
entailment
public function index($status = 'all') { $this->loadModel('Comment.Comments'); $this->_setCounters(); $search = ''; // fills form's input $conditions = ['table_alias' => $this->_manageTable]; if (in_array($status, ['pending', 'approved', 'spam', 'trash'])) { $conditions['Comments.status'] = $status; } else { $status = 'all'; $conditions['Comments.status IN'] = ['pending', 'approved']; } if (!empty($this->request->query['search'])) { $search = $this->request->query['search']; $conditions['OR'] = [ 'Comments.subject LIKE' => "%{$this->request->query['search']}%", 'Comments.body LIKE' => "%{$this->request->query['search']}%", ]; } $comments = $this->Comments ->find() ->contain(['Users']) ->where($conditions) ->order(['Comments.created' => 'DESC']) ->formatResults(function ($results) { return $results->map(function ($comment) { $comment->set('entity', $this->_inResponseTo($comment)); $comment->set( 'body', TextToolbox::trimmer( TextToolbox::plainProcessor( TextToolbox::stripHtmlTags($comment->body) ), 180 ) ); return $comment; }); }); $this->title(__d('comment', 'Comments List')); $this->set('search', $search); $this->set('filterBy', $status); $this->set('comments', $this->paginate($comments)); }
Field UI main action. Shows all the comments attached to the Table being managed. Possibles values for status are: - `all`: Comments marked as `pending` or `approved`. (by default) - `pending`: Comments awaiting for moderation. - `approved`: Comments approved and published. - `spam`: Comments marked as SPAM by Akismet. - `trash`: Comments that were sent to trash bin. @param string $status Filter comments by `status`, see list above @return void
entailment
public function edit($id) { $this->loadModel('Comment.Comments'); $comment = $this->Comments ->find() ->contain(['Users']) ->where(['Comments.id' => $id, 'Comments.table_alias' => $this->_manageTable]) ->first(); if (!$comment) { throw new RecordNotFoundException(__d('comment', 'Comment could not be found.')); } if ($this->request->data()) { $comment->accessible('*', false); $comment->accessible(['subject', 'body', 'author_name', 'author_email', 'author_web', 'status'], true); $validator = $comment->user_id ? 'default' : 'anonymous'; $this->Comments->patchEntity($comment, $this->request->data(), ['validate' => $validator]); $errors = $comment->errors(); if (empty($errors)) { $this->Comments->save($comment, ['associated' => false]); $this->Flash->success(__d('comment', 'Comment saved!.')); $this->redirect($this->referer()); } else { $this->Flash->danger(__d('comment', 'Comment could not be saved, please check your information.')); } } $this->title(__d('comment', 'Editing Comment')); $this->set('comment', $comment); }
Edit form for given comment. @param int $id Comment id @return void Redirects to previous page @throws \Cake\ORM\Exception\RecordNotFoundException When comment was not found
entailment
public function status($id, $status) { if (in_array($status, ['pending', 'approved', 'spam', 'trash'])) { $this->loadModel('Comment.Comments'); if ($comment = $this->Comments->get($id)) { $comment->set('status', $status); $this->Comments->save($comment); } } $this->title(__d('comment', 'Change Comment Status')); $this->redirect($this->referer()); }
Changes the status of the given comment. @param int $id Comment id @param string $status New status for the comment @return void Redirects to previous page
entailment
public function delete($id) { $this->loadModel('Comment.Comments'); $comment = $this->Comments ->find() ->where(['Comments.id' => $id, 'Comments.table_alias' => $this->_manageTable]) ->first(); if ($comment) { if ($this->Comments->delete($comment)) { $this->Flash->success(__d('comment', 'Comment was successfully deleted!')); } else { $this->Flash->danger(__d('comment', 'Comment could not be deleted, please try again.')); } } else { $this->Flash->danger(__d('comment', 'Invalid comment, comment was not found.')); } $this->title(__d('comment', 'Delete Comment')); $this->redirect($this->referer()); }
Permanently deletes the given comment. @param int $id Comment id @return void Redirects to previous page
entailment
public function emptyTrash() { $this->loadModel('Comment.Comments'); $this->Comments->deleteAll(['Comments.status' => 'trash', 'Comments.table_alias' => $this->_manageTable]); $this->Flash->success(__d('comment', 'All comments in trash were successfully removed!')); $this->title(__d('comment', 'Empty Trash')); $this->redirect($this->referer()); }
Permanently deletes all comments marked as "trash". @return void Redirects to previous page
entailment
protected function _setCounters() { $this->loadModel('Comment.Comments'); $pending = $this->Comments->find()->where(['Comments.status' => 'pending', 'Comments.table_alias' => $this->_manageTable])->count(); $approved = $this->Comments->find()->where(['Comments.status' => 'approved', 'Comments.table_alias' => $this->_manageTable])->count(); $spam = $this->Comments->find()->where(['Comments.status' => 'spam', 'Comments.table_alias' => $this->_manageTable])->count(); $trash = $this->Comments->find()->where(['Comments.status' => 'trash', 'Comments.table_alias' => $this->_manageTable])->count(); $this->set('pendingCounter', $pending); $this->set('approvedCounter', $approved); $this->set('spamCounter', $spam); $this->set('trashCounter', $trash); }
Sets a few view-variables holding counters for each status ("pending", "approved", "spam" or "trash"). @return void
entailment
public function isAccessibleByUser($roles = null) { if ($roles === null) { $roles = $this->get('roles'); } if (empty($roles)) { return true; } $entityRolesID = []; foreach ((array)$roles as $role) { if ($role instanceof EntityInterface) { $entityRolesID[] = $role->get('id'); } elseif (is_array($role) && array_key_exists('id', $role)) { $entityRolesID[] = $role['id']; } elseif (is_integer($role)) { $entityRolesID[] = $role; } } $intersect = array_intersect($entityRolesID, (array)user()->get('role_ids')); return !empty($intersect); }
Whether this entity can be accessed by current user based on his/her roles. @param array|null $roles Array list of roles to checks against to, or NULL to automatically use entity's "roles" property @return bool False if user has no permissions to see this entity due to role restrictions, true otherwise
entailment
public function getOptionParser() { $parser = parent::getOptionParser(); $parser ->description('Table schema manipulator.') ->addSubcommand('schema', [ 'help' => 'Allows to add or drop virtual columns to tables.', 'parser' => $this->Schema->getOptionParser(), ]) ->addSubcommand('info', [ 'help' => 'Display information of virtual columns attached to tables.', 'parser' => $this->Info->getOptionParser(), ]); return $parser; }
Gets the option parser instance and configures it. @return \Cake\Console\ConsoleOptionParser
entailment
public function scope(Query $query, $bundle = null) { $orderClause = $query->clause('order'); if (!$orderClause) { return $query; } $class = new \ReflectionClass($orderClause); $property = $class->getProperty('_conditions'); $property->setAccessible(true); $conditions = $property->getValue($orderClause); foreach ($conditions as $column => $direction) { if (empty($column) || in_array($column, (array)$this->_table->schema()->columns()) || // ignore real columns !in_array($column, $this->_toolbox->getAttributeNames()) ) { continue; } $conditions['(' . $this->_subQuery($column, $bundle) . ')'] = $direction; unset($conditions[$column]); } $property->setValue($orderClause, $conditions); return $query; }
{@inheritDoc} Look for virtual columns in query's WHERE clause. @param \Cake\ORM\Query $query The query to scope @param string|null $bundle Consider attributes only for a specific bundle @return \Cake\ORM\Query The modified query object
entailment
protected function _subQuery($column, $bundle = null) { $alias = $this->_table->alias(); $pk = $this->_table->primaryKey(); $type = $this->_toolbox->getType($column); $subConditions = [ 'EavAttribute.table_alias' => $this->_table->table(), 'EavValues.entity_id' => "{$alias}.{$pk}", 'EavAttribute.name' => $column, ]; if (!empty($bundle)) { $subConditions['EavAttribute.bundle'] = $bundle; } $subQuery = TableRegistry::get('Eav.EavValues') ->find() ->contain(['EavAttribute']) ->select(["EavValues.value_{$type}"]) ->where($subConditions) ->sql(); return str_replace([':c0', ':c1', ':c2', ':c3'], [ '"' . $this->_table->table() . '"', "{$alias}.{$pk}", '"' . $column . '"', '"' . $bundle . '"' ], $subQuery); }
Generates a SQL sub-query for replacing in ORDER BY clause. @param string $column Name of the column being replaced by this sub-query @param string|null $bundle Consider attributes only for a specific bundle @return string SQL sub-query statement
entailment
public function normalize($version, $fullVersion = null) { $version = trim($version); if (null === $fullVersion) { $fullVersion = $version; } // ignore aliases and just assume the alias is required instead of the source if (preg_match('{^([^,\s]+) +as +([^,\s]+)$}', $version, $match)) { $version = $match[1]; } // ignore build metadata if (preg_match('{^([^,\s+]+)\+[^\s]+$}', $version, $match)) { $version = $match[1]; } // match master-like branches if (preg_match('{^(?:dev-)?(?:master|trunk|default)$}i', $version)) { return '9999999-dev'; } if ('dev-' === strtolower(substr($version, 0, 4))) { return 'dev-' . substr($version, 4); } // match classical versioning if (preg_match('{^v?(\d{1,3})(\.\d+)?(\.\d+)?(\.\d+)?' . self::$modifierRegex . '$}i', $version, $matches)) { $version = $matches[1] . (!empty($matches[2]) ? $matches[2] : '.0') . (!empty($matches[3]) ? $matches[3] : '.0') . (!empty($matches[4]) ? $matches[4] : '.0'); $index = 5; } elseif (preg_match('{^v?(\d{4}(?:[.:-]?\d{2}){1,6}(?:[.:-]?\d{1,3})?)' . self::$modifierRegex . '$}i', $version, $matches)) { // match date-based versioning $version = preg_replace('{\D}', '-', $matches[1]); $index = 2; } elseif (preg_match('{^v?(\d{4,})(\.\d+)?(\.\d+)?(\.\d+)?' . self::$modifierRegex . '$}i', $version, $matches)) { $version = $matches[1] . (!empty($matches[2]) ? $matches[2] : '.0') . (!empty($matches[3]) ? $matches[3] : '.0') . (!empty($matches[4]) ? $matches[4] : '.0'); $index = 5; } // add version modifiers if a version was matched if (isset($index)) { if (!empty($matches[$index])) { if ('stable' === $matches[$index]) { return $version; } $version .= '-' . $this->expandStability($matches[$index]) . (!empty($matches[$index + 1]) ? $matches[$index + 1] : ''); } if (!empty($matches[$index + 2])) { $version .= '-dev'; } return $version; } // match dev branches if (preg_match('{(.*?)[.-]?dev$}i', $version, $match)) { try { return $this->normalizeBranch($match[1]); } catch (\Exception $e) { } } $extraMessage = ''; if (preg_match('{ +as +' . preg_quote($version) . '$}', $fullVersion)) { $extraMessage = ' in "' . $fullVersion . '", the alias must be an exact version'; } elseif (preg_match('{^' . preg_quote($version) . ' +as +}', $fullVersion)) { $extraMessage = ' in "' . $fullVersion . '", the alias source must be an exact version, if it is a branch name you should prefix it with dev-'; } throw new \UnexpectedValueException('Invalid version string "' . $version . '"' . $extraMessage); }
Normalizes a version string to be able to perform comparisons on it @param string $version Version @param string $fullVersion optional complete version string to give more context @throws \UnexpectedValueException @return string
entailment
public function parseConstraints($constraints) { $prettyConstraint = $constraints; if (preg_match('{^([^,\s]*?)@(' . implode('|', array_keys(BasePackage::$stabilities)) . ')$}i', $constraints, $match)) { $constraints = empty($match[1]) ? '*' : $match[1]; } if (preg_match('{^(dev-[^,\s@]+?|[^,\s@]+?\.x-dev)#.+$}i', $constraints, $match)) { $constraints = $match[1]; } $orConstraints = preg_split('{\s*\|\|?\s*}', trim($constraints)); $orGroups = []; foreach ($orConstraints as $constraints) { $andConstraints = preg_split('{(?<!^|as|[=>< ,]) *(?<!-)[, ](?!-) *(?!,|as|$)}', $constraints); if (count($andConstraints) > 1) { $constraintObjects = []; foreach ($andConstraints as $constraint) { $constraintObjects = array_merge($constraintObjects, $this->parseConstraint($constraint)); } } else { $constraintObjects = $this->parseConstraint($andConstraints[0]); } if (1 === count($constraintObjects)) { $constraint = $constraintObjects[0]; } else { $constraint = new MultiConstraint($constraintObjects); } $orGroups[] = $constraint; } if (1 === count($orGroups)) { $constraint = $orGroups[0]; } else { $constraint = new MultiConstraint($orGroups, false); } $constraint->setPrettyString($prettyConstraint); return $constraint; }
Parses as constraint string into LinkConstraint objects @param string $constraints Constraints @return \Composer\Package\LinkConstraint\LinkConstraintInterface
entailment
public function manipulateVersionString($matches, $position, $increment = 0, $pad = '0') { for ($i = 4; $i > 0; $i--) { if ($i > $position) { $matches[$i] = $pad; } elseif ($i == $position && $increment) { $matches[$i] += $increment; // If $matches[$i] was 0, carry the decrement if ($matches[$i] < 0) { $matches[$i] = $pad; $position--; // Return null on a carry overflow if ($i == 1) { return; } } } } return $matches[1] . '.' . $matches[2] . '.' . $matches[3] . '.' . $matches[4]; }
Increment, decrement, or simply pad a version number. Support function for {@link parseConstraint()} @param array $matches Array with version parts in array indexes 1,2,3,4 @param int $position 1,2,3,4 - which segment of the version to decrement @param int $increment Increment @param string $pad The string to pad version parts after $position @return string The new version
entailment
public function buildRules(RulesChecker $rules) { // check max instances limit $rules->addCreate(function ($instance, $options) { $info = (array)$instance->info(); if (isset($info['maxInstances']) && $info['maxInstances'] > 0) { if (!$instance->get('eav_attribute')) { return false; } $count = $this ->find() ->select(['FieldInstances.id', 'FieldInstances.handler', 'EavAttribute.id', 'EavAttribute.table_alias']) ->contain(['EavAttribute']) ->where([ 'EavAttribute.table_alias' => $instance->get('eav_attribute')->get('table_alias'), 'FieldInstances.handler' => $instance->get('handler'), ]) ->count(); return ($count <= (intval($info['maxInstances']) - 1)); } return true; }, 'maxInstances', [ 'errorField' => 'label', 'message' => __d('field', 'No more instances of this field can be attached, limit reached.'), ]); return $rules; }
Application rules. @param \Cake\ORM\RulesChecker $rules The rule checker @return \Cake\ORM\RulesChecker
entailment
public function validationDefault(Validator $validator) { $validator ->notEmpty('handler', __d('field', 'Invalid field type.')) ->add('label', [ 'notBlank' => [ 'rule' => 'notBlank', 'message' => __d('field', 'You need to provide a label.'), ], 'length' => [ 'rule' => ['minLength', 3], 'message' => __d('field', 'Label need to be at least 3 characters long'), ], ]); return $validator; }
Default validation rules set. @param \Cake\Validation\Validator $validator The validator object @return \Cake\Validation\Validator
entailment
public function beforeFind(Event $event, Query $query, ArrayObject $options, $primary) { $viewModes = $this->viewModes(); $query->formatResults(function ($results) use ($viewModes) { return $results->map(function ($instance) use ($viewModes) { if (!is_object($instance)) { return $instance; } foreach ($viewModes as $viewMode) { $instanceViewModes = $instance->view_modes; $viewModeDefaults = array_merge([ 'label_visibility' => 'above', 'shortcodes' => false, 'hidden' => false, 'ordering' => 0, ], (array)$instance->defaultViewModeSettings($viewMode)); if (!isset($instanceViewModes[$viewMode])) { $instanceViewModes[$viewMode] = []; } $instanceViewModes[$viewMode] = array_merge($viewModeDefaults, $instanceViewModes[$viewMode]); $instance->set('view_modes', $instanceViewModes); } $settingsDefaults = (array)$instance->defaultSettings(); if (!empty($settingsDefaults)) { $instanceSettings = $instance->get('settings'); foreach ($settingsDefaults as $k => $v) { if (!isset($instanceSettings[$k])) { $instanceSettings[$k] = $v; } } $instance->set('settings', $instanceSettings); } return $instance; }); }); }
Here we set default values for each view mode if they were not defined before. @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 void
entailment
public function beforeSave(Event $event, FieldInstance $instance, ArrayObject $options = null) { $result = $instance->beforeAttach(); if ($result === false) { return false; } return true; }
Triggers the callback "beforeAttach" if a new instance is being created. @param \Cake\Event\Event $event The event that was triggered @param \Field\Model\Entity\FieldInstance $instance The Field Instance that is going to be saved @param \ArrayObject $options The options passed to the save method @return bool False if save operation should not continue, true otherwise
entailment
public function afterSave(Event $event, FieldInstance $instance, ArrayObject $options = null) { if ($instance->isNew()) { $instance->afterAttach(); } }
Triggers the callback "afterAttach" if a new instance was created. @param \Cake\Event\Event $event The event that was triggered @param \Field\Model\Entity\FieldInstance $instance The Field Instance that was saved @param \ArrayObject $options the options passed to the save method @return void
entailment
public function beforeDelete(Event $event, FieldInstance $instance, ArrayObject $options = null) { $result = $instance->beforeDetach(); if ($result === false) { return false; } $this->_deleted = $this->get($instance->get('id'), ['contain' => ['EavAttribute']]); return true; }
Triggers the callback "beforeDetach". @param \Cake\Event\Event $event The event that was triggered @param \Field\Model\Entity\FieldInstance $instance The Field Instance that is going to be deleted @param \ArrayObject $options the options passed to the delete method @return bool False if delete operation should not continue, true otherwise
entailment
public function afterDelete(Event $event, FieldInstance $instance, ArrayObject $options = null) { if (!empty($this->_deleted)) { TableRegistry::get('Eav.EavAttributes')->delete($this->_deleted->get('eav_attribute')); $instance->afterDetach(); $this->_deleted = null; } }
Triggers the callback "afterDetach", it also deletes all associated records in the "field_values" table. @param \Cake\Event\Event $event The event that was triggered @param \Field\Model\Entity\FieldInstance $instance The Field Instance that was deleted @param \ArrayObject $options the options passed to the delete method @return void
entailment
public function initialize(array $config) { $this->hasMany('BlockRegions', [ 'className' => 'Block.BlockRegions', 'foreignKey' => 'block_id', 'dependent' => true, 'propertyName' => 'region', ]); $this->hasMany('Copies', [ 'className' => 'Block.Blocks', 'foreignKey' => 'copy_id', 'dependent' => true, 'propertyName' => 'copies', 'cascadeCallbacks' => true, ]); $this->belongsToMany('User.Roles', [ 'className' => 'User.Roles', 'foreignKey' => 'block_id', 'joinTable' => 'blocks_roles', 'dependent' => false, 'propertyName' => 'roles', ]); $this->addBehavior('Serializable', [ 'columns' => ['locale', 'settings'] ]); }
Initialize method. @param array $config The configuration for the Table. @return void
entailment
public function unused() { $ids = []; foreach ([$this->inFrontTheme(), $this->inBackTheme()] as $bundle) { foreach ($bundle as $region => $blocks) { foreach ($blocks as $block) { $ids[] = $block->get('id'); } } } $notIn = array_unique($ids); $notIn = empty($notIn) ? ['0'] : $notIn; return $this->find() ->where([ 'OR' => [ 'Blocks.id NOT IN' => $notIn, 'Blocks.status' => 0, ] ]) ->all() ->filter(function ($block) { return $block->renderable(); }); }
Gets a list of all blocks that are NOT renderable. @return \Cake\Collection\CollectionInterface
entailment
protected function _inTheme($type = 'front') { $theme = option("{$type}_theme"); $composer = plugin($theme)->composer(true); $regions = $composer['extra']['regions']; $out = []; foreach ($regions as $slug => $name) { $blocks = $this->find() ->matching('BlockRegions', function ($q) use ($slug, $theme) { return $q->where([ 'BlockRegions.theme' => $theme, 'BlockRegions.region' => $slug, ]); }) ->where(['Blocks.status' => 1]) ->all() ->filter(function ($block) { return $block->renderable(); }) ->sortBy(function ($block) { return $block->region->ordering; }, SORT_ASC); $out[$name] = $blocks; } return $out; }
Gets a list of all blocks renderable in the given theme type (frontend or backend). @param string $type Possible values are 'front' or 'back' @return array Blocks index by region name
entailment
public function validationWidget(Validator $validator) { return $validator ->requirePresence('title') ->add('title', [ 'notBlank' => [ 'rule' => 'notBlank', 'message' => __d('block', 'You need to provide a title.'), ], 'length' => [ 'rule' => ['minLength', 3], 'message' => __d('block', 'Title need to be at least 3 characters long.'), ], ]) ->requirePresence('description') ->add('description', [ 'notBlank' => [ 'rule' => 'notBlank', 'message' => __d('block', 'You need to provide a description.'), ], 'length' => [ 'rule' => ['minLength', 3], 'message' => __d('block', 'Description need to be at least 3 characters long.'), ], ]) ->add('visibility', 'validVisibility', [ 'rule' => function ($value, $context) { return in_array($value, ['except', 'only', 'php']); }, 'message' => __d('block', 'Invalid visibility.'), ]) ->allowEmpty('pages') ->add('pages', 'validPHP', [ 'rule' => function ($value, $context) { if (!empty($context['data']['visibility']) && $context['data']['visibility'] === 'php') { return strpos($value, '<?php') !== false && strpos($value, '?>') !== false; } return true; }, 'message' => __d('block', 'Invalid PHP code, make sure that tags "<?php" & "?>" are present.') ]) ->requirePresence('handler', 'create', __d('block', 'This field is required.')) ->add('handler', 'validHandler', [ 'rule' => 'notBlank', 'on' => 'create', 'message' => __d('block', 'Invalid block handler'), ]); }
Default validation rules. @param \Cake\Validation\Validator $validator The validator object @return \Cake\Validation\Validator
entailment
public function validationCustom(Validator $validator) { return $this->validationWidget($validator) ->requirePresence('body') ->add('body', [ 'notBlank' => [ 'rule' => 'notBlank', 'message' => __d('block', "You need to provide a content for block's body."), ], 'length' => [ 'rule' => ['minLength', 3], 'message' => __d('block', "Block's body need to be at least 3 characters long."), ], ]); }
Validation rules for custom blocks. Plugins may define their own blocks, in these cases the "body" value is optional. But blocks created by users (on the Blocks administration page) are required to have a valid "body". @param \Cake\Validation\Validator $validator The validator object @return \Cake\Validation\Validator
entailment
public function settingsValidate(Event $event, array $data, ArrayObject $options) { if (!empty($options['entity']) && $options['entity']->has('handler')) { $block = $options['entity']; if (!$block->isCustom()) { $validator = new Validator(); $block->validateSettings($data, $validator); $errors = $validator->errors((array)$data); foreach ($errors as $k => $v) { $block->errors("settings:{$k}", $v); } } } }
Validates block 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 beforeSave(Event $event, Block $block, ArrayObject $options = null) { $result = $block->beforeSave(); if ($result === false) { return false; } return true; }
Triggered before block is persisted in DB. @param \Cake\Event\Event $event The event that was triggered @param \Block\Model\Entity\Block $block The block entity being saved @param \ArrayObject $options Additional options given as an array @return bool False if save operation should not continue, true otherwise
entailment
public function afterSave(Event $event, Block $block, ArrayObject $options = null) { $block->afterSave(); $this->clearCache(); }
Triggered after block was persisted in DB. All cached blocks are automatically removed. @param \Cake\Event\Event $event The event that was triggered @param \Block\Model\Entity\Block $block The block entity that was saved @param \ArrayObject $options Additional options given as an array @return void
entailment
public function alterTextarea(MethodInvocation $invocation) { $helper = $invocation->getThis(); list($fieldName, $options) = array_pad($invocation->getArguments(), 2, null); if (!empty($options['class']) && strpos($options['class'], 'ckeditor') !== false && $helper instanceof FormHelper ) { static::$_counter++; $editorId = 'ck-editor-' . static::$_counter; $options['class'] .= ' ' . $editorId; $view = $this->getProperty($helper, '_View'); if (!static::$_scriptsLoaded) { static::$_scriptsLoaded = true; $filebrowserBrowseUrl = $view->Url->build(['plugin' => 'Wysiwyg', 'controller' => 'finder']); $view->Html->script('Wysiwyg./ckeditor/ckeditor.js', ['block' => true]); $view->Html->script('Wysiwyg./ckeditor/adapters/jquery.js', ['block' => true]); $view->Html->scriptBlock('$(document).ready(function () { CKEDITOR.editorConfig = function(config) { config.filebrowserBrowseUrl = "' . $filebrowserBrowseUrl . '"; }; });', ['block' => true]); $this->_includeLinksToContents($view); } } $this->setProperty($invocation, 'arguments', [$fieldName, $options]); return $invocation->proceed(); }
Converts the given text area into a WYSIWYG editor. @param \Go\Aop\Intercept\MethodInvocation $invocation Invocation @Around("execution(public CMS\View\Helper\FormHelper->textarea(*))") @return bool Whether object invocation should proceed or not
entailment
protected function _includeLinksToContents($view) { $items = []; $contents = TableRegistry::get('Content.Contents') ->find('all', ['fieldable' => false]) ->contain(['ContentTypes']) ->where(['status' => 1]) ->order(['sticky' => 'DESC', 'modified' => 'DESC']); foreach ($contents as $content) { $items[] = ["{$content->type}: " . h($content->title), $view->Url->build($content->url, true)]; } $view->Html->scriptBlock('var linksToContentsItems = ' . json_encode($items) . ';', ['block' => true]); $view->Html->scriptBlock('var linksToContentsLabel = "' . __d('wysiwyg', 'Link to content') . '";', ['block' => true]); $view->Html->script('Wysiwyg.ckeditor.content.links.js', ['block' => true]); }
Alters CKEditor's link plugin. Allows to link to QuickAppsCMS's contents, adds to layout header some JS code and files. @param \Cake\View\View $view Instance of view class @return void
entailment
public function beforeRender(Event $event) { $this->_beforeRender($event); $this->loadModel('Content.ContentTypes'); $this->Breadcrumb->push('/admin/content/types'); $contentType = $this->ContentTypes ->find() ->where(['slug' => $this->request->query['type']]) ->first(); switch ($this->request->action) { case 'index': $this->Breadcrumb ->push('/admin/content/manage') ->push(__d('content', 'Content Types'), '/admin/content/types') ->push(__d('content', 'Type "{0}"', $contentType->name), '/admin/content/types/edit/' . $contentType->slug) ->push(__d('content', 'Fields'), ['plugin' => 'Content', 'controller' => 'fields', 'action' => 'index', 'prefix' => 'admin']); break; case 'configure': $this->Breadcrumb ->push('/admin/content/manage') ->push(__d('content', 'Content Types'), '/admin/content/types') ->push(__d('content', 'Type "{0}"', $contentType->name), '/admin/content/types/edit/' . $contentType->slug) ->push(__d('content', 'Fields'), ['plugin' => 'Content', 'controller' => 'fields', 'action' => 'index', 'prefix' => 'admin']) ->push(__d('content', 'Configure Field "{0}"', $this->viewVars['instance']->label), '#'); break; case 'attach': $this->Breadcrumb ->push('/admin/content/manage') ->push(__d('content', 'Content Types'), '/admin/content/types') ->push(__d('content', 'Type "{0}"', $contentType->name), '/admin/content/types/edit/' . $contentType->slug) ->push(__d('content', 'Attach New Field'), ''); break; case 'viewModeList': $this->Breadcrumb ->push('/admin/content/manage') ->push(__d('content', 'Content Types'), '/admin/content/types') ->push(__d('content', 'Type "{0}"', $contentType->name), '/admin/content/types/edit/' . $contentType->slug) ->push(__d('content', 'View Mode "{0}"', $this->viewVars['viewModeInfo']['name']), ''); break; case 'viewModeEdit': $this->Breadcrumb ->push('/admin/content/manage') ->push(__d('content', 'Content Types'), '/admin/content/types') ->push(__d('content', 'Type "{0}"', $contentType->name), '/admin/content/types/edit/' . $contentType->slug) ->push(__d('content', 'View Mode "{0}"', $this->viewVars['viewModeInfo']['name']), ['plugin' => 'Content', 'controller' => 'fields', 'action' => 'view_mode_list', 'prefix' => 'admin', $this->viewVars['viewMode']]) ->push(__d('content', 'Field: {0}', $this->viewVars['instance']->label), ''); break; } }
Before every action of this controller. We sets appropriate breadcrumbs based on current action being requested. @param \Cake\Event\Event $event The event that was triggered @return void
entailment
public function scope(Query $query, TokenInterface $token) { $column = $this->config('field'); $value = $token->value(); if (!$column || empty($value)) { return $query; } list($conjunction, $value) = $this->_prepareConjunction($token); $tableAlias = $this->_table->alias(); $conditions = [ "{$tableAlias}.{$column} {$conjunction}" => $value, ]; if ($token->where() === 'or') { $query->orWhere($conditions); } elseif ($token->where() === 'and') { $query->andWhere($conditions); } else { $query->where($conditions); } return $query; }
{@inheritDoc}
entailment
protected function _prepareConjunction(TokenInterface $token) { $value = $token->value(); $conjunction = strtolower($this->config('conjunction')); if ($conjunction == 'auto') { $conjunction = strpos($value, ',') !== false ? 'in' : 'like'; } if ($conjunction == 'in') { $value = array_slice(explode(',', $value), 0, $this->config('inSlice')); $conjunction = $token->negated() ? 'NOT IN' : 'IN'; } elseif ($conjunction == 'like') { $value = str_replace(['*', '!'], ['%', '_'], $value); $conjunction = $token->negated() ? 'NOT LIKE' : 'LIKE'; } elseif ($conjunction == '=') { $conjunction = $token->negated() ? '<>' : ''; } elseif ($conjunction == '<>') { $conjunction = $token->negated() ? '' : '<>'; } return [$conjunction, $value]; }
Calculates the conjunction to use and the value to use with such conjunction based on the given token. @param \Search\Parser\TokenInterface $token Token for which calculating the conjunction @return array Numeric index array, where the first key (0) is the conjunction, and the second (1) is the value.
entailment
public static function get($plugin = null) { $cacheKey = "get({$plugin})"; $cache = static::cache($cacheKey); if ($cache !== null) { return $cache; } if ($plugin === null) { $collection = []; foreach ((array)quickapps('plugins') as $plugin) { $plugin = PackageFactory::create($plugin['name']); if ($plugin instanceof PluginPackage) { $collection[] = $plugin; } } return static::cache($cacheKey, collection($collection)); } $package = PackageFactory::create($plugin); if ($package instanceof PluginPackage) { return static::cache($cacheKey, $package); } throw new FatalErrorException(__d('cms', 'Plugin "{0}" was not found', $plugin)); }
Get the given plugin as an object, or a collection of objects if not specified. @param string $plugin Plugin name to get, or null to get a collection of all plugin objects @return \CMS\Core\Package\PluginPackage|\Cake\Collection\Collection @throws \Cake\Error\FatalErrorException When requested plugin was not found
entailment
public static function scan($ignoreThemes = false) { $cacheKey = "scan({$ignoreThemes})"; $cache = static::cache($cacheKey); if (!$cache) { $cache = []; $paths = App::path('Plugin'); $Folder = new Folder(); $Folder->sort = true; foreach ($paths as $path) { $Folder->cd($path); foreach ($Folder->read(true, true, true)[0] as $dir) { $name = basename($dir); $cache[$name] = normalizePath("{$dir}/"); } } // look for Cake plugins installed using Composer if (file_exists(VENDOR_INCLUDE_PATH . 'cakephp-plugins.php')) { $cakePlugins = (array)include VENDOR_INCLUDE_PATH . 'cakephp-plugins.php'; if (!empty($cakePlugins['plugins'])) { $cache = Hash::merge($cakePlugins['plugins'], $cache); } } // filter, remove hidden folders and others foreach ($cache as $name => $path) { if (strpos($name, '.') === 0) { unset($cache[$name]); } elseif ($name == 'CMS') { unset($cache[$name]); } elseif ($ignoreThemes && str_ends_with($name, 'Theme')) { unset($cache[$name]); } } $cache = static::cache($cacheKey, $cache); } return $cache; }
Scan plugin directories and returns plugin names and their paths within file system. We consider "plugin name" as the name of the container directory. Example output: ```php [ 'Users' => '/full/path/plugins/Users/', 'ThemeManager' => '/full/path/plugins/ThemeManager/', ... 'MySuperPlugin' => '/full/path/plugins/MySuperPlugin/', 'DarkGreenTheme' => '/full/path/plugins/DarkGreenTheme/', ] ``` If $ignoreThemes is set to true `DarkGreenTheme` will not be part of the result. NOTE: All paths includes trailing slash. @param bool $ignoreThemes Whether include themes as well or not @return array Associative array as `PluginName` => `/full/path/to/PluginName`
entailment
public static function validateJson($json, $errorMessages = false) { if (is_string($json) && is_readable($json) && !is_dir($json)) { $json = json_decode((new File($json))->read(), true); } $errors = []; if (!is_array($json) || empty($json)) { $errors[] = __d('cms', 'Corrupt JSON information.'); } else { if (!isset($json['type'])) { $errors[] = __d('cms', 'Missing field: "{0}"', 'type'); } if (!isset($json['name'])) { $errors[] = __d('cms', 'Missing field: "{0}"', 'name'); } elseif (!preg_match('/^(.+)\/(.+)+$/', $json['name'])) { $errors[] = __d('cms', 'Invalid field: "{0}" ({1}). It should be: {2}', 'name', $json['name'], '{author-name}/{package-name}'); } elseif (str_ends_with(strtolower($json['name']), 'theme')) { if (!isset($json['extra']['regions'])) { $errors[] = __d('cms', 'Missing field: "{0}"', 'extra.regions'); } } } if ($errorMessages) { return $errors; } return empty($errors); }
Validates a composer.json file. Below a list of validation rules that are applied: - must be a valid JSON file. - key `name` must be present and follow the pattern `author/package` - key `type` must be present. - key `extra.regions` must be present if it's a theme (its name ends with `-theme`, e.g. `quickapps/blue-sky-theme`) ### Usage: ```php $json = json_decode(file_gets_content('/path/to/composer.json'), true); Plugin::validateJson($json); // OR: Plugin::validateJson('/path/to/composer.json'); ``` @param array|string $json JSON given as an array result of `json_decode(..., true)`, or a string as path to where .json file can be found @param bool $errorMessages If set to true an array of error messages will be returned, if set to false boolean result will be returned; true on success, false on validation failure. Defaults to false (boolean result) @return array|bool
entailment
public static function checkReverseDependency($plugin) { if (!($plugin instanceof PluginPackage)) { list(, $pluginName) = packageSplit($plugin, true); $plugin = static::get($pluginName); } return $plugin->requiredBy()->toArray(); }
Checks if there is any active plugin that depends of $plugin. @param string|CMS\Package\PluginPackage $plugin Plugin name, package name (as `vendor/package`) or plugin package object result of `static::get()` @return array A list of all plugin names that depends on $plugin, an empty array means that no other plugins depends on $pluginName, so $plugin can be safely deleted or turned off. @throws \Cake\Error\FatalErrorException When requested plugin was not found @see \CMS\Core\Plugin::get()
entailment
public static function languagesList($full = false, $sort = true) { $languages = []; if ($full) { foreach (static::$_catalog as $code => $info) { $languages[$code] = $info['language']; } } else { foreach (quickapps('languages') as $code => $data) { $languages[$code] = $data['name']; } } if ($sort) { asort($languages); } return $languages; }
Gets a list of languages suitable for select boxes. @param bool $full Set to true to return the entire list of languages (from catalog). Set to false (by default) to get a list of installed languages @param bool $sort Sort languages alphabetically if set to true (by default). @return void
entailment
public static function flagsList() { $flags = []; $Folder = new Folder(Plugin::path('Locale') . 'webroot/img/flags/'); foreach ($Folder->read()[1] as $icon) { $value = $icon; $label = str_replace_last('.gif', '', $icon); $flags[$value] = $label; } asort($flags); return $flags; }
Gets a list of counties flags suitable for select boxes. @return array
entailment
public function search($vocabularyId) { $this->loadModel('Taxonomy.Terms'); $out = []; $text = $this->request->query['q']; $terms = $this->Terms ->find() ->select(['id', 'name']) ->where(['name LIKE' => "%%{$text}%%", 'vocabulary_id' => $vocabularyId]) ->limit(10) ->all(); foreach ($terms as $term) { $out[] = ['id' => $term->id, 'name' => $term->name]; } die(json_encode($out)); }
Shows a list of matching terms. @param int $vocabularyId Vocabulary's ID for which render its terms @return void
entailment
public function trigger($eventName) { if (is_string($eventName)) { $eventName = [$eventName, $this]; } $data = func_get_args(); array_shift($data); if (strpos($eventName[0], '::') > 0) { list($instance, $eventName[0]) = explode('::', $eventName[0]); return EventDispatcher::instance($instance)->triggerArray($eventName, $data); } return EventDispatcher::instance()->triggerArray($eventName, $data); }
Triggers the given event name. This method provides a shortcut for: ```php $this->trigger('EventName', $arg1, $arg2, ..., $argn); ``` You can provide a subject to use by passing an array as first arguments where the first element is the event name and the second one is the subject, if no subject is given `$this` will be used by default: ```php $this->trigger(['GetTime', new MySubject()], $arg_0, $arg_1, ..., $arg_n); ``` You can also indicate an EventDispatcher instance to use by prefixing the event name with `<InstanceName>::`, for instance: ```php $this->trigger('Blog::EventName', $arg1, $arg2, ..., $argn); ``` This will use the EventDispacher instance named `Blog` and will trigger the event `EventName` within that instance. @param array|string $eventName The event name to trigger @return \Cake\Event\Event The event object that was fired @see CMS\Event\EventDispatcher::trigger()
entailment
public function netmountPrepare($options) { if (empty($options['consumerKey']) && defined('ELFINDER_DROPBOX_CONSUMERKEY')) $options['consumerKey'] = ELFINDER_DROPBOX_CONSUMERKEY; if (empty($options['consumerSecret']) && defined('ELFINDER_DROPBOX_CONSUMERSECRET')) $options['consumerSecret'] = ELFINDER_DROPBOX_CONSUMERSECRET; if ($options['user'] === 'init') { if (! $this->dropbox_phpFound || empty($options['consumerKey']) || empty($options['consumerSecret']) || !class_exists('PDO')) { return array('exit' => true, 'body' => '{msg:errNetMountNoDriver}'); } if (defined('ELFINDER_DROPBOX_USE_CURL_PUT')) { $this->oauth = new Dropbox_OAuth_Curl($options['consumerKey'], $options['consumerSecret']); } else { if (class_exists('OAuth')) { $this->oauth = new Dropbox_OAuth_PHP($options['consumerKey'], $options['consumerSecret']); } else { if (! class_exists('HTTP_OAuth_Consumer')) { // We're going to try to load in manually include 'HTTP/OAuth/Consumer.php'; } if (class_exists('HTTP_OAuth_Consumer')) { $this->oauth = new Dropbox_OAuth_PEAR($options['consumerKey'], $options['consumerSecret']); } } } if (! $this->oauth) { return array('exit' => true, 'body' => '{msg:errNetMountNoDriver}'); } if ($options['pass'] === 'init') { $html = ''; if (isset($_SESSION['elFinderDropboxTokens'])) { // token check try { list(, $accessToken, $accessTokenSecret) = $_SESSION['elFinderDropboxTokens']; $this->oauth->setToken($accessToken, $accessTokenSecret); $this->dropbox = new Dropbox_API($this->oauth, $this->options['root']); $this->dropbox->getAccountInfo(); $script = '<script> $("#'.$options['id'].'").elfinder("instance").trigger("netmount", {protocol: "dropbox", mode: "done"}); </script>'; $html = $script; } catch (Dropbox_Exception $e) { unset($_SESSION['elFinderDropboxTokens']); } } if (! $html) { // get customdata $cdata = ''; $innerKeys = array('cmd', 'host', 'options', 'pass', 'protocol', 'user'); $post = (strtolower($_SERVER['REQUEST_METHOD']) === 'post')? $_POST : $_GET; foreach($post as $k => $v) { if (! in_array($k, $innerKeys)) { $cdata .= '&' . $k . '=' . rawurlencode($v); } } if (strpos($options['url'], 'http') !== 0 ) { $options['url'] = $this->getConnectorUrl(); } $callback = $options['url'] . '?cmd=netmount&protocol=dropbox&host=dropbox.com&user=init&pass=return&node='.$options['id'].$cdata; try { $tokens = $this->oauth->getRequestToken(); $url= $this->oauth->getAuthorizeUrl(rawurlencode($callback)); } catch (Dropbox_Exception $e) { return array('exit' => true, 'body' => '{msg:errAccess}'); } $_SESSION['elFinderDropboxAuthTokens'] = $tokens; $html = '<input id="elf-volumedriver-dropbox-host-btn" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" value="{msg:btnApprove}" type="button" onclick="window.open(\''.$url.'\')">'; $html .= '<script> $("#'.$options['id'].'").elfinder("instance").trigger("netmount", {protocol: "dropbox", mode: "makebtn"}); </script>'; } return array('exit' => true, 'body' => $html); } else { $this->oauth->setToken($_SESSION['elFinderDropboxAuthTokens']); unset($_SESSION['elFinderDropboxAuthTokens']); $tokens = $this->oauth->getAccessToken(); $_SESSION['elFinderDropboxTokens'] = array($_GET['uid'], $tokens['token'], $tokens['token_secret']); $out = array( 'node' => $_GET['node'], 'json' => '{"protocol": "dropbox", "mode": "done"}', 'bind' => 'netmount' ); return array('exit' => 'callback', 'out' => $out); } } if (isset($_SESSION['elFinderDropboxTokens'])) { list($options['dropboxUid'], $options['accessToken'], $options['accessTokenSecret']) = $_SESSION['elFinderDropboxTokens']; } unset($options['user'], $options['pass']); return $options; }
Prepare Call from elFinder::netmout() before volume->mount() @return Array @author Naoki Sawada
entailment
public function netunmount($netVolumes, $key) { $count = 0; $dropboxUid = ''; if (isset($netVolumes[$key])) { $dropboxUid = $netVolumes[$key]['dropboxUid']; } foreach($netVolumes as $volume) { if (@$volume['host'] === 'dropbox' && @$volume['dropboxUid'] === $dropboxUid) { $count++; } } if ($count === 1) { $this->DB->exec('drop table '.$this->DB_TableName); foreach(glob(rtrim($this->options['tmbPath'], '\\/').DIRECTORY_SEPARATOR.$this->tmbPrefix.'*.png') as $tmb) { unlink($tmb); } } return true; }
process of on netunmount Drop table `dropbox` & rm thumbs @param array $options @return boolean
entailment
private function getConnectorUrl() { $url = ((isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off')? 'https://' : 'http://') . $_SERVER['SERVER_NAME'] // host . ($_SERVER['SERVER_PORT'] == 80 ? '' : ':' . $_SERVER['SERVER_PORT']) // port . $_SERVER['REQUEST_URI']; // path & query list($url) = explode('?', $url); return $url; }
Get script url @return string full URL @author Naoki Sawada
entailment
protected function init() { if (!class_exists('PDO')) { return $this->setError('PHP PDO class is require.'); } if (!$this->options['consumerKey'] || !$this->options['consumerSecret'] || !$this->options['accessToken'] || !$this->options['accessTokenSecret']) { return $this->setError('Required options undefined.'); } if (empty($this->options['metaCachePath']) && defined('ELFINDER_DROPBOX_META_CACHE_PATH')) { $this->options['metaCachePath'] = ELFINDER_DROPBOX_META_CACHE_PATH; } // make net mount key $this->netMountKey = md5(join('-', array('dropbox', $this->options['path']))); if (! $this->oauth) { if (defined('ELFINDER_DROPBOX_USE_CURL_PUT')) { $this->oauth = new Dropbox_OAuth_Curl($this->options['consumerKey'], $this->options['consumerSecret']); } else { if (class_exists('OAuth')) { $this->oauth = new Dropbox_OAuth_PHP($this->options['consumerKey'], $this->options['consumerSecret']); } else { if (! class_exists('HTTP_OAuth_Consumer')) { // We're going to try to load in manually include 'HTTP/OAuth/Consumer.php'; } if (class_exists('HTTP_OAuth_Consumer')) { $this->oauth = new Dropbox_OAuth_PEAR($this->options['consumerKey'], $this->options['consumerSecret']); } } } } if (! $this->oauth) { return $this->setError('OAuth extension not loaded.'); } // normalize root path $this->root = $this->options['path'] = $this->_normpath($this->options['path']); if (empty($this->options['alias'])) { $this->options['alias'] = ($this->options['path'] === '/')? 'Dropbox.com' : 'Dropbox'.$this->options['path']; } $this->rootName = $this->options['alias']; $this->options['separator'] = '/'; try { $this->oauth->setToken($this->options['accessToken'], $this->options['accessTokenSecret']); $this->dropbox = new Dropbox_API($this->oauth, $this->options['root']); } catch (Dropbox_Exception $e) { unset($_SESSION['elFinderDropboxTokens']); return $this->setError('Dropbox error: '.$e->getMessage()); } // user if (empty($this->options['dropboxUid'])) { try { $res = $this->dropbox->getAccountInfo(); $this->options['dropboxUid'] = $res['uid']; } catch (Dropbox_Exception $e) { unset($_SESSION['elFinderDropboxTokens']); return $this->setError('Dropbox error: '.$e->getMessage()); } } $this->dropboxUid = $this->options['dropboxUid']; $this->tmbPrefix = 'dropbox'.base_convert($this->dropboxUid, 10, 32); if (!empty($this->options['tmpPath'])) { if ((is_dir($this->options['tmpPath']) || @mkdir($this->options['tmpPath'])) && is_writable($this->options['tmpPath'])) { $this->tmp = $this->options['tmpPath']; } } if (!$this->tmp && is_writable($this->options['tmbPath'])) { $this->tmp = $this->options['tmbPath']; } if (!empty($this->options['metaCachePath'])) { if ((is_dir($this->options['metaCachePath']) || @mkdir($this->options['metaCachePath'])) && is_writable($this->options['metaCachePath'])) { $this->metaCache = $this->options['metaCachePath']; } } if (!$this->metaCache && $this->tmp) { $this->metaCache = $this->tmp; } if (!$this->tmp) { $this->disabled[] = 'archive'; $this->disabled[] = 'extract'; } if (!$this->metaCache) { return $this->setError('Cache dirctory (metaCachePath or tmp) is require.'); } // setup PDO if (! $this->options['PDO_DSN']) { $this->options['PDO_DSN'] = 'sqlite:'.$this->metaCache.DIRECTORY_SEPARATOR.'.elFinder_dropbox_db_'.md5($this->dropboxUid.$this->options['consumerSecret']); } // DataBase table name $this->DB_TableName = $this->options['PDO_DBName']; // DataBase check or make table try { $this->DB = new PDO($this->options['PDO_DSN'], $this->options['PDO_User'], $this->options['PDO_Pass'], $this->options['PDO_Options']); if (! $this->checkDB()) { return $this->setError('Can not make DB table'); } } catch (PDOException $e) { return $this->setError('PDO connection failed: '.$e->getMessage()); } $res = $this->deltaCheck(!empty($_REQUEST['init'])); if ($res !== true) { if (is_string($res)) { return $this->setError($res); } else { return $this->setError('Could not check API "delta"'); } } return true; }
Prepare FTP connection Connect to remote server and check if credentials are correct, if so, store the connection id in $ftp_conn @return bool @author Dmitry (dio) Levashov @author Cem (DiscoFever)
entailment
private function checkDB() { $res = $this->query('select * from sqlite_master where type=\'table\' and name=\'dropbox\'; '); if (! $res) { try { $this->DB->exec('create table '.$this->DB_TableName.'(path text, fname text, dat blob, isdir integer);'); $this->DB->exec('create index nameidx on '.$this->DB_TableName.'(path, fname)'); $this->DB->exec('create index isdiridx on '.$this->DB_TableName.'(isdir)'); } catch (PDOException $e) { return $this->setError($e->getMessage()); } } return true; }
Check DB for delta cache @return void
entailment
private function query($sql) { if ($sth = $this->DB->query($sql)) { $res = $sth->fetchAll(PDO::FETCH_COLUMN); } else { $res = false; } return $res; }
DB query and fetchAll @param string $sql @return boolean|array
entailment
private function getDBdat($path) { if ($res = $this->query('select dat from '.$this->DB_TableName.' where path='.$this->DB->quote(strtolower(dirname($path))).' and fname='.$this->DB->quote(strtolower(basename($path))).' limit 1')) { return unserialize($res[0]); } else { return array(); } }
Get dat(dropbox metadata) from DB @param string $path @return array dropbox metadata
entailment
private function updateDBdat($path, $dat) { return $this->query('update '.$this->DB_TableName.' set dat='.$this->DB->quote(serialize($dat)) . ', isdir=' . ($dat['is_dir']? 1 : 0) . ' where path='.$this->DB->quote(strtolower(dirname($path))).' and fname='.$this->DB->quote(strtolower(basename($path)))); }
Update DB dat(dropbox metadata) @param string $path @param array $dat @return bool|array
entailment
protected function deltaCheck($refresh = true) { $chk = false; if (! $refresh && $chk = $this->query('select dat from '.$this->DB_TableName.' where path=\'\' and fname=\'\' limit 1')) { $chk = unserialize($chk[0]); } if ($chk && ($chk['mtime'] + $this->options['metaCacheTime']) > $_SERVER['REQUEST_TIME']) { return true; } try { $more = true; $this->DB->beginTransaction(); if ($res = $this->query('select dat from '.$this->DB_TableName.' where path=\'\' and fname=\'\' limit 1')) { $res = unserialize($res[0]); $cursor = $res['cursor']; } else { $cursor = ''; } $delete = false; $reset = false; do { @ ini_set('max_execution_time', 120); $_info = $this->dropbox->delta($cursor); if (! empty($_info['reset'])) { $this->DB->exec('TRUNCATE table '.$this->DB_TableName); $this->DB->exec('insert into '.$this->DB_TableName.' values(\'\', \'\', \''.serialize(array('cursor' => '', 'mtime' => 0)).'\', 0);'); $this->DB->exec('insert into '.$this->DB_TableName.' values(\'/\', \'\', \''.serialize(array( 'path' => '/', 'is_dir' => 1, 'mime_type' => '', 'bytes' => 0 )).'\', 0);'); $reset = true; } $cursor = $_info['cursor']; foreach($_info['entries'] as $entry) { $key = strtolower($entry[0]); $pkey = strtolower(dirname($key)); $path = $this->DB->quote($pkey); $fname = $this->DB->quote(strtolower(basename($key))); $where = 'where path='.$path.' and fname='.$fname; if (empty($entry[1])) { $this->DB->exec('delete from '.$this->DB_TableName.' '.$where); ! $delete && $delete = true; continue; } $sql = 'select path from '.$this->DB_TableName.' '.$where.' limit 1'; if (! $reset && $this->query($sql)) { $this->DB->exec('update '.$this->DB_TableName.' set dat='.$this->DB->quote(serialize($entry[1])).', isdir='.($entry[1]['is_dir']? 1 : 0).' ' .$where); } else { $this->DB->exec('insert into '.$this->DB_TableName.' values ('.$path.', '.$fname.', '.$this->DB->quote(serialize($entry[1])).', '.(int)$entry[1]['is_dir'].')'); } } } while (! empty($_info['has_more'])); $this->DB->exec('update '.$this->DB_TableName.' set dat='.$this->DB->quote(serialize(array('cursor'=>$cursor, 'mtime'=>$_SERVER['REQUEST_TIME']))).' where path=\'\' and fname=\'\''); if (! $this->DB->commit()) { $e = $this->DB->errorInfo(); return $e[2]; } if ($delete) { $this->DB->exec('vacuum'); } } catch(Dropbox_Exception $e) { return $e->getMessage(); } return true; }
Get delta data and DB update @param boolean $refresh force refresh @return true|string error message
entailment
protected function parseRaw($raw) { $stat = array(); $stat['rev'] = isset($raw['rev'])? $raw['rev'] : 'root'; $stat['name'] = basename($raw['path']); $stat['mime'] = $raw['is_dir']? 'directory' : $raw['mime_type']; $stat['size'] = $stat['mime'] == 'directory' ? 0 : $raw['bytes']; $stat['ts'] = isset($raw['client_mtime'])? strtotime($raw['client_mtime']) : (isset($raw['modified'])? strtotime($raw['modified']) : $_SERVER['REQUEST_TIME']); $stat['dirs'] = 0; if ($raw['is_dir']) { $stat['dirs'] = (int)(bool)$this->query('select path from '.$this->DB_TableName.' where isdir=1 and path='.$this->DB->quote(strtolower($raw['path']))); } if (!empty($raw['url'])) { $stat['url'] = $raw['url']; } else { $stat['url'] = '1'; } if (isset($raw['width'])) $stat['width'] = $raw['width']; if (isset($raw['height'])) $stat['height'] = $raw['height']; return $stat; }
Parse line from dropbox metadata output and return file stat (array) @param string $raw line from ftp_rawlist() output @return array @author Dmitry Levashov
entailment
protected function cacheDir($path) { $this->dirsCache[$path] = array(); $res = $this->query('select dat from '.$this->DB_TableName.' where path='.$this->DB->quote(strtolower($path))); if ($res) { foreach($res as $raw) { $raw = unserialize($raw); if ($stat = $this->parseRaw($raw)) { $stat = $this->updateCache($raw['path'], $stat); if (empty($stat['hidden'])) { $this->dirsCache[$path][] = $raw['path']; } } } } return $this->dirsCache[$path]; }
Cache dir contents @param string $path dir path @return void @author Dmitry Levashov
entailment
protected function doSearch($path, $q, $mimes) { $result = array(); $sth = $this->DB->prepare('select dat from '.$this->DB_TableName.' WHERE path LIKE ? AND fname LIKE ?'); $sth->execute(array('%'.(($path === '/')? '' : strtolower($path)), '%'.strtolower($q).'%')); $res = $sth->fetchAll(PDO::FETCH_COLUMN); if ($res) { foreach($res as $raw) { $raw = unserialize($raw); if ($stat = $this->parseRaw($raw)) { if (!isset($this->cache[$raw['path']])) { $stat = $this->updateCache($raw['path'], $stat); } if ($stat['mime'] !== 'directory' || $this->mimeAccepted($stat['mime'], $mimes)) { $result[] = $this->stat($raw['path']); } } } } return $result; }
Recursive files search @param string $path dir path @param string $q search string @param array $mimes @return array @author Naoki Sawada
entailment
protected function copy($src, $dst, $name) { $this->clearcache(); return $this->_copy($src, $dst, $name) ? $this->_joinPath($dst, $name) : $this->setError(elFinder::ERROR_COPY, $this->_path($src)); }
Copy file/recursive copy dir only in current volume. Return new file path or false. @param string $src source path @param string $dst destination dir path @param string $name new file name (optionaly) @return string|false @author Dmitry (dio) Levashov @author Naoki Sawada
entailment
protected function remove($path, $force = false, $recursive = false) { $stat = $this->stat($path); $stat['realpath'] = $path; $this->rmTmb($stat); $this->clearcache(); if (empty($stat)) { return $this->setError(elFinder::ERROR_RM, $this->_path($path), elFinder::ERROR_FILE_NOT_FOUND); } if (!$force && !empty($stat['locked'])) { return $this->setError(elFinder::ERROR_LOCKED, $this->_path($path)); } if ($stat['mime'] == 'directory') { if (!$recursive && !$this->_rmdir($path)) { return $this->setError(elFinder::ERROR_RM, $this->_path($path)); } } else { if (!$recursive && !$this->_unlink($path)) { return $this->setError(elFinder::ERROR_RM, $this->_path($path)); } } $this->removed[] = $stat; return true; }
Remove file/ recursive remove dir @param string $path file path @param bool $force try to remove even if file locked @return bool @author Dmitry (dio) Levashov @author Naoki Sawada
entailment
protected function createTmb($path, $stat) { if (!$stat || !$this->canCreateTmb($path, $stat)) { return false; } $name = $this->tmbname($stat); $tmb = $this->tmbPath.DIRECTORY_SEPARATOR.$name; // copy image into tmbPath so some drivers does not store files on local fs if (! $data = $this->getThumbnail($path, $this->options['getTmbSize'])) { return false; } if (! file_put_contents($tmb, $data)) { return false; } $result = false; $tmbSize = $this->tmbSize; if (($s = getimagesize($tmb)) == false) { return false; } /* If image smaller or equal thumbnail size - just fitting to thumbnail square */ if ($s[0] <= $tmbSize && $s[1] <= $tmbSize) { $result = $this->imgSquareFit($tmb, $tmbSize, $tmbSize, 'center', 'middle', $this->options['tmbBgColor'], 'png' ); } else { if ($this->options['tmbCrop']) { /* Resize and crop if image bigger than thumbnail */ if (!(($s[0] > $tmbSize && $s[1] <= $tmbSize) || ($s[0] <= $tmbSize && $s[1] > $tmbSize) ) || ($s[0] > $tmbSize && $s[1] > $tmbSize)) { $result = $this->imgResize($tmb, $tmbSize, $tmbSize, true, false, 'png'); } if (($s = getimagesize($tmb)) != false) { $x = $s[0] > $tmbSize ? intval(($s[0] - $tmbSize)/2) : 0; $y = $s[1] > $tmbSize ? intval(($s[1] - $tmbSize)/2) : 0; $result = $this->imgCrop($tmb, $tmbSize, $tmbSize, $x, $y, 'png'); } } else { $result = $this->imgResize($tmb, $tmbSize, $tmbSize, true, true, $this->imgLib, 'png'); $result = $this->imgSquareFit($tmb, $tmbSize, $tmbSize, 'center', 'middle', $this->options['tmbBgColor'], 'png' ); } } if (!$result) { unlink($tmb); return false; } return $name; }
Create thumnbnail and return it's URL on success @param string $path file path @param string $mime file mime type @return string|false @author Dmitry (dio) Levashov @author Naoki Sawada
entailment
protected function getThumbnail($path, $size = 'small') { try { return $this->dropbox->getThumbnail($path, $size); } catch (Dropbox_Exception $e) { return false; } }
Get thumbnail from dropbox.com @param string $path @param string $size @return string | boolean
entailment
public function getContentUrl($hash, $options = array()) { if (($file = $this->file($hash)) == false || !$file['url'] || $file['url'] == 1) { $path = $this->decode($hash); $cache = $this->getDBdat($path); $url = ''; if (isset($cache['share']) && strpos($cache['share'], $this->dropbox_dlhost) !== false) { $res = $this->getHttpResponseHeader($cache['share']); if (preg_match("/^HTTP\/[01\.]+ ([0-9]{3})/", $res, $match)) { if ($match[1] < 400) { $url = $cache['share']; } } } if (! $url) { try { $res = $this->dropbox->share($path, null, false); $url = $res['url']; if (strpos($url, 'www.dropbox.com') === false) { $res = $this->getHttpResponseHeader($url); if (preg_match('/^location:\s*(http[^\s]+)/im', $res, $match)) { $url = $match[1]; } } list($url) = explode('?', $url); $url = str_replace('www.dropbox.com', $this->dropbox_dlhost, $url); if (! isset($cache['share']) || $cache['share'] !== $url) { $cache['share'] = $url; $this->updateDBdat($path, $cache); } } catch (Dropbox_Exception $e) { return false; } } return $url; } return $file['url']; }
Return content URL @param string $hash file hash @param array $options options @return array @author Naoki Sawada
entailment
private function getHttpResponseHeader($url) { if (function_exists('curl_exec')) { $c = curl_init(); curl_setopt( $c, CURLOPT_RETURNTRANSFER, true ); curl_setopt( $c, CURLOPT_CUSTOMREQUEST, 'HEAD' ); curl_setopt( $c, CURLOPT_HEADER, 1 ); curl_setopt( $c, CURLOPT_NOBODY, true ); curl_setopt( $c, CURLOPT_URL, $url ); $res = curl_exec( $c ); } else { require_once 'HTTP/Request2.php'; try { $request2 = new HTTP_Request2(); $request2->setConfig(array( 'ssl_verify_peer' => false, 'ssl_verify_host' => false )); $request2->setUrl($url); $request2->setMethod(HTTP_Request2::METHOD_HEAD); $result = $request2->send(); $res = array(); $res[] = 'HTTP/'.$result->getVersion().' '.$result->getStatus().' '.$result->getReasonPhrase(); foreach($result->getHeader() as $key => $val) { $res[] = $key . ': ' . $val; } $res = join("\r\n", $res); } catch( HTTP_Request2_Exception $e ){ $res = ''; } catch (Exception $e){ $res = ''; } } return $res; }
Get HTTP request response header string @param string $url target URL @return string @author Naoki Sawada
entailment
protected function _normpath($path) { $path = str_replace(DIRECTORY_SEPARATOR, '/', $path); $path = '/' . ltrim($path, '/'); return $path; }
Return normalized path, this works the same as os.path.normpath() in Python @param string $path path @return string @author Troex Nevelin
entailment
protected function _stat($path) { if ($raw = $this->getDBdat($path)) { return $this->parseRaw($raw); } return false; }
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) { return ($stat = $this->stat($path)) && isset($stat['dirs']) ? $stat['dirs'] : 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) { if (strpos($mime, 'image') !== 0) return ''; $cache = $this->getDBdat($path); if (isset($cache['width']) && isset($cache['height'])) { return $cache['width'].'x'.$cache['height']; } $ret = ''; if ($work = $this->getWorkFile($path)) { if ($size = @getimagesize($work)) { $cache['width'] = $size[0]; $cache['height'] = $size[1]; $this->updateDBdat($path, $cache); $ret = $size[0].'x'.$size[1]; } } is_file($work) && @unlink($work); return $ret; }
Return object width and height Ususaly 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 _scandir($path) { return isset($this->dirsCache[$path]) ? $this->dirsCache[$path] : $this->cacheDir($path); }
Return files list in directory. @param string $path dir path @return array @author Dmitry (dio) Levashov @author Cem (DiscoFever)
entailment
protected function _fopen($path, $mode='rb') { if (($mode == 'rb' || $mode == 'r')) { try { $res = $this->dropbox->media($path); $url = parse_url($res['url']); $fp = stream_socket_client('ssl://'.$url['host'].':443'); fputs($fp, "GET {$url['path']} HTTP/1.0\r\n"); fputs($fp, "Host: {$url['host']}\r\n"); fputs($fp, "\r\n"); while(trim(fgets($fp)) !== ''){}; return $fp; } catch (Dropbox_Exception $e) { return false; } } if ($this->tmp) { $contents = $this->_getContents($path); if ($contents === false) { return false; } if ($local = $this->getTempFile($path)) { if (file_put_contents($local, $contents, LOCK_EX) !== false) { return @fopen($local, $mode); } } } return false; }
Open file and return file pointer @param string $path file path @param bool $write open file for writing @return resource|false @author Dmitry (dio) Levashov
entailment
protected function _mkdir($path, $name) { $path = $this->_normpath($path.'/'.$name); try { $this->dropbox->createFolder($path); } catch (Dropbox_Exception $e) { $this->deltaCheck(); if ($this->dir($this->encode($path))) { return $path; } return $this->setError('Dropbox error: '.$e->getMessage()); } $this->deltaCheck(); return $path; }
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 _copy($source, $targetDir, $name) { $path = $this->_normpath($targetDir.'/'.$name); try { $this->dropbox->copy($source, $path); } catch (Dropbox_Exception $e) { return $this->setError('Dropbox error: '.$e->getMessage()); } $this->deltaCheck(); return true; }
Copy file into another file @param string $source source file path @param string $targetDir target directory path @param string $name new file name @return bool @author Dmitry (dio) Levashov
entailment
protected function _move($source, $targetDir, $name) { $target = $this->_normpath($targetDir.'/'.$name); try { $this->dropbox->move($source, $target); } catch (Dropbox_Exception $e) { return $this->setError('Dropbox error: '.$e->getMessage()); } $this->deltaCheck(); return $target; }
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 _unlink($path) { try { $this->dropbox->delete($path); } catch (Dropbox_Exception $e) { return $this->setError('Dropbox error: '.$e->getMessage()); } $this->deltaCheck(); return true; }
Remove file @param string $path file path @return bool @author Dmitry (dio) Levashov
entailment
protected function _save($fp, $path, $name, $stat) { if ($name) $path .= '/'.$name; $path = $this->_normpath($path); try { $this->dropbox->putFile($path, $fp); } catch (Dropbox_Exception $e) { return $this->setError('Dropbox error: '.$e->getMessage()); } $this->deltaCheck(); if (is_array($stat)) { $raw = $this->getDBdat($path); if (isset($stat['width'])) $raw['width'] = $stat['width']; if (isset($stat['height'])) $raw['height'] = $stat['height']; $this->updateDBdat($path, $raw); } 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 _getContents($path) { $contents = ''; try { $contents = $this->dropbox->getFile($path); } catch (Dropbox_Exception $e) { return $this->setError('Dropbox error: '.$e->getMessage()); } return $contents; }
Get file contents @param string $path file path @return string|false @author Dmitry (dio) Levashov
entailment
protected function _filePutContents($path, $content) { $res = false; if ($local = $this->getTempFile($path)) { if (@file_put_contents($local, $content, LOCK_EX) !== false && ($fp = @fopen($local, 'rb'))) { clearstatcache(); $res = $this->_save($fp, $path, '', array()); @fclose($fp); } file_exists($local) && @unlink($local); } return $res; }
Write a string to a file @param string $path file path @param string $content new file content @return bool @author Dmitry (dio) Levashov
entailment