sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function operatorPromote(Query $query, TokenInterface $token) { $value = strtolower($token->value()); $conjunction = $token->negated() ? '<>' : ''; $conditions = []; if ($value === 'true') { $conditions = ["Contents.promote {$conjunction}" => 1]; } elseif ($value === 'false') { $conditions = ['Contents.promote {$conjunction}' => 0]; } if (!empty($conditions)) { if ($token->where() === 'or') { $query->orWhere($conditions); } elseif ($token->where() === 'and') { $query->andWhere($conditions); } else { $query->where($conditions); } } return $query; }
Handles "promote" search operator. promote:<true|false> @param \Cake\ORM\Query $query The query object @param \Search\Parser\TokenInterface $token Operator token @return \Cake\ORM\Query
entailment
public function operatorAuthor(Query $query, TokenInterface $token) { $value = explode(',', $token->value()); if (!empty($value)) { $conjunction = $token->negated() ? 'NOT IN' : 'IN'; $subQuery = TableRegistry::get('User.Users')->find() ->select(['id']) ->where(["Users.username {$conjunction}" => $value]); if ($token->where() === 'or') { $query->orWhere(['Contents.created_by IN' => $subQuery]); } elseif ($token->where() === 'and') { $query->andWhere(['Contents.created_by IN' => $subQuery]); } else { $query->where(['Contents.created_by IN' => $subQuery]); } } return $query; }
Handles "author" search operator. author:<username1>,<username2>, ... @param \Cake\ORM\Query $query The query object @param \Search\Parser\TokenInterface $token Operator token @return \Cake\ORM\Query
entailment
public function operatorterm(Query $query, TokenInterface $token) { $terms = explode(',', strtolower($token->value())); $conjunction = $token->negated() ? 'NOT IN' : 'IN'; if (empty($terms)) { return $query; } $conditions = [ "Contents.id {$conjunction}" => TableRegistry::get('Taxonomy.EntitiesTerms') ->find() ->select(['EntitiesTerms.entity_id']) ->where(['EntitiesTerms.table_alias' => $this->alias()]) ->matching('Terms', function ($q) use ($terms) { return $q->where(['Terms.slug IN' => $terms]); }) ]; if (!empty($conditions)) { if ($token->where() === 'or') { $query->orWhere($conditions); } elseif ($token->where() === 'and') { $query->andWhere($conditions); } else { $query->where($conditions); } } return $query; }
Handles "term" search operator. term:term1-slug,term2-slug,... @param \Cake\ORM\Query $query The query object @param \Search\Parser\TokenInterface $token Operator token @return \Cake\ORM\Query
entailment
protected function _calculateHash($entity) { $hash = []; foreach ($entity->visibleProperties() as $property) { if (strpos($property, 'created') === false && strpos($property, 'created_by') === false && strpos($property, 'modified') === false && strpos($property, 'modified_by') === false ) { if ($property == '_fields') { foreach ($entity->get('_fields') as $field) { if ($field instanceof \Field\Model\Entity\Field) { $hash[] = is_object($field->value) || is_array($field->value) ? md5(serialize($field->value)) : md5($field->value); } } } else { $hash[] = $entity->get($property); } } } return md5(serialize($hash)); }
Generates a unique hash for the given entity. Used by revision system to detect if an entity has changed or not. @param \Cake\Datasource\EntityInterface $entity The entity for which calculate its hash @return string MD5 hash for this particular entity
entailment
protected function connect() { if (!($this->connect = ftp_connect($this->options['host'], $this->options['port'], $this->options['timeout']))) { return $this->setError('Unable to connect to FTP server '.$this->options['host']); } if (!ftp_login($this->connect, $this->options['user'], $this->options['pass'])) { $this->umount(); return $this->setError('Unable to login into '.$this->options['host']); } // switch off extended passive mode - may be usefull for some servers //@ftp_exec($this->connect, 'epsv4 off' ); // enter passive mode if required $this->options['mode'] = 'active'; ftp_pasv($this->connect, $this->options['mode'] == 'passive'); // enter root folder if (!ftp_chdir($this->connect, $this->root)) { $this->umount(); return $this->setError('Unable to open root folder.'); } $stat = array(); $stat['name'] = $this->root; $stat['mime'] = 'directory'; $this->filesCache[$this->root] = $stat; $this->cacheDir($this->root); return true; }
Connect to ftp server @return bool
entailment
protected function parseRaw($raw) { $info = preg_split("/\s+/", $raw, 9); $stat = array(); $stat['name'] = join(" ", array_slice($info, 3, 9)); $stat['read'] = true; if ($info[2] == '<DIR>') { $stat['size'] = 0; $stat['mime'] = 'directory'; } else { $stat['size'] = $info[2]; $stat['mime'] = $this->mimetype($stat['name']); } return $stat; }
Parse line from ftp_rawlist() output and return file stat (array) @param string $raw line from ftp_rawlist() output @return array
entailment
protected function cacheDir($path) { $this->dirsCache[$path] = array(); if (preg_match('/\'|\"/', $path)) { foreach (ftp_nlist($this->connect, $path) as $p) { if (($stat = $this->_stat($p)) &&empty($stat['hidden'])) { // $files[] = $stat; $this->dirsCache[$path][] = $p; } } return; } foreach (ftp_rawlist($this->connect, $path) as $raw) { if (($stat = $this->parseRaw($raw))) { $p = $path.DIRECTORY_SEPARATOR.$stat['name']; // $files[] = $stat; $this->dirsCache[$path][] = $p; //$stat['name'] = $p; $this->filesCache[$p] = $stat; } } }
Cache dir contents @param string $path dir path @return void
entailment
protected function init() { if (!($this->options['host'] || $this->options['socket']) || !$this->options['user'] || !$this->options['pass'] || !$this->options['db'] || !$this->options['path'] || !$this->options['files_table']) { return false; } $this->db = new mysqli($this->options['host'], $this->options['user'], $this->options['pass'], $this->options['db'], $this->options['port'], $this->options['socket']); if ($this->db->connect_error || @mysqli_connect_error()) { return false; } $this->db->set_charset('utf8'); if ($res = $this->db->query('SHOW TABLES')) { while ($row = $res->fetch_array()) { if ($row[0] == $this->options['files_table']) { $this->tbf = $this->options['files_table']; break; } } } if (!$this->tbf) { return false; } $this->updateCache($this->options['path'], $this->_stat($this->options['path'])); return true; }
Prepare driver before mount volume. Connect to db, check required tables and fetch root path @return bool @author Dmitry (dio) Levashov
entailment
protected function configure() { parent::configure(); if (($tmp = $this->options['tmpPath'])) { if (!file_exists($tmp)) { if (@mkdir($tmp)) { @chmod($tmp, $this->options['tmbPathMode']); } } $this->tmpPath = is_dir($tmp) && is_writable($tmp) ? $tmp : false; } if (!$this->tmpPath && $this->tmbPath && $this->tmbPathWritable) { $this->tmpPath = $this->tmbPath; } $this->mimeDetect = 'internal'; }
Set tmp path @return void @author Dmitry (dio) Levashov
entailment
public function debug() { $debug = parent::debug(); $debug['sqlCount'] = $this->sqlCnt; if ($this->dbError) { $debug['dbError'] = $this->dbError; } return $debug; }
Return debug info for client @return array @author Dmitry (dio) Levashov
entailment
protected function query($sql) { $this->sqlCnt++; $res = $this->db->query($sql); if (!$res) { $this->dbError = $this->db->error; } return $res; }
Perform sql query and return result. Increase sqlCnt and save error if occured @param string $sql query @return misc @author Dmitry (dio) Levashov
entailment
protected function make($path, $name, $mime) { $sql = 'INSERT INTO %s (`parent_id`, `name`, `size`, `mtime`, `mime`, `content`, `read`, `write`) VALUES ("%s", "%s", 0, %d, "%s", "", "%d", "%d")'; $sql = sprintf($sql, $this->tbf, $path, $this->db->real_escape_string($name), time(), $mime, $this->defaults['read'], $this->defaults['write']); // echo $sql; return $this->query($sql) && $this->db->affected_rows > 0; }
Create empty object with required mimetype @param string $path parent dir path @param string $name object name @param string $mime mime type @return bool @author Dmitry (dio) Levashov
entailment
public function search($q, $mimes) { $result = array(); $sql = 'SELECT f.id, f.parent_id, f.name, f.size, f.mtime AS ts, f.mime, f.read, f.write, f.locked, f.hidden, f.width, f.height, 0 AS dirs FROM %s AS f WHERE f.name RLIKE "%s"'; $sql = sprintf($sql, $this->tbf, $this->db->real_escape_string($q)); if (($res = $this->query($sql))) { while ($row = $res->fetch_assoc()) { if ($this->mimeAccepted($row['mime'], $mimes)) { $id = $row['id']; if ($row['parent_id']) { $row['phash'] = $this->encode($row['parent_id']); } if ($row['mime'] == 'directory') { unset($row['width']); unset($row['height']); } else { unset($row['dirs']); } unset($row['id']); unset($row['parent_id']); if (($stat = $this->updateCache($id, $row)) && empty($stat['hidden'])) { $result[] = $stat; } } } } return $result; }
Search files @param string $q search string @param array $mimes @return array @author Dmitry (dio) Levashov
entailment
protected function cacheDir($path) { $this->dirsCache[$path] = array(); $sql = 'SELECT f.id, f.parent_id, f.name, f.size, f.mtime AS ts, f.mime, f.read, f.write, f.locked, f.hidden, f.width, f.height, IF(ch.id, 1, 0) AS dirs FROM '.$this->tbf.' AS f LEFT JOIN '.$this->tbf.' AS ch ON ch.parent_id=f.id AND ch.mime="directory" WHERE f.parent_id="'.$path.'" GROUP BY f.id'; $res = $this->query($sql); if ($res) { while ($row = $res->fetch_assoc()) { // debug($row); $id = $row['id']; if ($row['parent_id']) { $row['phash'] = $this->encode($row['parent_id']); } if ($row['mime'] == 'directory') { unset($row['width']); unset($row['height']); } else { unset($row['dirs']); } unset($row['id']); unset($row['parent_id']); if (($stat = $this->updateCache($id, $row)) && empty($stat['hidden'])) { $this->dirsCache[$path][] = $id; } } } return $this->dirsCache[$path]; }
Cache dir contents @param string $path dir path @return void @author Dmitry Levashov
entailment
protected function getParents($path) { $parents = array(); while ($path) { if ($file = $this->stat($path)) { array_unshift($parents, $path); $path = isset($file['phash']) ? $this->decode($file['phash']) : false; } } if (count($parents)) { array_pop($parents); } return $parents; }
Return array of parents paths (ids) @param int $path file path (id) @return array @author Dmitry (dio) Levashov
entailment
protected function loadFilePath($path) { $realPath = realpath($path); if (DIRECTORY_SEPARATOR == '\\') { // windows $realPath = str_replace('\\', '\\\\', $realPath); } return $this->db->real_escape_string($realPath); }
Return correct file path for LOAD_FILE method @param string $path file path (id) @return string @author Troex Nevelin
entailment
protected function _dirname($path) { return ($stat = $this->stat($path)) ? ($stat['phash'] ? $this->decode($stat['phash']) : $this->root) : false; }
Return parent directory path @param string $path file path @return string @author Dmitry (dio) Levashov
entailment
protected function _joinPath($dir, $name) { $sql = 'SELECT id FROM '.$this->tbf.' WHERE parent_id="'.$dir.'" AND name="'.$this->db->real_escape_string($name).'"'; if (($res = $this->query($sql)) && ($r = $res->fetch_assoc())) { $this->updateCache($r['id'], $this->_stat($r['id'])); return $r['id']; } return -1; }
Join dir name and file name and return full path @param string $dir @param string $name @return string @author Dmitry (dio) Levashov
entailment
protected function _path($path) { if (($file = $this->stat($path)) == false) { return ''; } $parentsIds = $this->getParents($path); $path = ''; foreach ($parentsIds as $id) { $dir = $this->stat($id); $path .= $dir['name'].$this->separator; } return $path.$file['name']; }
Return fake path started from root dir @param string $path file path @return string @author Dmitry (dio) Levashov
entailment
protected function _inpath($path, $parent) { return $path == $parent ? true : in_array($parent, $this->getParents($path)); }
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 _dimensions($path, $mime) { return ($stat = $this->stat($path)) && isset($stat['width']) && isset($stat['height']) ? $stat['width'].'x'.$stat['height'] : ''; }
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 _mkdir($path, $name) { return $this->make($path, $name, 'directory') ? $this->_joinPath($path, $name) : 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) { return $this->make($path, $name, 'text/plain') ? $this->_joinPath($path, $name) : 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 _copy($source, $targetDir, $name) { $this->clearcache(); $id = $this->_joinPath($targetDir, $name); $sql = $id > 0 ? sprintf('REPLACE INTO %s (id, parent_id, name, content, size, mtime, mime, width, height, `read`, `write`, `locked`, `hidden`) (SELECT %d, %d, name, content, size, mtime, mime, width, height, `read`, `write`, `locked`, `hidden` FROM %s WHERE id=%d)', $this->tbf, $id, $this->_dirname($id), $this->tbf, $source) : sprintf('INSERT INTO %s (parent_id, name, content, size, mtime, mime, width, height, `read`, `write`, `locked`, `hidden`) SELECT %d, "%s", content, size, %d, mime, width, height, `read`, `write`, `locked`, `hidden` FROM %s WHERE id=%d', $this->tbf, $targetDir, $this->db->real_escape_string($name), time(), $this->tbf, $source); return $this->query($sql); }
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) { $sql = 'UPDATE %s SET parent_id=%d, name="%s" WHERE id=%d LIMIT 1'; $sql = sprintf($sql, $this->tbf, $targetDir, $this->db->real_escape_string($name), $source); return $this->query($sql) && $this->db->affected_rows > 0 ? $source : 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 _unlink($path) { return $this->query(sprintf('DELETE FROM %s WHERE id=%d AND mime!="directory" LIMIT 1', $this->tbf, $path)) && $this->db->affected_rows; }
Remove file @param string $path file path @return bool @author Dmitry (dio) Levashov
entailment
protected function _rmdir($path) { return $this->query(sprintf('DELETE FROM %s WHERE id=%d AND mime="directory" LIMIT 1', $this->tbf, $path)) && $this->db->affected_rows; }
Remove dir @param string $path dir path @return bool @author Dmitry (dio) Levashov
entailment
protected function _setContent($path, $fp) { rewind($fp); $fstat = fstat($fp); $size = $fstat['size']; }
undocumented function @return void @author Dmitry Levashov
entailment
protected function _save($fp, $dir, $name, $stat) { $this->clearcache(); $mime = $stat['mime']; $w = !empty($stat['width']) ? $stat['width'] : 0; $h = !empty($stat['height']) ? $stat['height'] : 0; $id = $this->_joinPath($dir, $name); rewind($fp); $stat = fstat($fp); $size = $stat['size']; if (($tmpfile = tempnam($this->tmpPath, $this->id))) { if (($trgfp = fopen($tmpfile, 'wb')) == false) { unlink($tmpfile); } else { while (!feof($fp)) { fwrite($trgfp, fread($fp, 8192)); } fclose($trgfp); $sql = $id > 0 ? 'REPLACE INTO %s (id, parent_id, name, content, size, mtime, mime, width, height) VALUES ('.$id.', %d, "%s", LOAD_FILE("%s"), %d, %d, "%s", %d, %d)' : 'INSERT INTO %s (parent_id, name, content, size, mtime, mime, width, height) VALUES (%d, "%s", LOAD_FILE("%s"), %d, %d, "%s", %d, %d)'; $sql = sprintf($sql, $this->tbf, $dir, $this->db->real_escape_string($name), $this->loadFilePath($tmpfile), $size, time(), $mime, $w, $h); $res = $this->query($sql); unlink($tmpfile); if ($res) { return $id > 0 ? $id : $this->db->insert_id; } } } $content = ''; rewind($fp); while (!feof($fp)) { $content .= fread($fp, 8192); } $sql = $id > 0 ? 'REPLACE INTO %s (id, parent_id, name, content, size, mtime, mime, width, height) VALUES ('.$id.', %d, "%s", "%s", %d, %d, "%s", %d, %d)' : 'INSERT INTO %s (parent_id, name, content, size, mtime, mime, width, height) VALUES (%d, "%s", "%s", %d, %d, "%s", %d, %d)'; $sql = sprintf($sql, $this->tbf, $dir, $this->db->real_escape_string($name), $this->db->real_escape_string($content), $size, time(), $mime, $w, $h); unset($content); if ($this->query($sql)) { return $id > 0 ? $id : $this->db->insert_id; } return false; }
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) { return ($res = $this->query(sprintf('SELECT content FROM %s WHERE id=%d', $this->tbf, $path))) && ($r = $res->fetch_assoc()) ? $r['content'] : false; }
Get file contents @param string $path file path @return string|false @author Dmitry (dio) Levashov
entailment
protected function _filePutContents($path, $content) { return $this->query(sprintf('UPDATE %s SET content="%s", size=%d, mtime=%d WHERE id=%d LIMIT 1', $this->tbf, $this->db->real_escape_string($content), strlen($content), time(), $path)); }
Write a string to a file @param string $path file path @param string $content new file content @return bool @author Dmitry (dio) Levashov
entailment
public static function columnName($column) { list($tableName, $fieldName) = pluginSplit((string)$column); if (!$fieldName) { $fieldName = $tableName; } $fieldName = preg_replace('/\s{2,}/', ' ', $fieldName); list($fieldName, ) = explode(' ', trim($fieldName)); return $fieldName; }
Gets a clean column name from query expression. ### Example: ```php EavToolbox::columnName('Tablename.some_column'); // returns "some_column" EavToolbox::columnName('my_column'); // returns "my_column" ``` @param string $column Column name from query @return string
entailment
public function propertyExists(EntityInterface $entity, $property) { $visibleProperties = $entity->visibleProperties(); return in_array($property, $visibleProperties); }
Checks if the provided entity has defined certain $property, regardless of its value. @param \Cake\Datasource\EntityInterface $entity The entity to check @param string $property The property name @return bool True if exists
entailment
public function attributes($bundle = null) { $key = empty($bundle) ? '@all' : $bundle; if (isset($this->_attributes[$key])) { return $this->_attributes[$key]; } $this->_attributes[$key] = []; $cacheKey = $this->_table->table() . '_' . $key; $attrs = Cache::read($cacheKey, 'eav_table_attrs'); if (empty($attrs)) { $conditions = ['EavAttributes.table_alias' => $this->_table->table()]; if (!empty($bundle)) { $conditions['EavAttributes.bundle'] = $bundle; } $attrs = TableRegistry::get('Eav.EavAttributes') ->find() ->where($conditions) ->all() ->toArray(); Cache::write($cacheKey, $attrs, 'eav_table_attrs'); } foreach ($attrs as $attr) { $this->_attributes[$key][$attr->get('name')] = $attr; } return $this->attributes($bundle); }
Gets all attributes added to this table. @param string|null $bundle Get attributes within given bundle, or all of them regardless of the bundle if not provided @return array List of attributes indexed by name (virtual column name)
entailment
public function getAttributeIds($bundle = null) { $attributes = $this->attributes($bundle); $ids = []; foreach ($attributes as $name => $info) { $ids[] = $info['id']; } return $ids; }
Gets a list of attribute IDs. @param string $bundle Filter by bundle name @return array
entailment
public function extractEntityIds(CollectionInterface $results) { $entityIds = []; $results->each(function ($entity) use (&$entityIds) { if ($entity instanceof EntityInterface) { $entityIds[] = $this->getEntityId($entity); } }); return $entityIds; }
Given a collection of entities gets the ID of all of them. This method iterates the given set and invokes `getEntityId()` for every entity in the set. @param \Cake\Collection\CollectionInterface $results Set of entities @return array List of entity ids suitable for EAV logic
entailment
public function getEntityId(EntityInterface $entity) { $pk = []; $keys = $this->_table->primaryKey(); $keys = !is_array($keys) ? [$keys] : $keys; foreach ($keys as $key) { $pk[] = $entity->get($key); } return implode(':', $pk); }
Calculates entity's primary key. If PK is composed of multiple columns they will be merged with `:` symbol. For example, consider `Users` table with composed PK <nick, email>, then for certain User entity this method could return: john-locke:[email protected] @param \Cake\Datasource\EntityInterface $entity The entity @return string
entailment
public function driver(Query $query) { $conn = $query->connection(null); list(, $driver) = namespaceSplit(strtolower(get_class($conn->driver()))); return $driver; }
Gets the name of the class driver used by the given $query to access the DB. @param \Cake\ORM\Query $query The query to inspect @return string Lowercased drive name. e.g. `mysql`
entailment
public function scope(Query $query, TokenInterface $token) { $fields = $this->config('fields'); if ($token->negated() || empty($fields)) { return $query; } $tableAlias = $this->_table->alias(); $fields = $this->config('fields'); $value = strtolower($token->value()); if (is_string($fields)) { $fields = [$fields]; } foreach (explode(';', $value) as $segment) { $parts = explode(',', $segment); if (in_array($parts[0], $fields)) { $dir = empty($parts[1]) || !in_array($parts[1], ['asc', 'desc']) ? 'asc' : $parts[1]; $query->order(["{$tableAlias}.{$parts[0]}" => $dir]); } } return $query; }
{@inheritDoc}
entailment
public function validate(Field $field, Validator $validator) { if (!$field->metadata->required) { return true; } $validator ->notEmpty($field->name, __d('field', 'You must select a date/time.')) ->add($field->name, 'validDate', [ 'rule' => function ($value, $context) { return DateToolbox::createFromFormat($value['format'], $value['date']) !== false; }, 'message' => __d('field', 'Invalid date/time given.'), ]); return true; }
{@inheritDoc}
entailment
public function beforeSave(Field $field, $post) { if (!empty($post['date']) && !empty($post['format'])) { $date = $post['date']; $format = $post['format']; if ($date = DateToolbox::createFromFormat($format, $date)) { $field->set('extra', $post['date']); } else { $field->metadata->entity->errors($field->name, __d('field', 'Invalid date/time, it must match the the pattern: {0}', $format)); return false; } $field->set('value', date_timestamp_get($date)); } else { $field->set('value', null); } return true; }
{@inheritDoc} - extra: Holds string date incoming from POST - value: Holds datetime information
entailment
public function login() { $this->loadModel('User.Users'); $this->viewBuilder()->layout('login'); if ($this->request->is('post')) { $loginBlocking = plugin('User')->settings('failed_login_attempts') && plugin('User')->settings('failed_login_attempts_block_seconds'); $continue = true; if ($loginBlocking) { Cache::config('users_login', [ 'duration' => '+' . plugin('User')->settings('failed_login_attempts_block_seconds') . ' seconds', 'path' => CACHE, 'engine' => 'File', 'prefix' => 'qa_', 'groups' => ['acl'] ]); $cacheName = 'login_failed_' . env('REMOTE_ADDR'); $cache = Cache::read($cacheName, 'users_login'); if ($cache && $cache['attempts'] >= plugin('User')->settings('failed_login_attempts')) { $blockTime = (int)plugin('User')->settings('failed_login_attempts_block_seconds'); $this->Flash->warning(__d('user', 'You have reached the maximum number of login attempts. Try again in {0} minutes.', $blockTime / 60)); $continue = false; } } if ($continue) { $user = $this->Auth->identify(); if ($user) { $this->Auth->setUser($user); if (!empty($user['id'])) { try { $user = $this->Users->get($user['id']); if ($user) { $this->Users->touch($user, 'Users.login'); $this->Users->save($user); } } catch (\Exception $e) { // invalid user } } return $this->redirect($this->Auth->redirectUrl()); } else { if ($loginBlocking && isset($cache) && isset($cacheName)) { $cacheStruct = [ 'attempts' => 0, 'last_attempt' => 0, 'ip' => '', 'request_log' => [] ]; $cache = array_merge($cacheStruct, $cache); $cache['attempts'] += 1; $cache['last_attempt'] = time(); $cache['ip'] = env('REMOTE_ADDR'); $cache['request_log'][] = [ 'data' => $this->request->data, 'time' => time(), ]; Cache::write($cacheName, $cache, 'users_login'); } $this->Flash->danger(__d('user', 'Username or password is incorrect.')); } } } $user = $this->Users->newEntity(); $this->title(__d('user', 'Login')); $this->set(compact('user')); }
Renders the login form. @return \Cake\Network\Response|null
entailment
public function logout() { $result = $this->Auth->logout(); $this->viewBuilder()->layout('login'); $this->title(__d('user', 'Logout')); if ($result) { return $this->redirect($result); } else { $this->Flash->danger(__d('user', 'Something went wrong, and logout operation could not be completed.')); return $this->redirect($this->referer()); } }
Logout. @return \Cake\Network\Response|null
entailment
public function pluginFile() { if (!empty($this->request->query['file'])) { $path = $this->request->query['file']; $path = str_replace_once('#', '', $path); $file = str_replace('//', '/', ROOT . "/plugins/{$path}"); if ((strpos($file, 'webroot') !== false || strpos($file, '.tmb') !== false) && file_exists($file)) { $this->response->file($file); return $this->response; } } die; }
Returns the given plugin's file within webroot directory. @return void
entailment
public function initialize(array $config) { $this->belongsTo('Vocabularies', [ 'className' => 'Taxonomy.Vocabularies', 'propertyName' => 'vocabulary' ]); $this->hasMany('EntitiesTerms', [ 'className' => 'Taxonomy.EntitiesTerms', 'propertyName' => 'entities_cache', 'dependent' => true, ]); $this->addBehavior('Timestamp'); $this->addBehavior('Sluggable', ['label' => 'name', 'on' => 'both']); }
Initialize a table instance. Called after the constructor. @param array $config Configuration options passed to the constructor @return void
entailment
public function validate(Field $field, Validator $validator) { if ($field->metadata->required) { $validator ->add($field->name, 'isRequired', [ 'rule' => function ($value, $context) use ($field) { if (isset($context['data'][$field->name])) { $count = 0; foreach ($context['data'][$field->name] as $k => $file) { if (is_integer($k)) { $count++; } } return $count > 0; } return false; }, 'message' => __d('field', 'You must upload one file at least.') ]); } if ($field->metadata->settings['multi'] !== 'custom') { $maxFiles = intval($field->metadata->settings['multi']); } else { $maxFiles = intval($field->metadata->settings['multi_custom']); } $validator ->add($field->name, 'numberOfFiles', [ 'rule' => function ($value, $context) use ($field, $maxFiles) { if (isset($context['data'][$field->name])) { $count = 0; foreach ($context['data'][$field->name] as $k => $file) { if (is_integer($k)) { $count++; } } return $count <= $maxFiles; } return false; }, 'message' => __d('field', 'You can upload {0} files as maximum.', $maxFiles) ]); if (!empty($field->metadata->settings['extensions'])) { $extensions = $field->metadata->settings['extensions']; $extensions = array_map('strtolower', array_map('trim', explode(',', $extensions))); $validator ->add($field->name, 'extensions', [ 'rule' => function ($value, $context) use ($field, $extensions) { if (isset($context['data'][$field->name])) { foreach ($context['data'][$field->name] as $k => $file) { if (is_integer($k)) { $ext = strtolower(str_replace('.', '', strrchr($file['file_name'], '.'))); if (!in_array($ext, $extensions)) { return false; } } } return true; } return false; }, 'message' => __d('field', 'Invalid file extension. Allowed extension are: {0}', $field->metadata->settings['extensions']) ]); } return true; }
{@inheritDoc}
entailment
public function beforeSave(Field $field, $post) { // FIX Removes the "dummy" input from extra if exists, the "dummy" input is // used to force Field Handler to work when empty POST information is sent $extra = []; foreach ((array)$field->extra as $k => $v) { if (is_integer($k)) { $extra[] = $v; } } $field->set('extra', $extra); $files = (array)$post; if (!empty($files)) { $value = []; foreach ($files as $k => $file) { if (!is_integer($k)) { unset($files[$k]); continue; } else { $file = array_merge([ 'mime_icon' => '', 'file_name' => '', 'file_size' => '', 'description' => '', ], (array)$file); } $value[] = trim("{$file['file_name']} {$file['description']}"); } $field->set('value', implode(' ', $value)); $field->set('extra', $files); } if ($field->metadata->value_id) { $newFileNames = Hash::extract($files, '{n}.file_name'); try { $prevFiles = (array)TableRegistry::get('Eav.EavValues') ->get($field->metadata->value_id) ->extra; } catch (\Exception $ex) { $prevFiles = []; } foreach ($prevFiles as $f) { if (!in_array($f['file_name'], $newFileNames)) { $file = normalizePath(WWW_ROOT . "/files/{$field->metadata->settings['upload_folder']}/{$f['file_name']}", DS); $file = new File($file); $file->delete(); } } } return true; }
{@inheritDoc} - extra: Holds a list (array) of files and their in formation (mime-icon, file name, etc). - value: Holds a text containing all file names separated by space.
entailment
protected function _setName($value) { $value = strip_tags($value); $value = str_replace(["\n", "\r"], '', $value); return trim($value); }
Removes any invalid characters from term's name. @param string $value Term's name @return string
entailment
public function beforeFilter(Event $event) { if (is_readable(ROOT . '/config/settings.php')) { $this->redirect('/'); } $this->_prepareLayout(); $this->viewBuilder() ->className('CMS\View\View') ->theme(false) ->layout('Installer.startup') ->helpers(['Menu.Menu']); if (!empty($this->request->query['locale']) && !in_array($this->request->params['action'], ['language', 'index'])) { I18n::locale($this->request->query['locale']); $this->request->session()->write('installation.language', I18n::locale()); } elseif ($this->request->session()->read('installation.language')) { I18n::locale($this->request->session()->read('installation.language')); } Router::addUrlFilter(function ($params, $request) { if (!in_array($request->params['action'], ['language', 'index'])) { $params['locale'] = I18n::locale(); } return $params; }); }
{@inheritDoc} @param \Cake\Event\Event $event The event that was triggered @return void
entailment
public function language() { $languages = [ 'en_US' => [ 'url' => '/installer/startup/requirements?locale=en_US', 'welcome' => 'Welcome to QuickAppsCMS', 'action' => 'Click here to install in English' ] ]; $Folder = new Folder(Plugin::classPath('Installer') . 'Locale'); foreach ($Folder->read(false, true, true)[0] as $path) { $code = basename($path); $file = $path . '/installer.po'; if (is_readable($file)) { I18n::locale($code); // trick for __d() $languages[$code] = [ 'url' => "/installer/startup/requirements?locale={$code}", 'welcome' => __d('installer', 'Welcome to QuickAppsCMS'), 'action' => __d('installer', 'Click here to install in English') ]; } } I18n::locale('en_US'); $this->title('Welcome to QuickAppsCMS'); $this->set('languages', $languages); $this->_step(); }
First step of the installation process. User must select the language they want to use for the installation process. @return void
entailment
public function requirements() { if (!$this->_step('language')) { $this->redirect(['plugin' => 'Installer', 'controller' => 'startup', 'action' => 'language']); } $tests = $this->_getTester(); $errors = $tests->errors(); if (empty($errors)) { $this->_step(); } $this->title(__d('installer', 'Server Requirements')); $this->set('errors', $errors); }
Second step of the installation process. We check server requirements here. @return void
entailment
public function license() { if (!$this->_step('requirements')) { $this->redirect(['plugin' => 'Installer', 'controller' => 'startup', 'action' => 'requirements']); } $this->title(__d('installer', 'License Agreement')); $this->_step(); }
Third step of the installation process. License agreement. @return void
entailment
public function database() { if (!$this->_step('license')) { $this->redirect(['plugin' => 'Installer', 'controller' => 'startup', 'action' => 'license']); } if (!empty($this->request->data)) { $dbInstaller = new DatabaseInstaller(); if ($dbInstaller->install($this->request->data())) { $this->_step(); $this->redirect(['plugin' => 'Installer', 'controller' => 'startup', 'action' => 'account']); } else { $errors = ''; foreach ($dbInstaller->errors() as $error) { $errors .= "\t<li>{$error}</li>\n"; } $this->Flash->danger("<ul>\n{$errors}</ul>\n"); } } $this->title(__d('installer', 'Database Configuration')); }
Fourth step of the installation process. User must introduce database connection information. @return void
entailment
public function account() { if (!$this->_step('database')) { $this->redirect(['plugin' => 'Installer', 'controller' => 'startup', 'action' => 'database']); } $this->loadModel('User.Users'); $user = $this->Users->newEntity(); if ($this->request->data()) { $data = $this->request->data; $data['roles'] = ['_ids' => [1]]; $user = $this->Users->newEntity($data); if ($this->Users->save($user)) { $this->Flash->success(__d('installer', 'Account created you can now login!')); $this->_step(); $this->redirect(['plugin' => 'Installer', 'controller' => 'startup', 'action' => 'finish']); } else { $this->Flash->danger(__d('installer', 'Account could not be created, please check your information.')); } } $this->title(__d('installer', 'Create New Account')); $this->set('user', $user); }
Fifth step of the installation process. Create a new administrator user account. @return void
entailment
public function finish() { if ($this->request->data()) { if (rename(ROOT . '/config/settings.php.tmp', ROOT . '/config/settings.php')) { snapshot(); $this->request->session()->delete('Startup'); if (!empty($this->request->data['home'])) { $this->redirect('/'); } else { $this->redirect('/admin'); } } else { $this->Flash->danger(__d('installer', 'Unable to continue, check write permission for the "/config" directory.')); } } $this->title(__d('installer', 'Finish Installation')); }
Last step of the installation process. Here we say "thanks" and redirect to site's frontend or backend. @return void
entailment
protected function _step($check = null) { $_steps = (array)$this->request->session()->read('Startup._steps'); if ($check === null) { $_steps[] = $this->request->params['action']; $_steps = array_unique($_steps); $this->request->session()->write('Startup._steps', $_steps); } elseif (is_string($check)) { return in_array($check, $_steps); } return false; }
Check if the given step name was completed. Or marks current step as completed. If $check is set to NULL, it marks current step (controller's action name) as completed. If $check is set to a string, it checks if that step was completed before. This allows steps to control user navigation, so users can not pass to the next step without completing all previous steps. @param null|string $check Name of the step to check, or false to mark as completed current step @return bool
entailment
protected function _prepareLayout() { $menu = [ __d('installer', 'Welcome') => [ 'url' => ['plugin' => 'Installer', 'controller' => 'startup', 'action' => 'language'], 'active' => ($this->request->action === 'language') ], __d('installer', 'System Requirements') => [ 'url' => ['plugin' => 'Installer', 'controller' => 'startup', 'action' => 'requirements'], 'active' => ($this->request->action === 'requirements') ], __d('installer', 'License Agreement') => [ 'url' => ['plugin' => 'Installer', 'controller' => 'startup', 'action' => 'license'], 'active' => ($this->request->action === 'license') ], __d('installer', 'Database Setup') => [ 'url' => ['plugin' => 'Installer', 'controller' => 'startup', 'action' => 'database'], 'active' => ($this->request->action === 'database') ], __d('installer', 'Your Account') => [ 'url' => ['plugin' => 'Installer', 'controller' => 'startup', 'action' => 'account'], 'active' => ($this->request->action === 'account') ], __d('installer', 'Finish') => [ 'url' => ['plugin' => 'Installer', 'controller' => 'startup', 'action' => 'finish'], 'active' => ($this->request->action === 'finish') ], ]; $this->set('menu', $menu); }
Sets some view-variables used across all steps. @return void
entailment
public function index() { $this->loadModel('User.Users'); $users = $this->Users->find()->contain(['Roles']); if (!empty($this->request->query['filter'])) { $this->Users->search($this->request->query['filter'], $users); } $this->title(__d('user', 'Users List')); $this->set('users', $this->paginate($users)); $this->Breadcrumb->push('/admin/user/manage'); }
Shows a list of all registered users. @return void
entailment
public function add() { $this->loadModel('User.Users'); $user = $this->Users->newEntity(); $user = $this->Users->attachFields($user); $languages = LocaleToolbox::languagesList(); $roles = $this->Users->Roles->find('list', [ 'conditions' => [ 'id NOT IN' => [ROLE_ID_AUTHENTICATED, ROLE_ID_ANONYMOUS] ] ]); if ($this->request->data()) { $user->accessible('id', false); $data = $this->request->data; if (isset($data['welcome_message'])) { $sendWelcomeMessage = (bool)$data['welcome_message']; unset($data['welcome_message']); } else { $sendWelcomeMessage = false; } $user = $this->Users->patchEntity($user, $data); if ($this->Users->save($user)) { if ($sendWelcomeMessage) { NotificationManager::welcome($user)->send(); } $this->Flash->success(__d('user', 'User successfully registered!')); $this->redirect(['plugin' => 'User', 'controller' => 'manage', 'action' => 'edit', $user->id]); } else { $this->Flash->danger(__d('user', 'User could not be registered, please check your information.')); } } $this->title(__d('user', 'Register New User')); $this->set(compact('user', 'roles', 'languages')); $this->Breadcrumb->push('/admin/user/manage'); }
Adds a new user. @return void
entailment
public function edit($id) { $this->loadModel('User.Users'); $user = $this->Users->get($id, ['contain' => ['Roles']]); $languages = LocaleToolbox::languagesList(); $roles = $this->Users->Roles->find('list', [ 'conditions' => [ 'id NOT IN' => [ROLE_ID_AUTHENTICATED, ROLE_ID_ANONYMOUS] ] ]); if ($this->request->data()) { $user->accessible(['id', 'username'], false); $user = $this->Users->patchEntity($user, $this->request->data); if ($this->Users->save($user)) { $this->Flash->success(__d('user', 'User information successfully updated!')); $this->redirect($this->referer()); } else { $this->Flash->danger(__d('user', 'User information could not be saved, please check your information.')); } } $this->title(__d('user', 'Editing User')); $this->set(compact('user', 'roles', 'languages')); $this->Breadcrumb->push('/admin/user/manage'); }
Edits the given user's information. @param int $id User's ID @return void
entailment
public function block($id) { $this->loadModel('User.Users'); $user = $this->Users->get($id, [ 'fields' => ['id', 'name', 'email'], 'contain' => ['Roles'], ]); if (!in_array(ROLE_ID_ADMINISTRATOR, $user->role_ids)) { if ($this->Users->updateAll(['status' => 0], ['id' => $user->id])) { $this->Flash->success(__d('user', 'User {0} was successfully blocked!', $user->name)); $user->updateToken(); NotificationManager::blocked($user)->send(); } else { $this->Flash->danger(__d('user', 'User could not be blocked, please try again.')); } } else { $this->Flash->warning(__d('user', 'Administrator users cannot be blocked.')); } $this->title(__d('user', 'Block User Account')); $this->redirect($this->referer()); }
Blocks the given user account. After account is blocked token is regenerated, so user cannot login using a known token. @param int $id User's ID @return void Redirects to previous page
entailment
public function activate($id) { $this->loadModel('User.Users'); $user = $this->Users->get($id, ['fields' => ['id', 'name', 'email']]); if ($this->Users->updateAll(['status' => 1], ['id' => $user->id])) { NotificationManager::activated($user)->send(); $this->Flash->success(__d('user', 'User {0} was successfully activated!', $user->name)); } else { $this->Flash->danger(__d('user', 'User could not be activated, please try again.')); } $this->title(__d('user', 'Unblock User Account')); $this->redirect($this->referer()); }
Activates the given user account. @param int $id User's ID @return void Redirects to previous page
entailment
public function passwordInstructions($id) { $this->loadModel('User.Users'); $user = $this->Users->get($id, ['fields' => ['id', 'name', 'email']]); if ($user) { NotificationManager::passwordRequest($user)->send(); $this->Flash->success(__d('user', 'Instructions we successfully sent to {0}', $user->name)); } else { $this->Flash->danger(__d('user', 'User was not found.')); } $this->title(__d('user', 'Recovery Instructions')); $this->redirect($this->referer()); }
Sends password recovery instructions to the given user. @param int $id User's ID @return void Redirects to previous page
entailment
public function delete($id) { $this->loadModel('User.Users'); $user = $this->Users->get($id, ['contain' => ['Roles']]); if (in_array(ROLE_ID_ADMINISTRATOR, $user->role_ids) && $this->Users->countAdministrators() === 1 ) { $this->Flash->danger(__d('user', 'You cannot remove this user as it is the last administrator available.')); } else { if ($this->Users->delete($user)) { NotificationManager::canceled($user)->send(); $this->Flash->success(__d('user', 'User successfully removed!')); $this->redirect($this->referer()); } else { $this->Flash->danger(__d('user', 'User could not be removed.')); } } $this->title(__d('user', 'Remove User Account')); $this->redirect($this->referer()); }
Removes the given user. @param int $id User's ID @return void Redirects to previous page
entailment
public function isAllowed($aco) { $cacheKey = 'isAllowed(' . $this->get('id') . ", {$aco})"; $cache = static::cache($cacheKey); if ($cache === null) { $cache = TableRegistry::get('User.Permissions')->check($this, $aco); static::cache($cacheKey, $cache); } return $cache; }
Verifies this user is allowed access the given ACO. ### Usage: ```php // Checks if current user is allowed to edit created contents: user()->isAllowed('Content/Admin/Manage/edit'); ``` @param string $aco An ACO path. e.g. `Plugin/Prefix/Controller/action` @return bool True if user can access ACO, false otherwise
entailment
public function avatar($options = []) { $options = (array)$options; $options += [ 's' => 80, 'd' => 'mm', 'r' => 'g' ]; $url = 'http://www.gravatar.com/avatar/'; $url .= md5(strtolower(trim($this->get('email')))); $url .= "?s={$options['s']}&d={$options['d']}&r={$options['r']}"; return $url; }
Gets user avatar image's URL. Powered by Gravatar, it uses user's email to get avatar image URL from Gravatar service. Use this method instead of `avatar` property when you need to customize avatar's parameters such as `size`, etc. ```php $user->avatar(['s' => 150]); // instead of: $user->avatar; ``` @param array $options Array of options for Gravatar API @return string URL to user's avatar @link http://www.gravatar.com
entailment
protected function _getRoleIds() { $ids = []; if (!$this->has('roles')) { return $ids; } foreach ($this->roles as $k => $role) { $ids[] = $role->id; } return $ids; }
Gets an array list of role IDs this user belongs to. @return array
entailment
protected function _getRoleNames() { $names = []; if (!$this->has('roles')) { return $names; } foreach ($this->roles as $k => $role) { $names[] = $role->name; } return $names; }
Gets an array list of role NAMES this user belongs to. @return array
entailment
protected function _getRoleSlugs() { $slugs = []; if (!$this->has('roles')) { return $slugs; } foreach ($this->roles as $role) { $slugs[] = $role->slug; } return $slugs; }
Gets an array list of role NAMES this user belongs to. @return array
entailment
protected function _getCancelCode() { if (!$this->has('password') && !$this->has('id')) { throw new FatalErrorException(__d('user', 'Cannot generated cancel code for this user: unknown user ID.')); } if (!$this->has('password')) { $password = TableRegistry::get('User.Users') ->get($this->id, ['fields' => ['password']]) ->get('password'); } else { $password = $this->password; } return Security::hash($password, 'md5', true); }
Generates cancel code for this user. @return string @throws \Cake\Error\FatalErrorException When code cannot be created
entailment
public function eav($status = null) { if ($status === null) { return $this->config('status'); } $this->config('status', (bool)$status); }
Gets/sets EAV status. - TRUE: Enables EAV behavior so virtual columns WILL be fetched from database. - FALSE: Disables EAV behavior so virtual columns WLL NOT be fetched from database. @param bool|null $status EAV status to set, or null to get current state @return void|bool Current status if `$status` is set to null
entailment
public function addColumn($name, array $options = [], $errors = true) { if (in_array($name, (array)$this->_table->schema()->columns())) { throw new FatalErrorException(__d('eav', 'The column name "{0}" cannot be used as it is already defined in the table "{1}"', $name, $this->_table->alias())); } $data = $options + [ 'type' => 'string', 'bundle' => null, 'searchable' => true, 'overwrite' => false, ]; $data['type'] = $this->_toolbox->mapType($data['type']); if (!in_array($data['type'], EavToolbox::$types)) { throw new FatalErrorException(__d('eav', 'The column {0}({1}) could not be created as "{2}" is not a valid type.', $name, $data['type'], $data['type'])); } $data['name'] = $name; $data['table_alias'] = $this->_table->table(); $attr = TableRegistry::get('Eav.EavAttributes')->find() ->where([ 'name' => $data['name'], 'table_alias' => $data['table_alias'], 'bundle IS' => $data['bundle'], ]) ->limit(1) ->first(); if ($attr && !$data['overwrite']) { throw new FatalErrorException(__d('eav', 'Virtual column "{0}" already defined, use the "overwrite" option if you want to change it.', $name)); } if ($attr) { $attr = TableRegistry::get('Eav.EavAttributes')->patchEntity($attr, $data); } else { $attr = TableRegistry::get('Eav.EavAttributes')->newEntity($data); } $success = (bool)TableRegistry::get('Eav.EavAttributes')->save($attr); Cache::clear(false, 'eav_table_attrs'); if ($errors) { return (array)$attr->errors(); } return (bool)$success; }
Defines a new virtual-column, or update if already defined. ### Usage: ```php $errors = $this->Users->addColumn('user-age', [ 'type' => 'integer', 'bundle' => 'some-bundle-name', 'extra' => [ 'option1' => 'value1' ] ], true); if (empty($errors)) { // OK } else { // ERROR debug($errors); } ``` The third argument can be set to FALSE to get a boolean response: ```php $success = $this->Users->addColumn('user-age', [ 'type' => 'integer', 'bundle' => 'some-bundle-name', 'extra' => [ 'option1' => 'value1' ] ]); if ($success) { // OK } else { // ERROR } ``` @param string $name Column name. e.g. `user-age` @param array $options Column configuration options @param bool $errors If set to true will return an array list of errors instead of boolean response. Defaults to TRUE @return bool|array True on success or array of error messages, depending on $error argument @throws \Cake\Error\FatalErrorException When provided column name collides with existing column names. And when an invalid type is provided
entailment
public function dropColumn($name, $bundle = null) { $attr = TableRegistry::get('Eav.EavAttributes')->find() ->where([ 'name' => $name, 'table_alias' => $this->_table->table(), 'bundle IS' => $bundle, ]) ->limit(1) ->first(); Cache::clear(false, 'eav_table_attrs'); if ($attr) { return (bool)TableRegistry::get('Eav.EavAttributes')->delete($attr); } return false; }
Drops an existing column. @param string $name Name of the column to drop @param string|null $bundle Removes the column within a particular bundle @return bool True on success, false otherwise
entailment
public function listColumns($bundle = null) { $columns = []; foreach ($this->_toolbox->attributes($bundle) as $name => $attr) { $columns[$name] = [ 'id' => $attr->get('id'), 'bundle' => $attr->get('bundle'), 'name' => $name, 'type' => $attr->get('type'), 'searchable ' => $attr->get('searchable'), 'extra ' => $attr->get('extra'), ]; } return $columns; }
Gets a list of virtual columns attached to this table. @param string|null $bundle Get attributes within given bundle, or all of them regardless of the bundle if not provided @return array Columns information indexed by column name
entailment
public function updateEavCache(EntityInterface $entity) { if (!$this->config('cacheMap')) { return false; } $attrsById = []; foreach ($this->_toolbox->attributes() as $attr) { $attrsById[$attr['id']] = $attr; } if (empty($attrsById)) { return true; // nothing to cache } $query = TableRegistry::get('Eav.EavValues') ->find('all') ->where([ 'EavValues.eav_attribute_id IN' => array_keys($attrsById), 'EavValues.entity_id' => $this->_toolbox->getEntityId($entity), ]) ->toArray(); $values = []; foreach ($query as $v) { $type = $attrsById[$v->get('eav_attribute_id')]->get('type'); $name = $attrsById[$v->get('eav_attribute_id')]->get('name'); $values[$name] = $this->_toolbox->marshal($v->get("value_{$type}"), $type); } $toUpdate = []; foreach ((array)$this->config('cacheMap') as $column => $fields) { $cache = []; if (in_array('*', $fields)) { $cache = $values; } else { foreach ($fields as $field) { if (isset($values[$field])) { $cache[$field] = $values[$field]; } } } $toUpdate[$column] = (string)serialize(new CachedColumn($cache)); } if (!empty($toUpdate)) { $conditions = []; // scope to entity's PK (composed PK supported) $keys = $this->_table->primaryKey(); $keys = !is_array($keys) ? [$keys] : $keys; foreach ($keys as $key) { // TO-DO: check key exists in entity's visible properties list. // Throw an error otherwise as PK MUST be correctly calculated. $conditions[$key] = $entity->get($key); } if (empty($conditions)) { return false; } return (bool)$this->_table->updateAll($toUpdate, $conditions); } return true; }
Update EAV cache for the specified $entity. @param \Cake\Datasource\EntityInterface $entity The entity to update @return bool Success
entailment
public function beforeFind(Event $event, Query $query, ArrayObject $options, $primary) { $status = array_key_exists('eav', $options) ? $options['eav'] : $this->config('status'); if ($status) { $options['bundle'] = !isset($options['bundle']) ? null : $options['bundle']; $this->_initScopes(); if (empty($this->_queryScopes['Eav\\Model\\Behavior\\QueryScope\\SelectScope'])) { return $query; } $selectedVirtual = $this->_queryScopes['Eav\\Model\\Behavior\\QueryScope\\SelectScope']->getVirtualColumns($query, $options['bundle']); $args = compact('options', 'primary', 'selectedVirtual'); $query = $this->_scopeQuery($query, $options['bundle']); return $query->formatResults(function ($results) use ($args) { return $this->_hydrateEntities($results, $args); }, Query::PREPEND); } }
Attaches virtual properties to entities. This method is also responsible of looking for virtual columns in SELECT and WHERE clauses (if applicable) and properly scope the Query object. Query scoping is performed by the `_scopeQuery()` method. EAV can be enabled or disabled on the fly using `eav` finder option, or `eav()` method. When mixing, `eav` option has the highest priority: ```php $this->Articles->eav(false); $articlesNoVirtual = $this->Articles->find('all'); $articlesWithVirtual = $this->Articles->find('all', ['eav' => true]); ``` @param \Cake\Event\Event $event The beforeFind event that was triggered @param \Cake\ORM\Query $query The original query to modify @param \ArrayObject $options Additional options given as an array @param bool $primary Whether this find is a primary query or not @return bool|null
entailment
protected function _hydrateEntities(CollectionInterface $entities, array $args) { $values = $this->_prepareSetValues($entities, $args); return $entities->map(function ($entity) use ($values) { if ($entity instanceof EntityInterface) { $entity = $this->_prepareCachedColumns($entity); $entityId = $this->_toolbox->getEntityId($entity); $entityValues = isset($values[$entityId]) ? $values[$entityId] : []; $hydrator = $this->config('hydrator'); $entity = $hydrator($entity, $entityValues); if ($entity === null) { // mark as NULL_ENTITY $entity = self::NULL_ENTITY; } } return $entity; }) ->filter(function ($entity) { // remove all entities marked as NULL_ENTITY return $entity !== self::NULL_ENTITY; }); }
Attach EAV attributes for every entity in the provided result-set. This method iterates over each retrieved entity and invokes the `hydrateEntity()` method. This last should return the altered entity object with all its virtual properties, however if this method returns NULL the entity will be removed from the resulting collection. @param \Cake\Collection\CollectionInterface $entities Set of entities to be processed @param array $args Contains three keys: "options" and "primary" given to the originating beforeFind(), and "selectedVirtual", a list of virtual columns selected in the originating find query @return \Cake\Collection\CollectionInterface New set with altered entities
entailment
public function hydrateEntity(EntityInterface $entity, array $values) { foreach ($values as $value) { if (!$this->_toolbox->propertyExists($entity, $value['property_name'])) { $entity->set($value['property_name'], $value['value']); $entity->dirty($value['property_name'], false); } } // force cache-columns to be of the proper type as they might be NULL if // entity has not been updated yet. if ($this->config('cacheMap')) { foreach ($this->config('cacheMap') as $column => $fields) { if ($this->_toolbox->propertyExists($entity, $column) && !($entity->get($column) instanceof Entity)) { $entity->set($column, new Entity); } } } return $entity; }
Hydrates a single entity and returns it. Returning NULL indicates the entity should be removed from the resulting collection. @param \Cake\Datasource\EntityInterface $entity The entity to hydrate @param array $values Holds stored virtual values for this particular entity @return bool|null|\Cake\Datasource\EntityInterface
entailment
protected function _prepareSetValues(CollectionInterface $entities, array $args) { $entityIds = $this->_toolbox->extractEntityIds($entities); $result = []; if (empty($entityIds)) { return $result; } $selectedVirtual = $args['selectedVirtual']; $bundle = $args['options']['bundle']; $validColumns = array_values($selectedVirtual); $validNames = array_intersect($this->_toolbox->getAttributeNames($bundle), $validColumns); $attrsById = []; foreach ($this->_toolbox->attributes($bundle) as $name => $attr) { if (in_array($name, $validNames)) { $attrsById[$attr['id']] = $attr; } } if (empty($attrsById)) { return $result; } $fetchedRawValues = TableRegistry::get('Eav.EavValues') ->find('all') ->bufferResults(false) ->where([ 'EavValues.eav_attribute_id IN' => array_keys($attrsById), 'EavValues.entity_id IN' => $entityIds, ]) ->all() ->map(function ($value) use ($attrsById, $selectedVirtual) { $attrName = $attrsById[$value->get('eav_attribute_id')]->get('name'); $attrType = $attrsById[$value->get('eav_attribute_id')]->get('type'); $alias = array_search($attrName, $selectedVirtual); return [ 'attribute_id' => $value->get('eav_attribute_id'), 'entity_id' => $value->get('entity_id'), 'property_name' => is_string($alias) ? $alias : $attrName, 'property_name_real' => $attrName, 'aliased' => is_string($alias), 'value' => $this->_toolbox->marshal($value->get("value_{$attrType}"), $attrType), ]; }) ->groupBy('entity_id') ->map(function ($values) { return (new Collection($values))->indexBy('attribute_id')->toArray(); }) ->toArray(); $fetchedValues = []; foreach ($entityIds as $entityId) { $fetchedValues[$entityId] = []; $values = !empty($fetchedRawValues[$entityId]) ? $fetchedRawValues[$entityId] : []; foreach ($attrsById as $attrId => $attributeInfo) { if (isset($values[$attrId])) { $fetchedValues[$entityId][] = $values[$attrId]; } else { $fetchedValues[$entityId][] = [ 'attribute_id' => $attrId, 'entity_id' => $entityId, 'property_name' => $attributeInfo->get('name'), 'property_name_real' => $attributeInfo->get('name'), 'aliased' => false, 'value' => null, ]; } } } return $fetchedValues; }
Retrieves all virtual values of all the entities within the given result-set. @param \Cake\Collection\CollectionInterface $entities Set of entities @param array $args Contains two keys: "options" and "primary" given to the originating beforeFind(), and "selectedVirtual" a list of virtual columns selected in the originating find query @return array Virtual values indexed by entity ID
entailment
public function beforeMarshal(Event $event, ArrayObject $data, ArrayObject $options) { $bundle = !empty($options['bundle']) ? $options['bundle'] : null; $attrs = array_keys($this->_toolbox->attributes($bundle)); foreach ($data as $property => $value) { if (!in_array($property, $attrs)) { continue; } $dataType = $this->_toolbox->getType($property); $marshaledValue = $this->_toolbox->marshal($value, $dataType); $data[$property] = $marshaledValue; } }
Triggered before data is converted into entities. Converts incoming POST data to its corresponding types. @param \Cake\Event\Event $event The event that was triggered @param \ArrayObject $data The POST data to be merged with entity @param \ArrayObject $options The options passed to the marshaller @return void
entailment
public function buildMarshalMap($marshaller, $map, $options) { $bundle = !empty($options['bundle']) ? $options['bundle'] : null; $attrs = $this->_toolbox->attributes($bundle); $map = []; foreach ($attrs as $name => $info) { $map[$name] = function ($value, $entity) use ($info) { return $this->_toolbox->marshal($value, $info['type']); }; } return $map; }
Ensures that virtual properties are included in the marshalling process. @param \Cake\ORM\Marhshaller $marshaller The marhshaller of the table the behavior is attached to. @param array $map The property map being built. @param array $options The options array used in the marshalling call. @return array A map of `[property => callable]` of additional properties to marshal.
entailment
public function afterSave(Event $event, EntityInterface $entity, ArrayObject $options) { $valuesTable = TableRegistry::get('Eav.EavValues'); $result = $valuesTable ->connection() ->transactional(function () use ($valuesTable, $entity, $options) { $attrsById = []; $updatedAttrs = []; foreach ($this->_toolbox->attributes() as $name => $attr) { if (!$this->_toolbox->propertyExists($entity, $name)) { continue; } $attrsById[$attr->get('id')] = $attr; } if (empty($attrsById)) { return true; // nothing to do } $values = $valuesTable ->find() ->where([ 'eav_attribute_id IN' => array_keys($attrsById), 'entity_id' => $this->_toolbox->getEntityId($entity), ]); // NOTE: row level locking only supported by MySQL and Postgres. $driver = $this->_toolbox->driver($values); if (in_array($driver, ['mysql', 'postgres'])) { $values->epilog('FOR UPDATE'); } foreach ($values as $value) { $updatedAttrs[] = $value->get('eav_attribute_id'); $info = $attrsById[$value->get('eav_attribute_id')]; $type = $this->_toolbox->getType($info->get('name')); $marshaledValue = $this->_toolbox->marshal($entity->get($info->get('name')), $type); $value->set("value_{$type}", $marshaledValue); $entity->set($info->get('name'), $marshaledValue); $valuesTable->save($value); } foreach ($this->_toolbox->attributes() as $name => $attr) { if (!$this->_toolbox->propertyExists($entity, $name)) { continue; } if (!in_array($attr->get('id'), $updatedAttrs)) { $type = $this->_toolbox->getType($name); $value = $valuesTable->newEntity([ 'eav_attribute_id' => $attr->get('id'), 'entity_id' => $this->_toolbox->getEntityId($entity), ]); $marshaledValue = $this->_toolbox->marshal($entity->get($name), $type); $value->set("value_{$type}", $marshaledValue); $entity->set($name, $marshaledValue); $valuesTable->save($value); } } if ($this->config('cacheMap')) { $this->updateEavCache($entity); } return true; }); return $result; }
Save virtual values after an entity's real values were saved. @param \Cake\Event\Event $event The event that was triggered @param \Cake\Datasource\EntityInterface $entity The entity that was saved @param \ArrayObject $options Additional options given as an array @return bool True always
entailment
public function afterDelete(Event $event, EntityInterface $entity, ArrayObject $options) { if (!$options['atomic']) { throw new FatalErrorException(__d('eav', 'Entities in fieldable tables can only be deleted using transactions. Set [atomic = true]')); } $valuesToDelete = TableRegistry::get('Eav.EavValues') ->find() ->contain('EavAttribute') ->where([ 'EavAttribute.table_alias' => $this->_table->table(), 'EavValues.entity_id' => $this->_toolbox->getEntityId($entity), ]); foreach ($valuesToDelete as $value) { TableRegistry::get('Eav.EavValues')->delete($value); } }
After an entity was removed from database. Here is when EAV values are removed from DB. @param \Cake\Event\Event $event The event that was triggered @param \Cake\Datasource\EntityInterface $entity The entity that was deleted @param \ArrayObject $options Additional options given as an array @throws \Cake\Error\FatalErrorException When using this behavior in non-atomic mode @return void
entailment
protected function _prepareCachedColumns(EntityInterface $entity) { if ($this->config('cacheMap')) { foreach ((array)$this->config('cacheMap') as $column => $fields) { if (in_array($column, $entity->visibleProperties())) { $string = $entity->get($column); if ($string == serialize(false) || unserialize($string) !== false) { $entity->set($column, unserialize($string)); } else { $entity->set($column, new CachedColumn()); } } } } return $entity; }
Prepares entity's cache-columns (those defined using `cache` option). @param \Cake\Datasource\EntityInterface $entity The entity to prepare @return \Cake\Datasource\EntityInterfa Modified entity
entailment
protected function _scopeQuery(Query $query, $bundle = null) { $this->_initScopes(); foreach ($this->_queryScopes as $scope) { if ($scope instanceof QueryScopeInterface) { $query = $scope->scope($query, $bundle); } } return $query; }
Look for virtual columns in some query's clauses. @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 _initScopes() { foreach ((array)$this->config('queryScope') as $className) { if (!empty($this->_queryScopes[$className])) { continue; } if (class_exists($className)) { $instance = new $className($this->_table); if ($instance instanceof QueryScopeInterface) { $this->_queryScopes[$className] = $instance; } } } }
Initializes the scope objects @return void
entailment
protected function _getHandlerName() { $handler = $this->get('handler'); if (class_exists($handler)) { $handler = new $handler(); $info = $handler->info(); if (!empty($info['name'])) { return $info['name']; } } return $this->get('handler'); }
Gets a human-readable name of the field handler class. @return string
entailment
public function initialize(array $config) { $this->belongsToMany('Roles', [ 'className' => 'User.Roles', 'joinTable' => 'users_roles', 'through' => 'UsersRoles', 'propertyName' => 'roles', ]); $this->addBehavior('Timestamp', [ 'events' => [ 'Model.beforeSave' => [ 'created' => 'new', ], 'Users.login' => [ 'last_login' => 'always' ] ] ]); $this->addBehavior('Search.Searchable', [ 'fields' => function ($user) { $words = ''; $words .= empty($user->name) ?: " {$user->name}"; $words .= empty($user->username) ?: " {$user->username}"; $words .= empty($user->email) ?: " {$user->email}"; $words .= empty($user->web) ?: " {$user->web}"; if (!empty($user->_fields)) { foreach ($user->_fields as $vf) { $words .= ' ' . trim($vf->value); } } return $words; } ]); $this->addBehavior('Field.Fieldable'); $this->addSearchOperator('created', 'Search.Date', ['field' => 'created']); $this->addSearchOperator('limit', 'Search.Limit'); $this->addSearchOperator('email', 'Search.Generic', ['field' => 'email', 'conjunction' => 'auto']); $this->addSearchOperator('order', 'Search.Order', ['fields' => ['name', 'username', 'email', 'web']]); }
Initialize a table instance. Called after the constructor. @param array $config Configuration options passed to the constructor @return void
entailment
public function validationDefault(Validator $validator) { $validator ->requirePresence('name') ->notEmpty('name', __d('user', 'You must provide a name.')) ->requirePresence('username', 'create') ->add('username', [ 'characters' => [ 'rule' => function ($value, $context) { return preg_match('/^[a-zA-Z0-9\_]{3,}$/', $value) === 1; }, 'provider' => 'table', 'message' => __d('user', 'Invalid username. Only letters, numbers and "_" symbol, and at least three characters long.'), ], ]) ->requirePresence('email') ->notEmpty('email', __d('user', 'e-mail cannot be empty.')) ->requirePresence('password', 'create') ->allowEmpty('password', 'update') ->add('password', [ 'compare' => [ 'rule' => function ($value, $context) { $value2 = isset($context['data']['password2']) ? $context['data']['password2'] : false; return (new DefaultPasswordHasher)->check($value2, $value) || $value == $value2; }, 'message' => __d('user', 'Password mismatch.'), ] ]) ->allowEmpty('web') ->add('web', 'validUrl', [ 'rule' => 'url', 'message' => __d('user', 'Invalid URL.'), ]); return $this->_applyPasswordPolicies($validator); }
Default validation rules. @param \Cake\Validation\Validator $validator Validator object @return \Cake\Validation\Validator
entailment
public function beforeSave(Event $event, User $user) { if (!$user->isNew() && $user->has('password') && empty($user->password)) { $user->unsetProperty('password'); $user->dirty('password', false); } }
If not password is sent means user is not changing it. @param \Cake\Event\Event $event The event that was triggered @param \User\Model\Entity\User $user User entity being saved @return void
entailment
public function updateToken(User $user) { if (!$user->has('id')) { throw new FatalErrorException(__d('user', 'UsersTable::updateToken(), no ID was found for the given entity.')); } $token = md5(uniqid($user->id, true)); $count = $this->find()->where(['Users.token' => $token])->limit(1)->count(); while ($count > 0) { $token = str_shuffle(md5(uniqid($user->id, true) . rand(1, 9999))); $count = $this->find()->where(['Users.token' => $token])->limit(1)->count(); } $user->set('token', $token); $user->set('token_expiration', time() + USER_TOKEN_EXPIRATION); $this->updateAll([ 'token' => $user->get('token'), 'token_expiration' => $user->get('token_expiration'), ], ['id' => $user->id]); return $user; }
Generates a unique token for the given user entity. The generated token is automatically persisted on DB. Tokens are unique within the entire DB and follows the pattern below: <32-random-letters-and-numbers> @param \User\Model\Entity\User $user The user for which generate the token @return \User\Model\Entity\User The user entity with a the new token property @throws \Cake\Error\FatalErrorException When an invalid user entity was given
entailment
protected function _applyPasswordPolicies(Validator $validator) { $rules = []; if (plugin('User')->settings('password_min_length')) { $len = intval(plugin('User')->settings('password_min_length')); $rules['length'] = [ 'rule' => function ($value, $context) use ($len) { return mb_strlen($this->_getRawPassword($context)) >= $len; }, 'message' => __d('user', 'Password must be at least {0} characters long.', $len), ]; } if (plugin('User')->settings('password_uppercase')) { $rules['uppercase'] = [ 'rule' => function ($value, $context) { return (bool)preg_match('/[\p{Lu}]/u', $this->_getRawPassword($context)); }, 'message' => __d('user', 'Password must contain at least one uppercase character (A-Z).'), ]; } if (plugin('User')->settings('password_lowercase')) { $rules['lowercase'] = [ 'rule' => function ($value, $context) { return (bool)preg_match('/[\p{Ll}]/u', $this->_getRawPassword($context)); }, 'message' => __d('user', 'Password must contain at least one lowercase character (a-z).'), ]; } if (plugin('User')->settings('password_number')) { $rules['number'] = [ 'rule' => function ($value, $context) { return (bool)preg_match('/[\p{N}]/u', $this->_getRawPassword($context)); }, 'message' => __d('user', 'Password must contain at least one numeric character (1-9).'), ]; } if (plugin('User')->settings('password_non_alphanumeric')) { $rules['non_alphanumeric'] = [ 'rule' => function ($value, $context) { return (bool)preg_match('/[^\p{L}\p{N}]/u', $this->_getRawPassword($context)); }, 'message' => __d('user', 'Password must contain at least one non-alphanumeric character (e.g. #%?).'), ]; } $validator->add('password', $rules); return $validator; }
Alters validator object and applies password constraints. @param \Cake\Validation\Validator $validator Validator object @return \Cake\Validation\Validator
entailment
public function afterSave(Event $event, EntityInterface $entity, ArrayObject $options) { $isNew = $entity->isNew(); if (($this->config('on') === 'update' && $isNew) || ($this->config('on') === 'insert' && !$isNew) || (isset($options['index']) && $options['index'] === false) ) { return; } $this->_table->dispatchEvent('Model.beforeIndex', compact('entity')); $success = $this->searchEngine()->index($entity); $this->_table->dispatchEvent('Model.afterIndex', compact('entity', 'success')); }
Generates a list of words after each entity is saved. Triggers the following events: - `Model.beforeIndex`: Before entity gets indexed by the configured search engine adapter. First argument is the entity instance being indexed. - `Model.afterIndex`: After entity was indexed by the configured search engine adapter. First argument is the entity instance that was indexed, and second indicates whether the indexing process completed correctly or not. @param \Cake\Event\Event $event The event that was triggered @param \Cake\Datasource\EntityInterface $entity The entity that was saved @param \ArrayObject $options Additional options @return void
entailment
public function beforeDelete(Event $event, EntityInterface $entity, ArrayObject $options) { $this->_table->dispatchEvent('Model.beforeRemoveIndex', compact('entity')); $success = $this->searchEngine()->delete($entity); $this->_table->dispatchEvent('Model.afterRemoveIndex', compact('entity', 'success')); return $success; }
Prepares entity to delete its words-index. Triggers the following events: - `Model.beforeRemoveIndex`: Before entity's index is removed. First argument is the affected entity instance. - `Model.afterRemoveIndex`: After entity's index is removed. First argument is the affected entity instance, and second indicates whether the index-removing process completed correctly or not. @param \Cake\Event\Event $event The event that was triggered @param \Cake\Datasource\EntityInterface $entity The entity that was removed @param \ArrayObject $options Additional options @return bool
entailment
public function search($criteria, Query $query = null, array $options = []) { if ($query === null) { $query = $this->_table->find(); } return $this->searchEngine()->search($criteria, $query, $options); }
Gets entities matching the given search criteria. @param mixed $criteria A search-criteria compatible with the Search Engine being used @param \Cake\ORM\Query|null $query The query to scope, or null to create one @param array $options Additional parameter used to control the search process provided by attached Engine @return \Cake\ORM\Query Scoped query @throws Cake\Error\FatalErrorException When query gets corrupted while processing tokens
entailment
public function searchEngine(EngineInterface $engine = null) { if ($engine !== null) { $this->_engine = $engine; } return $this->_engine; }
Gets/sets search engine instance. @return \Search\Engine\EngineInterface
entailment
public function addSearchOperator($name, $handler, array $options = []) { $name = Inflector::underscore($name); $operator = [ 'name' => $name, 'handler' => false, 'options' => [], ]; if (is_string($handler)) { if (method_exists($this->_table, $handler)) { $operator['handler'] = $handler; } else { list($plugin, $class) = pluginSplit($handler); if ($plugin) { $className = $plugin === 'Search' ? "Search\\Operator\\{$class}Operator" : "{$plugin}\\Model\\Search\\{$class}Operator"; $className = str_replace('OperatorOperator', 'Operator', $className); } else { $className = $class; } $operator['handler'] = $className; $operator['options'] = $options; } } elseif (is_object($handler) || is_callable($handler)) { $operator['handler'] = $handler; } $this->config("operators.{$name}", $operator); }
Registers a new operator method. Allowed formats are: ```php $this->addSearchOperator('created', 'operatorCreated'); ``` The above will use Table's `operatorCreated()` method to handle the "created" operator. --- ```php $this->addSearchOperator('created', 'MyPlugin.Limit'); ``` The above will use `MyPlugin\Model\Search\LimitOperator` class to handle the "limit" operator. Note the `Operator` suffix. --- ```php $this->addSearchOperator('created', 'MyPlugin.Limit', ['my_option' => 'option_value']); ``` Similar as before, but in this case you can provide some configuration options passing an array as above. --- ```php $this->addSearchOperator('created', 'Full\ClassName'); ``` Or you can indicate a full class name to use. --- ```php $this->addSearchOperator('created', function ($query, $token) { // scope $query return $query; }); ``` You can simply pass a callable function to handle the operator, this callable must return the altered $query object. --- ```php $this->addSearchOperator('created', new CreatedOperator($table, $options)); ``` In this case you can directly pass an instance of an operator handler, this object should extends the `Search\Operator` abstract class. @param string $name Underscored operator's name. e.g. `author` @param mixed $handler A valid handler as described above @return void
entailment
public function enableSearchOperator($name) { if (isset($this->_config['operators'][":{$name}"])) { $this->_config['operators'][$name] = $this->_config['operators'][":{$name}"]; unset($this->_config['operators'][":{$name}"]); } }
Enables a an operator. @param string $name Name of the operator to be enabled @return void
entailment
public function disableSearchOperator($name) { if (isset($this->_config['operators'][$name])) { $this->_config['operators'][":{$name}"] = $this->_config['operators'][$name]; unset($this->_config['operators'][$name]); } }
Disables an operator. @param string $name Name of the operator to be disabled @return void
entailment
public function applySearchOperator(Query $query, TokenInterface $token) { if (!$token->isOperator()) { return $query; } $callable = $this->_operatorCallable($token->name()); if (is_callable($callable)) { $query = $callable($query, $token); if (!($query instanceof Query)) { throw new FatalErrorException(__d('search', 'Error while processing the "{0}" token in the search criteria.', $operator)); } } else { $result = $this->_triggerOperator($query, $token); if ($result instanceof Query) { $query = $result; } } return $query; }
Given a query instance applies the provided token representing a search operator. @param \Cake\ORM\Query $query The query to be scope @param \Search\TokenInterface $token Token describing an operator. e.g `-op_name:op_value` @return \Cake\ORM\Query Scoped query
entailment