_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q249300 | WorkerPool.setSemaphore | validation | public function setSemaphore(Semaphore $semaphore) {
if ($this->created) {
throw new WorkerPoolException('Cannot set the Worker Pool Size for a created pool.');
}
if (!$semaphore->isCreated()) {
throw new \InvalidArgumentException('The Semaphore hasn\'t yet been created.');
}
$this->semaphore = $semaphore;
return $this;
} | php | {
"resource": ""
} |
q249301 | WorkerPool.createWorker | validation | private function createWorker($i) {
$sockets = array();
if (socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $sockets) === FALSE) {
// clean_up using posix_kill & pcntl_wait
throw new \RuntimeException('socket_create_pair failed.');
return;
}
$processId = pcntl_fork();
if ($processId < 0) {
// cleanup using posix_kill & pcntl_wait
throw new \RuntimeException('pcntl_fork failed.');
return;
}
elseif ($processId === 0) {
// WE ARE IN THE CHILD
$this->workerProcesses = new ProcessDetailsCollection(); // we do not have any children
$this->workerPoolSize = 0; // we do not have any children
socket_close($sockets[1]); // close the parent socket
$this->runWorkerProcess($this->worker, new SimpleSocket($sockets[0]), $i);
}
else {
// WE ARE IN THE PARENT
socket_close($sockets[0]); // close child socket
// create the child
$this->workerProcesses->addFree(new ProcessDetails($processId, new SimpleSocket($sockets[1])));
}
} | php | {
"resource": ""
} |
q249302 | WorkerPool.runWorkerProcess | validation | protected function runWorkerProcess(WorkerInterface $worker, SimpleSocket $simpleSocket, $i) {
$replacements = array(
'basename' => basename($_SERVER['PHP_SELF']),
'fullname' => $_SERVER['PHP_SELF'],
'class' => get_class($worker),
'i' => $i,
'state' => 'free'
);
ProcessDetails::setProcessTitle($this->childProcessTitleFormat, $replacements);
$this->worker->onProcessCreate($this->semaphore);
while (TRUE) {
$output = array('pid' => getmypid());
try {
$replacements['state'] = 'free';
ProcessDetails::setProcessTitle($this->childProcessTitleFormat, $replacements);
$cmd = $simpleSocket->receive();
// invalid response from parent?
if (!isset($cmd['cmd'])) {
break;
}
$replacements['state'] = 'busy';
ProcessDetails::setProcessTitle($this->childProcessTitleFormat, $replacements);
if ($cmd['cmd'] == 'run') {
try {
$output['data'] = $this->worker->run($cmd['data']);
} catch (\Exception $e) {
$output['workerException'] = array(
'class' => get_class($e),
'message' => $e->getMessage(),
'trace' => $e->getTraceAsString()
);
}
// send back the output
$simpleSocket->send($output);
} elseif ($cmd['cmd'] == 'exit') {
break;
}
} catch (SimpleSocketException $e) {
break;
} catch (\Exception $e) {
// send Back the exception
$output['poolException'] = array(
'class' => get_class($e),
'message' => $e->getMessage(),
'trace' => $e->getTraceAsString()
);
$simpleSocket->send($output);
}
}
$this->worker->onProcessDestroy();
$this->exitPhp(0);
} | php | {
"resource": ""
} |
q249303 | WorkerPool.destroy | validation | public function destroy($maxWaitSecs = null) {
if ($maxWaitSecs === null) {
$maxWaitSecs = $this->child_timeout_sec;
}
if (!$this->created) {
throw new WorkerPoolException('The pool hasn\'t yet been created.');
}
$this->created = FALSE;
if ($this->parentPid === getmypid()) {
$maxWaitSecs = ((int)$maxWaitSecs) * 2;
if ($maxWaitSecs <= 1) {
$maxWaitSecs = 2;
}
// send the exit instruction
foreach ($this->workerProcesses as $processDetails) {
try {
$processDetails->getSocket()->send(array('cmd' => 'exit'));
} catch (\Exception $e) {
}
}
// wait up to 10 seconds
for ($i = 0; $i < $maxWaitSecs; $i++) {
usleep(500000); // 0.5 seconds
pcntl_signal_dispatch();
if ($this->workerPoolSize == 0) {
break;
}
}
// reset signals
foreach ($this->signals as $signo) {
pcntl_signal($signo, SIG_DFL);
}
// kill all remaining processes
$this->workerProcesses->killAllProcesses();
usleep(500000); // 0.5 seconds
// reap the remaining signals
$this->reaper();
// destroy the semaphore
$this->semaphore->destroy();
unset($this->workerProcesses);
}
return $this;
} | php | {
"resource": ""
} |
q249304 | WorkerPool.reaper | validation | protected function reaper($pid = -1) {
if (!is_int($pid)) {
$pid = -1;
}
$childpid = pcntl_waitpid($pid, $status, WNOHANG);
while ($childpid > 0) {
$stopSignal = pcntl_wstopsig($status);
if (pcntl_wifexited($stopSignal) === FALSE) {
array_push($this->results, array(
'pid' => $childpid,
'abnormalChildReturnCode' => $stopSignal
));
}
$processDetails = $this->workerProcesses->getProcessDetails($childpid);
if ($processDetails !== NULL) {
$this->workerPoolSize--;
$this->workerProcesses->remove($processDetails);
unset($processDetails);
}
$childpid = pcntl_waitpid($pid, $status, WNOHANG);
}
} | php | {
"resource": ""
} |
q249305 | WorkerPool.getFreeAndBusyWorkers | validation | public function getFreeAndBusyWorkers() {
$free = $this->getFreeWorkers();
return array(
'free' => $free,
'busy' => $this->workerPoolSize - $free,
'total' => $this->workerPoolSize
);
} | php | {
"resource": ""
} |
q249306 | WorkerPool.getNextFreeWorker | validation | protected function getNextFreeWorker() {
$sec = 0;
while (TRUE) {
$this->collectWorkerResults($sec);
$freeProcess = $this->workerProcesses->takeFreeProcess();
if ($freeProcess !== NULL) {
return $freeProcess;
}
$sec = $this->child_timeout_sec;
if ($this->workerPoolSize <= 0) {
throw new WorkerPoolException('All workers were gone.');
}
}
return NULL;
} | php | {
"resource": ""
} |
q249307 | WorkerPool.collectWorkerResults | validation | protected function collectWorkerResults($sec = 0) {
$this->respawnIfRequired();
// dispatch signals
pcntl_signal_dispatch();
if (isset($this->workerProcesses) === FALSE) {
throw new WorkerPoolException('There is no list of worker processes. Maybe you destroyed the worker pool?', 1401179881);
}
$result = SimpleSocket::select($this->workerProcesses->getSockets(), array(), array(), $sec);
foreach ($result['read'] as $socket) {
/** @var $socket SimpleSocket */
$processId = $socket->annotation['pid'];
$result = $socket->receive();
$possibleArrayKeys = array('data', 'poolException', 'workerException');
if (is_array($result) && count(($resultTypes = array_intersect(array_keys($result), $possibleArrayKeys))) === 1) {
// If the result has the expected format, free the worker and store the result.
// Otherwise, the worker may be abnormally terminated (fatal error, exit(), ...) and will
// fall in the reapers arms.
$this->workerProcesses->registerFreeProcessId($processId);
$result['pid'] = $processId;
$resultType = reset($resultTypes);
// Do not store NULL
if ($resultType !== 'data' || $result['data'] !== NULL) {
array_push($this->results, $result);
}
}
}
// dispatch signals
pcntl_signal_dispatch();
$this->respawnIfRequired();
} | php | {
"resource": ""
} |
q249308 | WorkerPool.run | validation | public function run($input) {
while ($this->workerPoolSize > 0) {
try {
$processDetailsOfFreeWorker = $this->getNextFreeWorker();
$processDetailsOfFreeWorker->getSocket()->send(array('cmd' => 'run', 'data' => $input));
return $processDetailsOfFreeWorker->getPid();
} catch (\Exception $e) {
pcntl_signal_dispatch();
}
}
throw new WorkerPoolException('Unable to run the task.');
} | php | {
"resource": ""
} |
q249309 | LdapConnection.connect | validation | public function connect()
{
$port = $this->ssl ? $this::PORT_SSL : $this::PORT;
$hostname = $this->domainController->getHostname();
return $this->connection = ldap_connect($hostname, $port);
} | php | {
"resource": ""
} |
q249310 | LdapConnection.bind | validation | public function bind($username, $password)
{
// Tries to run the LDAP Connection as TLS
if ($this->tls) {
if ( ! ldap_start_tls($this->connection)) {
throw new ConnectionException('Unable to Connect to LDAP using TLS.');
}
}
try {
$this->bound = ldap_bind($this->connection, $username, $password);
} catch (ErrorException $e) {
$this->bound = false;
}
return $this->bound;
} | php | {
"resource": ""
} |
q249311 | LdapConnection.getDomainControllerStrategy | validation | private function getDomainControllerStrategy(array $domain_controller)
{
$protocol = $this->ssl ? $this::PROTOCOL_SSL : $this::PROTOCOL;
if (count($domain_controller) === 1) {
return new SingleDomainController($protocol, $domain_controller);
}
if ($this->backup === true) {
return new RebindDomainController($protocol, $domain_controller);
} else {
return new LoadBalancingDomainController($protocol, $domain_controller);
}
} | php | {
"resource": ""
} |
q249312 | LdapAuthUserProvider.retrieveByCredentials | validation | public function retrieveByCredentials(array $credentials)
{
$username = $credentials['username'];
$result = $this->ldap->find($username);
if( !is_null($result) ){
$user = new $this->model;
$user->build( $result );
return $user;
}
return null;
} | php | {
"resource": ""
} |
q249313 | LdapAuthUserProvider.validateCredentials | validation | public function validateCredentials(Authenticatable $user, array $credentials)
{
return $this->ldap->auth(
$user->dn,
$credentials['password']
);
} | php | {
"resource": ""
} |
q249314 | GuzzleClient.post | validation | public function post($endpoint, $data, $headers = [])
{
$request = new Request('POST', $endpoint, $headers, $data);
$response = $this->guzzle->send($request);
return $this->handle($response);
} | php | {
"resource": ""
} |
q249315 | GuzzleClient.delete | validation | public function delete($endpoint, $headers = [])
{
$request = new Request('DELETE', $endpoint, $headers);
$response = $this->guzzle->send($request);
return $this->handle($response);
} | php | {
"resource": ""
} |
q249316 | GuzzleClient.handle | validation | private function handle(Response $response)
{
$stream = stream_for($response->getBody());
$data = json_decode($stream->getContents());
return $data;
} | php | {
"resource": ""
} |
q249317 | Firebase.post | validation | public function post($endpoint, $data, $query = [])
{
$endpoint = $this->buildUri($endpoint, $query);
$headers = $this->buildHeaders();
$data = $this->prepareData($data);
$this->response = $this->client->post($endpoint, $data, $headers);
return $this->response;
} | php | {
"resource": ""
} |
q249318 | Firebase.delete | validation | public function delete($endpoint, $query = [])
{
$endpoint = $this->buildUri($endpoint, $query);
$headers = $this->buildHeaders();
$this->response = $this->client->delete($endpoint, $headers);
return $this->response;
} | php | {
"resource": ""
} |
q249319 | Firebase.buildUri | validation | protected function buildUri($endpoint, $options = [])
{
if ($this->token !== '') {
$options['auth'] = $this->token;
}
return $this->base.'/'.ltrim($endpoint, '/').'.json?'.http_build_query($options, '', '&');
} | php | {
"resource": ""
} |
q249320 | Log.& | validation | public function &getErrors($channel = null)
{
// Uses the passed channel or fallback to the current selected channel
$channel = $this->namespaceChannel($channel);
if ( ! isset($this->console['errors'][$channel]) ) {
$this->console['errors'][$channel] = array();
}
return $this->console['errors'][$channel];
} | php | {
"resource": ""
} |
q249321 | Log.& | validation | public function &getReports($channel = null)
{
// Uses the passed channel or fallback to the current selected channel
$channel = $this->namespaceChannel($channel);
if (!isset($this->console['reports'][$channel])) {
// Create a new empty array to return as reference
$this->console['reports'][$channel] = array();
}
return $this->console['reports'][$channel];
} | php | {
"resource": ""
} |
q249322 | Log.error | validation | public function error($message)
{
if ($message) {
if (is_int($message) && isset($this->errorList[$message])) {
/*
* If the message is of type integer use a predefine
* error message
*/
$errorMessage = $this->errorList[$message];
$this->report("Error[{$message}]: {$errorMessage}"); //Report The error
} else {
$errorMessage = $message;
$this->report("Error: {$errorMessage}"); //Report The error
}
$errors = &$this->getErrors();
$errors[] = $errorMessage;
}
return $this;
} | php | {
"resource": ""
} |
q249323 | Log.report | validation | public function report($message)
{
$channel = $this->currentChannel;
if ($message) {
// Log the report to the console
$reports = &$this->getReports($channel);
$reports[] = $message;
}
return $this;
} | php | {
"resource": ""
} |
q249324 | Log.& | validation | public function &getFormErrors($channel = '')
{
// Uses the passed channel or fallback to the current selected channel
$channel = $this->namespaceChannel($channel);
if (!isset($this->console['form'][$channel])) {
$this->console['form'][$channel] = array();
}
return $this->console['form'][$channel];
} | php | {
"resource": ""
} |
q249325 | Log.clearErrors | validation | public function clearErrors($channelName='')
{
$channel = $this->namespaceChannel($channelName);
// Clear any existing errors for the channel
$this->console['errors'][$channel] = array();
$this->console['form'][$channel] = array();
} | php | {
"resource": ""
} |
q249326 | Log.addPredefinedError | validation | public function addPredefinedError($id, $message = '')
{
if (is_array($id)) {
$this->errorList = array_diff_key($this->errorList, $id) + $id;
} else {
$this->errorList[$id] = $message;
}
} | php | {
"resource": ""
} |
q249327 | Log.cleanConsole | validation | private function cleanConsole()
{
$channel = $this->namespaceChannel($this->currentChannel);
if (empty($this->console['errors'][$channel])) {
unset($this->console['errors'][$channel]);
}
if (empty($this->console['form'][$channel])) {
unset($this->console['form'][$channel]);
}
if (empty($this->console['reports'][$channel])) {
unset($this->console['reports'][$channel]);
}
} | php | {
"resource": ""
} |
q249328 | DB.getConnection | validation | public function getConnection()
{
if (!($this->log instanceof Log)) {
$this->log = new Log('DB');
}
// Use cached connection if already connected to server
if ($this->connection instanceof \PDO) {
return $this->connection;
}
$this->log->report('Connecting to database...');
try{
$this->connection = new \PDO($this->generateDSN(), $this->user, $this->password);
$this->log->report('Connected to database.');
} catch ( \PDOException $e ){
$this->log->error('Failed to connect to database, [SQLSTATE] ' . $e->getCode());
}
// Check is the connection to server succeed
if ($this->connection instanceof \PDO) {
return $this->connection;
} else {
// There was an error connecting to the DB server
return false;
}
} | php | {
"resource": ""
} |
q249329 | Hash.generateUserPassword | validation | public function generateUserPassword(User $user, $password, $generateOld = false)
{
$registrationDate = $user->RegDate;
$pre = $this->encode($registrationDate);
$pos = substr($registrationDate, 5, 1);
$post = $this->encode($registrationDate * (substr($registrationDate, $pos, 1)));
$finalString = $pre . $password . $post;
return $generateOld ? md5($finalString) : sha1($finalString);
} | php | {
"resource": ""
} |
q249330 | Hash.encode | validation | static protected function encode($number)
{
$k = self::$encoder;
preg_match_all("/[1-9][0-9]|[0-9]/", $number, $a);
$n = '';
$o = count($k);
foreach ($a[0] as $i) {
if ($i < $o) {
$n .= $k[$i];
} else {
$n .= '1' . $k[$i - $o];
}
}
return $n;
} | php | {
"resource": ""
} |
q249331 | Hash.generate | validation | static public function generate($uid = 0, $hash = false)
{
if ($uid) {
$e_uid = self::encode($uid);
$e_uid_length = strlen($e_uid);
$e_uid_length = str_pad($e_uid_length, 2, 0, STR_PAD_LEFT);
$e_uid_pos = rand(10, 32 - $e_uid_length - 1);
if (!$hash) {
$hash = sha1(uniqid(rand(), true));
}
$code = $e_uid_pos . $e_uid_length;
$code .= substr($hash, 0, $e_uid_pos - strlen($code));
$code .= $e_uid;
$code .= substr($hash, strlen($code));
return $code;
} else {
return sha1(uniqid(rand(), true));
}
} | php | {
"resource": ""
} |
q249332 | Hash.examine | validation | static public function examine($hash)
{
if (strlen($hash) == 40 && preg_match("/^[0-9]{4}/", $hash)) {
$e_uid_pos = substr($hash, 0, 2);
$e_uid_length = substr($hash, 2, 2);
$e_uid = substr($hash, $e_uid_pos, $e_uid_length);
$uid = self::decode($e_uid);
preg_match('/^([0-9]{4})(.{2,' . ($e_uid_pos - 4) . '})(' . $e_uid . ')/', $hash, $excerpt);
$partial = $excerpt[2];
return array($uid, $partial);
}
else
{
/*
* The hash is not valid
*/
return array(false, false);
}
} | php | {
"resource": ""
} |
q249333 | Hash.decode | validation | static public function decode($number)
{
$k = self::$encoder;
preg_match_all('/[1][a-zA-Z]|[2-9]|[a-zA-Z]|[0]/', $number, $a);
$n = '';
$o = count($k);
foreach ($a[0] as $i) {
$f = preg_match('/1([a-zA-Z])/', $i, $v);
if ($f == true) {
$i = $o + array_search($v[1], $k);
} else {
$i = array_search($i, $k);
}
$n .= $i;
}
return $n;
} | php | {
"resource": ""
} |
q249334 | Collection.get | validation | public function get($keyPath)
{
$stops = explode('.', $keyPath);
$value = $this;
foreach ($stops as $key) {
if ($value instanceof Collection) {
// Move one step deeper into the collection
$value = $value->$key;
} else {
/*
* One more stops still pending and the current
* value is not a collection, terminate iteration
* and set value to null
*/
$value = null;
break;
}
}
return $value;
} | php | {
"resource": ""
} |
q249335 | Collection.set | validation | public function set($keyPath, $value)
{
$stops = explode('.', $keyPath);
$currentLocation = $previousLocation = $this;
foreach ($stops as $key) {
if ($currentLocation instanceof Collection) {
// Move one step deeper into the collection
if (!($currentLocation->$key instanceof Collection)) {
$currentLocation->$key = array();
}
} else {
$currentLocation = array();
$currentLocation->$key = array();
}
$previousLocation = $currentLocation;
$currentLocation = $currentLocation->$key;
}
// Set the value
$previousLocation->$key = $value;
} | php | {
"resource": ""
} |
q249336 | Cookie.add | validation | public function add()
{
if (!headers_sent()) {
// Set the cookie via PHP headers
$added = setcookie(
$this->name,
$this->value,
round(time() + 60 * 60 * 24 * $this->lifetime),
$this->path,
$this->host
);
} else {
//Headers have been sent use JavaScript to set the cookie
echo "<script>";
echo '
function setCookie(c_name,value,expiredays){
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : "; expires="+exdate.toUTCString()) + "; domain="+ escape("' . $this->host . '") + "; path=" + escape("' . $this->path . '");
}
';
echo "setCookie('{$this->name}','{$this->value}',{$this->lifetime})";
echo "</script>";
$added = true;
}
return $added;
} | php | {
"resource": ""
} |
q249337 | Cookie.destroy | validation | public function destroy()
{
if (!is_null($this->getValue())) {
if (!headers_sent()) {
return setcookie(
$this->name,
'',
time() - 3600,
$this->path,
$this->host
); //Deletes Cookie
} else {
return false;
}
} else {
// The cookie does not exists, there is nothing to destroy
return true;
}
} | php | {
"resource": ""
} |
q249338 | Session.validate | validation | private function validate()
{
/*
* Get the correct IP
*/
$server = new Collection($_SERVER);
$ip = $server->HTTP_X_FORWARDED_FOR;
if (is_null($ip) && $server->REMOTE_ADDR)
{
$ip = $server->REMOTE_ADDR;
}
if (!is_null($this->_ip)) {
if ($this->_ip != $ip) {
/*
* Destroy the session in the IP stored in the session is different
* then the IP of the current request
*/
$this->destroy();
}
} else {
/*
* Save the current request IP in the session
*/
$this->_ip = $ip;
}
} | php | {
"resource": ""
} |
q249339 | UserBase.toCollection | validation | protected function toCollection($data)
{
if (is_array($data)) {
return new Collection($data);
} else {
if (!($data instanceof Collection)) {
// Invalid input type, return empty collection
$data = new Collection();
}
}
return $data;
} | php | {
"resource": ""
} |
q249340 | UserBase.validateAll | validation | protected function validateAll($includeAllRules = false)
{
if ($includeAllRules) {
/*
* Include fields that might not have been included
*/
$fieldData = new Collection(array_fill_keys(array_keys($this->_validations->toArray()), null));
$fieldData->update($this->_updates->toArray());
}
else
{
$fieldData = clone $this->_updates;
}
foreach ($fieldData->toArray() as $field => $val) {
//Match double fields
$field2 = $field . '2';
if (!is_null($fieldData->$field2)) {
// Compared the two double fields
if ($val != $fieldData->$field2) {
$this->log->formError($field, ucfirst($field) . 's did not match');
} else {
$this->log->report(ucfirst($field) . 's matched');
}
}
// Trim white spaces at end and start
if ($this->_updates->$field) {
$this->_updates->$field = trim($val);
}
// Check if a validation rule exists for the field
if ($validation = $this->_validations->$field) {
$this->validate($field, $validation->limit, $validation->regEx);
}
}
return !$this->log->hasError();
} | php | {
"resource": ""
} |
q249341 | UserBase.validate | validation | protected function validate($name, $limit, $regEx = false)
{
$Name = ucfirst($name);
$value = $this->_updates->$name;
$length = explode('-', $limit);
$min = intval($length[0]);
$max = intval($length[1]);
if (!$max and !$min) {
$this->log->error("Invalid second parameter for the $name validation");
return false;
}
if (!$value) {
if (is_null($value)) {
$this->log->report("Missing index $name from the input");
}
if (strlen($value) == $min) {
$this->log->report("$Name is blank and optional - skipped");
return true;
}
$this->log->formError($name, "$Name is required.");
return false;
}
// Validate the value maximum length
if (strlen($value) > $max) {
$this->log->formError($name, "The $Name is larger than $max characters.");
return false;
}
// Validate the value minimum length
if (strlen($value) < $min) {
$this->log->formError($name, "The $Name is too short. It should at least be $min characters long");
return false;
}
// Validate the value pattern
if ($regEx) {
preg_match($regEx, $value, $match);
if (preg_match($regEx, $value, $match) === 0) {
$this->log->formError($name, "The $Name \"{$value}\" is not valid");
return false;
}
}
/*
* If the execution reaches this point then the field value
* is considered to be valid
*/
$this->log->report("The $name is Valid");
return true;
} | php | {
"resource": ""
} |
q249342 | DB_Table.getRow | validation | public function getRow($arguments)
{
$sql = 'SELECT * FROM _table_ WHERE _arguments_ LIMIT 1';
if (!$stmt = $this->getStatement($sql, $arguments)) {
// Something went wrong executing the SQL statement
return false;
} else {
return $stmt->fetch();
}
} | php | {
"resource": ""
} |
q249343 | DB_Table.getStatement | validation | public function getStatement($sql, $args = false)
{
// The parsed sql statement
$query = $this->buildQuery($sql, $args);
if ($connection = $this->db->getConnection()) {
//Prepare the statement
if ($stmt = $connection->prepare($query)) {
//Log the SQL Query first
$this->log->report("SQL Statement: {$query}");
// When fetched return an object
$stmt->setFetchMode(\PDO::FETCH_INTO, new Collection());
// If arguments were passed execute the statement
if ($args) {
$this->log->report("SQL Data Sent: [" . implode(', ', $args) . "]");
$stmt->execute($args);
}
// Handles any error during execution
if ($stmt->errorCode() > 0) {
$error = $stmt->errorInfo();
$this->log->error("PDO({$error[0]})[{$error[1]}] {$error[2]}");
return false;
}
return $stmt;
} else {
$this->log->error('Failed to create a PDO statement with: ' . $query);
return false;
}
} else {
// Failed to connect to the database
return false;
}
} | php | {
"resource": ""
} |
q249344 | DB_Table.buildQuery | validation | private function buildQuery($sql, $arguments = null)
{
if (is_array($arguments)) {
$finalArgs = array();
foreach ($arguments as $field => $val) {
// Parametrize the arguments
$finalArgs[] = " {$field}=:{$field}";
}
// Join all the arguments as a string
$finalArgs = implode(' AND', $finalArgs);
if (strpos($sql, ' _arguments_')) {
// Place the arguments string in the placeholder
$sql = str_replace(' _arguments_', $finalArgs, $sql);
} else {
// Appends the parameters string the sql query
// $sql .= $finalArgs; TODO: Watch this expression if it is on use
}
}
//Replace the _table_ placeholder
$sql = str_replace(' _table_', " {$this->tableName} ", $sql);
return $sql;
} | php | {
"resource": ""
} |
q249345 | DB_Table.query | validation | public function query($sql, $arguments = false)
{
if (!$stmt = $this->getStatement($sql, $arguments)) {
// Something went wrong executing the SQL statement
return false;
} else {
return $stmt;
}
} | php | {
"resource": ""
} |
q249346 | DB_Table.runQuery | validation | public function runQuery($sql, $arguments = false)
{
if (!$stmt = $this->getStatement($sql, $arguments)) {
// Something went wrong executing the SQL statement
return false;
}
// If there are no arguments, execute the statement
if (!$arguments) {
$stmt->execute();
}
$rows = $stmt->rowCount();
if ($rows > 0) {
//Good, Rows where affected
$this->log->report("$rows row(s) where Affected");
return true;
} else {
//Bad, No Rows where Affected
$this->log->report('No rows were Affected');
return false;
}
} | php | {
"resource": ""
} |
q249347 | ContentReviewEmails.getEmailBody | validation | protected function getEmailBody($config, $variables)
{
$template = SSViewer::fromString($config->ReviewBody);
$value = $template->process(ArrayData::create($variables));
// Cast to HTML
return DBField::create_field('HTMLText', (string) $value);
} | php | {
"resource": ""
} |
q249348 | ContentReviewEmails.getTemplateVariables | validation | protected function getTemplateVariables($recipient, $config, $pages)
{
return [
'Subject' => $config->ReviewSubject,
'PagesCount' => $pages->count(),
'FromEmail' => $config->ReviewFrom,
'ToFirstName' => $recipient->FirstName,
'ToSurname' => $recipient->Surname,
'ToEmail' => $recipient->Email,
];
} | php | {
"resource": ""
} |
q249349 | ContentReviewDefaultSettings.getReviewFrom | validation | public function getReviewFrom()
{
$from = $this->owner->getField('ReviewFrom');
if ($from) {
return $from;
}
// Fall back to admin email
return Config::inst()->get(Email::class, 'admin_email');
} | php | {
"resource": ""
} |
q249350 | ContentReviewDefaultSettings.getWithDefault | validation | protected function getWithDefault($field)
{
$value = $this->owner->getField($field);
if ($value) {
return $value;
}
// fallback to default value
$defaults = $this->owner->config()->get('defaults');
if (isset($defaults[$field])) {
return $defaults[$field];
}
} | php | {
"resource": ""
} |
q249351 | ContentReviewCompatability.start | validation | public static function start()
{
$compatibility = [
self::SUBSITES => null,
];
if (ClassInfo::exists(Subsite::class)) {
$compatibility[self::SUBSITES] = Subsite::$disable_subsite_filter;
Subsite::disable_subsite_filter(true);
}
return $compatibility;
} | php | {
"resource": ""
} |
q249352 | ContentReviewNotificationJob.queueNextRun | validation | protected function queueNextRun()
{
$nextRun = new ContentReviewNotificationJob();
$nextRunTime = mktime(
Config::inst()->get(__CLASS__, 'next_run_hour'),
Config::inst()->get(__CLASS__, 'next_run_minute'),
0,
date("m"),
date("d") + Config::inst()->get(__CLASS__, 'next_run_in_days'),
date("Y")
);
singleton(QueuedJobService::class)->queueJob(
$nextRun,
date("Y-m-d H:i:s", $nextRunTime)
);
} | php | {
"resource": ""
} |
q249353 | SiteTreeContentReview.merge_owners | validation | public static function merge_owners(SS_List $groups, SS_List $members)
{
$contentReviewOwners = new ArrayList();
if ($groups->count()) {
$groupIDs = [];
foreach ($groups as $group) {
$familyIDs = $group->collateFamilyIDs();
if (is_array($familyIDs)) {
$groupIDs = array_merge($groupIDs, array_values($familyIDs));
}
}
array_unique($groupIDs);
if (count($groupIDs)) {
$groupMembers = DataObject::get(Member::class)
->where("\"Group\".\"ID\" IN (" . implode(",", $groupIDs) . ")")
->leftJoin("Group_Members", "\"Member\".\"ID\" = \"Group_Members\".\"MemberID\"")
/** @skipUpgrade */
->leftJoin('Group', "\"Group_Members\".\"GroupID\" = \"Group\".\"ID\"");
$contentReviewOwners->merge($groupMembers);
}
}
$contentReviewOwners->merge($members);
$contentReviewOwners->removeDuplicates();
return $contentReviewOwners;
} | php | {
"resource": ""
} |
q249354 | SiteTreeContentReview.getReviewDate | validation | public function getReviewDate(SiteTree $page = null)
{
if ($page === null) {
$page = $this->owner;
}
if ($page->obj('NextReviewDate')->exists()) {
return $page->obj('NextReviewDate');
}
$options = $this->owner->getOptions();
if (!$options) {
return false;
}
if (!$options->ReviewPeriodDays) {
return false;
}
// Failover to check on ReviewPeriodDays + LastEdited
$nextReviewUnixSec = strtotime(' + ' . $options->ReviewPeriodDays . ' days', DBDatetime::now()->getTimestamp());
$date = DBDate::create('NextReviewDate');
$date->setValue($nextReviewUnixSec);
return $date;
} | php | {
"resource": ""
} |
q249355 | SiteTreeContentReview.addReviewNote | validation | public function addReviewNote(Member $reviewer, $message)
{
$reviewLog = ContentReviewLog::create();
$reviewLog->Note = $message;
$reviewLog->ReviewerID = $reviewer->ID;
$this->owner->ReviewLogs()->add($reviewLog);
} | php | {
"resource": ""
} |
q249356 | SiteTreeContentReview.advanceReviewDate | validation | public function advanceReviewDate()
{
$nextDateTimestamp = false;
$options = $this->getOptions();
if ($options && $options->ReviewPeriodDays) {
$nextDateTimestamp = strtotime(
' + ' . $options->ReviewPeriodDays . ' days',
DBDatetime::now()->getTimestamp()
);
$this->owner->NextReviewDate = DBDate::create()->setValue($nextDateTimestamp)->Format(DBDate::ISO_DATE);
$this->owner->write();
}
return (bool)$nextDateTimestamp;
} | php | {
"resource": ""
} |
q249357 | SiteTreeContentReview.canBeReviewedBy | validation | public function canBeReviewedBy(Member $member = null)
{
if (!$this->owner->obj("NextReviewDate")->exists()) {
return false;
}
if ($this->owner->obj("NextReviewDate")->InFuture()) {
return false;
}
$options = $this->getOptions();
if (!$options) {
return false;
}
if (!$options
// Options can be a SiteConfig with different extension applied
|| (!$options->hasExtension(__CLASS__)
&& !$options->hasExtension(ContentReviewDefaultSettings::class))
) {
return false;
}
if ($options->OwnerGroups()->count() == 0 && $options->OwnerUsers()->count() == 0) {
return false;
}
if (!$member) {
return true;
}
if ($member->inGroups($options->OwnerGroups())) {
return true;
}
if ($options->OwnerUsers()->find("ID", $member->ID)) {
return true;
}
return false;
} | php | {
"resource": ""
} |
q249358 | SiteTreeContentReview.onBeforeWrite | validation | public function onBeforeWrite()
{
// Only update if DB fields have been changed
$changedFields = $this->owner->getChangedFields(true, 2);
if ($changedFields) {
$this->owner->LastEditedByName = $this->owner->getEditorName();
$this->owner->OwnerNames = $this->owner->getOwnerNames();
}
// If the user changed the type, we need to recalculate the review date.
if ($this->owner->isChanged("ContentReviewType", 2)) {
if ($this->owner->ContentReviewType == "Disabled") {
$this->setDefaultReviewDateForDisabled();
} elseif ($this->owner->ContentReviewType == "Custom") {
$this->setDefaultReviewDateForCustom();
} else {
$this->setDefaultReviewDateForInherited();
}
}
// Ensure that a inherited page always have a next review date
if ($this->owner->ContentReviewType == "Inherit" && !$this->owner->NextReviewDate) {
$this->setDefaultReviewDateForInherited();
}
// We need to update all the child pages that inherit this setting. We can only
// change children after this record has been created, otherwise the stageChildren
// method will grab all pages in the DB (this messes up unit testing)
if (!$this->owner->exists()) {
return;
}
// parent page change its review period
// && !$this->owner->isChanged('ContentReviewType', 2)
if ($this->owner->isChanged('ReviewPeriodDays', 2)) {
$nextReviewUnixSec = strtotime(
' + ' . $this->owner->ReviewPeriodDays . ' days',
DBDatetime::now()->getTimestamp()
);
$this->owner->NextReviewDate = DBDate::create()->setValue($nextReviewUnixSec)->Format('y-MM-dd');
}
} | php | {
"resource": ""
} |
q249359 | ReviewContentHandler.Form | validation | public function Form($object)
{
$placeholder = _t(__CLASS__ . '.Placeholder', 'Add comments (optional)');
$title = _t(__CLASS__ . '.MarkAsReviewedAction', 'Mark as reviewed');
$fields = FieldList::create([
HiddenField::create('ID', null, $object->ID),
HiddenField::create('ClassName', null, $object->baseClass()),
TextareaField::create('Review', '')
->setAttribute('placeholder', $placeholder)
->setSchemaData(['attributes' => ['placeholder' => $placeholder]])
]);
$action = FormAction::create('savereview', $title)
->setTitle($title)
->setUseButtonTag(false)
->addExtraClass('review-content__action btn btn-primary');
$actions = FieldList::create([$action]);
$form = Form::create($this->controller, $this->name, $fields, $actions)
->setHTMLID('Form_EditForm_ReviewContent')
->addExtraClass('form--no-dividers review-content__form');
return $form;
} | php | {
"resource": ""
} |
q249360 | ReviewContentHandler.submitReview | validation | public function submitReview($record, $data)
{
/** @var DataObject|SiteTreeContentReview $record */
if (!$this->canSubmitReview($record)) {
throw new ValidationException(_t(
__CLASS__ . '.ErrorReviewPermissionDenied',
'It seems you don\'t have the necessary permissions to submit a content review'
));
}
$notes = (!empty($data['Review']) ? $data['Review'] : _t(__CLASS__ . '.NoComments', '(no comments)'));
$record->addReviewNote(Security::getCurrentUser(), $notes);
$record->advanceReviewDate();
$request = $this->controller->getRequest();
$message = _t(__CLASS__ . '.Success', 'Review successfully added');
if ($request->getHeader('X-Formschema-Request')) {
return $message;
} elseif (Director::is_ajax()) {
$response = HTTPResponse::create($message, 200);
$response->addHeader('Content-Type', 'text/html; charset=utf-8');
return $response;
}
return $this->controller->redirectBack();
} | php | {
"resource": ""
} |
q249361 | ReviewContentHandler.canSubmitReview | validation | public function canSubmitReview($record)
{
if (!$record->canEdit()
|| !$record->hasMethod('canBeReviewedBy')
|| !$record->canBeReviewedBy(Security::getCurrentUser())
) {
return false;
}
return true;
} | php | {
"resource": ""
} |
q249362 | ContentReviewCMSExtension.ReviewContentForm | validation | public function ReviewContentForm(HTTPRequest $request)
{
// Get ID either from posted back value, or url parameter
$id = $request->param('ID') ?: $request->postVar('ID');
return $this->getReviewContentForm($id);
} | php | {
"resource": ""
} |
q249363 | ContentReviewCMSExtension.getReviewContentForm | validation | public function getReviewContentForm($id)
{
$page = $this->findRecord(['ID' => $id]);
$user = Security::getCurrentUser();
if (!$page->canEdit() || ($page->hasMethod('canBeReviewedBy') && !$page->canBeReviewedBy($user))) {
$this->owner->httpError(403, _t(
__CLASS__.'.ErrorItemPermissionDenied',
'It seems you don\'t have the necessary permissions to review this content'
));
return null;
}
$form = $this->getReviewContentHandler()->Form($page);
$form->setValidationResponseCallback(function (ValidationResult $errors) use ($form, $id) {
$schemaId = $this->owner->join_links($this->owner->Link('schema/ReviewContentForm'), $id);
return $this->getSchemaResponse($schemaId, $form, $errors);
});
return $form;
} | php | {
"resource": ""
} |
q249364 | ContentReviewCMSExtension.savereview | validation | public function savereview($data, Form $form)
{
$page = $this->findRecord($data);
$results = $this->getReviewContentHandler()->submitReview($page, $data);
if (is_null($results)) {
return null;
}
if ($this->getSchemaRequested()) {
// Send extra "message" data with schema response
$extraData = ['message' => $results];
$schemaId = $this->owner->join_links($this->owner->Link('schema/ReviewContentForm'), $page->ID);
return $this->getSchemaResponse($schemaId, $form, null, $extraData);
}
return $results;
} | php | {
"resource": ""
} |
q249365 | ContentReviewCMSExtension.findRecord | validation | protected function findRecord($data)
{
if (empty($data["ID"])) {
throw new HTTPResponse_Exception("No record ID", 404);
}
$page = null;
$id = $data["ID"];
if (is_numeric($id)) {
$page = SiteTree::get()->byID($id);
}
if (!$page || !$page->ID) {
throw new HTTPResponse_Exception("Bad record ID #{$id}", 404);
}
return $page;
} | php | {
"resource": ""
} |
q249366 | ContentReviewCMSExtension.getSchemaRequested | validation | protected function getSchemaRequested()
{
$parts = $this->owner->getRequest()->getHeader(LeftAndMain::SCHEMA_HEADER);
return !empty($parts);
} | php | {
"resource": ""
} |
q249367 | ContentReviewCMSExtension.getSchemaResponse | validation | protected function getSchemaResponse($schemaID, $form = null, ValidationResult $errors = null, $extraData = [])
{
$parts = $this->owner->getRequest()->getHeader(LeftAndMain::SCHEMA_HEADER);
$data = $this->owner
->getFormSchema()
->getMultipartSchema($parts, $schemaID, $form, $errors);
if ($extraData) {
$data = array_merge($data, $extraData);
}
$response = HTTPResponse::create(Convert::raw2json($data));
$response->addHeader('Content-Type', 'application/json');
return $response;
} | php | {
"resource": ""
} |
q249368 | UserIdentity.findByUsernameOrEmail | validation | public static function findByUsernameOrEmail($emailOrUsername)
{
if (filter_var($emailOrUsername, FILTER_VALIDATE_EMAIL)) {
return UserIdentity::findByEmail($emailOrUsername);
}
return UserIdentity::findByUsername($emailOrUsername);
} | php | {
"resource": ""
} |
q249369 | UserIdentity.findByPasswordResetToken | validation | public static function findByPasswordResetToken($id, $code)
{
if (!static::isPasswordResetTokenValid($code)) {
return NULL;
}
return static::findOne([
'id' => $id,
'password_reset_token' => $code,
'status' => self::STATUS_ACTIVE,
]);
} | php | {
"resource": ""
} |
q249370 | ProfileController.actionIndex | validation | public function actionIndex()
{
$profile = Profile::findOne(['uid' => Yii::$app->user->id]);
if ($profile == NULL)
throw new NotFoundHttpException;
return $this->render('index', ['profile' => $profile]);
} | php | {
"resource": ""
} |
q249371 | Twig_Error_Syntax.addSuggestions | validation | public function addSuggestions($name, array $items)
{
if (!$alternatives = self::computeAlternatives($name, $items)) {
return;
}
$this->appendMessage(sprintf(' Did you mean "%s"?', implode('", "', $alternatives)));
} | php | {
"resource": ""
} |
q249372 | Twig_Node_SandboxedPrint.removeNodeFilter | validation | protected function removeNodeFilter(Twig_Node $node)
{
if ($node instanceof Twig_Node_Expression_Filter) {
return $this->removeNodeFilter($node->getNode('node'));
}
return $node;
} | php | {
"resource": ""
} |
q249373 | Twig_Error.getSourceContext | validation | public function getSourceContext()
{
return $this->filename ? new Twig_Source($this->sourceCode, $this->filename, $this->sourcePath) : null;
} | php | {
"resource": ""
} |
q249374 | Twig_Error.setSourceContext | validation | public function setSourceContext(Twig_Source $source = null)
{
if (null === $source) {
$this->sourceCode = $this->filename = $this->sourcePath = null;
} else {
$this->sourceCode = $source->getCode();
$this->filename = $source->getName();
$this->sourcePath = $source->getPath();
}
$this->updateRepr();
} | php | {
"resource": ""
} |
q249375 | Twig_TemplateWrapper.renderBlock | validation | public function renderBlock($name, $context = array())
{
$context = $this->env->mergeGlobals($context);
$level = ob_get_level();
ob_start();
try {
$this->template->displayBlock($name, $context);
} catch (Exception $e) {
while (ob_get_level() > $level) {
ob_end_clean();
}
throw $e;
} catch (Throwable $e) {
while (ob_get_level() > $level) {
ob_end_clean();
}
throw $e;
}
return ob_get_clean();
} | php | {
"resource": ""
} |
q249376 | Twig_TemplateWrapper.displayBlock | validation | public function displayBlock($name, $context = array())
{
$this->template->displayBlock($name, $this->env->mergeGlobals($context));
} | php | {
"resource": ""
} |
q249377 | Twig_Environment.setCache | validation | public function setCache($cache)
{
if (is_string($cache)) {
$this->originalCache = $cache;
$this->cache = new Twig_Cache_Filesystem($cache);
} elseif (false === $cache) {
$this->originalCache = $cache;
$this->cache = new Twig_Cache_Null();
} elseif (null === $cache) {
@trigger_error('Using "null" as the cache strategy is deprecated since version 1.23 and will be removed in Twig 2.0.', E_USER_DEPRECATED);
$this->originalCache = false;
$this->cache = new Twig_Cache_Null();
} elseif ($cache instanceof Twig_CacheInterface) {
$this->originalCache = $this->cache = $cache;
} else {
throw new LogicException(sprintf('Cache can only be a string, false, or a Twig_CacheInterface implementation.'));
}
} | php | {
"resource": ""
} |
q249378 | Twig_Environment.getCacheFilename | validation | public function getCacheFilename($name)
{
@trigger_error(sprintf('The %s method is deprecated since version 1.22 and will be removed in Twig 2.0.', __METHOD__), E_USER_DEPRECATED);
$key = $this->cache->generateKey($name, $this->getTemplateClass($name));
return !$key ? false : $key;
} | php | {
"resource": ""
} |
q249379 | Twig_Environment.getTemplateClass | validation | public function getTemplateClass($name, $index = null)
{
$key = $this->getLoader()->getCacheKey($name).$this->optionsHash;
return $this->templateClassPrefix.hash('sha256', $key).(null === $index ? '' : '_'.$index);
} | php | {
"resource": ""
} |
q249380 | Twig_Environment.load | validation | public function load($name)
{
if ($name instanceof Twig_TemplateWrapper) {
return $name;
}
if ($name instanceof Twig_Template) {
return new Twig_TemplateWrapper($this, $name);
}
return new Twig_TemplateWrapper($this, $this->loadTemplate($name));
} | php | {
"resource": ""
} |
q249381 | Twig_Environment.createTemplate | validation | public function createTemplate($template)
{
$name = sprintf('__string_template__%s', hash('sha256', $template, false));
$loader = new Twig_Loader_Chain(array(
new Twig_Loader_Array(array($name => $template)),
$current = $this->getLoader(),
));
$this->setLoader($loader);
try {
$template = $this->loadTemplate($name);
} catch (Exception $e) {
$this->setLoader($current);
throw $e;
} catch (Throwable $e) {
$this->setLoader($current);
throw $e;
}
$this->setLoader($current);
return $template;
} | php | {
"resource": ""
} |
q249382 | Twig_Environment.isTemplateFresh | validation | public function isTemplateFresh($name, $time)
{
if (0 === $this->lastModifiedExtension) {
foreach ($this->extensions as $extension) {
$r = new ReflectionObject($extension);
if (file_exists($r->getFileName()) && ($extensionTime = filemtime($r->getFileName())) > $this->lastModifiedExtension) {
$this->lastModifiedExtension = $extensionTime;
}
}
}
return $this->lastModifiedExtension <= $time && $this->getLoader()->isFresh($name, $time);
} | php | {
"resource": ""
} |
q249383 | Twig_Environment.clearCacheFiles | validation | public function clearCacheFiles()
{
@trigger_error(sprintf('The %s method is deprecated since version 1.22 and will be removed in Twig 2.0.', __METHOD__), E_USER_DEPRECATED);
if (is_string($this->originalCache)) {
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->originalCache), RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
if ($file->isFile()) {
@unlink($file->getPathname());
}
}
}
} | php | {
"resource": ""
} |
q249384 | Twig_Environment.getLexer | validation | public function getLexer()
{
@trigger_error(sprintf('The %s() method is deprecated since version 1.25 and will be removed in 2.0.', __FUNCTION__), E_USER_DEPRECATED);
if (null === $this->lexer) {
$this->lexer = new Twig_Lexer($this);
}
return $this->lexer;
} | php | {
"resource": ""
} |
q249385 | Twig_Environment.tokenize | validation | public function tokenize($source, $name = null)
{
if (!$source instanceof Twig_Source) {
@trigger_error(sprintf('Passing a string as the $source argument of %s() is deprecated since version 1.27. Pass a Twig_Source instance instead.', __METHOD__), E_USER_DEPRECATED);
$source = new Twig_Source($source, $name);
}
if (null === $this->lexer) {
$this->lexer = new Twig_Lexer($this);
}
return $this->lexer->tokenize($source);
} | php | {
"resource": ""
} |
q249386 | Twig_Environment.getParser | validation | public function getParser()
{
@trigger_error(sprintf('The %s() method is deprecated since version 1.25 and will be removed in 2.0.', __FUNCTION__), E_USER_DEPRECATED);
if (null === $this->parser) {
$this->parser = new Twig_Parser($this);
}
return $this->parser;
} | php | {
"resource": ""
} |
q249387 | Twig_Environment.parse | validation | public function parse(Twig_TokenStream $stream)
{
if (null === $this->parser) {
$this->parser = new Twig_Parser($this);
}
return $this->parser->parse($stream);
} | php | {
"resource": ""
} |
q249388 | Twig_Environment.getCompiler | validation | public function getCompiler()
{
@trigger_error(sprintf('The %s() method is deprecated since version 1.25 and will be removed in 2.0.', __FUNCTION__), E_USER_DEPRECATED);
if (null === $this->compiler) {
$this->compiler = new Twig_Compiler($this);
}
return $this->compiler;
} | php | {
"resource": ""
} |
q249389 | Twig_Environment.compile | validation | public function compile(Twig_NodeInterface $node)
{
if (null === $this->compiler) {
$this->compiler = new Twig_Compiler($this);
}
return $this->compiler->compile($node)->getSource();
} | php | {
"resource": ""
} |
q249390 | Twig_Environment.compileSource | validation | public function compileSource($source, $name = null)
{
if (!$source instanceof Twig_Source) {
@trigger_error(sprintf('Passing a string as the $source argument of %s() is deprecated since version 1.27. Pass a Twig_Source instance instead.', __METHOD__), E_USER_DEPRECATED);
$source = new Twig_Source($source, $name);
}
try {
return $this->compile($this->parse($this->tokenize($source)));
} catch (Twig_Error $e) {
$e->setSourceContext($source);
throw $e;
} catch (Exception $e) {
throw new Twig_Error_Syntax(sprintf('An exception has been thrown during the compilation of a template ("%s").', $e->getMessage()), -1, $source, $e);
}
} | php | {
"resource": ""
} |
q249391 | Twig_Environment.initRuntime | validation | public function initRuntime()
{
$this->runtimeInitialized = true;
foreach ($this->getExtensions() as $name => $extension) {
if (!$extension instanceof Twig_Extension_InitRuntimeInterface) {
$m = new ReflectionMethod($extension, 'initRuntime');
if ('Twig_Extension' !== $m->getDeclaringClass()->getName()) {
@trigger_error(sprintf('Defining the initRuntime() method in the "%s" extension is deprecated since version 1.23. Use the `needs_environment` option to get the Twig_Environment instance in filters, functions, or tests; or explicitly implement Twig_Extension_InitRuntimeInterface if needed (not recommended).', $name), E_USER_DEPRECATED);
}
}
$extension->initRuntime($this);
}
} | php | {
"resource": ""
} |
q249392 | Twig_Environment.hasExtension | validation | public function hasExtension($class)
{
$class = ltrim($class, '\\');
if (!isset($this->extensionsByClass[$class]) && class_exists($class, false)) {
// For BC/FC with namespaced aliases
$class = new ReflectionClass($class);
$class = $class->name;
}
if (isset($this->extensions[$class])) {
if ($class !== get_class($this->extensions[$class])) {
@trigger_error(sprintf('Referencing the "%s" extension by its name (defined by getName()) is deprecated since 1.26 and will be removed in Twig 2.0. Use the Fully Qualified Extension Class Name instead.', $class), E_USER_DEPRECATED);
}
return true;
}
return isset($this->extensionsByClass[$class]);
} | php | {
"resource": ""
} |
q249393 | Twig_Environment.getExtension | validation | public function getExtension($class)
{
$class = ltrim($class, '\\');
if (!isset($this->extensionsByClass[$class]) && class_exists($class, false)) {
// For BC/FC with namespaced aliases
$class = new ReflectionClass($class);
$class = $class->name;
}
if (isset($this->extensions[$class])) {
if ($class !== get_class($this->extensions[$class])) {
@trigger_error(sprintf('Referencing the "%s" extension by its name (defined by getName()) is deprecated since 1.26 and will be removed in Twig 2.0. Use the Fully Qualified Extension Class Name instead.', $class), E_USER_DEPRECATED);
}
return $this->extensions[$class];
}
if (!isset($this->extensionsByClass[$class])) {
throw new Twig_Error_Runtime(sprintf('The "%s" extension is not enabled.', $class));
}
return $this->extensionsByClass[$class];
} | php | {
"resource": ""
} |
q249394 | Twig_Environment.removeExtension | validation | public function removeExtension($name)
{
@trigger_error(sprintf('The %s method is deprecated since version 1.12 and will be removed in Twig 2.0.', __METHOD__), E_USER_DEPRECATED);
if ($this->extensionInitialized) {
throw new LogicException(sprintf('Unable to remove extension "%s" as extensions have already been initialized.', $name));
}
$class = ltrim($name, '\\');
if (!isset($this->extensionsByClass[$class]) && class_exists($class, false)) {
// For BC/FC with namespaced aliases
$class = new ReflectionClass($class);
$class = $class->name;
}
if (isset($this->extensions[$class])) {
if ($class !== get_class($this->extensions[$class])) {
@trigger_error(sprintf('Referencing the "%s" extension by its name (defined by getName()) is deprecated since 1.26 and will be removed in Twig 2.0. Use the Fully Qualified Extension Class Name instead.', $class), E_USER_DEPRECATED);
}
unset($this->extensions[$class]);
}
unset($this->extensions[$class]);
$this->updateOptionsHash();
} | php | {
"resource": ""
} |
q249395 | Twig_Environment.addFunction | validation | public function addFunction($name, $function = null)
{
if (!$name instanceof Twig_SimpleFunction && !($function instanceof Twig_SimpleFunction || $function instanceof Twig_FunctionInterface)) {
throw new LogicException('A function must be an instance of Twig_FunctionInterface or Twig_SimpleFunction.');
}
if ($name instanceof Twig_SimpleFunction) {
$function = $name;
$name = $function->getName();
} else {
@trigger_error(sprintf('Passing a name as a first argument to the %s method is deprecated since version 1.21. Pass an instance of "Twig_SimpleFunction" instead when defining function "%s".', __METHOD__, $name), E_USER_DEPRECATED);
}
if ($this->extensionInitialized) {
throw new LogicException(sprintf('Unable to add function "%s" as extensions have already been initialized.', $name));
}
$this->staging->addFunction($name, $function);
} | php | {
"resource": ""
} |
q249396 | Twig_Environment.addGlobal | validation | public function addGlobal($name, $value)
{
if ($this->extensionInitialized || $this->runtimeInitialized) {
if (null === $this->globals) {
$this->globals = $this->initGlobals();
}
if (!array_key_exists($name, $this->globals)) {
// The deprecation notice must be turned into the following exception in Twig 2.0
@trigger_error(sprintf('Registering global variable "%s" at runtime or when the extensions have already been initialized is deprecated since version 1.21.', $name), E_USER_DEPRECATED);
//throw new LogicException(sprintf('Unable to add global "%s" as the runtime or the extensions have already been initialized.', $name));
}
}
if ($this->extensionInitialized || $this->runtimeInitialized) {
// update the value
$this->globals[$name] = $value;
} else {
$this->staging->addGlobal($name, $value);
}
} | php | {
"resource": ""
} |
q249397 | Twig_Loader_Filesystem.addPath | validation | public function addPath($path, $namespace = self::MAIN_NAMESPACE)
{
// invalidate the cache
$this->cache = $this->errorCache = array();
$checkPath = $this->isAbsolutePath($path) ? $path : $this->rootPath.$path;
if (!is_dir($checkPath)) {
throw new Twig_Error_Loader(sprintf('The "%s" directory does not exist ("%s").', $path, $checkPath));
}
$this->paths[$namespace][] = rtrim($path, '/\\');
} | php | {
"resource": ""
} |
q249398 | Twig_Loader_Filesystem.prependPath | validation | public function prependPath($path, $namespace = self::MAIN_NAMESPACE)
{
// invalidate the cache
$this->cache = $this->errorCache = array();
$checkPath = $this->isAbsolutePath($path) ? $path : $this->rootPath.$path;
if (!is_dir($checkPath)) {
throw new Twig_Error_Loader(sprintf('The "%s" directory does not exist ("%s").', $path, $checkPath));
}
$path = rtrim($path, '/\\');
if (!isset($this->paths[$namespace])) {
$this->paths[$namespace][] = $path;
} else {
array_unshift($this->paths[$namespace], $path);
}
} | php | {
"resource": ""
} |
q249399 | User.register | validation | public function register($isSuperAdmin = FALSE, $status = 1)
{
if ($this->getIsNewRecord() == FALSE) {
throw new RuntimeException('Calling "' . __CLASS__ . '::' . __METHOD__ . '" on existing user');
}
// Set to 1 if isSuperAdmin is true else set to 0
$this->super_admin = $isSuperAdmin ? 1 : 0;
// Set status
$this->status = $status;
// Save user data to the database
if ($this->save()) {
return TRUE;
}
return FALSE;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.