repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
nabu-3/core
nabu/http/app/CNabuHTTPStandaloneApplication.php
CNabuHTTPStandaloneApplication.addTarget
protected function addTarget(CNabuSiteTarget $nb_site_target, $default = false) { $nb_site = $this->nb_engine->getHTTPServer()->getSite(); if ($nb_site instanceof CNabuSite) { return $nb_site->addTarget($nb_site_target, $default); } else { throw new ENabuCoreException(ENabuCoreException::ERROR_SITE_NOT_INSTANTIATED); } }
php
protected function addTarget(CNabuSiteTarget $nb_site_target, $default = false) { $nb_site = $this->nb_engine->getHTTPServer()->getSite(); if ($nb_site instanceof CNabuSite) { return $nb_site->addTarget($nb_site_target, $default); } else { throw new ENabuCoreException(ENabuCoreException::ERROR_SITE_NOT_INSTANTIATED); } }
[ "protected", "function", "addTarget", "(", "CNabuSiteTarget", "$", "nb_site_target", ",", "$", "default", "=", "false", ")", "{", "$", "nb_site", "=", "$", "this", "->", "nb_engine", "->", "getHTTPServer", "(", ")", "->", "getSite", "(", ")", ";", "if", ...
Adds an existing Site Target instance to the list of targets. @param CNabuSiteTarget $nb_site_target The Site Target instance to be added. @return CNabuSiteTarget Returns the instance target passed as param in $nb_site_target. @throws ENabuCoreException Throws an exception if the Site is not initialized.
[ "Adds", "an", "existing", "Site", "Target", "instance", "to", "the", "list", "of", "targets", "." ]
8a93a91ba146536d66f57821e6f23f9175d8bd11
https://github.com/nabu-3/core/blob/8a93a91ba146536d66f57821e6f23f9175d8bd11/nabu/http/app/CNabuHTTPStandaloneApplication.php#L194-L202
train
nabu-3/core
nabu/http/app/CNabuHTTPStandaloneApplication.php
CNabuHTTPStandaloneApplication.setLoginTarget
public function setLoginTarget(CNabuSiteTarget $nb_site_target) { $nb_site = $this->nb_engine->getHTTPServer()->getSite(); if ($nb_site instanceof CNabuSite) { return $nb_site->setLoginTarget($nb_site_target); } else { throw new ENabuCoreException(ENabuCoreException::ERROR_SITE_NOT_INSTANTIATED); } }
php
public function setLoginTarget(CNabuSiteTarget $nb_site_target) { $nb_site = $this->nb_engine->getHTTPServer()->getSite(); if ($nb_site instanceof CNabuSite) { return $nb_site->setLoginTarget($nb_site_target); } else { throw new ENabuCoreException(ENabuCoreException::ERROR_SITE_NOT_INSTANTIATED); } }
[ "public", "function", "setLoginTarget", "(", "CNabuSiteTarget", "$", "nb_site_target", ")", "{", "$", "nb_site", "=", "$", "this", "->", "nb_engine", "->", "getHTTPServer", "(", ")", "->", "getSite", "(", ")", ";", "if", "(", "$", "nb_site", "instanceof", ...
Sets the Login Target when private zones are requested. @param CNabuSiteTarget $nb_site_target Site Target to be setted. @return Returns the target setted. @throws ENabuCoreException Throws an exception it the Site is not initialized.
[ "Sets", "the", "Login", "Target", "when", "private", "zones", "are", "requested", "." ]
8a93a91ba146536d66f57821e6f23f9175d8bd11
https://github.com/nabu-3/core/blob/8a93a91ba146536d66f57821e6f23f9175d8bd11/nabu/http/app/CNabuHTTPStandaloneApplication.php#L210-L218
train
nabu-3/core
nabu/http/app/CNabuHTTPStandaloneApplication.php
CNabuHTTPStandaloneApplication.addRootSiteMapForURL
public function addRootSiteMapForURL($order, CNabuRole $nb_role = null) { if ($nb_role === null) { $nb_role = $this->nb_engine->getHTTPServer()->getSite()->getDefaultRole(); } $nb_site_map = new CNabuBuiltInSiteMap(); $nb_site_map->setOrder($order); return $this->addRootSiteMap($nb_site_map); }
php
public function addRootSiteMapForURL($order, CNabuRole $nb_role = null) { if ($nb_role === null) { $nb_role = $this->nb_engine->getHTTPServer()->getSite()->getDefaultRole(); } $nb_site_map = new CNabuBuiltInSiteMap(); $nb_site_map->setOrder($order); return $this->addRootSiteMap($nb_site_map); }
[ "public", "function", "addRootSiteMapForURL", "(", "$", "order", ",", "CNabuRole", "$", "nb_role", "=", "null", ")", "{", "if", "(", "$", "nb_role", "===", "null", ")", "{", "$", "nb_role", "=", "$", "this", "->", "nb_engine", "->", "getHTTPServer", "(",...
Adds a new Site Map root node of type URL. @param int $order Order for the node. @param CNabuRole $nb_role Default role for this Site Map. If null, uses the default Role of the Site. @return CNabuBuiltInSiteMap Returns the created instance
[ "Adds", "a", "new", "Site", "Map", "root", "node", "of", "type", "URL", "." ]
8a93a91ba146536d66f57821e6f23f9175d8bd11
https://github.com/nabu-3/core/blob/8a93a91ba146536d66f57821e6f23f9175d8bd11/nabu/http/app/CNabuHTTPStandaloneApplication.php#L226-L236
train
nabu-3/core
nabu/http/app/CNabuHTTPStandaloneApplication.php
CNabuHTTPStandaloneApplication.addRootSiteMapForTarget
public function addRootSiteMapForTarget(CNabuSiteTarget $nb_site_target, $order, CNabuRole $nb_role = null) { if ($nb_role === null) { $nb_role = $this->nb_engine->getHTTPServer()->getSite()->getDefaultRole(); } $nb_site_map = new CNabuBuiltInSiteMap(); $nb_site_map->setSiteTarget($nb_site_target) ->setOrder($order) ; return $this->addRootSiteMap($nb_site_map); }
php
public function addRootSiteMapForTarget(CNabuSiteTarget $nb_site_target, $order, CNabuRole $nb_role = null) { if ($nb_role === null) { $nb_role = $this->nb_engine->getHTTPServer()->getSite()->getDefaultRole(); } $nb_site_map = new CNabuBuiltInSiteMap(); $nb_site_map->setSiteTarget($nb_site_target) ->setOrder($order) ; return $this->addRootSiteMap($nb_site_map); }
[ "public", "function", "addRootSiteMapForTarget", "(", "CNabuSiteTarget", "$", "nb_site_target", ",", "$", "order", ",", "CNabuRole", "$", "nb_role", "=", "null", ")", "{", "if", "(", "$", "nb_role", "===", "null", ")", "{", "$", "nb_role", "=", "$", "this"...
Adds a new Site Map root node of type Target. @param CNabuSiteTarget $nb_site_target @param int $order Order for the node. @param CNabuRole $nb_role Default role for this Site Map. If null, uses the default Role of the Site. @return CNabuBuiltInSiteMap Returns the created instance
[ "Adds", "a", "new", "Site", "Map", "root", "node", "of", "type", "Target", "." ]
8a93a91ba146536d66f57821e6f23f9175d8bd11
https://github.com/nabu-3/core/blob/8a93a91ba146536d66f57821e6f23f9175d8bd11/nabu/http/app/CNabuHTTPStandaloneApplication.php#L245-L257
train
nabu-3/core
nabu/http/app/CNabuHTTPStandaloneApplication.php
CNabuHTTPStandaloneApplication.addRootSiteMap
public function addRootSiteMap(CNabuSiteMap $nb_site_map) { $nb_site = $this->nb_engine->getHTTPServer()->getSite(); if ($nb_site instanceof CNabuSite) { return $nb_site->addSiteMap($nb_site_map); } else { throw new ENabuCoreException(ENabuCoreException::ERROR_SITE_NOT_INSTANTIATED); } }
php
public function addRootSiteMap(CNabuSiteMap $nb_site_map) { $nb_site = $this->nb_engine->getHTTPServer()->getSite(); if ($nb_site instanceof CNabuSite) { return $nb_site->addSiteMap($nb_site_map); } else { throw new ENabuCoreException(ENabuCoreException::ERROR_SITE_NOT_INSTANTIATED); } }
[ "public", "function", "addRootSiteMap", "(", "CNabuSiteMap", "$", "nb_site_map", ")", "{", "$", "nb_site", "=", "$", "this", "->", "nb_engine", "->", "getHTTPServer", "(", ")", "->", "getSite", "(", ")", ";", "if", "(", "$", "nb_site", "instanceof", "CNabu...
Add an existing Site Map root node. @param CNabuSiteMap $nb_site_map The Site Map node to be added to root nodes. @return CNabuSiteMap Returns the Site Map instance passed as param in $nb_site_map. @throws ENabuCoreException Throws this exception when the Site is not initialized.
[ "Add", "an", "existing", "Site", "Map", "root", "node", "." ]
8a93a91ba146536d66f57821e6f23f9175d8bd11
https://github.com/nabu-3/core/blob/8a93a91ba146536d66f57821e6f23f9175d8bd11/nabu/http/app/CNabuHTTPStandaloneApplication.php#L265-L273
train
nabu-3/core
nabu/http/app/CNabuHTTPStandaloneApplication.php
CNabuHTTPStandaloneApplication.newMedioteca
public function newMedioteca($key) { $nb_medioteca = new CNabuBuiltInMedioteca(); $nb_medioteca->setKey($key); return $this->addMedioteca($nb_medioteca); }
php
public function newMedioteca($key) { $nb_medioteca = new CNabuBuiltInMedioteca(); $nb_medioteca->setKey($key); return $this->addMedioteca($nb_medioteca); }
[ "public", "function", "newMedioteca", "(", "$", "key", ")", "{", "$", "nb_medioteca", "=", "new", "CNabuBuiltInMedioteca", "(", ")", ";", "$", "nb_medioteca", "->", "setKey", "(", "$", "key", ")", ";", "return", "$", "this", "->", "addMedioteca", "(", "$...
Creates a new BuiltIn Medioteca and adds them to the Mediotecas Manager. @param string $key Key to locate the Medioteca. @return CNabuMedioteca Returns the inserted Medioteca to allow cascade chain methods.
[ "Creates", "a", "new", "BuiltIn", "Medioteca", "and", "adds", "them", "to", "the", "Mediotecas", "Manager", "." ]
8a93a91ba146536d66f57821e6f23f9175d8bd11
https://github.com/nabu-3/core/blob/8a93a91ba146536d66f57821e6f23f9175d8bd11/nabu/http/app/CNabuHTTPStandaloneApplication.php#L322-L328
train
vanilla/garden-db
src/Model.php
Model.getPrimaryKey
public function getPrimaryKey() { if ($this->primaryKey === null) { $schema = $this->getSchema(); $pk = []; foreach ($schema->getSchemaArray()['properties'] as $column => $property) { if (!empty($property['primary'])) { $pk[] = $column; } } $this->primaryKey = $pk; } return $this->primaryKey; }
php
public function getPrimaryKey() { if ($this->primaryKey === null) { $schema = $this->getSchema(); $pk = []; foreach ($schema->getSchemaArray()['properties'] as $column => $property) { if (!empty($property['primary'])) { $pk[] = $column; } } $this->primaryKey = $pk; } return $this->primaryKey; }
[ "public", "function", "getPrimaryKey", "(", ")", "{", "if", "(", "$", "this", "->", "primaryKey", "===", "null", ")", "{", "$", "schema", "=", "$", "this", "->", "getSchema", "(", ")", ";", "$", "pk", "=", "[", "]", ";", "foreach", "(", "$", "sch...
Get the primaryKey. @return array Returns the primaryKey.
[ "Get", "the", "primaryKey", "." ]
2634229fb7a161f649ad371e59a973ccbbe72247
https://github.com/vanilla/garden-db/blob/2634229fb7a161f649ad371e59a973ccbbe72247/src/Model.php#L72-L85
train
vanilla/garden-db
src/Model.php
Model.mapID
protected function mapID($id) { $idArray = (array)$id; $result = []; foreach ($this->getPrimaryKey() as $i => $column) { if (isset($idArray[$i])) { $result[$column] = $idArray[$i]; } elseif (isset($idArray[$column])) { $result[$column] = $idArray[$column]; } else { $result[$column] = null; } } return $result; }
php
protected function mapID($id) { $idArray = (array)$id; $result = []; foreach ($this->getPrimaryKey() as $i => $column) { if (isset($idArray[$i])) { $result[$column] = $idArray[$i]; } elseif (isset($idArray[$column])) { $result[$column] = $idArray[$column]; } else { $result[$column] = null; } } return $result; }
[ "protected", "function", "mapID", "(", "$", "id", ")", "{", "$", "idArray", "=", "(", "array", ")", "$", "id", ";", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "getPrimaryKey", "(", ")", "as", "$", "i", "=>", "$", "col...
Map primary key values to the primary key name. @param mixed $id An ID value or an array of ID values. If an array is passed and the model has a mult-column primary key then all of the values must be in order. @return array Returns an associative array mapping column names to values.
[ "Map", "primary", "key", "values", "to", "the", "primary", "key", "name", "." ]
2634229fb7a161f649ad371e59a973ccbbe72247
https://github.com/vanilla/garden-db/blob/2634229fb7a161f649ad371e59a973ccbbe72247/src/Model.php#L125-L140
train
vanilla/garden-db
src/Model.php
Model.getSchema
final public function getSchema() { if ($this->schema === null) { $this->schema = $this->fetchSchema(); } return $this->schema; }
php
final public function getSchema() { if ($this->schema === null) { $this->schema = $this->fetchSchema(); } return $this->schema; }
[ "final", "public", "function", "getSchema", "(", ")", "{", "if", "(", "$", "this", "->", "schema", "===", "null", ")", "{", "$", "this", "->", "schema", "=", "$", "this", "->", "fetchSchema", "(", ")", ";", "}", "return", "$", "this", "->", "schema...
Gets the row schema for this model. @return Schema Returns a schema.
[ "Gets", "the", "row", "schema", "for", "this", "model", "." ]
2634229fb7a161f649ad371e59a973ccbbe72247
https://github.com/vanilla/garden-db/blob/2634229fb7a161f649ad371e59a973ccbbe72247/src/Model.php#L147-L152
train
vanilla/garden-db
src/Model.php
Model.fetchSchema
protected function fetchSchema() { $columns = $this->getDb()->fetchColumnDefs($this->name); if ($columns === null) { throw new \InvalidArgumentException("Cannot fetch schema foor {$this->name}."); } $schema = [ 'type' => 'object', 'dbtype' => 'table', 'properties' => $columns ]; $required = $this->requiredFields($columns); if (!empty($required)) { $schema['required'] = $required; } return new Schema($schema); }
php
protected function fetchSchema() { $columns = $this->getDb()->fetchColumnDefs($this->name); if ($columns === null) { throw new \InvalidArgumentException("Cannot fetch schema foor {$this->name}."); } $schema = [ 'type' => 'object', 'dbtype' => 'table', 'properties' => $columns ]; $required = $this->requiredFields($columns); if (!empty($required)) { $schema['required'] = $required; } return new Schema($schema); }
[ "protected", "function", "fetchSchema", "(", ")", "{", "$", "columns", "=", "$", "this", "->", "getDb", "(", ")", "->", "fetchColumnDefs", "(", "$", "this", "->", "name", ")", ";", "if", "(", "$", "columns", "===", "null", ")", "{", "throw", "new", ...
Fetch the row schema from the database meta info. This method works fine as-is, but can also be overridden to provide more specific schema information for the model. This method is called only once for the object and then is cached in a property so you don't need to implement caching of your own. If you are going to override this method we recommend you still call the parent method and add its result to your schema. Here is an example: ```php protected function fetchSchema() { $schema = Schema::parse([ 'body:s', // make the column required even if it isn't in the db. 'attributes:o?' // accept an object instead of string ]); $dbSchema = parent::fetchSchema(); $schema->add($dbSchema, true); return $schema; } ``` @return Schema Returns the row schema.
[ "Fetch", "the", "row", "schema", "from", "the", "database", "meta", "info", "." ]
2634229fb7a161f649ad371e59a973ccbbe72247
https://github.com/vanilla/garden-db/blob/2634229fb7a161f649ad371e59a973ccbbe72247/src/Model.php#L180-L198
train
vanilla/garden-db
src/Model.php
Model.requiredFields
private function requiredFields(array $columns) { $required = []; foreach ($columns as $name => $column) { if (empty($column['autoIncrement']) && !isset($column['default']) && empty($column['allowNull'])) { $required[] = $name; } } return $required; }
php
private function requiredFields(array $columns) { $required = []; foreach ($columns as $name => $column) { if (empty($column['autoIncrement']) && !isset($column['default']) && empty($column['allowNull'])) { $required[] = $name; } } return $required; }
[ "private", "function", "requiredFields", "(", "array", "$", "columns", ")", "{", "$", "required", "=", "[", "]", ";", "foreach", "(", "$", "columns", "as", "$", "name", "=>", "$", "column", ")", "{", "if", "(", "empty", "(", "$", "column", "[", "'a...
Figure out the schema required fields from a list of columns. A column is required if it meets all of the following criteria. - The column does not have an auto increment. - The column does not have a default value. - The column does not allow null. @param array $columns An array of column schemas.
[ "Figure", "out", "the", "schema", "required", "fields", "from", "a", "list", "of", "columns", "." ]
2634229fb7a161f649ad371e59a973ccbbe72247
https://github.com/vanilla/garden-db/blob/2634229fb7a161f649ad371e59a973ccbbe72247/src/Model.php#L211-L221
train
vanilla/garden-db
src/Model.php
Model.get
public function get(array $where) { $options = [ Db::OPTION_FETCH_MODE => $this->getFetchArgs(), 'rowCallback' => [$this, 'unserialize'] ]; $qry = new TableQuery($this->name, $where, $this->db, $options); $qry->setLimit($this->getDefaultLimit()) ->setOrder(...$this->getDefaultOrder()); return $qry; }
php
public function get(array $where) { $options = [ Db::OPTION_FETCH_MODE => $this->getFetchArgs(), 'rowCallback' => [$this, 'unserialize'] ]; $qry = new TableQuery($this->name, $where, $this->db, $options); $qry->setLimit($this->getDefaultLimit()) ->setOrder(...$this->getDefaultOrder()); return $qry; }
[ "public", "function", "get", "(", "array", "$", "where", ")", "{", "$", "options", "=", "[", "Db", "::", "OPTION_FETCH_MODE", "=>", "$", "this", "->", "getFetchArgs", "(", ")", ",", "'rowCallback'", "=>", "[", "$", "this", ",", "'unserialize'", "]", "]...
Query the model. @param array $where A where clause to filter the data. @return DatasetInterface
[ "Query", "the", "model", "." ]
2634229fb7a161f649ad371e59a973ccbbe72247
https://github.com/vanilla/garden-db/blob/2634229fb7a161f649ad371e59a973ccbbe72247/src/Model.php#L229-L240
train
vanilla/garden-db
src/Model.php
Model.query
public function query(array $where, array $options = []) { $options += [ 'order' => $this->getDefaultOrder(), 'limit' => $this->getDefaultLimit(), Db::OPTION_FETCH_MODE => $this->getFetchArgs() ]; $stmt = $this->db->get($this->name, $where, $options); return $stmt; }
php
public function query(array $where, array $options = []) { $options += [ 'order' => $this->getDefaultOrder(), 'limit' => $this->getDefaultLimit(), Db::OPTION_FETCH_MODE => $this->getFetchArgs() ]; $stmt = $this->db->get($this->name, $where, $options); return $stmt; }
[ "public", "function", "query", "(", "array", "$", "where", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "options", "+=", "[", "'order'", "=>", "$", "this", "->", "getDefaultOrder", "(", ")", ",", "'limit'", "=>", "$", "this", "->", "...
Query the database directly. @param array $where A where clause to filter the data. @param array $options Options to pass to the database. See {@link Db::get()}. @return \PDOStatement Returns a statement from the query.
[ "Query", "the", "database", "directly", "." ]
2634229fb7a161f649ad371e59a973ccbbe72247
https://github.com/vanilla/garden-db/blob/2634229fb7a161f649ad371e59a973ccbbe72247/src/Model.php#L249-L258
train
vanilla/garden-db
src/Model.php
Model.updateID
public function updateID($id, array $set): int { $r = $this->update($set, $this->mapID($id)); return $r; }
php
public function updateID($id, array $set): int { $r = $this->update($set, $this->mapID($id)); return $r; }
[ "public", "function", "updateID", "(", "$", "id", ",", "array", "$", "set", ")", ":", "int", "{", "$", "r", "=", "$", "this", "->", "update", "(", "$", "set", ",", "$", "this", "->", "mapID", "(", "$", "id", ")", ")", ";", "return", "$", "r",...
Update a row in the database with a known primary key. @param mixed $id A single ID value or an array for multi-column primary keys. @param array $set The columns to update. @return int Returns the number of affected rows. @throws ValidationException Throws an exception if the row doesn't validate. @throws \Garden\Schema\RefNotFoundException Throws an exception if you have an invalid schema reference.
[ "Update", "a", "row", "in", "the", "database", "with", "a", "known", "primary", "key", "." ]
2634229fb7a161f649ad371e59a973ccbbe72247
https://github.com/vanilla/garden-db/blob/2634229fb7a161f649ad371e59a973ccbbe72247/src/Model.php#L313-L316
train
vanilla/garden-db
src/Model.php
Model.validate
public function validate($row, $sparse = false) { $schema = $this->getSchema(); $valid = $schema->validate($row, ['sparse' => $sparse]); return $valid; }
php
public function validate($row, $sparse = false) { $schema = $this->getSchema(); $valid = $schema->validate($row, ['sparse' => $sparse]); return $valid; }
[ "public", "function", "validate", "(", "$", "row", ",", "$", "sparse", "=", "false", ")", "{", "$", "schema", "=", "$", "this", "->", "getSchema", "(", ")", ";", "$", "valid", "=", "$", "schema", "->", "validate", "(", "$", "row", ",", "[", "'spa...
Validate a row of data. @param array|\ArrayAccess $row The row to validate. @param bool $sparse Whether or not the validation should be sparse (during update). @return array Returns valid data. @throws ValidationException Throws an exception if the row doesn't validate. @throws \Garden\Schema\RefNotFoundException Throws an exception if you have an invalid schema reference.
[ "Validate", "a", "row", "of", "data", "." ]
2634229fb7a161f649ad371e59a973ccbbe72247
https://github.com/vanilla/garden-db/blob/2634229fb7a161f649ad371e59a973ccbbe72247/src/Model.php#L327-L332
train
nails/module-captcha
admin/controllers/Settings.php
Settings.index
public function index() { if (!userHasPermission('admin:captcha:settings:*')) { unauthorised(); } $oDb = Factory::service('Database'); $oInput = Factory::service('Input'); $oCaptchaDriverService = Factory::service('CaptchaDriver', 'nails/module-captcha'); if ($oInput->post()) { // Settings keys $sKeyCaptchaDriver = $oCaptchaDriverService->getSettingKey(); // Validation $oFormValidation = Factory::service('FormValidation'); $oFormValidation->set_rules($sKeyCaptchaDriver, '', 'required'); if ($oFormValidation->run()) { try { $oDb->trans_begin(); // Drivers $oCaptchaDriverService->saveEnabled($oInput->post($sKeyCaptchaDriver)); $oDb->trans_commit(); $this->data['success'] = 'Captcha settings were saved.'; } catch (\Exception $e) { $oDb->trans_rollback(); $this->data['error'] = 'There was a problem saving settings. ' . $e->getMessage(); } } else { $this->data['error'] = lang('fv_there_were_errors'); } } // -------------------------------------------------------------------------- // Get data $this->data['settings'] = appSetting(null, 'nails/module-captcha', true); $this->data['captcha_drivers'] = $oCaptchaDriverService->getAll(); $this->data['captcha_drivers_enabled'] = $oCaptchaDriverService->getEnabledSlug(); Helper::loadView('index'); }
php
public function index() { if (!userHasPermission('admin:captcha:settings:*')) { unauthorised(); } $oDb = Factory::service('Database'); $oInput = Factory::service('Input'); $oCaptchaDriverService = Factory::service('CaptchaDriver', 'nails/module-captcha'); if ($oInput->post()) { // Settings keys $sKeyCaptchaDriver = $oCaptchaDriverService->getSettingKey(); // Validation $oFormValidation = Factory::service('FormValidation'); $oFormValidation->set_rules($sKeyCaptchaDriver, '', 'required'); if ($oFormValidation->run()) { try { $oDb->trans_begin(); // Drivers $oCaptchaDriverService->saveEnabled($oInput->post($sKeyCaptchaDriver)); $oDb->trans_commit(); $this->data['success'] = 'Captcha settings were saved.'; } catch (\Exception $e) { $oDb->trans_rollback(); $this->data['error'] = 'There was a problem saving settings. ' . $e->getMessage(); } } else { $this->data['error'] = lang('fv_there_were_errors'); } } // -------------------------------------------------------------------------- // Get data $this->data['settings'] = appSetting(null, 'nails/module-captcha', true); $this->data['captcha_drivers'] = $oCaptchaDriverService->getAll(); $this->data['captcha_drivers_enabled'] = $oCaptchaDriverService->getEnabledSlug(); Helper::loadView('index'); }
[ "public", "function", "index", "(", ")", "{", "if", "(", "!", "userHasPermission", "(", "'admin:captcha:settings:*'", ")", ")", "{", "unauthorised", "(", ")", ";", "}", "$", "oDb", "=", "Factory", "::", "service", "(", "'Database'", ")", ";", "$", "oInpu...
Manage Captcha settings @return void
[ "Manage", "Captcha", "settings" ]
7b1c68959acb514c5e7a9bb12340a0bb80a8b7e5
https://github.com/nails/module-captcha/blob/7b1c68959acb514c5e7a9bb12340a0bb80a8b7e5/admin/controllers/Settings.php#L62-L113
train
nails/module-auth
auth/controllers/MfaQuestion.php
MfaQuestion.askQuestion
protected function askQuestion() { // Ask away cap'n! $this->data['page']->title = lang('auth_twofactor_answer_title'); $this->loadStyles(NAILS_APP_PATH . 'application/modules/auth/views/mfa/question/ask.php'); Factory::service('View') ->load([ 'structure/header/blank', 'auth/mfa/question/ask', 'structure/footer/blank', ]); }
php
protected function askQuestion() { // Ask away cap'n! $this->data['page']->title = lang('auth_twofactor_answer_title'); $this->loadStyles(NAILS_APP_PATH . 'application/modules/auth/views/mfa/question/ask.php'); Factory::service('View') ->load([ 'structure/header/blank', 'auth/mfa/question/ask', 'structure/footer/blank', ]); }
[ "protected", "function", "askQuestion", "(", ")", "{", "// Ask away cap'n!", "$", "this", "->", "data", "[", "'page'", "]", "->", "title", "=", "lang", "(", "'auth_twofactor_answer_title'", ")", ";", "$", "this", "->", "loadStyles", "(", "NAILS_APP_PATH", "."...
Asks one of the user's questions @throws \Nails\Common\Exception\FactoryException
[ "Asks", "one", "of", "the", "user", "s", "questions" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/auth/controllers/MfaQuestion.php#L247-L258
train
locomotivemtl/charcoal-attachment
src/Charcoal/Attachment/Object/Attachment.php
Attachment.isPresentable
public function isPresentable($presenter = null) { if (is_bool($presenter)) { $this->presentable = $presenter; } return $this->presentable; }
php
public function isPresentable($presenter = null) { if (is_bool($presenter)) { $this->presentable = $presenter; } return $this->presentable; }
[ "public", "function", "isPresentable", "(", "$", "presenter", "=", "null", ")", "{", "if", "(", "is_bool", "(", "$", "presenter", ")", ")", "{", "$", "this", "->", "presentable", "=", "$", "presenter", ";", "}", "return", "$", "this", "->", "presentabl...
Determine if the model is for presentation or editing. @param boolean $presenter The presenter flag. @return boolean Returns TRUE if model is used for presentation; FALSE for editing.
[ "Determine", "if", "the", "model", "is", "for", "presentation", "or", "editing", "." ]
82963e414483e7a0fc75e30894db0bba376dbd2d
https://github.com/locomotivemtl/charcoal-attachment/blob/82963e414483e7a0fc75e30894db0bba376dbd2d/src/Charcoal/Attachment/Object/Attachment.php#L227-L234
train
locomotivemtl/charcoal-attachment
src/Charcoal/Attachment/Object/Attachment.php
Attachment.setContainerObj
public function setContainerObj($obj) { if ($obj === null) { $this->containerObj = null; return $this; } if (!$obj instanceof AttachmentContainerInterface) { throw new InvalidArgumentException(sprintf( 'Container object must be an instance of %s; received %s', AttachmentContainerInterface::class, (is_object($obj) ? get_class($obj) : gettype($obj)) )); } if (!$obj->id()) { throw new InvalidArgumentException(sprintf( 'Container object must have an ID.', (is_object($obj) ? get_class($obj) : gettype($obj)) )); } $this->containerObj = $obj; return $this; }
php
public function setContainerObj($obj) { if ($obj === null) { $this->containerObj = null; return $this; } if (!$obj instanceof AttachmentContainerInterface) { throw new InvalidArgumentException(sprintf( 'Container object must be an instance of %s; received %s', AttachmentContainerInterface::class, (is_object($obj) ? get_class($obj) : gettype($obj)) )); } if (!$obj->id()) { throw new InvalidArgumentException(sprintf( 'Container object must have an ID.', (is_object($obj) ? get_class($obj) : gettype($obj)) )); } $this->containerObj = $obj; return $this; }
[ "public", "function", "setContainerObj", "(", "$", "obj", ")", "{", "if", "(", "$", "obj", "===", "null", ")", "{", "$", "this", "->", "containerObj", "=", "null", ";", "return", "$", "this", ";", "}", "if", "(", "!", "$", "obj", "instanceof", "Att...
Set the attachment's container instance. @param AttachmentContainerInterface|null $obj The container object or NULL. @throws InvalidArgumentException If the given object is invalid. @return Attachment
[ "Set", "the", "attachment", "s", "container", "instance", "." ]
82963e414483e7a0fc75e30894db0bba376dbd2d
https://github.com/locomotivemtl/charcoal-attachment/blob/82963e414483e7a0fc75e30894db0bba376dbd2d/src/Charcoal/Attachment/Object/Attachment.php#L280-L306
train
locomotivemtl/charcoal-attachment
src/Charcoal/Attachment/Object/Attachment.php
Attachment.microType
public function microType() { $classname = get_called_class(); if (!isset(static::$resolvedType[$classname])) { $reflect = new ReflectionClass($this); static::$resolvedType[$classname] = strtolower($reflect->getShortName()); } return static::$resolvedType[$classname]; }
php
public function microType() { $classname = get_called_class(); if (!isset(static::$resolvedType[$classname])) { $reflect = new ReflectionClass($this); static::$resolvedType[$classname] = strtolower($reflect->getShortName()); } return static::$resolvedType[$classname]; }
[ "public", "function", "microType", "(", ")", "{", "$", "classname", "=", "get_called_class", "(", ")", ";", "if", "(", "!", "isset", "(", "static", "::", "$", "resolvedType", "[", "$", "classname", "]", ")", ")", "{", "$", "reflect", "=", "new", "Ref...
Retrieve the unqualified class name. @return string Returns the short name of the model's class, the part without the namespace.
[ "Retrieve", "the", "unqualified", "class", "name", "." ]
82963e414483e7a0fc75e30894db0bba376dbd2d
https://github.com/locomotivemtl/charcoal-attachment/blob/82963e414483e7a0fc75e30894db0bba376dbd2d/src/Charcoal/Attachment/Object/Attachment.php#L345-L356
train
locomotivemtl/charcoal-attachment
src/Charcoal/Attachment/Object/Attachment.php
Attachment.heading
public function heading() { $heading = $this->render((string)$this->heading); if (!$heading) { $heading = $this->translator()->translation('{{ objType }} #{{ id }}', [ '{{ objType }}' => ucfirst($this->microType()), '{{ id }}' => $this->id() ]); } return $heading; }
php
public function heading() { $heading = $this->render((string)$this->heading); if (!$heading) { $heading = $this->translator()->translation('{{ objType }} #{{ id }}', [ '{{ objType }}' => ucfirst($this->microType()), '{{ id }}' => $this->id() ]); } return $heading; }
[ "public", "function", "heading", "(", ")", "{", "$", "heading", "=", "$", "this", "->", "render", "(", "(", "string", ")", "$", "this", "->", "heading", ")", ";", "if", "(", "!", "$", "heading", ")", "{", "$", "heading", "=", "$", "this", "->", ...
Retrieve the attachment's heading template. @return Translation|string|null
[ "Retrieve", "the", "attachment", "s", "heading", "template", "." ]
82963e414483e7a0fc75e30894db0bba376dbd2d
https://github.com/locomotivemtl/charcoal-attachment/blob/82963e414483e7a0fc75e30894db0bba376dbd2d/src/Charcoal/Attachment/Object/Attachment.php#L373-L385
train
locomotivemtl/charcoal-attachment
src/Charcoal/Attachment/Object/Attachment.php
Attachment.setDescription
public function setDescription($description) { $this->description = $this->translator()->translation($description); if ($this->isPresentable()) { foreach ($this->description->data() as $lang => $trans) { $this->description[$lang] = $this->resolveUrls($trans); } } return $this; }
php
public function setDescription($description) { $this->description = $this->translator()->translation($description); if ($this->isPresentable()) { foreach ($this->description->data() as $lang => $trans) { $this->description[$lang] = $this->resolveUrls($trans); } } return $this; }
[ "public", "function", "setDescription", "(", "$", "description", ")", "{", "$", "this", "->", "description", "=", "$", "this", "->", "translator", "(", ")", "->", "translation", "(", "$", "description", ")", ";", "if", "(", "$", "this", "->", "isPresenta...
Set the attachment's description. @param string $description The description of the object. @return self
[ "Set", "the", "attachment", "s", "description", "." ]
82963e414483e7a0fc75e30894db0bba376dbd2d
https://github.com/locomotivemtl/charcoal-attachment/blob/82963e414483e7a0fc75e30894db0bba376dbd2d/src/Charcoal/Attachment/Object/Attachment.php#L585-L596
train
locomotivemtl/charcoal-attachment
src/Charcoal/Attachment/Object/Attachment.php
Attachment.setFileSize
public function setFileSize($size) { if ($size === null) { $this->fileSize = null; return $this; } if (!is_numeric($size)) { throw new InvalidArgumentException('File size must be an integer or a float.'); } $this->fileSize = $size; return $this; }
php
public function setFileSize($size) { if ($size === null) { $this->fileSize = null; return $this; } if (!is_numeric($size)) { throw new InvalidArgumentException('File size must be an integer or a float.'); } $this->fileSize = $size; return $this; }
[ "public", "function", "setFileSize", "(", "$", "size", ")", "{", "if", "(", "$", "size", "===", "null", ")", "{", "$", "this", "->", "fileSize", "=", "null", ";", "return", "$", "this", ";", "}", "if", "(", "!", "is_numeric", "(", "$", "size", ")...
Set the size of the attached file. @param integer|float $size A file size in bytes; the one of the attached. @throws InvalidArgumentException If provided argument is not of type 'integer' or 'float'. @return self
[ "Set", "the", "size", "of", "the", "attached", "file", "." ]
82963e414483e7a0fc75e30894db0bba376dbd2d
https://github.com/locomotivemtl/charcoal-attachment/blob/82963e414483e7a0fc75e30894db0bba376dbd2d/src/Charcoal/Attachment/Object/Attachment.php#L683-L698
train
locomotivemtl/charcoal-attachment
src/Charcoal/Attachment/Object/Attachment.php
Attachment.preDelete
public function preDelete() { $attId = $this->id(); $joinProto = $this->modelFactory()->get(Join::class); $loader = $this->collectionLoader(); $loader->setModel($joinProto); $collection = $loader->addFilter('attachment_id', $attId)->load(); foreach ($collection as $obj) { $obj->delete(); } return parent::preDelete(); }
php
public function preDelete() { $attId = $this->id(); $joinProto = $this->modelFactory()->get(Join::class); $loader = $this->collectionLoader(); $loader->setModel($joinProto); $collection = $loader->addFilter('attachment_id', $attId)->load(); foreach ($collection as $obj) { $obj->delete(); } return parent::preDelete(); }
[ "public", "function", "preDelete", "(", ")", "{", "$", "attId", "=", "$", "this", "->", "id", "(", ")", ";", "$", "joinProto", "=", "$", "this", "->", "modelFactory", "(", ")", "->", "get", "(", "Join", "::", "class", ")", ";", "$", "loader", "="...
Event called before _deleting_ the attachment. @see Charcoal\Source\StorableTrait::preDelete() For the "create" Event. @see Charcoal\Attachment\Traits\AttachmentAwareTrait::removeJoins @return boolean
[ "Event", "called", "before", "_deleting_", "the", "attachment", "." ]
82963e414483e7a0fc75e30894db0bba376dbd2d
https://github.com/locomotivemtl/charcoal-attachment/blob/82963e414483e7a0fc75e30894db0bba376dbd2d/src/Charcoal/Attachment/Object/Attachment.php#L924-L938
train
mirko-pagliai/me-cms
src/Controller/Component/LoginRecorderComponent.php
LoginRecorderComponent.getFileArray
public function getFileArray() { if (!$this->FileArray) { $user = $this->getConfig('user'); is_true_or_fail(is_positive($user), __d('me_cms', 'You have to set a valid user id'), InvalidArgumentException::class); $this->FileArray = new FileArray(LOGIN_RECORDS . 'user_' . $user . '.log'); } return $this->FileArray; }
php
public function getFileArray() { if (!$this->FileArray) { $user = $this->getConfig('user'); is_true_or_fail(is_positive($user), __d('me_cms', 'You have to set a valid user id'), InvalidArgumentException::class); $this->FileArray = new FileArray(LOGIN_RECORDS . 'user_' . $user . '.log'); } return $this->FileArray; }
[ "public", "function", "getFileArray", "(", ")", "{", "if", "(", "!", "$", "this", "->", "FileArray", ")", "{", "$", "user", "=", "$", "this", "->", "getConfig", "(", "'user'", ")", ";", "is_true_or_fail", "(", "is_positive", "(", "$", "user", ")", ",...
Gets the `FileArray` instance @return \Tools\FileArray @throws InvalidArgumentException @uses $FileArray
[ "Gets", "the", "FileArray", "instance" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Controller/Component/LoginRecorderComponent.php#L58-L67
train
mirko-pagliai/me-cms
src/Utility/Checkups/PHP.php
PHP.extensions
public function extensions() { foreach ($this->extensionsToCheck as $extension) { $extensions[$extension] = extension_loaded($extension); } return $extensions; }
php
public function extensions() { foreach ($this->extensionsToCheck as $extension) { $extensions[$extension] = extension_loaded($extension); } return $extensions; }
[ "public", "function", "extensions", "(", ")", "{", "foreach", "(", "$", "this", "->", "extensionsToCheck", "as", "$", "extension", ")", "{", "$", "extensions", "[", "$", "extension", "]", "=", "extension_loaded", "(", "$", "extension", ")", ";", "}", "re...
Checks if some extensions are loaded @return array Array with extension name as key and boolean as value @uses $extensionsToCheck
[ "Checks", "if", "some", "extensions", "are", "loaded" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Utility/Checkups/PHP.php#L34-L41
train
drdplusinfo/tables
DrdPlus/Tables/Theurgist/Spells/SpellParameters/Difficulty.php
Difficulty.getCurrentRealmsIncrement
public function getCurrentRealmsIncrement(): int { $currentDifficulty = $this->getValue(); $maximalDifficulty = $this->getMaximal(); if ($currentDifficulty <= $maximalDifficulty) { return 0; } $additionalDifficulty = $currentDifficulty - $maximalDifficulty; $steps = $additionalDifficulty / $this->getDifficultyAddition()->getDifficultyAdditionPerStep(); $realmsIncrement = $steps * $this->getDifficultyAddition()->getRealmsChangePerAdditionStep(); return (int)\ceil($realmsIncrement); // even a tiny piece of a higher realm means the lower realm is not able to create that formula }
php
public function getCurrentRealmsIncrement(): int { $currentDifficulty = $this->getValue(); $maximalDifficulty = $this->getMaximal(); if ($currentDifficulty <= $maximalDifficulty) { return 0; } $additionalDifficulty = $currentDifficulty - $maximalDifficulty; $steps = $additionalDifficulty / $this->getDifficultyAddition()->getDifficultyAdditionPerStep(); $realmsIncrement = $steps * $this->getDifficultyAddition()->getRealmsChangePerAdditionStep(); return (int)\ceil($realmsIncrement); // even a tiny piece of a higher realm means the lower realm is not able to create that formula }
[ "public", "function", "getCurrentRealmsIncrement", "(", ")", ":", "int", "{", "$", "currentDifficulty", "=", "$", "this", "->", "getValue", "(", ")", ";", "$", "maximalDifficulty", "=", "$", "this", "->", "getMaximal", "(", ")", ";", "if", "(", "$", "cur...
How much have to be realms increased to manage total difficulty @return int
[ "How", "much", "have", "to", "be", "realms", "increased", "to", "manage", "total", "difficulty" ]
7a577ddbd1748369eec4e84effcc92ffcb54d1f3
https://github.com/drdplusinfo/tables/blob/7a577ddbd1748369eec4e84effcc92ffcb54d1f3/DrdPlus/Tables/Theurgist/Spells/SpellParameters/Difficulty.php#L113-L125
train
nails/module-console
src/Command/BaseAlias.php
BaseAlias.configure
protected function configure() { if (empty(static::COMMAND)) { throw new NailsException('static::COMMAND must be defined'); } if (empty(static::ALIAS)) { throw new NailsException('static::ALIAS must be defined'); } // -------------------------------------------------------------------------- $this->setName(static::ALIAS); $this->setDescription('Alias to <info>' . static::COMMAND . '</info>'); }
php
protected function configure() { if (empty(static::COMMAND)) { throw new NailsException('static::COMMAND must be defined'); } if (empty(static::ALIAS)) { throw new NailsException('static::ALIAS must be defined'); } // -------------------------------------------------------------------------- $this->setName(static::ALIAS); $this->setDescription('Alias to <info>' . static::COMMAND . '</info>'); }
[ "protected", "function", "configure", "(", ")", "{", "if", "(", "empty", "(", "static", "::", "COMMAND", ")", ")", "{", "throw", "new", "NailsException", "(", "'static::COMMAND must be defined'", ")", ";", "}", "if", "(", "empty", "(", "static", "::", "ALI...
Configures the app @throws NailsException @return void
[ "Configures", "the", "app" ]
bef013213c914af33172293a386e2738ceedc12d
https://github.com/nails/module-console/blob/bef013213c914af33172293a386e2738ceedc12d/src/Command/BaseAlias.php#L29-L43
train
froq/froq-http
src/response/Body.php
Body.setContentType
public function setContentType(string $contentType, string $contentCharset = null): self { $this->contentType = $contentType; if ($contentCharset !== null) { $this->setContentCharset($contentCharset); } return $this; }
php
public function setContentType(string $contentType, string $contentCharset = null): self { $this->contentType = $contentType; if ($contentCharset !== null) { $this->setContentCharset($contentCharset); } return $this; }
[ "public", "function", "setContentType", "(", "string", "$", "contentType", ",", "string", "$", "contentCharset", "=", "null", ")", ":", "self", "{", "$", "this", "->", "contentType", "=", "$", "contentType", ";", "if", "(", "$", "contentCharset", "!==", "n...
Set content type. @param string $contentType @param string|null $contentCharset @return self
[ "Set", "content", "type", "." ]
067207669b5054b867b7df2b5557acf1d43f572a
https://github.com/froq/froq-http/blob/067207669b5054b867b7df2b5557acf1d43f572a/src/response/Body.php#L160-L169
train
froq/froq-http
src/response/Body.php
Body.isImage
public function isImage(): bool { return is_resource($this->content) && in_array($this->contentType, [ self::CONTENT_TYPE_IMAGE_JPEG, self::CONTENT_TYPE_IMAGE_PNG, self::CONTENT_TYPE_IMAGE_GIF, ]); }
php
public function isImage(): bool { return is_resource($this->content) && in_array($this->contentType, [ self::CONTENT_TYPE_IMAGE_JPEG, self::CONTENT_TYPE_IMAGE_PNG, self::CONTENT_TYPE_IMAGE_GIF, ]); }
[ "public", "function", "isImage", "(", ")", ":", "bool", "{", "return", "is_resource", "(", "$", "this", "->", "content", ")", "&&", "in_array", "(", "$", "this", "->", "contentType", ",", "[", "self", "::", "CONTENT_TYPE_IMAGE_JPEG", ",", "self", "::", "...
Is image. @return bool @since 3.9
[ "Is", "image", "." ]
067207669b5054b867b7df2b5557acf1d43f572a
https://github.com/froq/froq-http/blob/067207669b5054b867b7df2b5557acf1d43f572a/src/response/Body.php#L230-L235
train
merk/Dough
lib/Dough/Exchanger/ArrayExchanger.php
ArrayExchanger.getRate
public function getRate($fromCurrency, $toCurrency) { if ($fromCurrency === $toCurrency) { return 1; } $currencyString = "{$fromCurrency}-{$toCurrency}"; if (!isset($this->rates[$currencyString])) { throw new NoExchangeRateException(sprintf( 'Cannot convert %s to %s, no exchange rate found.', $fromCurrency, $toCurrency )); } return $this->rates[$currencyString]; }
php
public function getRate($fromCurrency, $toCurrency) { if ($fromCurrency === $toCurrency) { return 1; } $currencyString = "{$fromCurrency}-{$toCurrency}"; if (!isset($this->rates[$currencyString])) { throw new NoExchangeRateException(sprintf( 'Cannot convert %s to %s, no exchange rate found.', $fromCurrency, $toCurrency )); } return $this->rates[$currencyString]; }
[ "public", "function", "getRate", "(", "$", "fromCurrency", ",", "$", "toCurrency", ")", "{", "if", "(", "$", "fromCurrency", "===", "$", "toCurrency", ")", "{", "return", "1", ";", "}", "$", "currencyString", "=", "\"{$fromCurrency}-{$toCurrency}\"", ";", "i...
Returns the conversion rate between two currencies. @param string $fromCurrency @param string $toCurrency @return float @throws \Dough\Exception\NoExchangeRateException when the exchanger doesnt have a rate for the specified currencies.
[ "Returns", "the", "conversion", "rate", "between", "two", "currencies", "." ]
af36775564fbaf46a8018acc4f1fd993530c1a96
https://github.com/merk/Dough/blob/af36775564fbaf46a8018acc4f1fd993530c1a96/lib/Dough/Exchanger/ArrayExchanger.php#L54-L70
train
mirko-pagliai/me-cms
src/Controller/PagesCategoriesController.php
PagesCategoriesController.view
public function view($slug = null) { //The category can be passed as query string, from a widget if ($this->request->getQuery('q')) { return $this->redirect([$this->request->getQuery('q')]); } $category = $this->PagesCategories->findActiveBySlug($slug) ->select(['id', 'title']) ->contain($this->PagesCategories->Pages->getAlias(), function (Query $q) { return $q->find('active')->select(['category_id', 'slug', 'title']); }) ->cache(sprintf('category_%s', md5($slug)), $this->PagesCategories->getCacheName()) ->firstOrFail(); $this->set(compact('category')); }
php
public function view($slug = null) { //The category can be passed as query string, from a widget if ($this->request->getQuery('q')) { return $this->redirect([$this->request->getQuery('q')]); } $category = $this->PagesCategories->findActiveBySlug($slug) ->select(['id', 'title']) ->contain($this->PagesCategories->Pages->getAlias(), function (Query $q) { return $q->find('active')->select(['category_id', 'slug', 'title']); }) ->cache(sprintf('category_%s', md5($slug)), $this->PagesCategories->getCacheName()) ->firstOrFail(); $this->set(compact('category')); }
[ "public", "function", "view", "(", "$", "slug", "=", "null", ")", "{", "//The category can be passed as query string, from a widget", "if", "(", "$", "this", "->", "request", "->", "getQuery", "(", "'q'", ")", ")", "{", "return", "$", "this", "->", "redirect",...
Lists pages for a category @param string $slug Category slug @return \Cake\Network\Response|null|void
[ "Lists", "pages", "for", "a", "category" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Controller/PagesCategoriesController.php#L43-L59
train
locomotivemtl/charcoal-attachment
src/Charcoal/Attachment/Object/Join.php
Join.getObject
public function getObject() { if ($this->sourceObject === null && $this->isSourceObjectResolved === false) { $this->isSourceObjectResolved = true; try { $model = $this->modelFactory()->create($this->objectType())->load($this->objectId()); if ($model->id()) { $this->sourceObject = $model; } } catch (Exception $e) { throw new LogicException(sprintf( 'Could not load the source object of the relationship: %s', $e->getMessage() ), 0, $e); } } return $this->sourceObject; }
php
public function getObject() { if ($this->sourceObject === null && $this->isSourceObjectResolved === false) { $this->isSourceObjectResolved = true; try { $model = $this->modelFactory()->create($this->objectType())->load($this->objectId()); if ($model->id()) { $this->sourceObject = $model; } } catch (Exception $e) { throw new LogicException(sprintf( 'Could not load the source object of the relationship: %s', $e->getMessage() ), 0, $e); } } return $this->sourceObject; }
[ "public", "function", "getObject", "(", ")", "{", "if", "(", "$", "this", "->", "sourceObject", "===", "null", "&&", "$", "this", "->", "isSourceObjectResolved", "===", "false", ")", "{", "$", "this", "->", "isSourceObjectResolved", "=", "true", ";", "try"...
Retrieve the source object of the relationship. @throws LogicException If the relationship is broken or incomplete. @return ModelInterface|null
[ "Retrieve", "the", "source", "object", "of", "the", "relationship", "." ]
82963e414483e7a0fc75e30894db0bba376dbd2d
https://github.com/locomotivemtl/charcoal-attachment/blob/82963e414483e7a0fc75e30894db0bba376dbd2d/src/Charcoal/Attachment/Object/Join.php#L152-L171
train
locomotivemtl/charcoal-attachment
src/Charcoal/Attachment/Object/Join.php
Join.getAttachment
public function getAttachment() { if ($this->relatedObject === null && $this->isRelatedObjectResolved === false) { $this->isRelatedObjectResolved = true; try { $model = $this->modelFactory()->create(Attachment::class)->load($this->attachmentId()); if ($model->id()) { $this->relatedObject = $model; $type = $model->type(); if ($type !== $model->objType()) { $this->relatedObject = $this->modelFactory()->create($type)->setData($model->data()); } } } catch (Exception $e) { throw new LogicException(sprintf( 'Could not load the related object of the relationship: %s', $e->getMessage() ), 0, $e); } } return $this->relatedObject; }
php
public function getAttachment() { if ($this->relatedObject === null && $this->isRelatedObjectResolved === false) { $this->isRelatedObjectResolved = true; try { $model = $this->modelFactory()->create(Attachment::class)->load($this->attachmentId()); if ($model->id()) { $this->relatedObject = $model; $type = $model->type(); if ($type !== $model->objType()) { $this->relatedObject = $this->modelFactory()->create($type)->setData($model->data()); } } } catch (Exception $e) { throw new LogicException(sprintf( 'Could not load the related object of the relationship: %s', $e->getMessage() ), 0, $e); } } return $this->relatedObject; }
[ "public", "function", "getAttachment", "(", ")", "{", "if", "(", "$", "this", "->", "relatedObject", "===", "null", "&&", "$", "this", "->", "isRelatedObjectResolved", "===", "false", ")", "{", "$", "this", "->", "isRelatedObjectResolved", "=", "true", ";", ...
Retrieve the related object of the relationship. @throws LogicException If the relationship is broken or incomplete. @return ModelInterface|null
[ "Retrieve", "the", "related", "object", "of", "the", "relationship", "." ]
82963e414483e7a0fc75e30894db0bba376dbd2d
https://github.com/locomotivemtl/charcoal-attachment/blob/82963e414483e7a0fc75e30894db0bba376dbd2d/src/Charcoal/Attachment/Object/Join.php#L179-L203
train
locomotivemtl/charcoal-attachment
src/Charcoal/Attachment/Object/Join.php
Join.getParent
public function getParent() { if ($this->parentRelation === null && $this->isParentRelationResolved === false) { $this->isParentRelationResolved = true; try { $source = $this->getObject(); if ($source instanceof AttachmentContainerInterface) { $model = $this->modelFactory()->create(self::class)->loadFrom('attachment_id', $source->id()); if ($model->id()) { $this->parentRelation = $model; } } } catch (Exception $e) { throw new LogicException(sprintf( 'Could not load the parent relationship: %s', $e->getMessage() ), 0, $e); } } return $this->parentRelation; }
php
public function getParent() { if ($this->parentRelation === null && $this->isParentRelationResolved === false) { $this->isParentRelationResolved = true; try { $source = $this->getObject(); if ($source instanceof AttachmentContainerInterface) { $model = $this->modelFactory()->create(self::class)->loadFrom('attachment_id', $source->id()); if ($model->id()) { $this->parentRelation = $model; } } } catch (Exception $e) { throw new LogicException(sprintf( 'Could not load the parent relationship: %s', $e->getMessage() ), 0, $e); } } return $this->parentRelation; }
[ "public", "function", "getParent", "(", ")", "{", "if", "(", "$", "this", "->", "parentRelation", "===", "null", "&&", "$", "this", "->", "isParentRelationResolved", "===", "false", ")", "{", "$", "this", "->", "isParentRelationResolved", "=", "true", ";", ...
Retrieve the parent relationship, if any. @todo Add support for multiple parents. @throws LogicException If the relationship is broken or incomplete. @return JoinInterface|null
[ "Retrieve", "the", "parent", "relationship", "if", "any", "." ]
82963e414483e7a0fc75e30894db0bba376dbd2d
https://github.com/locomotivemtl/charcoal-attachment/blob/82963e414483e7a0fc75e30894db0bba376dbd2d/src/Charcoal/Attachment/Object/Join.php#L212-L234
train
locomotivemtl/charcoal-attachment
src/Charcoal/Attachment/Object/Join.php
Join.setPosition
public function setPosition($position) { if ($position === null) { $this->position = null; return $this; } if (!is_numeric($position)) { throw new InvalidArgumentException( 'Position must be an integer.' ); } $this->position = (int)$position; return $this; }
php
public function setPosition($position) { if ($position === null) { $this->position = null; return $this; } if (!is_numeric($position)) { throw new InvalidArgumentException( 'Position must be an integer.' ); } $this->position = (int)$position; return $this; }
[ "public", "function", "setPosition", "(", "$", "position", ")", "{", "if", "(", "$", "position", "===", "null", ")", "{", "$", "this", "->", "position", "=", "null", ";", "return", "$", "this", ";", "}", "if", "(", "!", "is_numeric", "(", "$", "pos...
Set the relationship's position. Define the relation's sorting position amongst other attachments related to the source object and grouping. @param integer $position A position. @throws InvalidArgumentException If the position is not an integer (or numeric integer string). @return self
[ "Set", "the", "relationship", "s", "position", "." ]
82963e414483e7a0fc75e30894db0bba376dbd2d
https://github.com/locomotivemtl/charcoal-attachment/blob/82963e414483e7a0fc75e30894db0bba376dbd2d/src/Charcoal/Attachment/Object/Join.php#L392-L408
train
yawik/settings
src/Form/View/Helper/FormDisableElementsCapableFormSettings.php
FormDisableElementsCapableFormSettings.render
public function render(ElementInterface $element) { /* @var $element DisableElementsCapableFormSettings * @var $renderer \Zend\View\Renderer\PhpRenderer * @var $headscript \Zend\View\Helper\HeadScript * @var $basepath \Zend\View\Helper\BasePath */ $renderer = $this->getView(); $headscript = $renderer->plugin('headscript'); $basepath = $renderer->plugin('basepath'); $headscript->appendFile($basepath('modules/Settings/js/forms.decfs.js')); return '<ul class="disable-elements-list" id="' . $element->getAttribute('id') . '-list"' . '>' . $this->renderCheckboxes($element->getCheckboxes()) . '</ul>'; }
php
public function render(ElementInterface $element) { /* @var $element DisableElementsCapableFormSettings * @var $renderer \Zend\View\Renderer\PhpRenderer * @var $headscript \Zend\View\Helper\HeadScript * @var $basepath \Zend\View\Helper\BasePath */ $renderer = $this->getView(); $headscript = $renderer->plugin('headscript'); $basepath = $renderer->plugin('basepath'); $headscript->appendFile($basepath('modules/Settings/js/forms.decfs.js')); return '<ul class="disable-elements-list" id="' . $element->getAttribute('id') . '-list"' . '>' . $this->renderCheckboxes($element->getCheckboxes()) . '</ul>'; }
[ "public", "function", "render", "(", "ElementInterface", "$", "element", ")", "{", "/* @var $element DisableElementsCapableFormSettings\n * @var $renderer \\Zend\\View\\Renderer\\PhpRenderer\n * @var $headscript \\Zend\\View\\Helper\\HeadScript\n * @var $basepath \\Zend...
Renders a disabe form elements toggle checkboxes element.
[ "Renders", "a", "disabe", "form", "elements", "toggle", "checkboxes", "element", "." ]
fc49d14a5eec21fcc074ce29b1428d91191efecf
https://github.com/yawik/settings/blob/fc49d14a5eec21fcc074ce29b1428d91191efecf/src/Form/View/Helper/FormDisableElementsCapableFormSettings.php#L27-L42
train
yawik/settings
src/Form/View/Helper/FormDisableElementsCapableFormSettings.php
FormDisableElementsCapableFormSettings.renderCheckboxes
protected function renderCheckboxes($checkboxes) { $markup = ''; foreach ($checkboxes as $boxes) { $markup .= '<li class="disable-element">'; if (is_array($boxes)) { if (isset($boxes['__all__'])) { $markup .= $this->renderCheckbox($boxes['__all__'], 'disable-elements-toggle'); unset($boxes['__all__']); } $markup .= '<ul class="disable-elements">' . $this->renderCheckboxes($boxes) . '</ul>'; } else { $markup .= $this->renderCheckbox($boxes); } $markup .= '</li>'; } return $markup; }
php
protected function renderCheckboxes($checkboxes) { $markup = ''; foreach ($checkboxes as $boxes) { $markup .= '<li class="disable-element">'; if (is_array($boxes)) { if (isset($boxes['__all__'])) { $markup .= $this->renderCheckbox($boxes['__all__'], 'disable-elements-toggle'); unset($boxes['__all__']); } $markup .= '<ul class="disable-elements">' . $this->renderCheckboxes($boxes) . '</ul>'; } else { $markup .= $this->renderCheckbox($boxes); } $markup .= '</li>'; } return $markup; }
[ "protected", "function", "renderCheckboxes", "(", "$", "checkboxes", ")", "{", "$", "markup", "=", "''", ";", "foreach", "(", "$", "checkboxes", "as", "$", "boxes", ")", "{", "$", "markup", ".=", "'<li class=\"disable-element\">'", ";", "if", "(", "is_array"...
Recursively renders checkboxes. @param array $checkboxes the checkboxes spec array @return string
[ "Recursively", "renders", "checkboxes", "." ]
fc49d14a5eec21fcc074ce29b1428d91191efecf
https://github.com/yawik/settings/blob/fc49d14a5eec21fcc074ce29b1428d91191efecf/src/Form/View/Helper/FormDisableElementsCapableFormSettings.php#L51-L69
train
nails/module-pdf
src/Service/Pdf.php
Pdf.instantiate
protected function instantiate() { $oOptions = new Options(); $aOptions = []; // Default options foreach (self::DEFAULT_OPTIONS as $sOption => $mValue) { $aOptions[$sOption] = $mValue; } // Custom options override default options foreach ($this->aCustomOptions as $sOption => $mValue) { $aOptions[$sOption] = $mValue; } // Set the options foreach ($aOptions as $sOption => $mValue) { $oOptions->set($sOption, $mValue); } $this->oDomPdf = new Dompdf($oOptions); $this->setPaperSize($this->sPaperSize, $this->sPaperOrientation); return $this; }
php
protected function instantiate() { $oOptions = new Options(); $aOptions = []; // Default options foreach (self::DEFAULT_OPTIONS as $sOption => $mValue) { $aOptions[$sOption] = $mValue; } // Custom options override default options foreach ($this->aCustomOptions as $sOption => $mValue) { $aOptions[$sOption] = $mValue; } // Set the options foreach ($aOptions as $sOption => $mValue) { $oOptions->set($sOption, $mValue); } $this->oDomPdf = new Dompdf($oOptions); $this->setPaperSize($this->sPaperSize, $this->sPaperOrientation); return $this; }
[ "protected", "function", "instantiate", "(", ")", "{", "$", "oOptions", "=", "new", "Options", "(", ")", ";", "$", "aOptions", "=", "[", "]", ";", "// Default options", "foreach", "(", "self", "::", "DEFAULT_OPTIONS", "as", "$", "sOption", "=>", "$", "m...
Instantiate a new instance of DomPDF @return $this
[ "Instantiate", "a", "new", "instance", "of", "DomPDF" ]
69a090d3ff7d49a381b770d03f02a3adbc6c8b6c
https://github.com/nails/module-pdf/blob/69a090d3ff7d49a381b770d03f02a3adbc6c8b6c/src/Service/Pdf.php#L98-L122
train
nails/module-pdf
src/Service/Pdf.php
Pdf.setOption
public function setOption($sOption, $mValue) { $this->aCustomOptions[$sOption] = $mValue; $this->oDomPdf->set_option($sOption, $mValue); return $this; }
php
public function setOption($sOption, $mValue) { $this->aCustomOptions[$sOption] = $mValue; $this->oDomPdf->set_option($sOption, $mValue); return $this; }
[ "public", "function", "setOption", "(", "$", "sOption", ",", "$", "mValue", ")", "{", "$", "this", "->", "aCustomOptions", "[", "$", "sOption", "]", "=", "$", "mValue", ";", "$", "this", "->", "oDomPdf", "->", "set_option", "(", "$", "sOption", ",", ...
Defines a DomPDF constant, if not already defined @param string $sOption The name of the option @param string $mValue The value to give the option @return $this;
[ "Defines", "a", "DomPDF", "constant", "if", "not", "already", "defined" ]
69a090d3ff7d49a381b770d03f02a3adbc6c8b6c
https://github.com/nails/module-pdf/blob/69a090d3ff7d49a381b770d03f02a3adbc6c8b6c/src/Service/Pdf.php#L147-L152
train
nails/module-pdf
src/Service/Pdf.php
Pdf.setPaperSize
public function setPaperSize($sSize = null, $sOrientation = null) { $this->sPaperSize = $sSize ?: static::DEFAULT_PAPER_SIZE; $this->sPaperOrientation = $sOrientation ?: static::DEFAULT_PAPER_ORIENTATION; $this->oDomPdf->setPaper($this->sPaperSize, $this->sPaperOrientation); return $this; }
php
public function setPaperSize($sSize = null, $sOrientation = null) { $this->sPaperSize = $sSize ?: static::DEFAULT_PAPER_SIZE; $this->sPaperOrientation = $sOrientation ?: static::DEFAULT_PAPER_ORIENTATION; $this->oDomPdf->setPaper($this->sPaperSize, $this->sPaperOrientation); return $this; }
[ "public", "function", "setPaperSize", "(", "$", "sSize", "=", "null", ",", "$", "sOrientation", "=", "null", ")", "{", "$", "this", "->", "sPaperSize", "=", "$", "sSize", "?", ":", "static", "::", "DEFAULT_PAPER_SIZE", ";", "$", "this", "->", "sPaperOrie...
Alias for setting the paper size @param string $sSize The paper size to use @param string $sOrientation The paper orientation @return $this
[ "Alias", "for", "setting", "the", "paper", "size" ]
69a090d3ff7d49a381b770d03f02a3adbc6c8b6c
https://github.com/nails/module-pdf/blob/69a090d3ff7d49a381b770d03f02a3adbc6c8b6c/src/Service/Pdf.php#L180-L186
train
nails/module-pdf
src/Service/Pdf.php
Pdf.loadView
public function loadView($mViews, $aData = []) { $sHtml = ''; $aViews = array_filter((array) $mViews); $oView = Factory::service('View'); foreach ($aViews as $sView) { $sHtml .= $oView->load($sView, $aData, true); } $this->oDomPdf->loadHtml($sHtml); }
php
public function loadView($mViews, $aData = []) { $sHtml = ''; $aViews = array_filter((array) $mViews); $oView = Factory::service('View'); foreach ($aViews as $sView) { $sHtml .= $oView->load($sView, $aData, true); } $this->oDomPdf->loadHtml($sHtml); }
[ "public", "function", "loadView", "(", "$", "mViews", ",", "$", "aData", "=", "[", "]", ")", "{", "$", "sHtml", "=", "''", ";", "$", "aViews", "=", "array_filter", "(", "(", "array", ")", "$", "mViews", ")", ";", "$", "oView", "=", "Factory", "::...
Loads CI views and passes it as HTML to DomPDF @param mixed $mViews An array of views, or a single view as a string @param array $aData View variables to pass to the view @return void
[ "Loads", "CI", "views", "and", "passes", "it", "as", "HTML", "to", "DomPDF" ]
69a090d3ff7d49a381b770d03f02a3adbc6c8b6c
https://github.com/nails/module-pdf/blob/69a090d3ff7d49a381b770d03f02a3adbc6c8b6c/src/Service/Pdf.php#L213-L224
train
nails/module-pdf
src/Service/Pdf.php
Pdf.download
public function download($sFilename = '', $aOptions = []) { $sFilename = $sFilename ? $sFilename : self::DEFAULT_FILE_NAME; // Set the content attachment, by default send to the browser $aOptions['Attachment'] = 1; $this->oDomPdf->render(); $this->oDomPdf->stream($sFilename, $aOptions); exit(); }
php
public function download($sFilename = '', $aOptions = []) { $sFilename = $sFilename ? $sFilename : self::DEFAULT_FILE_NAME; // Set the content attachment, by default send to the browser $aOptions['Attachment'] = 1; $this->oDomPdf->render(); $this->oDomPdf->stream($sFilename, $aOptions); exit(); }
[ "public", "function", "download", "(", "$", "sFilename", "=", "''", ",", "$", "aOptions", "=", "[", "]", ")", "{", "$", "sFilename", "=", "$", "sFilename", "?", "$", "sFilename", ":", "self", "::", "DEFAULT_FILE_NAME", ";", "// Set the content attachment, b...
Renders the PDF and sends it to the browser as a download. @param string $sFilename The filename to give the PDF @param array $aOptions An array of options to pass to DomPDF's stream() method @return void|bool
[ "Renders", "the", "PDF", "and", "sends", "it", "to", "the", "browser", "as", "a", "download", "." ]
69a090d3ff7d49a381b770d03f02a3adbc6c8b6c
https://github.com/nails/module-pdf/blob/69a090d3ff7d49a381b770d03f02a3adbc6c8b6c/src/Service/Pdf.php#L236-L246
train
nails/module-pdf
src/Service/Pdf.php
Pdf.save
public function save($sPath, $sFilename) { if (!is_writable($sPath)) { $this->setError('Cannot write to ' . $sPath); return false; } $this->oDomPdf->render(); $bResult = (bool) file_put_contents( rtrim($sPath, '/') . '/' . $sFilename, $this->oDomPdf->output() ); $this->reset(); return $bResult; }
php
public function save($sPath, $sFilename) { if (!is_writable($sPath)) { $this->setError('Cannot write to ' . $sPath); return false; } $this->oDomPdf->render(); $bResult = (bool) file_put_contents( rtrim($sPath, '/') . '/' . $sFilename, $this->oDomPdf->output() ); $this->reset(); return $bResult; }
[ "public", "function", "save", "(", "$", "sPath", ",", "$", "sFilename", ")", "{", "if", "(", "!", "is_writable", "(", "$", "sPath", ")", ")", "{", "$", "this", "->", "setError", "(", "'Cannot write to '", ".", "$", "sPath", ")", ";", "return", "false...
Saves a PDF to disk @param string $sPath The path to save to @param string $sFilename The filename to give the PDF @return boolean
[ "Saves", "a", "PDF", "to", "disk" ]
69a090d3ff7d49a381b770d03f02a3adbc6c8b6c
https://github.com/nails/module-pdf/blob/69a090d3ff7d49a381b770d03f02a3adbc6c8b6c/src/Service/Pdf.php#L280-L296
train
nails/module-pdf
src/Service/Pdf.php
Pdf.saveToCdn
public function saveToCdn($sFilename, $sBucket = null) { if (Components::exists('nails/module-cdn')) { // Save temporary file $sCacheDir = CACHE_PATH; $sCacheFile = 'TEMP-PDF-' . md5(uniqid() . microtime(true)) . '.pdf'; if ($this->save($sCacheDir, $sCacheFile)) { $oCdn = Factory::service('Cdn', 'nails/module-cdn'); $oResult = $oCdn->objectCreate( $sCacheDir . $sCacheFile, $sBucket, ['filename_display' => $sFilename] ); if ($oResult) { @unlink($sCacheDir . $sCacheFile); $this->reset(); return $oResult; } else { $this->setError($oCdn->lastError()); return false; } } else { return false; } } else { $this->setError('CDN module is not available'); return false; } }
php
public function saveToCdn($sFilename, $sBucket = null) { if (Components::exists('nails/module-cdn')) { // Save temporary file $sCacheDir = CACHE_PATH; $sCacheFile = 'TEMP-PDF-' . md5(uniqid() . microtime(true)) . '.pdf'; if ($this->save($sCacheDir, $sCacheFile)) { $oCdn = Factory::service('Cdn', 'nails/module-cdn'); $oResult = $oCdn->objectCreate( $sCacheDir . $sCacheFile, $sBucket, ['filename_display' => $sFilename] ); if ($oResult) { @unlink($sCacheDir . $sCacheFile); $this->reset(); return $oResult; } else { $this->setError($oCdn->lastError()); return false; } } else { return false; } } else { $this->setError('CDN module is not available'); return false; } }
[ "public", "function", "saveToCdn", "(", "$", "sFilename", ",", "$", "sBucket", "=", "null", ")", "{", "if", "(", "Components", "::", "exists", "(", "'nails/module-cdn'", ")", ")", "{", "// Save temporary file", "$", "sCacheDir", "=", "CACHE_PATH", ";", "$",...
Saves the PDF to the CDN @param string $sFilename The filename to give the object @param string $sBucket The name of the bucket to upload to @return mixed stdClass on success, false on failure
[ "Saves", "the", "PDF", "to", "the", "CDN" ]
69a090d3ff7d49a381b770d03f02a3adbc6c8b6c
https://github.com/nails/module-pdf/blob/69a090d3ff7d49a381b770d03f02a3adbc6c8b6c/src/Service/Pdf.php#L308-L343
train
PitonCMS/Engine
app/Models/PageMapper.php
PageMapper.findPageById
public function findPageById($pageId) { $this->makeCollectionPageSelect(true); $this->sql .= ' and p.id = ?'; $this->bindValues[] = $pageId; return $this->findRow(); }
php
public function findPageById($pageId) { $this->makeCollectionPageSelect(true); $this->sql .= ' and p.id = ?'; $this->bindValues[] = $pageId; return $this->findRow(); }
[ "public", "function", "findPageById", "(", "$", "pageId", ")", "{", "$", "this", "->", "makeCollectionPageSelect", "(", "true", ")", ";", "$", "this", "->", "sql", ".=", "' and p.id = ?'", ";", "$", "this", "->", "bindValues", "[", "]", "=", "$", "pageId...
Find Page by ID Includes outer join to collection record @param int $pageId Page ID @return mixed Page Object | null
[ "Find", "Page", "by", "ID" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Models/PageMapper.php#L40-L47
train
PitonCMS/Engine
app/Models/PageMapper.php
PageMapper.findPublishedPageBySlug
public function findPublishedPageBySlug($pageSlug) { $this->makeSelect(); if (is_string($pageSlug)) { $this->sql .= ' and collection_id is null and slug = ?'; $this->bindValues[] = $pageSlug; } else { throw new Exception('Unknown page identifier type'); } $this->sql .= " and published_date <= '{$this->today()}'"; return $this->findRow(); }
php
public function findPublishedPageBySlug($pageSlug) { $this->makeSelect(); if (is_string($pageSlug)) { $this->sql .= ' and collection_id is null and slug = ?'; $this->bindValues[] = $pageSlug; } else { throw new Exception('Unknown page identifier type'); } $this->sql .= " and published_date <= '{$this->today()}'"; return $this->findRow(); }
[ "public", "function", "findPublishedPageBySlug", "(", "$", "pageSlug", ")", "{", "$", "this", "->", "makeSelect", "(", ")", ";", "if", "(", "is_string", "(", "$", "pageSlug", ")", ")", "{", "$", "this", "->", "sql", ".=", "' and collection_id is null and slu...
Find Published Page By Slug Finds published page by by slug Does not include collections @param mixed $pageSlug Page slug @return mixed Page object or null if not found
[ "Find", "Published", "Page", "By", "Slug" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Models/PageMapper.php#L57-L71
train
PitonCMS/Engine
app/Models/PageMapper.php
PageMapper.findPages
public function findPages($unpublished = false) { $this->makeSelect(); $this->sql .= " and collection_id is null"; if (!$unpublished) { $this->sql .= " and published_date <= '{$this->today()}'"; } return $this->find(); }
php
public function findPages($unpublished = false) { $this->makeSelect(); $this->sql .= " and collection_id is null"; if (!$unpublished) { $this->sql .= " and published_date <= '{$this->today()}'"; } return $this->find(); }
[ "public", "function", "findPages", "(", "$", "unpublished", "=", "false", ")", "{", "$", "this", "->", "makeSelect", "(", ")", ";", "$", "this", "->", "sql", ".=", "\" and collection_id is null\"", ";", "if", "(", "!", "$", "unpublished", ")", "{", "$", ...
Find All Pages Finds all pages, does not include element data Does not include collections @param bool $unpublished Filter on published pages @return mixed Array | null
[ "Find", "All", "Pages" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Models/PageMapper.php#L81-L91
train
PitonCMS/Engine
app/Models/PageMapper.php
PageMapper.findCollectionPagesById
public function findCollectionPagesById($collectionId, $published = true) { $this->makeCollectionPageSelect(); $this->sql .= ' and c.id = ?'; $this->bindValues[] = $collectionId; if ($published) { $this->sql .= " and p.published_date <= '{$this->today()}'"; } return $this->find(); }
php
public function findCollectionPagesById($collectionId, $published = true) { $this->makeCollectionPageSelect(); $this->sql .= ' and c.id = ?'; $this->bindValues[] = $collectionId; if ($published) { $this->sql .= " and p.published_date <= '{$this->today()}'"; } return $this->find(); }
[ "public", "function", "findCollectionPagesById", "(", "$", "collectionId", ",", "$", "published", "=", "true", ")", "{", "$", "this", "->", "makeCollectionPageSelect", "(", ")", ";", "$", "this", "->", "sql", ".=", "' and c.id = ?'", ";", "$", "this", "->", ...
Find Collection Pages by ID Finds all collection pages @param int $collectionId @param bool $published Filter on published collection pages @return mixed Array | null
[ "Find", "Collection", "Pages", "by", "ID" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Models/PageMapper.php#L113-L124
train
PitonCMS/Engine
app/Models/PageMapper.php
PageMapper.findPublishedCollectionPageBySlug
public function findPublishedCollectionPageBySlug($collectionSlug, $pageSlug) { $this->makeCollectionPageSelect(); $this->sql .= " and p.published_date <= '{$this->today()}'"; $this->sql .= ' and c.slug = ? and p.slug = ?'; $this->bindValues[] = $collectionSlug; $this->bindValues[] = $pageSlug; return $this->findRow(); }
php
public function findPublishedCollectionPageBySlug($collectionSlug, $pageSlug) { $this->makeCollectionPageSelect(); $this->sql .= " and p.published_date <= '{$this->today()}'"; $this->sql .= ' and c.slug = ? and p.slug = ?'; $this->bindValues[] = $collectionSlug; $this->bindValues[] = $pageSlug; return $this->findRow(); }
[ "public", "function", "findPublishedCollectionPageBySlug", "(", "$", "collectionSlug", ",", "$", "pageSlug", ")", "{", "$", "this", "->", "makeCollectionPageSelect", "(", ")", ";", "$", "this", "->", "sql", ".=", "\" and p.published_date <= '{$this->today()}'\"", ";",...
Find Published Collection Page By Slug Finds collection page by collection slug and page slug @param bool $published Filter on published collection pages @return mixed Array | null
[ "Find", "Published", "Collection", "Page", "By", "Slug" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Models/PageMapper.php#L133-L143
train
locomotivemtl/charcoal-email
src/Charcoal/Email/Email.php
Email.setData
public function setData(array $data) { foreach ($data as $prop => $val) { $func = [$this, $this->setter($prop)]; if (is_callable($func)) { call_user_func($func, $val); } else { $this->{$prop} = $val; } } return $this; }
php
public function setData(array $data) { foreach ($data as $prop => $val) { $func = [$this, $this->setter($prop)]; if (is_callable($func)) { call_user_func($func, $val); } else { $this->{$prop} = $val; } } return $this; }
[ "public", "function", "setData", "(", "array", "$", "data", ")", "{", "foreach", "(", "$", "data", "as", "$", "prop", "=>", "$", "val", ")", "{", "$", "func", "=", "[", "$", "this", ",", "$", "this", "->", "setter", "(", "$", "prop", ")", "]", ...
Set the email's data. @param array $data The data to set. @return Email Chainable
[ "Set", "the", "email", "s", "data", "." ]
99ccabcd0a91802e308177e0b6b626eaf0f940da
https://github.com/locomotivemtl/charcoal-email/blob/99ccabcd0a91802e308177e0b6b626eaf0f940da/src/Charcoal/Email/Email.php#L184-L196
train
locomotivemtl/charcoal-email
src/Charcoal/Email/Email.php
Email.campaign
public function campaign() { if ($this->campaign === null) { $this->campaign = $this->generateCampaign(); } return $this->campaign; }
php
public function campaign() { if ($this->campaign === null) { $this->campaign = $this->generateCampaign(); } return $this->campaign; }
[ "public", "function", "campaign", "(", ")", "{", "if", "(", "$", "this", "->", "campaign", "===", "null", ")", "{", "$", "this", "->", "campaign", "=", "$", "this", "->", "generateCampaign", "(", ")", ";", "}", "return", "$", "this", "->", "campaign"...
Get the campaign identifier. If it has not been explicitely set, it will be auto-generated (with uniqid). @return string
[ "Get", "the", "campaign", "identifier", "." ]
99ccabcd0a91802e308177e0b6b626eaf0f940da
https://github.com/locomotivemtl/charcoal-email/blob/99ccabcd0a91802e308177e0b6b626eaf0f940da/src/Charcoal/Email/Email.php#L225-L232
train
locomotivemtl/charcoal-email
src/Charcoal/Email/Email.php
Email.from
public function from() { if ($this->from === null) { $this->setFrom($this->config()->defaultFrom()); } return $this->from; }
php
public function from() { if ($this->from === null) { $this->setFrom($this->config()->defaultFrom()); } return $this->from; }
[ "public", "function", "from", "(", ")", "{", "if", "(", "$", "this", "->", "from", "===", "null", ")", "{", "$", "this", "->", "setFrom", "(", "$", "this", "->", "config", "(", ")", "->", "defaultFrom", "(", ")", ")", ";", "}", "return", "$", "...
Get the sender's email address. @return string
[ "Get", "the", "sender", "s", "email", "address", "." ]
99ccabcd0a91802e308177e0b6b626eaf0f940da
https://github.com/locomotivemtl/charcoal-email/blob/99ccabcd0a91802e308177e0b6b626eaf0f940da/src/Charcoal/Email/Email.php#L425-L432
train
locomotivemtl/charcoal-email
src/Charcoal/Email/Email.php
Email.replyTo
public function replyTo() { if ($this->replyTo === null) { $this->replyTo = $this->config()->defaultReplyTo(); } return $this->replyTo; }
php
public function replyTo() { if ($this->replyTo === null) { $this->replyTo = $this->config()->defaultReplyTo(); } return $this->replyTo; }
[ "public", "function", "replyTo", "(", ")", "{", "if", "(", "$", "this", "->", "replyTo", "===", "null", ")", "{", "$", "this", "->", "replyTo", "=", "$", "this", "->", "config", "(", ")", "->", "defaultReplyTo", "(", ")", ";", "}", "return", "$", ...
Get email address to reply to the message. @return string
[ "Get", "email", "address", "to", "reply", "to", "the", "message", "." ]
99ccabcd0a91802e308177e0b6b626eaf0f940da
https://github.com/locomotivemtl/charcoal-email/blob/99ccabcd0a91802e308177e0b6b626eaf0f940da/src/Charcoal/Email/Email.php#L452-L459
train
locomotivemtl/charcoal-email
src/Charcoal/Email/Email.php
Email.msgHtml
public function msgHtml() { if ($this->msgHtml === null) { $this->msgHtml = $this->generateMsgHtml(); } return $this->msgHtml; }
php
public function msgHtml() { if ($this->msgHtml === null) { $this->msgHtml = $this->generateMsgHtml(); } return $this->msgHtml; }
[ "public", "function", "msgHtml", "(", ")", "{", "if", "(", "$", "this", "->", "msgHtml", "===", "null", ")", "{", "$", "this", "->", "msgHtml", "=", "$", "this", "->", "generateMsgHtml", "(", ")", ";", "}", "return", "$", "this", "->", "msgHtml", "...
Get the email's HTML message body. If the message is not explitely set, it will be auto-generated from a template view. @return string
[ "Get", "the", "email", "s", "HTML", "message", "body", "." ]
99ccabcd0a91802e308177e0b6b626eaf0f940da
https://github.com/locomotivemtl/charcoal-email/blob/99ccabcd0a91802e308177e0b6b626eaf0f940da/src/Charcoal/Email/Email.php#L519-L525
train
locomotivemtl/charcoal-email
src/Charcoal/Email/Email.php
Email.msgTxt
public function msgTxt() { if ($this->msgTxt === null) { $this->msgTxt = $this->stripHtml($this->msgHtml()); } return $this->msgTxt; }
php
public function msgTxt() { if ($this->msgTxt === null) { $this->msgTxt = $this->stripHtml($this->msgHtml()); } return $this->msgTxt; }
[ "public", "function", "msgTxt", "(", ")", "{", "if", "(", "$", "this", "->", "msgTxt", "===", "null", ")", "{", "$", "this", "->", "msgTxt", "=", "$", "this", "->", "stripHtml", "(", "$", "this", "->", "msgHtml", "(", ")", ")", ";", "}", "return"...
Get the email's plain-text message body. If the plain-text message is not explitely set, it will be auto-generated from the HTML message. @return string
[ "Get", "the", "email", "s", "plain", "-", "text", "message", "body", "." ]
99ccabcd0a91802e308177e0b6b626eaf0f940da
https://github.com/locomotivemtl/charcoal-email/blob/99ccabcd0a91802e308177e0b6b626eaf0f940da/src/Charcoal/Email/Email.php#L555-L562
train
locomotivemtl/charcoal-email
src/Charcoal/Email/Email.php
Email.log
public function log() { if ($this->log === null) { $this->log = $this->config()->defaultLog(); } return $this->log; }
php
public function log() { if ($this->log === null) { $this->log = $this->config()->defaultLog(); } return $this->log; }
[ "public", "function", "log", "(", ")", "{", "if", "(", "$", "this", "->", "log", "===", "null", ")", "{", "$", "this", "->", "log", "=", "$", "this", "->", "config", "(", ")", "->", "defaultLog", "(", ")", ";", "}", "return", "$", "this", "->",...
Determine if logging is enabled for this particular email. @return boolean
[ "Determine", "if", "logging", "is", "enabled", "for", "this", "particular", "email", "." ]
99ccabcd0a91802e308177e0b6b626eaf0f940da
https://github.com/locomotivemtl/charcoal-email/blob/99ccabcd0a91802e308177e0b6b626eaf0f940da/src/Charcoal/Email/Email.php#L618-L624
train
locomotivemtl/charcoal-email
src/Charcoal/Email/Email.php
Email.track
public function track() { if ($this->track === null) { $this->track = $this->config()->defaultTrack(); } return $this->track; }
php
public function track() { if ($this->track === null) { $this->track = $this->config()->defaultTrack(); } return $this->track; }
[ "public", "function", "track", "(", ")", "{", "if", "(", "$", "this", "->", "track", "===", "null", ")", "{", "$", "this", "->", "track", "=", "$", "this", "->", "config", "(", ")", "->", "defaultTrack", "(", ")", ";", "}", "return", "$", "this",...
Determine if tracking is enabled for this particular email. @return boolean
[ "Determine", "if", "tracking", "is", "enabled", "for", "this", "particular", "email", "." ]
99ccabcd0a91802e308177e0b6b626eaf0f940da
https://github.com/locomotivemtl/charcoal-email/blob/99ccabcd0a91802e308177e0b6b626eaf0f940da/src/Charcoal/Email/Email.php#L643-L649
train
locomotivemtl/charcoal-email
src/Charcoal/Email/Email.php
Email.send
public function send() { $this->logger->debug( 'Attempting to send an email', $this->to() ); $mail = $this->phpMailer; try { $this->setSmtpOptions($mail); $mail->CharSet = 'UTF-8'; // Setting reply-to field, if required. $replyTo = $this->replyTo(); if ($replyTo) { $replyArr = $this->emailToArray($replyTo); $mail->addReplyTo($replyArr['email'], $replyArr['name']); } // Setting from (sender) field. $from = $this->from(); $fromArr = $this->emailToArray($from); $mail->setFrom($fromArr['email'], $fromArr['name']); // Setting to (recipients) field(s). $to = $this->to(); foreach ($to as $recipient) { $toArr = $this->emailToArray($recipient); $mail->addAddress($toArr['email'], $toArr['name']); } // Setting cc (carbon-copy) field(s). $cc = $this->cc(); foreach ($cc as $ccRecipient) { $ccArr = $this->emailToArray($ccRecipient); $mail->addCC($ccArr['email'], $ccArr['name']); } // Setting bcc (black-carbon-copy) field(s). $bcc = $this->bcc(); foreach ($bcc as $bccRecipient) { $bccArr = $this->emailToArray($bccRecipient); $mail->addBCC($bccArr['email'], $bccArr['name']); } // Setting attachment(s), if required. $attachments = $this->attachments(); foreach ($attachments as $att) { $mail->addAttachment($att); } $mail->isHTML(true); $mail->Subject = $this->subject(); $mail->Body = $this->msgHtml(); $mail->AltBody = $this->msgTxt(); $ret = $mail->send(); $this->logSend($ret, $mail); return $ret; } catch (Exception $e) { $this->logger->error( sprintf('Error sending email: %s', $e->getMessage()) ); } }
php
public function send() { $this->logger->debug( 'Attempting to send an email', $this->to() ); $mail = $this->phpMailer; try { $this->setSmtpOptions($mail); $mail->CharSet = 'UTF-8'; // Setting reply-to field, if required. $replyTo = $this->replyTo(); if ($replyTo) { $replyArr = $this->emailToArray($replyTo); $mail->addReplyTo($replyArr['email'], $replyArr['name']); } // Setting from (sender) field. $from = $this->from(); $fromArr = $this->emailToArray($from); $mail->setFrom($fromArr['email'], $fromArr['name']); // Setting to (recipients) field(s). $to = $this->to(); foreach ($to as $recipient) { $toArr = $this->emailToArray($recipient); $mail->addAddress($toArr['email'], $toArr['name']); } // Setting cc (carbon-copy) field(s). $cc = $this->cc(); foreach ($cc as $ccRecipient) { $ccArr = $this->emailToArray($ccRecipient); $mail->addCC($ccArr['email'], $ccArr['name']); } // Setting bcc (black-carbon-copy) field(s). $bcc = $this->bcc(); foreach ($bcc as $bccRecipient) { $bccArr = $this->emailToArray($bccRecipient); $mail->addBCC($bccArr['email'], $bccArr['name']); } // Setting attachment(s), if required. $attachments = $this->attachments(); foreach ($attachments as $att) { $mail->addAttachment($att); } $mail->isHTML(true); $mail->Subject = $this->subject(); $mail->Body = $this->msgHtml(); $mail->AltBody = $this->msgTxt(); $ret = $mail->send(); $this->logSend($ret, $mail); return $ret; } catch (Exception $e) { $this->logger->error( sprintf('Error sending email: %s', $e->getMessage()) ); } }
[ "public", "function", "send", "(", ")", "{", "$", "this", "->", "logger", "->", "debug", "(", "'Attempting to send an email'", ",", "$", "this", "->", "to", "(", ")", ")", ";", "$", "mail", "=", "$", "this", "->", "phpMailer", ";", "try", "{", "$", ...
Send the email to all recipients @return boolean Success / Failure. @todo Implement methods and property for toggling rich-text vs. plain-text emails (`$mail->isHTML(true)`).
[ "Send", "the", "email", "to", "all", "recipients" ]
99ccabcd0a91802e308177e0b6b626eaf0f940da
https://github.com/locomotivemtl/charcoal-email/blob/99ccabcd0a91802e308177e0b6b626eaf0f940da/src/Charcoal/Email/Email.php#L658-L727
train
locomotivemtl/charcoal-email
src/Charcoal/Email/Email.php
Email.setSmtpOptions
protected function setSmtpOptions(PHPMailer $mail) { $config = $this->config(); if (!$config['smtp']) { return; } $this->logger->debug( sprintf('Using SMTP "%s" server to send email', $config['smtp_hostname']) ); $mail->isSMTP(); $mail->Host = $config['smtp_hostname']; $mail->Port = $config['smtp_port']; $mail->SMTPAuth = $config['smtp_auth']; $mail->Username = $config['smtp_username']; $mail->Password = $config['smtp_password']; $mail->SMTPSecure = $config['smtp_security']; }
php
protected function setSmtpOptions(PHPMailer $mail) { $config = $this->config(); if (!$config['smtp']) { return; } $this->logger->debug( sprintf('Using SMTP "%s" server to send email', $config['smtp_hostname']) ); $mail->isSMTP(); $mail->Host = $config['smtp_hostname']; $mail->Port = $config['smtp_port']; $mail->SMTPAuth = $config['smtp_auth']; $mail->Username = $config['smtp_username']; $mail->Password = $config['smtp_password']; $mail->SMTPSecure = $config['smtp_security']; }
[ "protected", "function", "setSmtpOptions", "(", "PHPMailer", "$", "mail", ")", "{", "$", "config", "=", "$", "this", "->", "config", "(", ")", ";", "if", "(", "!", "$", "config", "[", "'smtp'", "]", ")", "{", "return", ";", "}", "$", "this", "->", ...
Set the SMTP's options for PHPMailer. @param PHPMailer $mail The PHPMailer to setup. @return void
[ "Set", "the", "SMTP", "s", "options", "for", "PHPMailer", "." ]
99ccabcd0a91802e308177e0b6b626eaf0f940da
https://github.com/locomotivemtl/charcoal-email/blob/99ccabcd0a91802e308177e0b6b626eaf0f940da/src/Charcoal/Email/Email.php#L735-L753
train
locomotivemtl/charcoal-email
src/Charcoal/Email/Email.php
Email.queue
public function queue($ts = null) { $recipients = $this->to(); $author = $this->from(); $subject = $this->subject(); $msgHtml = $this->msgHtml(); $msgTxt = $this->msgTxt(); $campaign = $this->campaign(); $queueId = $this->queueId(); foreach ($recipients as $to) { $queueItem = $this->queueItemFactory()->create(EmailQueueItem::class); $queueItem->setTo($to); $queueItem->setFrom($author); $queueItem->setSubject($subject); $queueItem->setMsgHtml($msgHtml); $queueItem->setMsgTxt($msgTxt); $queueItem->setCampaign($campaign); $queueItem->setProcessingDate($ts); $queueItem->setQueueId($queueId); $res = $queueItem->save(); } return true; }
php
public function queue($ts = null) { $recipients = $this->to(); $author = $this->from(); $subject = $this->subject(); $msgHtml = $this->msgHtml(); $msgTxt = $this->msgTxt(); $campaign = $this->campaign(); $queueId = $this->queueId(); foreach ($recipients as $to) { $queueItem = $this->queueItemFactory()->create(EmailQueueItem::class); $queueItem->setTo($to); $queueItem->setFrom($author); $queueItem->setSubject($subject); $queueItem->setMsgHtml($msgHtml); $queueItem->setMsgTxt($msgTxt); $queueItem->setCampaign($campaign); $queueItem->setProcessingDate($ts); $queueItem->setQueueId($queueId); $res = $queueItem->save(); } return true; }
[ "public", "function", "queue", "(", "$", "ts", "=", "null", ")", "{", "$", "recipients", "=", "$", "this", "->", "to", "(", ")", ";", "$", "author", "=", "$", "this", "->", "from", "(", ")", ";", "$", "subject", "=", "$", "this", "->", "subject...
Enqueue the email for each recipient. @param mixed $ts A date/time to initiate the queue processing. @return boolean Success / Failure.
[ "Enqueue", "the", "email", "for", "each", "recipient", "." ]
99ccabcd0a91802e308177e0b6b626eaf0f940da
https://github.com/locomotivemtl/charcoal-email/blob/99ccabcd0a91802e308177e0b6b626eaf0f940da/src/Charcoal/Email/Email.php#L761-L787
train
locomotivemtl/charcoal-email
src/Charcoal/Email/Email.php
Email.viewController
public function viewController() { $templateIdent = $this->templateIdent(); if (!$templateIdent) { return []; } $templateFactory = clone($this->templateFactory()); $templateFactory->setDefaultClass(GenericEmailTemplate::class); $template = $templateFactory->create($templateIdent); $template->setData($this->templateData()); return $template; }
php
public function viewController() { $templateIdent = $this->templateIdent(); if (!$templateIdent) { return []; } $templateFactory = clone($this->templateFactory()); $templateFactory->setDefaultClass(GenericEmailTemplate::class); $template = $templateFactory->create($templateIdent); $template->setData($this->templateData()); return $template; }
[ "public", "function", "viewController", "(", ")", "{", "$", "templateIdent", "=", "$", "this", "->", "templateIdent", "(", ")", ";", "if", "(", "!", "$", "templateIdent", ")", "{", "return", "[", "]", ";", "}", "$", "templateFactory", "=", "clone", "("...
Get the custom view controller for rendering the email's HTML message. Unlike typical `ViewableInterface` objects, the view controller is not the email itself but an external "email" template. @see ViewableInterface::viewController() @return \Charcoal\App\Template\TemplateInterface|array
[ "Get", "the", "custom", "view", "controller", "for", "rendering", "the", "email", "s", "HTML", "message", "." ]
99ccabcd0a91802e308177e0b6b626eaf0f940da
https://github.com/locomotivemtl/charcoal-email/blob/99ccabcd0a91802e308177e0b6b626eaf0f940da/src/Charcoal/Email/Email.php#L831-L846
train
locomotivemtl/charcoal-email
src/Charcoal/Email/Email.php
Email.generateMsgHtml
protected function generateMsgHtml() { $templateIdent = $this->templateIdent(); if (!$templateIdent) { $message = ''; } else { $message = $this->renderTemplate($templateIdent); } return $message; }
php
protected function generateMsgHtml() { $templateIdent = $this->templateIdent(); if (!$templateIdent) { $message = ''; } else { $message = $this->renderTemplate($templateIdent); } return $message; }
[ "protected", "function", "generateMsgHtml", "(", ")", "{", "$", "templateIdent", "=", "$", "this", "->", "templateIdent", "(", ")", ";", "if", "(", "!", "$", "templateIdent", ")", "{", "$", "message", "=", "''", ";", "}", "else", "{", "$", "message", ...
Get the email's HTML message from the template, if applicable. @see ViewableInterface::renderTemplate() @return string
[ "Get", "the", "email", "s", "HTML", "message", "from", "the", "template", "if", "applicable", "." ]
99ccabcd0a91802e308177e0b6b626eaf0f940da
https://github.com/locomotivemtl/charcoal-email/blob/99ccabcd0a91802e308177e0b6b626eaf0f940da/src/Charcoal/Email/Email.php#L908-L919
train
locomotivemtl/charcoal-email
src/Charcoal/Email/Email.php
Email.stripHtml
protected function stripHtml($html) { $str = html_entity_decode($html); // Strip HTML (Replace br with newline, remove "invisible" tags and strip other tags) $str = preg_replace('#<br[^>]*?>#siu', "\n", $str); $str = preg_replace( [ '#<applet[^>]*?.*?</applet>#siu', '#<embed[^>]*?.*?</embed>#siu', '#<head[^>]*?>.*?</head>#siu', '#<noframes[^>]*?.*?</noframes>#siu', '#<noscript[^>]*?.*?</noscript>#siu', '#<noembed[^>]*?.*?</noembed>#siu', '#<object[^>]*?.*?</object>#siu', '#<script[^>]*?.*?</script>#siu', '#<style[^>]*?>.*?</style>#siu' ], '', $str ); $str = strip_tags($str); // Trim whitespace $str = str_replace("\t", '', $str); $str = preg_replace('#\n\r|\r\n#', "\n", $str); $str = preg_replace('#\n{3,}#', "\n\n", $str); $str = preg_replace('/ {2,}/', ' ', $str); $str = implode("\n", array_map('trim', explode("\n", $str))); $str = trim($str)."\n"; return $str; }
php
protected function stripHtml($html) { $str = html_entity_decode($html); // Strip HTML (Replace br with newline, remove "invisible" tags and strip other tags) $str = preg_replace('#<br[^>]*?>#siu', "\n", $str); $str = preg_replace( [ '#<applet[^>]*?.*?</applet>#siu', '#<embed[^>]*?.*?</embed>#siu', '#<head[^>]*?>.*?</head>#siu', '#<noframes[^>]*?.*?</noframes>#siu', '#<noscript[^>]*?.*?</noscript>#siu', '#<noembed[^>]*?.*?</noembed>#siu', '#<object[^>]*?.*?</object>#siu', '#<script[^>]*?.*?</script>#siu', '#<style[^>]*?>.*?</style>#siu' ], '', $str ); $str = strip_tags($str); // Trim whitespace $str = str_replace("\t", '', $str); $str = preg_replace('#\n\r|\r\n#', "\n", $str); $str = preg_replace('#\n{3,}#', "\n\n", $str); $str = preg_replace('/ {2,}/', ' ', $str); $str = implode("\n", array_map('trim', explode("\n", $str))); $str = trim($str)."\n"; return $str; }
[ "protected", "function", "stripHtml", "(", "$", "html", ")", "{", "$", "str", "=", "html_entity_decode", "(", "$", "html", ")", ";", "// Strip HTML (Replace br with newline, remove \"invisible\" tags and strip other tags)", "$", "str", "=", "preg_replace", "(", "'#<br[^...
Convert an HTML string to plain-text. @param string $html The HTML string to convert. @return string The resulting plain-text string.
[ "Convert", "an", "HTML", "string", "to", "plain", "-", "text", "." ]
99ccabcd0a91802e308177e0b6b626eaf0f940da
https://github.com/locomotivemtl/charcoal-email/blob/99ccabcd0a91802e308177e0b6b626eaf0f940da/src/Charcoal/Email/Email.php#L961-L992
train
locomotivemtl/charcoal-email
src/Charcoal/Email/Email.php
Email.logSend
protected function logSend($result, $mailer) { if ($this->log() === false) { return; } if (!$result) { $this->logger->error('Email could not be sent.'); } else { $this->logger->debug( sprintf('Email "%s" sent successfully.', $this->subject()), $this->to() ); } $recipients = array_merge( $this->to(), $this->cc(), $this->bcc() ); foreach ($recipients as $to) { $log = $this->logFactory()->create('charcoal/email/email-log'); $log->setType('email'); $log->setAction('send'); $log->setRawResponse($mailer); $log->setMessageId($mailer->getLastMessageId()); $log->setCampaign($this->campaign()); $log->setSendDate('now'); $log->setFrom($mailer->From); $log->setTo($to); $log->setSubject($this->subject()); $log->save(); } }
php
protected function logSend($result, $mailer) { if ($this->log() === false) { return; } if (!$result) { $this->logger->error('Email could not be sent.'); } else { $this->logger->debug( sprintf('Email "%s" sent successfully.', $this->subject()), $this->to() ); } $recipients = array_merge( $this->to(), $this->cc(), $this->bcc() ); foreach ($recipients as $to) { $log = $this->logFactory()->create('charcoal/email/email-log'); $log->setType('email'); $log->setAction('send'); $log->setRawResponse($mailer); $log->setMessageId($mailer->getLastMessageId()); $log->setCampaign($this->campaign()); $log->setSendDate('now'); $log->setFrom($mailer->From); $log->setTo($to); $log->setSubject($this->subject()); $log->save(); } }
[ "protected", "function", "logSend", "(", "$", "result", ",", "$", "mailer", ")", "{", "if", "(", "$", "this", "->", "log", "(", ")", "===", "false", ")", "{", "return", ";", "}", "if", "(", "!", "$", "result", ")", "{", "$", "this", "->", "logg...
Log the send event for each recipient. @param boolean $result Success or failure. @param mixed $mailer The raw mailer. @return void
[ "Log", "the", "send", "event", "for", "each", "recipient", "." ]
99ccabcd0a91802e308177e0b6b626eaf0f940da
https://github.com/locomotivemtl/charcoal-email/blob/99ccabcd0a91802e308177e0b6b626eaf0f940da/src/Charcoal/Email/Email.php#L1001-L1041
train
aimeos/ai-gettext
lib/custom/src/MW/Translation/File/Mo.php
Mo.get
public function get( $original ) { $original = (string) $original; if( isset( $this->messages[$original] ) ) { return $this->messages[$original]; } return false; }
php
public function get( $original ) { $original = (string) $original; if( isset( $this->messages[$original] ) ) { return $this->messages[$original]; } return false; }
[ "public", "function", "get", "(", "$", "original", ")", "{", "$", "original", "=", "(", "string", ")", "$", "original", ";", "if", "(", "isset", "(", "$", "this", "->", "messages", "[", "$", "original", "]", ")", ")", "{", "return", "$", "this", ...
Returns the translations for the given original string @param string $original Untranslated string @return array|boolean List of translations or false if none is available
[ "Returns", "the", "translations", "for", "the", "given", "original", "string" ]
0e823215bf4b35e7e037f8c6c567e85a92d990e7
https://github.com/aimeos/ai-gettext/blob/0e823215bf4b35e7e037f8c6c567e85a92d990e7/lib/custom/src/MW/Translation/File/Mo.php#L68-L77
train
aimeos/ai-gettext
lib/custom/src/MW/Translation/File/Mo.php
Mo.extract
protected function extract() { $magic = $this->readInt( 'V' ); if( ( $magic === self::MAGIC1 ) || ( $magic === self::MAGIC3 ) ) { //to make sure it works for 64-bit platforms $byteOrder = 'V'; //low endian } elseif( $magic === ( self::MAGIC2 & 0xFFFFFFFF ) ) { $byteOrder = 'N'; //big endian } else { throw new \Aimeos\MW\Translation\Exception( 'Invalid MO file' ); } $this->readInt( $byteOrder ); $total = $this->readInt( $byteOrder ); //total string count $originals = $this->readInt( $byteOrder ); //offset of original table $trans = $this->readInt( $byteOrder ); //offset of translation table $this->seekto( $originals ); $originalTable = $this->readIntArray( $byteOrder, $total * 2 ); $this->seekto( $trans ); $translationTable = $this->readIntArray( $byteOrder, $total * 2 ); return $this->extractTable( $originalTable, $translationTable, $total ); }
php
protected function extract() { $magic = $this->readInt( 'V' ); if( ( $magic === self::MAGIC1 ) || ( $magic === self::MAGIC3 ) ) { //to make sure it works for 64-bit platforms $byteOrder = 'V'; //low endian } elseif( $magic === ( self::MAGIC2 & 0xFFFFFFFF ) ) { $byteOrder = 'N'; //big endian } else { throw new \Aimeos\MW\Translation\Exception( 'Invalid MO file' ); } $this->readInt( $byteOrder ); $total = $this->readInt( $byteOrder ); //total string count $originals = $this->readInt( $byteOrder ); //offset of original table $trans = $this->readInt( $byteOrder ); //offset of translation table $this->seekto( $originals ); $originalTable = $this->readIntArray( $byteOrder, $total * 2 ); $this->seekto( $trans ); $translationTable = $this->readIntArray( $byteOrder, $total * 2 ); return $this->extractTable( $originalTable, $translationTable, $total ); }
[ "protected", "function", "extract", "(", ")", "{", "$", "magic", "=", "$", "this", "->", "readInt", "(", "'V'", ")", ";", "if", "(", "(", "$", "magic", "===", "self", "::", "MAGIC1", ")", "||", "(", "$", "magic", "===", "self", "::", "MAGIC3", ")...
Extracts the messages and translations from the MO file @throws \Aimeos\MW\Translation\Exception If file content is invalid @return array Associative list of original singular as keys and one or more translations as values
[ "Extracts", "the", "messages", "and", "translations", "from", "the", "MO", "file" ]
0e823215bf4b35e7e037f8c6c567e85a92d990e7
https://github.com/aimeos/ai-gettext/blob/0e823215bf4b35e7e037f8c6c567e85a92d990e7/lib/custom/src/MW/Translation/File/Mo.php#L86-L109
train
aimeos/ai-gettext
lib/custom/src/MW/Translation/File/Mo.php
Mo.extractTable
protected function extractTable( $originalTable, $translationTable, $total ) { $messages = []; for( $i = 0; $i < $total; ++$i ) { $plural = null; $next = $i * 2; $this->seekto( $originalTable[$next + 2] ); $original = $this->read( $originalTable[$next + 1] ); $this->seekto( $translationTable[$next + 2] ); $translated = $this->read( $translationTable[$next + 1] ); if( $original === '' || $translated === '' ) { // Headers continue; } if( strpos( $original, "\x04" ) !== false ) { list( $context, $original ) = explode( "\x04", $original, 2 ); } if( strpos( $original, "\000" ) !== false ) { list( $original, $plural ) = explode( "\000", $original ); } if( $plural === null ) { $messages[$original] = $translated; continue; } $messages[$original] = []; foreach( explode( "\x00", $translated ) as $idx => $value ) { $messages[$original][$idx] = $value; } } return $messages; }
php
protected function extractTable( $originalTable, $translationTable, $total ) { $messages = []; for( $i = 0; $i < $total; ++$i ) { $plural = null; $next = $i * 2; $this->seekto( $originalTable[$next + 2] ); $original = $this->read( $originalTable[$next + 1] ); $this->seekto( $translationTable[$next + 2] ); $translated = $this->read( $translationTable[$next + 1] ); if( $original === '' || $translated === '' ) { // Headers continue; } if( strpos( $original, "\x04" ) !== false ) { list( $context, $original ) = explode( "\x04", $original, 2 ); } if( strpos( $original, "\000" ) !== false ) { list( $original, $plural ) = explode( "\000", $original ); } if( $plural === null ) { $messages[$original] = $translated; continue; } $messages[$original] = []; foreach( explode( "\x00", $translated ) as $idx => $value ) { $messages[$original][$idx] = $value; } } return $messages; }
[ "protected", "function", "extractTable", "(", "$", "originalTable", ",", "$", "translationTable", ",", "$", "total", ")", "{", "$", "messages", "=", "[", "]", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "total", ";", "++", "$", ...
Extracts the messages and their translations @param array $originalTable MO table for original strings @param array $translationTable MO table for translated strings @param integer $total Total number of translations @return array Associative list of original singular as keys and one or more translations as values
[ "Extracts", "the", "messages", "and", "their", "translations" ]
0e823215bf4b35e7e037f8c6c567e85a92d990e7
https://github.com/aimeos/ai-gettext/blob/0e823215bf4b35e7e037f8c6c567e85a92d990e7/lib/custom/src/MW/Translation/File/Mo.php#L120-L160
train
aimeos/ai-gettext
lib/custom/src/MW/Translation/File/Mo.php
Mo.readInt
protected function readInt( $byteOrder ) { if( ( $content = $this->read( 4 )) === false ) { return false; } $content = unpack( $byteOrder, $content ); return array_shift( $content ); }
php
protected function readInt( $byteOrder ) { if( ( $content = $this->read( 4 )) === false ) { return false; } $content = unpack( $byteOrder, $content ); return array_shift( $content ); }
[ "protected", "function", "readInt", "(", "$", "byteOrder", ")", "{", "if", "(", "(", "$", "content", "=", "$", "this", "->", "read", "(", "4", ")", ")", "===", "false", ")", "{", "return", "false", ";", "}", "$", "content", "=", "unpack", "(", "$...
Returns a single integer starting from the current position @param string $byteOrder Format code for unpack() @return integer Read integer
[ "Returns", "a", "single", "integer", "starting", "from", "the", "current", "position" ]
0e823215bf4b35e7e037f8c6c567e85a92d990e7
https://github.com/aimeos/ai-gettext/blob/0e823215bf4b35e7e037f8c6c567e85a92d990e7/lib/custom/src/MW/Translation/File/Mo.php#L169-L177
train
mirko-pagliai/me-cms
src/View/Cell/PagesWidgetsCell.php
PagesWidgetsCell.pages
public function pages() { //Returns on pages index if ($this->request->isUrl(['_name' => 'pagesCategories'])) { return; } $pages = $this->Pages->find('active') ->select(['title', 'slug']) ->order([sprintf('%s.title', $this->Pages->getAlias()) => 'ASC']) ->cache(sprintf('widget_list'), $this->Pages->getCacheName()) ->all(); $this->set(compact('pages')); }
php
public function pages() { //Returns on pages index if ($this->request->isUrl(['_name' => 'pagesCategories'])) { return; } $pages = $this->Pages->find('active') ->select(['title', 'slug']) ->order([sprintf('%s.title', $this->Pages->getAlias()) => 'ASC']) ->cache(sprintf('widget_list'), $this->Pages->getCacheName()) ->all(); $this->set(compact('pages')); }
[ "public", "function", "pages", "(", ")", "{", "//Returns on pages index", "if", "(", "$", "this", "->", "request", "->", "isUrl", "(", "[", "'_name'", "=>", "'pagesCategories'", "]", ")", ")", "{", "return", ";", "}", "$", "pages", "=", "$", "this", "-...
Pages list widget @return void
[ "Pages", "list", "widget" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/View/Cell/PagesWidgetsCell.php#L62-L76
train
nails/module-captcha
src/Service/Captcha.php
Captcha.generate
public function generate() { try { if (!$this->isEnabled()) { throw new CaptchaDriverException( 'Captcha driver has not been configured.' ); } $oResponse = $this->oDriver->generate(); if (!($oResponse instanceof CaptchaForm)) { throw new CaptchaDriverException( 'Driver must return an instance of \Nails\Captcha\Factory\CaptchaForm.' ); } } catch (\Exception $e) { $oResponse = Factory::factory('CaptchaForm', 'nails/module-captcha'); $oResponse->setHtml( '<p style="color: red; padding: 1rem; border: 1px solid red;">ERROR: ' . $e->getMessage() . '</p>' ); } return $oResponse; }
php
public function generate() { try { if (!$this->isEnabled()) { throw new CaptchaDriverException( 'Captcha driver has not been configured.' ); } $oResponse = $this->oDriver->generate(); if (!($oResponse instanceof CaptchaForm)) { throw new CaptchaDriverException( 'Driver must return an instance of \Nails\Captcha\Factory\CaptchaForm.' ); } } catch (\Exception $e) { $oResponse = Factory::factory('CaptchaForm', 'nails/module-captcha'); $oResponse->setHtml( '<p style="color: red; padding: 1rem; border: 1px solid red;">ERROR: ' . $e->getMessage() . '</p>' ); } return $oResponse; }
[ "public", "function", "generate", "(", ")", "{", "try", "{", "if", "(", "!", "$", "this", "->", "isEnabled", "(", ")", ")", "{", "throw", "new", "CaptchaDriverException", "(", "'Captcha driver has not been configured.'", ")", ";", "}", "$", "oResponse", "=",...
Returns the form markup for the captcha @return CaptchaForm
[ "Returns", "the", "form", "markup", "for", "the", "captcha" ]
7b1c68959acb514c5e7a9bb12340a0bb80a8b7e5
https://github.com/nails/module-captcha/blob/7b1c68959acb514c5e7a9bb12340a0bb80a8b7e5/src/Service/Captcha.php#L39-L65
train
emonkak/php-database
src/AbstractConnector.php
AbstractConnector.getPdo
public function getPdo() { if ($this->pdo === null) { $this->pdo = $this->doConnect(); } return $this->pdo; }
php
public function getPdo() { if ($this->pdo === null) { $this->pdo = $this->doConnect(); } return $this->pdo; }
[ "public", "function", "getPdo", "(", ")", "{", "if", "(", "$", "this", "->", "pdo", "===", "null", ")", "{", "$", "this", "->", "pdo", "=", "$", "this", "->", "doConnect", "(", ")", ";", "}", "return", "$", "this", "->", "pdo", ";", "}" ]
Gets the PDO connection of the database. And connect to the database if not connected yet. @return PDOInterface
[ "Gets", "the", "PDO", "connection", "of", "the", "database", ".", "And", "connect", "to", "the", "database", "if", "not", "connected", "yet", "." ]
ee135b976161a61e38d0e44913124c91d1ee038e
https://github.com/emonkak/php-database/blob/ee135b976161a61e38d0e44913124c91d1ee038e/src/AbstractConnector.php#L21-L27
train
emonkak/php-database
src/AbstractConnector.php
AbstractConnector.disconnect
public function disconnect() { if ($this->pdo !== null) { $this->doDisconnect($this->pdo); $this->pdo = null; } }
php
public function disconnect() { if ($this->pdo !== null) { $this->doDisconnect($this->pdo); $this->pdo = null; } }
[ "public", "function", "disconnect", "(", ")", "{", "if", "(", "$", "this", "->", "pdo", "!==", "null", ")", "{", "$", "this", "->", "doDisconnect", "(", "$", "this", "->", "pdo", ")", ";", "$", "this", "->", "pdo", "=", "null", ";", "}", "}" ]
Disconnects the connection.
[ "Disconnects", "the", "connection", "." ]
ee135b976161a61e38d0e44913124c91d1ee038e
https://github.com/emonkak/php-database/blob/ee135b976161a61e38d0e44913124c91d1ee038e/src/AbstractConnector.php#L42-L48
train
ommu/mod-core
controllers/MetaController.php
MetaController.performAjaxValidation
protected function performAjaxValidation($model) { if(isset($_POST['ajax']) && $_POST['ajax']==='ommu-meta-form') { echo CActiveForm::validate($model); Yii::app()->end(); } }
php
protected function performAjaxValidation($model) { if(isset($_POST['ajax']) && $_POST['ajax']==='ommu-meta-form') { echo CActiveForm::validate($model); Yii::app()->end(); } }
[ "protected", "function", "performAjaxValidation", "(", "$", "model", ")", "{", "if", "(", "isset", "(", "$", "_POST", "[", "'ajax'", "]", ")", "&&", "$", "_POST", "[", "'ajax'", "]", "===", "'ommu-meta-form'", ")", "{", "echo", "CActiveForm", "::", "vali...
Performs the AJAX validation. @param CModel the model to be validated
[ "Performs", "the", "AJAX", "validation", "." ]
68c90e76440e74ee93bcf82905a54d86c941b771
https://github.com/ommu/mod-core/blob/68c90e76440e74ee93bcf82905a54d86c941b771/controllers/MetaController.php#L309-L315
train
nails/module-auth
src/Model/User/Group.php
Group.setAsDefault
public function setAsDefault($mGroupIdOrSlug) { $oGroup = $this->getByIdOrSlug($mGroupIdOrSlug); if (!$oGroup) { $this->setError('Invalid Group'); } // -------------------------------------------------------------------------- $oDb = Factory::service('Database'); $oDb->trans_begin(); // Unset old default $oDb->set('is_default', false); $oDb->set('modified', 'NOW()', false); if (isLoggedIn()) { $oDb->set('modified_by', activeUser('id')); } $oDb->where('is_default', true); $oDb->update($this->getTableName()); // Set new default $oDb->set('is_default', true); $oDb->set('modified', 'NOW()', false); if (isLoggedIn()) { $oDb->set('modified_by', activeUser('id')); } $oDb->where('id', $oGroup->id); $oDb->update($this->getTableName()); if ($oDb->trans_status() === false) { $oDb->trans_rollback(); return false; } else { $oDb->trans_commit(); $this->getDefaultGroup(); return true; } }
php
public function setAsDefault($mGroupIdOrSlug) { $oGroup = $this->getByIdOrSlug($mGroupIdOrSlug); if (!$oGroup) { $this->setError('Invalid Group'); } // -------------------------------------------------------------------------- $oDb = Factory::service('Database'); $oDb->trans_begin(); // Unset old default $oDb->set('is_default', false); $oDb->set('modified', 'NOW()', false); if (isLoggedIn()) { $oDb->set('modified_by', activeUser('id')); } $oDb->where('is_default', true); $oDb->update($this->getTableName()); // Set new default $oDb->set('is_default', true); $oDb->set('modified', 'NOW()', false); if (isLoggedIn()) { $oDb->set('modified_by', activeUser('id')); } $oDb->where('id', $oGroup->id); $oDb->update($this->getTableName()); if ($oDb->trans_status() === false) { $oDb->trans_rollback(); return false; } else { $oDb->trans_commit(); $this->getDefaultGroup(); return true; } }
[ "public", "function", "setAsDefault", "(", "$", "mGroupIdOrSlug", ")", "{", "$", "oGroup", "=", "$", "this", "->", "getByIdOrSlug", "(", "$", "mGroupIdOrSlug", ")", ";", "if", "(", "!", "$", "oGroup", ")", "{", "$", "this", "->", "setError", "(", "'Inv...
Set's a group as the default group @param mixed $mGroupIdOrSlug The group's ID or slug @return boolean
[ "Set", "s", "a", "group", "as", "the", "default", "group" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User/Group.php#L46-L88
train
nails/module-auth
src/Model/User/Group.php
Group.getDefaultGroup
public function getDefaultGroup() { $aGroups = $this->getAll([ 'where' => [ ['is_default', true], ], ]); if (empty($aGroups)) { throw new NailsException('A default user group must be defined.'); } $this->oDefaultGroup = reset($aGroups); return $this->oDefaultGroup; }
php
public function getDefaultGroup() { $aGroups = $this->getAll([ 'where' => [ ['is_default', true], ], ]); if (empty($aGroups)) { throw new NailsException('A default user group must be defined.'); } $this->oDefaultGroup = reset($aGroups); return $this->oDefaultGroup; }
[ "public", "function", "getDefaultGroup", "(", ")", "{", "$", "aGroups", "=", "$", "this", "->", "getAll", "(", "[", "'where'", "=>", "[", "[", "'is_default'", ",", "true", "]", ",", "]", ",", "]", ")", ";", "if", "(", "empty", "(", "$", "aGroups", ...
Returns the default user group @return \stdClass
[ "Returns", "the", "default", "user", "group" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User/Group.php#L97-L112
train
nails/module-auth
src/Model/User/Group.php
Group.hasPermission
public function hasPermission($sSearch, $mGroup) { // Fetch the correct ACL if (is_numeric($mGroup)) { $oGroup = $this->getById($mGroup); if (isset($oGroup->acl)) { $aAcl = $oGroup->acl; unset($oGroup); } else { return false; } } elseif (isset($mGroup->acl)) { $aAcl = $mGroup->acl; } else { return false; } if (!$aAcl) { return false; } // -------------------------------------------------------------------------- // Super users or CLI users can do anything their heart's desire $oInput = Factory::service('Input'); if (in_array('admin:superuser', $aAcl) || $oInput::isCli()) { return true; } // -------------------------------------------------------------------------- /** * Test the ACL * We're going to use regular expressions here so we can allow for some * flexibility in the search, i.e admin:* would return true if the user has * access to any of admin. */ $bHasPermission = false; /** * Replace :* with :.* - this is a common mistake when using the permission * system (i.e., assuming that star on it's own will match) */ $sSearch = preg_replace('/:\*/', ':.*', $sSearch); foreach ($aAcl as $sPermission) { $sPattern = '/^' . $sSearch . '$/'; $bMatch = preg_match($sPattern, $sPermission); if ($bMatch) { $bHasPermission = true; break; } } return $bHasPermission; }
php
public function hasPermission($sSearch, $mGroup) { // Fetch the correct ACL if (is_numeric($mGroup)) { $oGroup = $this->getById($mGroup); if (isset($oGroup->acl)) { $aAcl = $oGroup->acl; unset($oGroup); } else { return false; } } elseif (isset($mGroup->acl)) { $aAcl = $mGroup->acl; } else { return false; } if (!$aAcl) { return false; } // -------------------------------------------------------------------------- // Super users or CLI users can do anything their heart's desire $oInput = Factory::service('Input'); if (in_array('admin:superuser', $aAcl) || $oInput::isCli()) { return true; } // -------------------------------------------------------------------------- /** * Test the ACL * We're going to use regular expressions here so we can allow for some * flexibility in the search, i.e admin:* would return true if the user has * access to any of admin. */ $bHasPermission = false; /** * Replace :* with :.* - this is a common mistake when using the permission * system (i.e., assuming that star on it's own will match) */ $sSearch = preg_replace('/:\*/', ':.*', $sSearch); foreach ($aAcl as $sPermission) { $sPattern = '/^' . $sSearch . '$/'; $bMatch = preg_match($sPattern, $sPermission); if ($bMatch) { $bHasPermission = true; break; } } return $bHasPermission; }
[ "public", "function", "hasPermission", "(", "$", "sSearch", ",", "$", "mGroup", ")", "{", "// Fetch the correct ACL", "if", "(", "is_numeric", "(", "$", "mGroup", ")", ")", "{", "$", "oGroup", "=", "$", "this", "->", "getById", "(", "$", "mGroup", ")", ...
Determines whether the specified group has a certain ACL permission @param string $sSearch The permission to check for @param mixed $mGroup The group to check for; if numeric, fetches group, if object uses that object @return boolean
[ "Determines", "whether", "the", "specified", "group", "has", "a", "certain", "ACL", "permission" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User/Group.php#L258-L320
train
nails/module-console
src/Utf8.php
Utf8.defineCharsetConstants
protected static function defineCharsetConstants() { /** * See vendor/codeigniter/framework/system/core/CodeIgniter.php for * details of what/why this is happening. */ $sCharset = strtoupper(config_item('charset')); ini_set('default_charset', $sCharset); if (extension_loaded('mbstring')) { define('MB_ENABLED', true); @ini_set('mbstring.internal_encoding', $sCharset); mb_substitute_character('none'); } else { define('MB_ENABLED', false); } if (extension_loaded('iconv')) { define('ICONV_ENABLED', true); @ini_set('iconv.internal_encoding', $sCharset); } else { define('ICONV_ENABLED', false); } if (is_php('5.6')) { ini_set('php.internal_encoding', $sCharset); } }
php
protected static function defineCharsetConstants() { /** * See vendor/codeigniter/framework/system/core/CodeIgniter.php for * details of what/why this is happening. */ $sCharset = strtoupper(config_item('charset')); ini_set('default_charset', $sCharset); if (extension_loaded('mbstring')) { define('MB_ENABLED', true); @ini_set('mbstring.internal_encoding', $sCharset); mb_substitute_character('none'); } else { define('MB_ENABLED', false); } if (extension_loaded('iconv')) { define('ICONV_ENABLED', true); @ini_set('iconv.internal_encoding', $sCharset); } else { define('ICONV_ENABLED', false); } if (is_php('5.6')) { ini_set('php.internal_encoding', $sCharset); } }
[ "protected", "static", "function", "defineCharsetConstants", "(", ")", "{", "/**\n * See vendor/codeigniter/framework/system/core/CodeIgniter.php for\n * details of what/why this is happening.\n */", "$", "sCharset", "=", "strtoupper", "(", "config_item", "(", "...
This method defines some items which are declared by CodeIgniter
[ "This", "method", "defines", "some", "items", "which", "are", "declared", "by", "CodeIgniter" ]
bef013213c914af33172293a386e2738ceedc12d
https://github.com/nails/module-console/blob/bef013213c914af33172293a386e2738ceedc12d/src/Utf8.php#L30-L58
train
vanilla/garden-db
src/ArraySet.php
ArraySet.sortData
protected function sortData() { $columns = $this->getOrder(); $order = []; foreach ($columns as $column) { if ($column[0] === '-') { $column = substr($column, 1); $order[$column] = -1; } else { $order[$column] = 1; } } $cmp = function ($a, $b) use ($order) { foreach ($order as $column => $desc) { $r = strnatcmp($a[$column], $b[$column]); if ($r !== 0) { return $r * $desc; } } return 0; }; usort($this->data, $cmp); }
php
protected function sortData() { $columns = $this->getOrder(); $order = []; foreach ($columns as $column) { if ($column[0] === '-') { $column = substr($column, 1); $order[$column] = -1; } else { $order[$column] = 1; } } $cmp = function ($a, $b) use ($order) { foreach ($order as $column => $desc) { $r = strnatcmp($a[$column], $b[$column]); if ($r !== 0) { return $r * $desc; } } return 0; }; usort($this->data, $cmp); }
[ "protected", "function", "sortData", "(", ")", "{", "$", "columns", "=", "$", "this", "->", "getOrder", "(", ")", ";", "$", "order", "=", "[", "]", ";", "foreach", "(", "$", "columns", "as", "$", "column", ")", "{", "if", "(", "$", "column", "[",...
Sort the internal array.
[ "Sort", "the", "internal", "array", "." ]
2634229fb7a161f649ad371e59a973ccbbe72247
https://github.com/vanilla/garden-db/blob/2634229fb7a161f649ad371e59a973ccbbe72247/src/ArraySet.php#L37-L61
train
vanilla/garden-db
src/ArraySet.php
ArraySet.getData
public function getData() { if ($this->toSort && !empty($this->getOrder())) { $this->sortData(); } if ($this->getLimit()) { return array_slice($this->data, $this->getOffset(), $this->getLimit()); } else { return $this->data; } }
php
public function getData() { if ($this->toSort && !empty($this->getOrder())) { $this->sortData(); } if ($this->getLimit()) { return array_slice($this->data, $this->getOffset(), $this->getLimit()); } else { return $this->data; } }
[ "public", "function", "getData", "(", ")", "{", "if", "(", "$", "this", "->", "toSort", "&&", "!", "empty", "(", "$", "this", "->", "getOrder", "(", ")", ")", ")", "{", "$", "this", "->", "sortData", "(", ")", ";", "}", "if", "(", "$", "this", ...
Get the underlying data array. @return array Returns the data.
[ "Get", "the", "underlying", "data", "array", "." ]
2634229fb7a161f649ad371e59a973ccbbe72247
https://github.com/vanilla/garden-db/blob/2634229fb7a161f649ad371e59a973ccbbe72247/src/ArraySet.php#L68-L78
train
vanilla/garden-db
src/ArraySet.php
ArraySet.setData
public function setData($data) { if ($data instanceof \Traversable) { $this->data = iterator_to_array($data); } else { $this->data = $data; } if (!empty($this->getOrder())) { $this->toSort = true; } return $this; }
php
public function setData($data) { if ($data instanceof \Traversable) { $this->data = iterator_to_array($data); } else { $this->data = $data; } if (!empty($this->getOrder())) { $this->toSort = true; } return $this; }
[ "public", "function", "setData", "(", "$", "data", ")", "{", "if", "(", "$", "data", "instanceof", "\\", "Traversable", ")", "{", "$", "this", "->", "data", "=", "iterator_to_array", "(", "$", "data", ")", ";", "}", "else", "{", "$", "this", "->", ...
Set the underlying data array. @param array|\Traversable $data @return $this
[ "Set", "the", "underlying", "data", "array", "." ]
2634229fb7a161f649ad371e59a973ccbbe72247
https://github.com/vanilla/garden-db/blob/2634229fb7a161f649ad371e59a973ccbbe72247/src/ArraySet.php#L86-L98
train
mirko-pagliai/cakephp-recaptcha-mailhide
src/Utility/Security.php
Security.decryptMail
public static function decryptMail($mail, $key = null, $hmacSalt = null) { return parent::decrypt(base64_decode($mail), $key ?: Configure::read('RecaptchaMailhide.encryptKey'), $hmacSalt); }
php
public static function decryptMail($mail, $key = null, $hmacSalt = null) { return parent::decrypt(base64_decode($mail), $key ?: Configure::read('RecaptchaMailhide.encryptKey'), $hmacSalt); }
[ "public", "static", "function", "decryptMail", "(", "$", "mail", ",", "$", "key", "=", "null", ",", "$", "hmacSalt", "=", "null", ")", "{", "return", "parent", "::", "decrypt", "(", "base64_decode", "(", "$", "mail", ")", ",", "$", "key", "?", ":", ...
Decrypts and decodes an email address @param string $mail Email address @param string $key The 256 bit/32 byte key to use as a cipher key. Leave `null` to use `Security.salt` @param string|null $hmacSalt The salt to use for the HMAC process. Leave `null` to use `Security.salt` @return string Decrypted email address
[ "Decrypts", "and", "decodes", "an", "email", "address" ]
d3a9acaea5382b20cd36f794d75265337d5cb3ac
https://github.com/mirko-pagliai/cakephp-recaptcha-mailhide/blob/d3a9acaea5382b20cd36f794d75265337d5cb3ac/src/Utility/Security.php#L32-L35
train
mirko-pagliai/cakephp-recaptcha-mailhide
src/Utility/Security.php
Security.encryptMail
public static function encryptMail($mail, $key = null, $hmacSalt = null) { return base64_encode(parent::encrypt($mail, $key ?: Configure::read('RecaptchaMailhide.encryptKey'), $hmacSalt)); }
php
public static function encryptMail($mail, $key = null, $hmacSalt = null) { return base64_encode(parent::encrypt($mail, $key ?: Configure::read('RecaptchaMailhide.encryptKey'), $hmacSalt)); }
[ "public", "static", "function", "encryptMail", "(", "$", "mail", ",", "$", "key", "=", "null", ",", "$", "hmacSalt", "=", "null", ")", "{", "return", "base64_encode", "(", "parent", "::", "encrypt", "(", "$", "mail", ",", "$", "key", "?", ":", "Confi...
Encrypts and encodes an email address @param string $mail Email address @param string $key The 256 bit/32 byte key to use as a cipher key. Leave `null` to use `Security.salt` @param string|null $hmacSalt The salt to use for the HMAC process. Leave `null` to use `Security.salt` @return string Encrypted email address
[ "Encrypts", "and", "encodes", "an", "email", "address" ]
d3a9acaea5382b20cd36f794d75265337d5cb3ac
https://github.com/mirko-pagliai/cakephp-recaptcha-mailhide/blob/d3a9acaea5382b20cd36f794d75265337d5cb3ac/src/Utility/Security.php#L46-L49
train
nails/module-auth
src/Controller/Base.php
Base.loadStyles
protected function loadStyles($sView) { // Test if a view has been provided by the app if (!is_file($sView)) { $oAsset = Factory::service('Asset'); $oAsset->clear(); $oAsset->load('nails.min.css', 'nails/common'); $oAsset->load('styles.min.css', 'nails/module-auth'); } }
php
protected function loadStyles($sView) { // Test if a view has been provided by the app if (!is_file($sView)) { $oAsset = Factory::service('Asset'); $oAsset->clear(); $oAsset->load('nails.min.css', 'nails/common'); $oAsset->load('styles.min.css', 'nails/module-auth'); } }
[ "protected", "function", "loadStyles", "(", "$", "sView", ")", "{", "// Test if a view has been provided by the app", "if", "(", "!", "is_file", "(", "$", "sView", ")", ")", "{", "$", "oAsset", "=", "Factory", "::", "service", "(", "'Asset'", ")", ";", "$",...
Loads Auth styles if supplied view does not exist @param string $sView The view to test @throws \Nails\Common\Exception\FactoryException
[ "Loads", "Auth", "styles", "if", "supplied", "view", "does", "not", "exist" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Controller/Base.php#L41-L50
train
PitonCMS/Engine
app/Library/Utilities/Json.php
Json.getJson
public function getJson($jsonFile, $jsonSchema = null) { if (isset($jsonSchema) && array_key_exists($jsonSchema, $this->validation)) { $validation = $this->validation[$jsonSchema]; } elseif ($jsonSchema === null) { $validation = $jsonSchema; } else { throw new Exception('Invalid jsonSchema validation key'); } try { return $this->decodeFile($jsonFile, $validation); } catch (\RuntimeException $e) { // Runtime errors such as file not found $this->errors[] = $e->getMessage(); } catch (ValidationFailedException $e) { // Schema validation errors $this->errors[] = $e->getMessage(); } catch (\Exception $e) { // Anything else we did not anticipate $this->errors[] = 'Unknown Exception in getPageDefinition()'; $this->errors[] = $e->getMessage(); } return null; }
php
public function getJson($jsonFile, $jsonSchema = null) { if (isset($jsonSchema) && array_key_exists($jsonSchema, $this->validation)) { $validation = $this->validation[$jsonSchema]; } elseif ($jsonSchema === null) { $validation = $jsonSchema; } else { throw new Exception('Invalid jsonSchema validation key'); } try { return $this->decodeFile($jsonFile, $validation); } catch (\RuntimeException $e) { // Runtime errors such as file not found $this->errors[] = $e->getMessage(); } catch (ValidationFailedException $e) { // Schema validation errors $this->errors[] = $e->getMessage(); } catch (\Exception $e) { // Anything else we did not anticipate $this->errors[] = 'Unknown Exception in getPageDefinition()'; $this->errors[] = $e->getMessage(); } return null; }
[ "public", "function", "getJson", "(", "$", "jsonFile", ",", "$", "jsonSchema", "=", "null", ")", "{", "if", "(", "isset", "(", "$", "jsonSchema", ")", "&&", "array_key_exists", "(", "$", "jsonSchema", ",", "$", "this", "->", "validation", ")", ")", "{"...
Get JSON Definition Validation errors are written to $this->errors @param string $jsonFile Path to page JSON file to decode @param string $jsonSchema Name of validation: settings|page @return mixed Object | null
[ "Get", "JSON", "Definition" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Library/Utilities/Json.php#L57-L82
train
mirko-pagliai/me-cms
src/Controller/SystemsController.php
SystemsController.acceptCookies
public function acceptCookies() { $this->response = $this->response->withCookie((new Cookie('cookies-policy', true))->withNeverExpire()); return $this->redirect($this->referer(['_name' => 'homepage'], true)); }
php
public function acceptCookies() { $this->response = $this->response->withCookie((new Cookie('cookies-policy', true))->withNeverExpire()); return $this->redirect($this->referer(['_name' => 'homepage'], true)); }
[ "public", "function", "acceptCookies", "(", ")", "{", "$", "this", "->", "response", "=", "$", "this", "->", "response", "->", "withCookie", "(", "(", "new", "Cookie", "(", "'cookies-policy'", ",", "true", ")", ")", "->", "withNeverExpire", "(", ")", ")"...
Accept cookies policy. It sets the cookie to remember the user accepted the cookie policy and redirects @return \Cake\Network\Response|null
[ "Accept", "cookies", "policy", ".", "It", "sets", "the", "cookie", "to", "remember", "the", "user", "accepted", "the", "cookie", "policy", "and", "redirects" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Controller/SystemsController.php#L33-L38
train
mirko-pagliai/me-cms
src/Controller/SystemsController.php
SystemsController.contactUs
public function contactUs() { //Checks if the "contact us" form is enabled if (!getConfig('default.contact_us')) { $this->Flash->error(I18N_DISABLED); return $this->redirect(['_name' => 'homepage']); } $contact = new ContactUsForm; if ($this->request->is('post')) { //Checks for reCAPTCHA, if requested if (!getConfig('security.recaptcha') || $this->Recaptcha->verify()) { //Sends the email if ($contact->execute($this->request->getData())) { $this->Flash->success(I18N_OPERATION_OK); return $this->redirect(['_name' => 'homepage']); } $this->Flash->error(I18N_OPERATION_NOT_OK); } else { $this->Flash->error(__d('me_cms', 'You must fill in the {0} control correctly', 'reCAPTCHA')); } } $this->set(compact('contact')); }
php
public function contactUs() { //Checks if the "contact us" form is enabled if (!getConfig('default.contact_us')) { $this->Flash->error(I18N_DISABLED); return $this->redirect(['_name' => 'homepage']); } $contact = new ContactUsForm; if ($this->request->is('post')) { //Checks for reCAPTCHA, if requested if (!getConfig('security.recaptcha') || $this->Recaptcha->verify()) { //Sends the email if ($contact->execute($this->request->getData())) { $this->Flash->success(I18N_OPERATION_OK); return $this->redirect(['_name' => 'homepage']); } $this->Flash->error(I18N_OPERATION_NOT_OK); } else { $this->Flash->error(__d('me_cms', 'You must fill in the {0} control correctly', 'reCAPTCHA')); } } $this->set(compact('contact')); }
[ "public", "function", "contactUs", "(", ")", "{", "//Checks if the \"contact us\" form is enabled", "if", "(", "!", "getConfig", "(", "'default.contact_us'", ")", ")", "{", "$", "this", "->", "Flash", "->", "error", "(", "I18N_DISABLED", ")", ";", "return", "$",...
"Contact us" form @return \Cake\Network\Response|null|void @see MeCms\Form\ContactUsForm @see MeCms\Mailer\ContactUsMailer
[ "Contact", "us", "form" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Controller/SystemsController.php#L46-L74
train
mirko-pagliai/me-cms
src/Controller/SystemsController.php
SystemsController.ipNotAllowed
public function ipNotAllowed() { //If the user's IP address is not banned if (!$this->request->isBanned()) { return $this->redirect($this->referer(['_name' => 'homepage'], true)); } $this->viewBuilder()->setLayout('login'); }
php
public function ipNotAllowed() { //If the user's IP address is not banned if (!$this->request->isBanned()) { return $this->redirect($this->referer(['_name' => 'homepage'], true)); } $this->viewBuilder()->setLayout('login'); }
[ "public", "function", "ipNotAllowed", "(", ")", "{", "//If the user's IP address is not banned", "if", "(", "!", "$", "this", "->", "request", "->", "isBanned", "(", ")", ")", "{", "return", "$", "this", "->", "redirect", "(", "$", "this", "->", "referer", ...
"IP not allowed" page @return \Cake\Network\Response|null|void
[ "IP", "not", "allowed", "page" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Controller/SystemsController.php#L80-L88
train
mirko-pagliai/me-cms
src/Controller/SystemsController.php
SystemsController.sitemap
public function sitemap() { //Checks if the sitemap exist and is not expired if (is_readable(SITEMAP)) { $time = Time::createFromTimestamp(filemtime(SITEMAP)); if (!$time->modify(getConfigOrFail('main.sitemap_expiration'))->isPast()) { $sitemap = file_get_contents(SITEMAP); } } if (empty($sitemap)) { $sitemap = gzencode(Sitemap::generate(), 9); (new File(SITEMAP, true, 0777))->write($sitemap); } return $this->response->withFile(SITEMAP); }
php
public function sitemap() { //Checks if the sitemap exist and is not expired if (is_readable(SITEMAP)) { $time = Time::createFromTimestamp(filemtime(SITEMAP)); if (!$time->modify(getConfigOrFail('main.sitemap_expiration'))->isPast()) { $sitemap = file_get_contents(SITEMAP); } } if (empty($sitemap)) { $sitemap = gzencode(Sitemap::generate(), 9); (new File(SITEMAP, true, 0777))->write($sitemap); } return $this->response->withFile(SITEMAP); }
[ "public", "function", "sitemap", "(", ")", "{", "//Checks if the sitemap exist and is not expired", "if", "(", "is_readable", "(", "SITEMAP", ")", ")", "{", "$", "time", "=", "Time", "::", "createFromTimestamp", "(", "filemtime", "(", "SITEMAP", ")", ")", ";", ...
Returns the site sitemap. If the sitemap doesn't exist or has expired, it generates and writes the sitemap. @return \Cake\Network\Response
[ "Returns", "the", "site", "sitemap", ".", "If", "the", "sitemap", "doesn", "t", "exist", "or", "has", "expired", "it", "generates", "and", "writes", "the", "sitemap", "." ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Controller/SystemsController.php#L110-L128
train
mirko-pagliai/me-cms
src/Controller/Admin/PhotosAlbumsController.php
PhotosAlbumsController.add
public function add() { $album = $this->PhotosAlbums->newEntity(); if ($this->request->is('post')) { $album = $this->PhotosAlbums->patchEntity($album, $this->request->getData()); if ($this->PhotosAlbums->save($album)) { $this->Flash->success(I18N_OPERATION_OK); return $this->redirect(['action' => 'index']); } $this->Flash->error(I18N_OPERATION_NOT_OK); } $this->set(compact('album')); }
php
public function add() { $album = $this->PhotosAlbums->newEntity(); if ($this->request->is('post')) { $album = $this->PhotosAlbums->patchEntity($album, $this->request->getData()); if ($this->PhotosAlbums->save($album)) { $this->Flash->success(I18N_OPERATION_OK); return $this->redirect(['action' => 'index']); } $this->Flash->error(I18N_OPERATION_NOT_OK); } $this->set(compact('album')); }
[ "public", "function", "add", "(", ")", "{", "$", "album", "=", "$", "this", "->", "PhotosAlbums", "->", "newEntity", "(", ")", ";", "if", "(", "$", "this", "->", "request", "->", "is", "(", "'post'", ")", ")", "{", "$", "album", "=", "$", "this",...
Adds photos album @return \Cake\Network\Response|null|void
[ "Adds", "photos", "album" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Controller/Admin/PhotosAlbumsController.php#L53-L70
train
mirko-pagliai/me-cms
src/Controller/Admin/PhotosAlbumsController.php
PhotosAlbumsController.edit
public function edit($id = null) { $album = $this->PhotosAlbums->get($id); if ($this->request->is(['patch', 'post', 'put'])) { $album = $this->PhotosAlbums->patchEntity($album, $this->request->getData()); if ($this->PhotosAlbums->save($album)) { $this->Flash->success(I18N_OPERATION_OK); return $this->redirect(['action' => 'index']); } $this->Flash->error(I18N_OPERATION_NOT_OK); } $this->set(compact('album')); }
php
public function edit($id = null) { $album = $this->PhotosAlbums->get($id); if ($this->request->is(['patch', 'post', 'put'])) { $album = $this->PhotosAlbums->patchEntity($album, $this->request->getData()); if ($this->PhotosAlbums->save($album)) { $this->Flash->success(I18N_OPERATION_OK); return $this->redirect(['action' => 'index']); } $this->Flash->error(I18N_OPERATION_NOT_OK); } $this->set(compact('album')); }
[ "public", "function", "edit", "(", "$", "id", "=", "null", ")", "{", "$", "album", "=", "$", "this", "->", "PhotosAlbums", "->", "get", "(", "$", "id", ")", ";", "if", "(", "$", "this", "->", "request", "->", "is", "(", "[", "'patch'", ",", "'p...
Edits photos album @param string $id Photos Album ID @return \Cake\Network\Response|null|void
[ "Edits", "photos", "album" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Controller/Admin/PhotosAlbumsController.php#L77-L94
train
mirko-pagliai/me-cms
src/Controller/Admin/PhotosAlbumsController.php
PhotosAlbumsController.delete
public function delete($id = null) { $this->request->allowMethod(['post', 'delete']); $album = $this->PhotosAlbums->get($id); //Before deleting, it checks if the album has some photos if (!$album->photo_count) { $this->PhotosAlbums->deleteOrFail($album); $this->Flash->success(I18N_OPERATION_OK); } else { $this->Flash->alert(I18N_BEFORE_DELETE); } return $this->redirect(['action' => 'index']); }
php
public function delete($id = null) { $this->request->allowMethod(['post', 'delete']); $album = $this->PhotosAlbums->get($id); //Before deleting, it checks if the album has some photos if (!$album->photo_count) { $this->PhotosAlbums->deleteOrFail($album); $this->Flash->success(I18N_OPERATION_OK); } else { $this->Flash->alert(I18N_BEFORE_DELETE); } return $this->redirect(['action' => 'index']); }
[ "public", "function", "delete", "(", "$", "id", "=", "null", ")", "{", "$", "this", "->", "request", "->", "allowMethod", "(", "[", "'post'", ",", "'delete'", "]", ")", ";", "$", "album", "=", "$", "this", "->", "PhotosAlbums", "->", "get", "(", "$...
Deletes photos album @param string $id Photos Album ID @return \Cake\Network\Response|null
[ "Deletes", "photos", "album" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Controller/Admin/PhotosAlbumsController.php#L100-L115
train
merk/Dough
lib/Dough/Twig/DoughExtension.php
DoughExtension.getAmount
public function getAmount(MoneyInterface $money = null, $currency = null) { if (null === $money) { return 0.0; } $reduced = $this->bank->reduce($money, $currency); return $reduced->getAmount(); }
php
public function getAmount(MoneyInterface $money = null, $currency = null) { if (null === $money) { return 0.0; } $reduced = $this->bank->reduce($money, $currency); return $reduced->getAmount(); }
[ "public", "function", "getAmount", "(", "MoneyInterface", "$", "money", "=", "null", ",", "$", "currency", "=", "null", ")", "{", "if", "(", "null", "===", "$", "money", ")", "{", "return", "0.0", ";", "}", "$", "reduced", "=", "$", "this", "->", "...
Gets the amount. @param MoneyInterface $money A MoneyInterface instance @param string $currency The currency code
[ "Gets", "the", "amount", "." ]
af36775564fbaf46a8018acc4f1fd993530c1a96
https://github.com/merk/Dough/blob/af36775564fbaf46a8018acc4f1fd993530c1a96/lib/Dough/Twig/DoughExtension.php#L52-L61
train
PitonCMS/Engine
app/Library/Utilities/Toolbox.php
Toolbox.truncateHtmlText
public function truncateHtmlText($text, $characters = 300) { // Clean up html tags and special characters $text = preg_replace('/<[^>]*>/', ' ', $text); $text = str_replace("\r", '', $text); // replace with empty space $text = str_replace("\n", ' ', $text); // replace with space $text = str_replace("\t", ' ', $text); // replace with space $text = preg_replace('/\s+/', ' ', $text); // remove multiple consecutive spaces $text = preg_replace('/^[\s]/', '', $text); // Remove leading space from excerpt $text = preg_replace('/[\s]$/', '', $text); // Remove trailing space from excerpt // If we are already within the limit, just return the text if (mb_strlen($text) <= $characters) { return $text; } // Truncate to character limit if longer than requested $text = substr($text, 0, $characters); // We don't want the string cut mid-word, so search for the last space and trim there $lastSpacePosition = strrpos($text, ' '); if (isset($lastSpacePosition)) { // Cut the text at this last word $text = substr($text, 0, $lastSpacePosition); } return $text; }
php
public function truncateHtmlText($text, $characters = 300) { // Clean up html tags and special characters $text = preg_replace('/<[^>]*>/', ' ', $text); $text = str_replace("\r", '', $text); // replace with empty space $text = str_replace("\n", ' ', $text); // replace with space $text = str_replace("\t", ' ', $text); // replace with space $text = preg_replace('/\s+/', ' ', $text); // remove multiple consecutive spaces $text = preg_replace('/^[\s]/', '', $text); // Remove leading space from excerpt $text = preg_replace('/[\s]$/', '', $text); // Remove trailing space from excerpt // If we are already within the limit, just return the text if (mb_strlen($text) <= $characters) { return $text; } // Truncate to character limit if longer than requested $text = substr($text, 0, $characters); // We don't want the string cut mid-word, so search for the last space and trim there $lastSpacePosition = strrpos($text, ' '); if (isset($lastSpacePosition)) { // Cut the text at this last word $text = substr($text, 0, $lastSpacePosition); } return $text; }
[ "public", "function", "truncateHtmlText", "(", "$", "text", ",", "$", "characters", "=", "300", ")", "{", "// Clean up html tags and special characters", "$", "text", "=", "preg_replace", "(", "'/<[^>]*>/'", ",", "' '", ",", "$", "text", ")", ";", "$", "text",...
Truncate HTML Text Accepts an HTML string, and returns just the unformatted text, truncated to the number of words @param string $text Input HTML string @param intger, $characters Number of characters to return @return string
[ "Truncate", "HTML", "Text" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Library/Utilities/Toolbox.php#L28-L55
train
PitonCMS/Engine
app/Library/Utilities/Toolbox.php
Toolbox.getDirectoryFiles
public function getDirectoryFiles($dirPath, $ignore = null) { $files = []; $pattern = '/^\..+'; // Ignore all dot files by default $splitCamelCase = '/(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/'; $ignoreDirectories = false; if (is_string($ignore) && !empty($ignore)) { // If 'dir' or 'directory' strings are set, then set flag to ignore directories if ($ignore === 'dir' || $ignore === 'directory') { $ignoreDirectories = true; } else { // Add it to the regex $pattern .= '|' . $ignore; } } elseif (is_array($ignore)) { // If 'dir' or 'directory' strings are set, then set flag to ignore directories if (in_array('dir', $ignore) || in_array('directory', $ignore)) { $ignoreDirectories = true; $ignore = array_diff($ignore, ['dir', 'directory']); } // Add it to the regex $multiIgnores = implode('|', $ignore); $pattern .= empty($multiIgnores) ? '' : '|' . $multiIgnores; } $pattern .= '/'; // Close regex if (is_dir($dirPath)) { foreach (new FilesystemIterator($dirPath) as $dirObject) { if (($ignoreDirectories && $dirObject->isDir()) || preg_match($pattern, $dirObject->getFilename())) { continue; } $baseName = $dirObject->getBasename('.' . $dirObject->getExtension()); $readableFileName = preg_replace($splitCamelCase, '$1 ', $baseName); $readableFileName = ucwords($readableFileName); $files[] = [ 'filename' => $dirObject->getFilename(), 'basename' => $baseName, 'readname' => $readableFileName ]; } } return $files; }
php
public function getDirectoryFiles($dirPath, $ignore = null) { $files = []; $pattern = '/^\..+'; // Ignore all dot files by default $splitCamelCase = '/(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/'; $ignoreDirectories = false; if (is_string($ignore) && !empty($ignore)) { // If 'dir' or 'directory' strings are set, then set flag to ignore directories if ($ignore === 'dir' || $ignore === 'directory') { $ignoreDirectories = true; } else { // Add it to the regex $pattern .= '|' . $ignore; } } elseif (is_array($ignore)) { // If 'dir' or 'directory' strings are set, then set flag to ignore directories if (in_array('dir', $ignore) || in_array('directory', $ignore)) { $ignoreDirectories = true; $ignore = array_diff($ignore, ['dir', 'directory']); } // Add it to the regex $multiIgnores = implode('|', $ignore); $pattern .= empty($multiIgnores) ? '' : '|' . $multiIgnores; } $pattern .= '/'; // Close regex if (is_dir($dirPath)) { foreach (new FilesystemIterator($dirPath) as $dirObject) { if (($ignoreDirectories && $dirObject->isDir()) || preg_match($pattern, $dirObject->getFilename())) { continue; } $baseName = $dirObject->getBasename('.' . $dirObject->getExtension()); $readableFileName = preg_replace($splitCamelCase, '$1 ', $baseName); $readableFileName = ucwords($readableFileName); $files[] = [ 'filename' => $dirObject->getFilename(), 'basename' => $baseName, 'readname' => $readableFileName ]; } } return $files; }
[ "public", "function", "getDirectoryFiles", "(", "$", "dirPath", ",", "$", "ignore", "=", "null", ")", "{", "$", "files", "=", "[", "]", ";", "$", "pattern", "=", "'/^\\..+'", ";", "// Ignore all dot files by default", "$", "splitCamelCase", "=", "'/(?<=[a-z])(...
Get Directory Files Scans a given directory, and returns a multi-dimension array of file names Ignores '.' '..' and sub directories by default $ignore accepts file names or regex patterns to ignore @param string $dirPath Path to directory to scan @param mixed $ignore String | Array @return array
[ "Get", "Directory", "Files" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Library/Utilities/Toolbox.php#L97-L145
train
drdplusinfo/tables
DrdPlus/Tables/Combat/Attacks/Partials/AbstractAttackNumberByDistanceTable.php
AbstractAttackNumberByDistanceTable.getOrderedByDistanceAsc
protected function getOrderedByDistanceAsc(): array { $values = $this->getIndexedValues(); uksort($values, function ($oneDistanceInMeters, $anotherDistanceInMeters) { /** @noinspection ExceptionsAnnotatingAndHandlingInspection */ $oneDistanceInMeters = ToFloat::toPositiveFloat($oneDistanceInMeters); /** @noinspection ExceptionsAnnotatingAndHandlingInspection */ $anotherDistanceInMeters = ToFloat::toPositiveFloat($anotherDistanceInMeters); return $oneDistanceInMeters <=> $anotherDistanceInMeters; // lowest first }); return $values; }
php
protected function getOrderedByDistanceAsc(): array { $values = $this->getIndexedValues(); uksort($values, function ($oneDistanceInMeters, $anotherDistanceInMeters) { /** @noinspection ExceptionsAnnotatingAndHandlingInspection */ $oneDistanceInMeters = ToFloat::toPositiveFloat($oneDistanceInMeters); /** @noinspection ExceptionsAnnotatingAndHandlingInspection */ $anotherDistanceInMeters = ToFloat::toPositiveFloat($anotherDistanceInMeters); return $oneDistanceInMeters <=> $anotherDistanceInMeters; // lowest first }); return $values; }
[ "protected", "function", "getOrderedByDistanceAsc", "(", ")", ":", "array", "{", "$", "values", "=", "$", "this", "->", "getIndexedValues", "(", ")", ";", "uksort", "(", "$", "values", ",", "function", "(", "$", "oneDistanceInMeters", ",", "$", "anotherDista...
Values may be already ordered from file, but have to be sure. @return array
[ "Values", "may", "be", "already", "ordered", "from", "file", "but", "have", "to", "be", "sure", "." ]
7a577ddbd1748369eec4e84effcc92ffcb54d1f3
https://github.com/drdplusinfo/tables/blob/7a577ddbd1748369eec4e84effcc92ffcb54d1f3/DrdPlus/Tables/Combat/Attacks/Partials/AbstractAttackNumberByDistanceTable.php#L35-L48
train
vanilla/garden-db
src/Drivers/MySqlDb.php
MySqlDb.buildSelect
protected function buildSelect($table, array $where, array $options = []) { $options += ['limit' => 0]; $sql = ''; // Build the select clause. if (!empty($options['columns'])) { $columns = array(); foreach ($options['columns'] as $value) { $columns[] = $this->escape($value); } $sql .= 'select '.implode(', ', $columns); } else { $sql .= "select *"; } // Build the from clause. if ($table instanceof Literal) { $table = $table->getValue($this); } else { $table = $this->prefixTable($table); } $sql .= "\nfrom $table"; // Build the where clause. $whereString = $this->buildWhere($where, Db::OP_AND); if ($whereString) { $sql .= "\nwhere ".$whereString; } // Build the order. if (!empty($options['order'])) { $orders = []; foreach ($options['order'] as $column) { if ($column[0] === '-') { $order = $this->escape(substr($column, 1)).' desc'; } else { $order = $this->escape($column); } $orders[] = $order; } $sql .= "\norder by ".implode(', ', $orders); } // Build the limit, offset. if (!empty($options['limit'])) { $limit = (int)$options['limit']; $sql .= "\nlimit $limit"; } if (!empty($options['offset'])) { $sql .= ' offset '.((int)$options['offset']); } elseif (isset($options['page'])) { $offset = $options['limit'] * ($options['page'] - 1); $sql .= ' offset '.$offset; } return $sql; }
php
protected function buildSelect($table, array $where, array $options = []) { $options += ['limit' => 0]; $sql = ''; // Build the select clause. if (!empty($options['columns'])) { $columns = array(); foreach ($options['columns'] as $value) { $columns[] = $this->escape($value); } $sql .= 'select '.implode(', ', $columns); } else { $sql .= "select *"; } // Build the from clause. if ($table instanceof Literal) { $table = $table->getValue($this); } else { $table = $this->prefixTable($table); } $sql .= "\nfrom $table"; // Build the where clause. $whereString = $this->buildWhere($where, Db::OP_AND); if ($whereString) { $sql .= "\nwhere ".$whereString; } // Build the order. if (!empty($options['order'])) { $orders = []; foreach ($options['order'] as $column) { if ($column[0] === '-') { $order = $this->escape(substr($column, 1)).' desc'; } else { $order = $this->escape($column); } $orders[] = $order; } $sql .= "\norder by ".implode(', ', $orders); } // Build the limit, offset. if (!empty($options['limit'])) { $limit = (int)$options['limit']; $sql .= "\nlimit $limit"; } if (!empty($options['offset'])) { $sql .= ' offset '.((int)$options['offset']); } elseif (isset($options['page'])) { $offset = $options['limit'] * ($options['page'] - 1); $sql .= ' offset '.$offset; } return $sql; }
[ "protected", "function", "buildSelect", "(", "$", "table", ",", "array", "$", "where", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "options", "+=", "[", "'limit'", "=>", "0", "]", ";", "$", "sql", "=", "''", ";", "// Build the select ...
Build a sql select statement. @param string|Identifier $table The name of the main table. @param array $where The where filter. @param array $options An array of additional query options. @return string Returns the select statement as a string. @see Db::get()
[ "Build", "a", "sql", "select", "statement", "." ]
2634229fb7a161f649ad371e59a973ccbbe72247
https://github.com/vanilla/garden-db/blob/2634229fb7a161f649ad371e59a973ccbbe72247/src/Drivers/MySqlDb.php#L134-L192
train
vanilla/garden-db
src/Drivers/MySqlDb.php
MySqlDb.getDbName
private function getDbName() { if (!isset($this->dbname)) { $this->dbname = $this->getPDO()->query('select database()')->fetchColumn(); } return $this->dbname; }
php
private function getDbName() { if (!isset($this->dbname)) { $this->dbname = $this->getPDO()->query('select database()')->fetchColumn(); } return $this->dbname; }
[ "private", "function", "getDbName", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "dbname", ")", ")", "{", "$", "this", "->", "dbname", "=", "$", "this", "->", "getPDO", "(", ")", "->", "query", "(", "'select database()'", ")", "-...
Get the current database name. @return mixed
[ "Get", "the", "current", "database", "name", "." ]
2634229fb7a161f649ad371e59a973ccbbe72247
https://github.com/vanilla/garden-db/blob/2634229fb7a161f649ad371e59a973ccbbe72247/src/Drivers/MySqlDb.php#L340-L345
train
vanilla/garden-db
src/Drivers/MySqlDb.php
MySqlDb.fetchIndexesDb
protected function fetchIndexesDb($table = '') { $stm = $this->get( new Identifier('information_schema', 'STATISTICS'), [ 'TABLE_SCHEMA' => $this->getDbName(), 'TABLE_NAME' => $this->prefixTable($table, false) ], [ 'columns' => [ 'INDEX_NAME', 'COLUMN_NAME', 'NON_UNIQUE' ], 'order' => ['INDEX_NAME', 'SEQ_IN_INDEX'] ] ); $indexRows = $stm->fetchAll(PDO::FETCH_ASSOC | PDO::FETCH_GROUP); $indexes = []; foreach ($indexRows as $indexName => $columns) { $index = [ 'type' => null, 'columns' => array_column($columns, 'COLUMN_NAME'), 'name' => $indexName ]; if ($indexName === 'PRIMARY') { $index['type'] = Db::INDEX_PK; } else { $index['type'] = $columns[0]['NON_UNIQUE'] ? Db::INDEX_IX : Db::INDEX_UNIQUE; } $indexes[] = $index; } return $indexes; }
php
protected function fetchIndexesDb($table = '') { $stm = $this->get( new Identifier('information_schema', 'STATISTICS'), [ 'TABLE_SCHEMA' => $this->getDbName(), 'TABLE_NAME' => $this->prefixTable($table, false) ], [ 'columns' => [ 'INDEX_NAME', 'COLUMN_NAME', 'NON_UNIQUE' ], 'order' => ['INDEX_NAME', 'SEQ_IN_INDEX'] ] ); $indexRows = $stm->fetchAll(PDO::FETCH_ASSOC | PDO::FETCH_GROUP); $indexes = []; foreach ($indexRows as $indexName => $columns) { $index = [ 'type' => null, 'columns' => array_column($columns, 'COLUMN_NAME'), 'name' => $indexName ]; if ($indexName === 'PRIMARY') { $index['type'] = Db::INDEX_PK; } else { $index['type'] = $columns[0]['NON_UNIQUE'] ? Db::INDEX_IX : Db::INDEX_UNIQUE; } $indexes[] = $index; } return $indexes; }
[ "protected", "function", "fetchIndexesDb", "(", "$", "table", "=", "''", ")", "{", "$", "stm", "=", "$", "this", "->", "get", "(", "new", "Identifier", "(", "'information_schema'", ",", "'STATISTICS'", ")", ",", "[", "'TABLE_SCHEMA'", "=>", "$", "this", ...
Get the indexes from the database. @param string $table The name of the table to get the indexes for. @return array|null
[ "Get", "the", "indexes", "from", "the", "database", "." ]
2634229fb7a161f649ad371e59a973ccbbe72247
https://github.com/vanilla/garden-db/blob/2634229fb7a161f649ad371e59a973ccbbe72247/src/Drivers/MySqlDb.php#L428-L463
train
vanilla/garden-db
src/Drivers/MySqlDb.php
MySqlDb.buildInsert
protected function buildInsert($table, array $row, $options = []) { if (self::val(Db::OPTION_UPSERT, $options)) { return $this->buildUpsert($table, $row, $options); } elseif (self::val(Db::OPTION_IGNORE, $options)) { $sql = 'insert ignore '; } elseif (self::val(Db::OPTION_REPLACE, $options)) { $sql = 'replace '; } else { $sql = 'insert '; } $sql .= $this->prefixTable($table); // Add the list of values. $sql .= "\n".$this->bracketList(array_keys($row), '`'). "\nvalues".$this->bracketList($row, "'"); return $sql; }
php
protected function buildInsert($table, array $row, $options = []) { if (self::val(Db::OPTION_UPSERT, $options)) { return $this->buildUpsert($table, $row, $options); } elseif (self::val(Db::OPTION_IGNORE, $options)) { $sql = 'insert ignore '; } elseif (self::val(Db::OPTION_REPLACE, $options)) { $sql = 'replace '; } else { $sql = 'insert '; } $sql .= $this->prefixTable($table); // Add the list of values. $sql .= "\n".$this->bracketList(array_keys($row), '`'). "\nvalues".$this->bracketList($row, "'"); return $sql; }
[ "protected", "function", "buildInsert", "(", "$", "table", ",", "array", "$", "row", ",", "$", "options", "=", "[", "]", ")", "{", "if", "(", "self", "::", "val", "(", "Db", "::", "OPTION_UPSERT", ",", "$", "options", ")", ")", "{", "return", "$", ...
Build an insert statement. @param string|Identifier $table The name of the table to insert to. @param array $row The row to insert. @param array $options An array of options for the insert. See {@link Db::insert} for the options. @return string Returns the the sql string of the insert statement.
[ "Build", "an", "insert", "statement", "." ]
2634229fb7a161f649ad371e59a973ccbbe72247
https://github.com/vanilla/garden-db/blob/2634229fb7a161f649ad371e59a973ccbbe72247/src/Drivers/MySqlDb.php#L506-L524
train