code
stringlengths 23
2.05k
| label_name
stringlengths 6
7
| label
int64 0
37
|
---|---|---|
public function Connected() {
if(!empty($this->smtp_conn)) {
$sock_status = socket_get_status($this->smtp_conn);
if($sock_status["eof"]) {
// the socket is valid but we are not connected
if($this->do_debug >= 1) {
$this->edebug("SMTP -> NOTICE:" . $this->CRLF . "EOF caught while checking if connected");
}
$this->Close();
return false;
}
return true; // everything looks good
}
return false;
} | CWE-20 | 0 |
public function manage() {
expHistory::set('manageable', $this->params);
// build out a SQL query that gets all the data we need and is sortable.
$sql = 'SELECT b.*, c.title as companyname, f.expfiles_id as file_id ';
$sql .= 'FROM '.DB_TABLE_PREFIX.'_banner b, '.DB_TABLE_PREFIX.'_companies c , '.DB_TABLE_PREFIX.'_content_expFiles f ';
$sql .= 'WHERE b.companies_id = c.id AND (b.id = f.content_id AND f.content_type="banner")';
$page = new expPaginator(array(
'model'=>'banner',
'sql'=>$sql,
'order'=>'title',
'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),
'controller'=>$this->params['controller'],
'action'=>$this->params['action'],
'src'=>$this->loc->src,
'columns'=>array(
gt('Title')=>'title',
gt('Company')=>'companyname',
gt('Impressions')=>'impressions',
gt('Clicks')=>'clicks'
)
));
assign_to_template(array(
'page'=>$page
));
} | CWE-74 | 1 |
function move_standalone() {
expSession::clearAllUsersSessionCache('navigation');
assign_to_template(array(
'parent' => $this->params['parent'],
));
}
| CWE-74 | 1 |
function categoryBreadcrumb() {
// global $db, $router;
//eDebug($this->category);
/*if(isset($router->params['action']))
{
$ancestors = $this->category->pathToNode();
}else if(isset($router->params['section']))
{
$current = $db->selectObject('section',' id= '.$router->params['section']);
$ancestors[] = $current;
if( $current->parent != -1 || $current->parent != 0 )
{
while ($db->selectObject('section',' id= '.$router->params['section']);)
if ($section->id == $id) {
$current = $section;
break;
}
}
}
eDebug($sections);
$ancestors = $this->category->pathToNode();
}*/
$ancestors = $this->category->pathToNode();
// eDebug($ancestors);
assign_to_template(array(
'ancestors' => $ancestors
));
} | CWE-74 | 1 |
public static function getIconName($module)
{
return isset(static::$iconNames[$module])
? static::$iconNames[$module]
: strtolower(str_replace('_', '-', $module));
} | CWE-863 | 11 |
public function AddAddress($address, $name = '') {
return $this->AddAnAddress('to', $address, $name);
} | CWE-20 | 0 |
protected function loginRequired()
{
Yii::$app->user->logout();
Yii::$app->user->loginRequired();
return false;
} | CWE-863 | 11 |
public function uploadCustomLogoAction(Request $request)
{
$fileExt = File::getFileExtension($_FILES['Filedata']['name']);
if (!in_array($fileExt, ['svg', 'png', 'jpg'])) {
throw new \Exception('Unsupported file format');
}
if ($fileExt === 'svg' && stripos(file_get_contents($_FILES['Filedata']['tmp_name']), '<script')) {
throw new \Exception('Scripts in SVG files are not supported');
}
$storage = Tool\Storage::get('admin');
$storage->writeStream(self::CUSTOM_LOGO_PATH, fopen($_FILES['Filedata']['tmp_name'], 'rb'));
// set content-type to text/html, otherwise (when application/json is sent) chrome will complain in
// Ext.form.Action.Submit and mark the submission as failed
$response = $this->adminJson(['success' => true]);
$response->headers->set('Content-Type', 'text/html');
return $response;
} | CWE-200 | 10 |
public function getBackendRequest()
{
return $this->backendRequest;
} | CWE-20 | 0 |
function delete_selected() {
$item = $this->event->find('first', 'id=' . $this->params['id']);
if ($item && $item->is_recurring == 1) {
$event_remaining = false;
$eventdates = $item->eventdate[0]->find('all', 'event_id=' . $item->id);
foreach ($eventdates as $ed) {
if (array_key_exists($ed->id, $this->params['dates'])) {
$ed->delete();
} else {
$event_remaining = true;
}
}
if (!$event_remaining) {
$item->delete(); // model will also ensure we delete all event dates
}
expHistory::back();
} else {
notfoundController::handle_not_found();
}
}
| CWE-74 | 1 |
public function afterSave($event) {
// look up current tags
$oldTags = $this->getTags();
$newTags = array();
foreach ($this->scanForTags() as $tag) {
if (!in_array($tag, $oldTags)) { // don't add duplicates if there are already tags
$tagModel = new Tags;
$tagModel->tag = $tag; // includes the #
$tagModel->type = get_class($this->getOwner());
$tagModel->itemId = $this->getOwner()->id;
$tagModel->itemName = $this->getOwner()->name;
$tagModel->taggedBy = Yii::app()->getSuName();
$tagModel->timestamp = time();
if ($tagModel->save())
$newTags[] = $tag;
}
}
$this->_tags = $newTags + $oldTags; // update tag cache
if (!empty($newTags) && $this->flowTriggersEnabled) {
X2Flow::trigger('RecordTagAddTrigger', array(
'model' => $this->getOwner(),
'tags' => $newTags,
));
}
} | CWE-20 | 0 |
public static function parseAndTrimExport($str, $isHTML = false) { //�Death from above�? �
//echo "1<br>"; eDebug($str);
$str = str_replace("�", "’", $str);
$str = str_replace("�", "‘", $str);
$str = str_replace("�", "®", $str);
$str = str_replace("�", "-", $str);
$str = str_replace("�", "—", $str);
$str = str_replace("�", "”", $str);
$str = str_replace("�", "“", $str);
$str = str_replace("\r\n", " ", $str);
$str = str_replace("\t", " ", $str);
$str = str_replace(",", "\,", $str);
$str = str_replace("�", "¼", $str);
$str = str_replace("�", "½", $str);
$str = str_replace("�", "¾", $str);
if (!$isHTML) {
$str = str_replace('\"', """, $str);
$str = str_replace('"', """, $str);
} else {
$str = str_replace('"', '""', $str);
}
//$str = htmlspecialchars($str);
//$str = utf8_encode($str);
$str = trim(str_replace("�", "™", $str));
//echo "2<br>"; eDebug($str,die);
return $str;
} | CWE-74 | 1 |
public static function getModelTypes($assoc = false) {
$modelTypes = Yii::app()->db->createCommand()
->selectDistinct('modelName')
->from('x2_fields')
->where('modelName!="Calendar"')
->order('modelName ASC')
->queryColumn();
if ($assoc === true) {
return array_combine($modelTypes, array_map(function($term) {
return Yii::t('app', X2Model::getModelTitle($term));
}, $modelTypes));
}
$modelTypes = array_map(function($term) {
return Yii::t('app', $term);
}, $modelTypes);
return $modelTypes;
} | CWE-20 | 0 |
protected function renderImageByGD($code)
{
$image = imagecreatetruecolor($this->width, $this->height);
$backColor = imagecolorallocate(
$image,
(int) ($this->backColor % 0x1000000 / 0x10000),
(int) ($this->backColor % 0x10000 / 0x100),
$this->backColor % 0x100
);
imagefilledrectangle($image, 0, 0, $this->width - 1, $this->height - 1, $backColor);
imagecolordeallocate($image, $backColor);
if ($this->transparent) {
imagecolortransparent($image, $backColor);
}
$foreColor = imagecolorallocate(
$image,
(int) ($this->foreColor % 0x1000000 / 0x10000),
(int) ($this->foreColor % 0x10000 / 0x100),
$this->foreColor % 0x100
);
$length = strlen($code);
$box = imagettfbbox(30, 0, $this->fontFile, $code);
$w = $box[4] - $box[0] + $this->offset * ($length - 1);
$h = $box[1] - $box[5];
$scale = min(($this->width - $this->padding * 2) / $w, ($this->height - $this->padding * 2) / $h);
$x = 10;
$y = round($this->height * 27 / 40);
for ($i = 0; $i < $length; ++$i) {
$fontSize = (int) (mt_rand(26, 32) * $scale * 0.8);
$angle = mt_rand(-10, 10);
$letter = $code[$i];
$box = imagettftext($image, $fontSize, $angle, $x, $y, $foreColor, $this->fontFile, $letter);
$x = $box[2] + $this->offset;
}
imagecolordeallocate($image, $foreColor);
ob_start();
imagepng($image);
imagedestroy($image);
return ob_get_clean();
} | CWE-330 | 12 |
function manage() {
global $db, $router, $user;
expHistory::set('manageable', $router->params);
assign_to_template(array(
'canManageStandalones' => self::canManageStandalones(),
'sasections' => $db->selectObjects('section', 'parent=-1'),
'user' => $user,
// 'canManagePagesets' => $user->isAdmin(),
// 'templates' => $db->selectObjects('section_template', 'parent=0'),
));
}
| CWE-74 | 1 |
public static function newFromStyle( $style, \DPL\Parameters $parameters ) {
$style = strtolower( $style );
switch ( $style ) {
case 'definition':
$class = 'DefinitionHeading';
break;
case 'h1':
case 'h2':
case 'h3':
case 'h4':
case 'h5':
case 'h6':
case 'header':
$class = 'TieredHeading';
break;
case 'ordered':
$class = 'OrderedHeading';
break;
case 'unordered':
$class = 'UnorderedHeading';
break;
default:
return null;
break;
}
$class = '\DPL\Heading\\' . $class;
return new $class( $parameters );
} | CWE-400 | 2 |
public static function parentPlaceholder($section = '')
{
if (! isset(static::$parentPlaceholder[$section])) {
static::$parentPlaceholder[$section] = '##parent-placeholder-'.sha1($section).'##';
}
return static::$parentPlaceholder[$section];
} | CWE-327 | 3 |
$fileName = ltrim(dirname($fileName) . '/' . basename($fileName, '.js'), '/.');
if (empty($fileName)) {
continue;
}
$templateBase = $inflector->filter(array(
'module' => $moduleName,
'controller' => $controllerName,
'file' => $fileName)
);
$templateExtend = $inflector->filter(array(
'module' => $moduleName,
'controller' => $this->Request()->getControllerName(),
'file' => $fileName)
);
if ($this->View()->templateExists($templateBase)) {
$template .= '{include file="' . $templateBase. '"}' . "\n";
}
if ($this->View()->templateExists($templateExtend)) {
$template .= '{include file="' . $templateExtend. '"}' . "\n";
}
} | CWE-20 | 0 |
static function searchUser(AuthLDAP $authldap) {
if (self::connectToServer($authldap->getField('host'), $authldap->getField('port'),
$authldap->getField('rootdn'),
Toolbox::decrypt($authldap->getField('rootdn_passwd'), GLPIKEY),
$authldap->getField('use_tls'),
$authldap->getField('deref_option'))) {
self::showLdapUsers();
} else {
echo "<div class='center b firstbloc'>".__('Unable to connect to the LDAP directory');
}
} | CWE-327 | 3 |
public function approve() {
expHistory::set('editable', $this->params);
/* The global constants can be overriden by passing appropriate params */
//sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet
$require_login = empty($this->params['require_login']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];
$require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];
$require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];
$notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];
if (empty($this->params['id'])) {
flash('error', gt('No ID supplied for note to approve'));
$lastUrl = expHistory::getLast('editable');
}
$simplenote = new expSimpleNote($this->params['id']);
assign_to_template(array(
'simplenote'=>$simplenote,
'require_login'=>$require_login,
'require_approval'=>$require_approval,
'require_notification'=>$require_notification,
'notification_email'=>$notification_email,
'tab'=>$this->params['tab']
));
} | CWE-74 | 1 |
$return[$index] = strip_tags($value);
if($return[$index] == 'zero')
$return[$index] = '0';
}
}
elseif($type == ARG_MULTISTRING) {
foreach($return as $index => $value) {
$return[$index] = strip_tags($value);
}
}
else
$return = strip_tags($return);
if(! empty($return) && $type == ARG_NUMERIC) {
if(! is_numeric($return)) {
return preg_replace('([^\d])', '', $return);
}
}
elseif(! empty($return) && $type == ARG_STRING) {
if(! is_string($return))
$return = $defaultvalue;
}
elseif(! empty($return) && $type == ARG_MULTINUMERIC) {
foreach($return as $index => $value) {
if(! is_numeric($value)) {
$return[$index] = preg_replace('([^\d])', '', $value);
}
}
return $return;
}
elseif(! empty($return) && $type == ARG_MULTISTRING) {
foreach($return as $index => $value) {
if(! is_string($value))
$return[$index] = $defaultvalue;
elseif($addslashes)
$return[$index] = addslashes($value);
}
return $return;
}
if(is_string($return)) {
if(strlen($return) == 0)
$return = $defaultvalue;
elseif($addslashes)
$return = addslashes($return);
}
return $return;
} | CWE-20 | 0 |
public function searchNew() {
global $db, $user;
//$this->params['query'] = str_ireplace('-','\-',$this->params['query']);
$sql = "select DISTINCT(p.id) as id, p.title, model, sef_url, f.id as fileid, ";
$sql .= "match (p.title,p.model,p.body) against ('" . $this->params['query'] . "*' IN BOOLEAN MODE) as relevance, ";
$sql .= "CASE when p.model like '" . $this->params['query'] . "%' then 1 else 0 END as modelmatch, ";
$sql .= "CASE when p.title like '%" . $this->params['query'] . "%' then 1 else 0 END as titlematch ";
$sql .= "from " . $db->prefix . "product as p INNER JOIN " .
$db->prefix . "content_expFiles as cef ON p.id=cef.content_id AND cef.content_type IN ('product','eventregistration','donation','giftcard') AND cef.subtype='mainimage' INNER JOIN " . $db->prefix .
"expFiles as f ON cef.expFiles_id = f.id WHERE ";
if (!$user->isAdmin()) $sql .= '(p.active_type=0 OR p.active_type=1) AND ';
$sql .= " match (p.title,p.model,p.body) against ('" . $this->params['query'] . "*' IN BOOLEAN MODE) AND p.parent_id=0 ";
$sql .= " HAVING relevance > 0 ";
//$sql .= "GROUP BY p.id ";
$sql .= "order by modelmatch,titlematch,relevance desc LIMIT 10";
eDebug($sql);
$res = $db->selectObjectsBySql($sql);
eDebug($res, true);
$ar = new expAjaxReply(200, gt('Here\'s the items you wanted'), $res);
$ar->send();
} | CWE-74 | 1 |
public function generateMessageFileName()
{
$time = microtime(true);
return date('Ymd-His-', $time) . sprintf('%04d', (int) (($time - (int) $time) * 10000)) . '-' . sprintf('%04d', mt_rand(0, 10000)) . '.eml';
} | CWE-330 | 12 |
function searchName() { return gt('Webpage'); }
| CWE-74 | 1 |
foreach ($day as $extevent) {
$event_cache = new stdClass();
$event_cache->feed = $extgcalurl;
$event_cache->event_id = $extevent->event_id;
$event_cache->title = $extevent->title;
$event_cache->body = $extevent->body;
$event_cache->eventdate = $extevent->eventdate->date;
if (isset($extevent->dateFinished) && $extevent->dateFinished != -68400)
$event_cache->dateFinished = $extevent->dateFinished;
if (isset($extevent->eventstart))
$event_cache->eventstart = $extevent->eventstart;
if (isset($extevent->eventend))
$event_cache->eventend = $extevent->eventend;
if (isset($extevent->is_allday))
$event_cache->is_allday = $extevent->is_allday;
$found = false;
if ($extevent->eventdate->date < $start) // prevent duplicating events crossing month boundaries
$found = $db->selectObject('event_cache','feed="'.$extgcalurl.'" AND event_id="'.$event_cache->event_id.'" AND eventdate='.$event_cache->eventdate);
if (!$found)
$db->insertObject($event_cache,'event_cache');
}
| CWE-74 | 1 |
foreach ($matches[1] as $index => $body) {
$parts = explode('_', $body);
$fileID = $parts[0];
$hash = $parts[1];
try {
$file = erLhcoreClassModelChatFile::fetch($fileID);
if (is_object($file) && $hash == $file->security_hash) {
$url = (erLhcoreClassSystem::$httpsMode == true ? 'https:' : 'http:') . '//' . $_SERVER['HTTP_HOST'] . erLhcoreClassDesign::baseurldirect('file/downloadfile') . "/{$file->id}/{$hash}";
$media[] = array(
'id' => $file->id,
'size' => $file->size,
'upload_name' => $file->upload_name,
'type' => $file->type,
'extension' => $file->extension,
'hash' => $hash,
'url' => $url,
);
$msg_text_cleaned = str_replace($matches[0][$index],'',$msg_text_cleaned);
}
} catch (Exception $e) {
}
} | CWE-116 | 15 |
foreach ($events as $event) {
$extevents[$date][] = $event;
}
| CWE-74 | 1 |
foreach ($week as $dayNum => $day) {
if ($dayNum == $now['mday']) {
$currentweek = $weekNum;
}
if ($dayNum <= $endofmonth) {
// $monthly[$weekNum][$dayNum]['number'] = ($monthly[$weekNum][$dayNum]['ts'] != -1) ? $db->countObjects("eventdate", $locsql . " AND date >= " . expDateTime::startOfDayTimestamp($day['ts']) . " AND date <= " . expDateTime::endOfDayTimestamp($day['ts'])) : -1;
$monthly[$weekNum][$dayNum]['number'] = ($monthly[$weekNum][$dayNum]['ts'] != -1) ? $ed->find("count", $locsql . " AND date >= " . expDateTime::startOfDayTimestamp($day['ts']) . " AND date <= " . expDateTime::endOfDayTimestamp($day['ts'])) : -1;
}
}
| CWE-74 | 1 |
public function test_valid_comment_allow_empty_content() {
add_filter( 'allow_empty_comment', '__return_true' );
$result = $this->myxmlrpcserver->wp_newComment(
array(
1,
'administrator',
'administrator',
self::$post->ID,
array(
'content' => ' ',
),
)
);
$this->assertNotIXRError( $result );
} | CWE-862 | 8 |
public function showall() {
expHistory::set('viewable', $this->params);
$limit = (isset($this->config['limit']) && $this->config['limit'] != '') ? $this->config['limit'] : 10;
if (!empty($this->params['view']) && ($this->params['view'] == 'showall_accordion' || $this->params['view'] == 'showall_tabbed')) {
$limit = '0';
}
$order = isset($this->config['order']) ? $this->config['order'] : "rank";
$page = new expPaginator(array(
'model'=>'photo',
'where'=>$this->aggregateWhereClause(),
'limit'=>$limit,
'order'=>$order,
'categorize'=>empty($this->config['usecategories']) ? false : $this->config['usecategories'],
'uncat'=>!empty($this->config['uncat']) ? $this->config['uncat'] : gt('Not Categorized'),
'groups'=>!isset($this->params['gallery']) ? array() : array($this->params['gallery']),
'grouplimit'=>!empty($this->params['view']) && $this->params['view'] == 'showall_galleries' ? 1 : null,
'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),
'controller'=>$this->baseclassname,
'action'=>$this->params['action'],
'src'=>$this->loc->src,
'columns'=>array(
gt('Title')=>'title'
),
));
assign_to_template(array(
'page'=>$page,
'params'=>$this->params,
));
} | CWE-74 | 1 |
public function getPurchaseOrderByJSON() {
if(!empty($this->params['vendor'])) {
$purchase_orders = $this->purchase_order->find('all', 'vendor_id=' . $this->params['vendor']);
} else {
$purchase_orders = $this->purchase_order->find('all');
}
echo json_encode($purchase_orders);
} | CWE-74 | 1 |
function unlockTables() {
$sql = "UNLOCK TABLES";
$res = mysqli_query($this->connection, $sql);
return $res;
} | CWE-74 | 1 |
public function update() {
global $user;
if (expSession::get('customer-signup')) expSession::set('customer-signup', false);
if (isset($this->params['address_country_id'])) {
$this->params['country'] = $this->params['address_country_id'];
unset($this->params['address_country_id']);
}
if (isset($this->params['address_region_id'])) {
$this->params['state'] = $this->params['address_region_id'];
unset($this->params['address_region_id']);
}
if ($user->isLoggedIn()) {
// check to see how many other addresses this user has already.
$count = $this->address->find('count', 'user_id='.$user->id);
// if this is first address save for this user we'll make this the default
if ($count == 0)
{
$this->params['is_default'] = 1;
$this->params['is_billing'] = 1;
$this->params['is_shipping'] = 1;
}
// associate this address with the current user.
$this->params['user_id'] = $user->id;
// save the object
$this->address->update($this->params);
}
else { //if (ecomconfig::getConfig('allow_anonymous_checkout')){
//user is not logged in, but allow anonymous checkout is enabled so we'll check
//a few things that we don't check in the parent 'stuff and create a user account.
$this->params['is_default'] = 1;
$this->params['is_billing'] = 1;
$this->params['is_shipping'] = 1;
$this->address->update($this->params);
}
expHistory::back();
} | CWE-74 | 1 |
self::assertSame($shouldBePresent, $request->hasHeader('Authorization'));
self::assertSame($shouldBePresent, $request->hasHeader('Cookie'));
return new Response(200);
}
]); | CWE-200 | 10 |
$loc = expCore::makeLocation('navigation', '', $standalone->id);
if (expPermissions::check('manage', $loc)) return true;
}
return false;
}
| CWE-74 | 1 |
private function _modifiedby( $option ) {
$this->addTable( 'revision_actor_temp', 'change_rev' );
$user = new \User;
$this->addWhere( $this->DB->addQuotes( $user->newFromName( $option )->getActorId() ) . ' = change_rev.revactor_actor AND change_rev.revactor_page = page_id' );
} | CWE-400 | 2 |
$newret = recyclebin::restoreFromRecycleBin($iLoc, $page_id);
if (!empty($newret)) $ret .= $newret . '<br>';
if ($iLoc->mod == 'container') {
$ret .= scan_container($container->internal, $page_id);
}
}
return $ret;
}
| CWE-74 | 1 |
$query->whereExists(function ($permissionQuery) use (&$tableDetails, $morphClass) {
/** @var Builder $permissionQuery */
$permissionQuery->select('id')->from('joint_permissions')
->whereColumn('joint_permissions.entity_id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
->where('entity_type', '=', $morphClass)
->where('action', '=', 'view')
->whereIn('role_id', $this->getCurrentUserRoles())
->where(function (QueryBuilder $query) {
$this->addJointHasPermissionCheck($query, $this->currentUser()->id);
});
}); | CWE-863 | 11 |
public function handle($stanza, $parent = false)
{
$message = $stanza->forwarded->message;
$jid = explode('/',(string)$message->attributes()->from);
$to = current(explode('/',(string)$message->attributes()->to));
if($message->composing)
$this->event('composing', array($jid[0], $to));
if($message->paused)
$this->event('paused', array($jid[0], $to));
if($message->gone)
$this->event('gone', array($jid[0], $to));
if($message->body || $message->subject) {
$m = new \Modl\Message;
$m->set($message, $stanza->forwarded);
if(!preg_match('#^\?OTR#', $m->body)) {
$md = new \Modl\MessageDAO;
$md->set($m);
$this->pack($m);
$this->deliver();
}
}
} | CWE-346 | 16 |
function process_subsections($parent_section, $subtpl) {
global $db, $router;
$section = new stdClass();
$section->parent = $parent_section->id;
$section->name = $subtpl->name;
$section->sef_name = $router->encode($section->name);
$section->subtheme = $subtpl->subtheme;
$section->active = $subtpl->active;
$section->public = $subtpl->public;
$section->rank = $subtpl->rank;
$section->page_title = $subtpl->page_title;
$section->keywords = $subtpl->keywords;
$section->description = $subtpl->description;
$section->id = $db->insertObject($section, 'section');
self::process_section($section, $subtpl);
}
| CWE-74 | 1 |
return \DPL\Variables::setVarDefault( $args );
}
return \DPL\Variables::getVar( $cmd );
} | CWE-400 | 2 |
function selectBillingOptions() {
} | CWE-74 | 1 |
$layout[$position] = array($elem => $initLayout[$position][$elem]) + $layout[$position]; // unshift key-value pair
$changed = true;
}
// remove obsolete widgets
$arrayDiff =
array_diff(array_keys($layoutWidgets), array_keys($initLayoutWidgets));
foreach($arrayDiff as $elem){
if(in_array ($elem, array_keys ($layout[$position]))) {
unset($layout[$position][$elem]);
$changed = true;
} else if($position === 'center' && in_array ($elem, array_keys ($layout['hidden']))) {
unset($layout['hidden'][$elem]);
$changed = true;
}
}
// ensure that widget properties are the same as those in the default layout
foreach($layout[$position] as $name=>$arr){
if (in_array ($name, array_keys ($initLayout[$position])) &&
$initLayout[$position][$name]['title'] !== $arr['title']) {
$layout[$position][$name]['title'] = $initLayout[$position][$name]['title'];
$changed = true;
}
}
if ($position === 'center') {
foreach($layout['hidden'] as $name=>$arr){
if (in_array ($name, array_keys ($initLayout[$position])) &&
$initLayout[$position][$name]['title'] !== $arr['title']) {
$layout['hidden'][$name]['title'] = $initLayout[$position][$name]['title'];
$changed = true;
}
}
}
if($changed){
$this->layout = json_encode($layout);
$this->update(array('layout'));
}
} | CWE-20 | 0 |
foreach($row as $key => $value) {
$type = gettype($value);
$sqltype=NULL;
switch($type) {
case "integer":
$sqltype = SQLITE3_INTEGER;
break;
case "string":
$sqltype = SQLITE3_TEXT;
break;
case "NULL":
$sqltype = SQLITE3_NULL;
break;
default:
$sqltype = "UNK";
}
$stmt->bindValue(":".$key, $value, $sqltype);
} | CWE-862 | 8 |
private function sendString ($string) {
$bytes_sent = fwrite($this->pop_conn, $string, strlen($string));
return $bytes_sent;
} | CWE-20 | 0 |
public function getBranches()
{
if (null === $this->branches) {
$branches = array();
$this->process->execute('git branch --no-color --no-abbrev -v', $output, $this->repoDir);
foreach ($this->process->splitLines($output) as $branch) {
if ($branch && !Preg::isMatch('{^ *[^/]+/HEAD }', $branch)) {
if (Preg::isMatch('{^(?:\* )? *(\S+) *([a-f0-9]+)(?: .*)?$}', $branch, $match)) {
$branches[$match[1]] = $match[2];
}
}
}
$this->branches = $branches;
}
return $this->branches;
} | CWE-20 | 0 |
public function params()
{
$project = $this->getProject();
$values = $this->request->getValues();
if (empty($values['action_name']) || empty($values['project_id']) || empty($values['event_name'])) {
$this->create();
return;
}
$action = $this->actionManager->getAction($values['action_name']);
$action_params = $action->getActionRequiredParameters();
if (empty($action_params)) {
$this->doCreation($project, $values + array('params' => array()));
}
$projects_list = $this->projectUserRoleModel->getActiveProjectsByUser($this->userSession->getId());
unset($projects_list[$project['id']]);
$this->response->html($this->template->render('action_creation/params', array(
'values' => $values,
'action_params' => $action_params,
'columns_list' => $this->columnModel->getList($project['id']),
'users_list' => $this->projectUserRoleModel->getAssignableUsersList($project['id']),
'projects_list' => $projects_list,
'colors_list' => $this->colorModel->getList(),
'categories_list' => $this->categoryModel->getList($project['id']),
'links_list' => $this->linkModel->getList(0, false),
'priorities_list' => $this->projectTaskPriorityModel->getPriorities($project),
'project' => $project,
'available_actions' => $this->actionManager->getAvailableActions(),
'swimlane_list' => $this->swimlaneModel->getList($project['id']),
'events' => $this->actionManager->getCompatibleEvents($values['action_name']),
)));
} | CWE-200 | 10 |
public function beforeSave () {
$valid = parent::beforeSave ();
if ($valid) {
$table = Yii::app()->db->schema->tables[$this->myTableName];
$existing = array_key_exists($this->fieldName, $table->columns) &&
$table->columns[$this->fieldName] instanceof CDbColumnSchema;
if($existing){
$valid = $this->modifyColumn();
}
}
return $valid;
} | CWE-20 | 0 |
$date->delete(); // event automatically deleted if all assoc eventdates are deleted
}
expHistory::back();
}
| CWE-74 | 1 |
public function testPOSTForRegularUser()
{
$post_resource = json_encode([
'label' => 'Test Request 9747 regular user',
'shortname' => 'test9747-regular-user',
'description' => 'Test of Request 9747 for REST API Project Creation',
'is_public' => true,
'template_id' => 100,
]);
$response = $this->getResponseByName(
REST_TestDataBuilder::TEST_USER_2_NAME,
$this->request_factory->createRequest(
'POST',
'projects'
)->withBody(
$this->stream_factory->createStream($post_resource)
)
);
self::assertEquals(201, $response->getStatusCode());
$create_project_id = json_decode($response->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR)['id'];
$this->removeAdminFromProjectMembers(
$create_project_id,
REST_TestDataBuilder::TEST_USER_2_NAME,
);
} | CWE-863 | 11 |
private function __checkIfPulledEventExistsAndAddOrUpdate($event, $eventId, &$successes, &$fails, $eventModel, $server, $user, $jobId)
{
// check if the event already exist (using the uuid)
$existingEvent = $eventModel->find('first', array('conditions' => array('Event.uuid' => $event['Event']['uuid'])));
$passAlong = $server['Server']['id'];
if (!$existingEvent) {
// add data for newly imported events
$result = $eventModel->_add($event, true, $user, $server['Server']['org_id'], $passAlong, true, $jobId);
if ($result === true) {
$successes[] = $eventId;
} else {
$fails[$eventId] = __('Failed (partially?) because of errors: ') . $result;
}
} else {
if (!$existingEvent['Event']['locked'] && !$server['Server']['internal']) {
$fails[$eventId] = __('Blocked an edit to an event that was created locally. This can happen if a synchronised event that was created on this instance was modified by an administrator on the remote side.');
} else {
$result = $eventModel->_edit($event, $user, $existingEvent['Event']['id'], $jobId, $passAlong);
if ($result === true) {
$successes[] = $eventId;
} elseif (isset($result['error'])) {
$fails[$eventId] = $result['error'];
} else {
$fails[$eventId] = json_encode($result);
}
}
}
} | CWE-269 | 6 |
$object->size = convert_size($cur->getSize());
$object->mtime = date('D, j M, Y', $cur->getMTime());
list($object->perms, $object->chmod) = $this->_getPermissions($cur->getPerms());
// Find the file type
$object->type = $this->_getFileType($cur);
// make the link depending on if it's a file or a dir
if ($cur->isDir()) {
$object->link = '<a href="' . get_url('plugin/file_manager/browse/' . $this->path . $object->name) . '">' . $object->name . '</a>';
} else {
$object->link = '<a href="' . get_url('plugin/file_manager/view/' . $this->path . $object->name . (endsWith($object->name, URL_SUFFIX) ? '?has_url_suffix=1' : '')) . '">' . $object->name . '</a>';
}
$files[$object->name] = $object;
} | CWE-20 | 0 |
$masteroption->delete();
}
// delete the mastergroup
$db->delete('optiongroup', 'optiongroup_master_id='.$mastergroup->id);
$mastergroup->delete();
expHistory::back();
} | CWE-74 | 1 |
public function view() {
$params = func_get_args();
$content = '';
$filename = urldecode(join('/', $params));
// Sanitize filename for securtiy
// We don't allow backlinks
if (strpos($filename, '..') !== false) {
/*
if (Plugin::isEnabled('statistics_api')) {
$user = null;
if (AuthUser::isLoggedIn())
$user = AuthUser::getUserName();
$ip = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : ($_SERVER['REMOTE_ADDR']);
$event = array('event_type' => 'hack_attempt', // simple event type identifier
'description' => __('A possible hack attempt was detected.'), // translatable description
'ipaddress' => $ip,
'username' => $user);
Observer::notify('stats_file_manager_hack_attempt', $event);
}
*/
}
$filename = str_replace('..', '', $filename);
// Clean up nicely
$filename = str_replace('//', '', $filename);
// We don't allow leading slashes
$filename = preg_replace('/^\//', '', $filename);
// Check if file had URL_SUFFIX - if so, append it to filename
$filename .= (isset($_GET['has_url_suffix']) && $_GET['has_url_suffix']==='1') ? URL_SUFFIX : '';
$file = FILES_DIR . '/' . $filename;
if (!$this->_isImage($file) && file_exists($file)) {
$content = file_get_contents($file);
}
$this->display('file_manager/views/view', array(
'csrf_token' => SecureToken::generateToken(BASE_URL.'plugin/file_manager/save/'.$filename),
'is_image' => $this->_isImage($file),
'filename' => $filename,
'content' => $content
));
} | CWE-20 | 0 |
protected function renderImageByImagick($code)
{
$backColor = $this->transparent ? new \ImagickPixel('transparent') : new \ImagickPixel('#' . str_pad(dechex($this->backColor), 6, 0, STR_PAD_LEFT));
$foreColor = new \ImagickPixel('#' . str_pad(dechex($this->foreColor), 6, 0, STR_PAD_LEFT));
$image = new \Imagick();
$image->newImage($this->width, $this->height, $backColor);
$draw = new \ImagickDraw();
$draw->setFont($this->fontFile);
$draw->setFontSize(30);
$fontMetrics = $image->queryFontMetrics($draw, $code);
$length = strlen($code);
$w = (int) $fontMetrics['textWidth'] - 8 + $this->offset * ($length - 1);
$h = (int) $fontMetrics['textHeight'] - 8;
$scale = min(($this->width - $this->padding * 2) / $w, ($this->height - $this->padding * 2) / $h);
$x = 10;
$y = round($this->height * 27 / 40);
for ($i = 0; $i < $length; ++$i) {
$draw = new \ImagickDraw();
$draw->setFont($this->fontFile);
$draw->setFontSize((int) (mt_rand(26, 32) * $scale * 0.8));
$draw->setFillColor($foreColor);
$image->annotateImage($draw, $x, $y, mt_rand(-10, 10), $code[$i]);
$fontMetrics = $image->queryFontMetrics($draw, $code[$i]);
$x += (int) $fontMetrics['textWidth'] + $this->offset;
}
$image->setImageFormat('png');
return $image->getImageBlob();
} | CWE-330 | 12 |
function current_user_get_bug_filter( $p_project_id = null ) {
$f_filter_string = gpc_get_string( 'filter', '' );
$t_filter = '';
if( !is_blank( $f_filter_string ) ) {
if( is_numeric( $f_filter_string ) ) {
$t_token = token_get_value( TOKEN_FILTER );
if( null != $t_token ) {
$t_filter = json_decode( $t_token, true );
}
} else {
$t_filter = json_decode( $f_filter_string, true );
}
$t_filter = filter_ensure_valid_filter( $t_filter );
} else if( !filter_is_cookie_valid() ) {
$t_filter = filter_get_default();
} else {
$t_user_id = auth_get_current_user_id();
$t_filter = user_get_bug_filter( $t_user_id, $p_project_id );
}
return $t_filter;
} | CWE-200 | 10 |
function test_username_avoids_anon_flow() {
add_filter( 'xmlrpc_allow_anonymous_comments', '__return_true' );
$comment_args = array(
1,
'administrator',
'administrator',
self::$post->ID,
array(
'author' => 'WordPress',
'author_email' => 'noreply at wordpress.org',
'content' => 'Test Anon Comments',
),
);
$result = $this->myxmlrpcserver->wp_newComment( $comment_args );
$comment = get_comment( $result );
$user_id = get_user_by( 'login', 'administrator' )->ID;
$this->assertSame( $user_id, (int) $comment->user_id );
} | CWE-862 | 8 |
function prepareInputForUpdate($input) {
if (isset($input["rootdn_passwd"])) {
if (empty($input["rootdn_passwd"])) {
unset($input["rootdn_passwd"]);
} else {
$input["rootdn_passwd"] = Toolbox::encrypt(stripslashes($input["rootdn_passwd"]),
GLPIKEY);
}
}
if (isset($input["_blank_passwd"]) && $input["_blank_passwd"]) {
$input['rootdn_passwd'] = '';
}
// Set attributes in lower case
if (count($input)) {
foreach ($input as $key => $val) {
if (preg_match('/_field$/', $key)) {
$input[$key] = Toolbox::strtolower($val);
}
}
}
//do not permit to override sync_field
if ($this->isSyncFieldEnabled()
&& isset($input['sync_field'])
&& $this->isSyncFieldUsed()
) {
if ($input['sync_field'] == $this->fields['sync_field']) {
unset($input['sync_field']);
} else {
Session::addMessageAfterRedirect(
__('Synchronization field cannot be changed once in use.'),
false,
ERROR
);
return false;
};
}
return $input;
} | CWE-327 | 3 |
function edit_internalalias() {
$section = isset($this->params['id']) ? $this->section->find($this->params['id']) : new section($this->params);
if ($section->parent == -1) {
notfoundController::handle_not_found();
exit;
} // doesn't work for standalone pages
if (empty($section->id)) {
$section->public = 1;
if (!isset($section->parent)) {
// This is another precaution. The parent attribute
// should ALWAYS be set by the caller.
//FJD - if that's the case, then we should die.
notfoundController::handle_not_authorized();
exit;
//$section->parent = 0;
}
}
assign_to_template(array(
'section' => $section,
'glyphs' => self::get_glyphs(),
));
}
| CWE-74 | 1 |
function configure() {
expHistory::set('editable', $this->params);
// little bit of trickery so that that categories can have their own configs
$this->loc->src = "@globalstoresettings";
$config = new expConfig($this->loc);
$this->config = $config->config;
$pullable_modules = expModules::listInstalledControllers($this->baseclassname, $this->loc);
$views = expTemplate::get_config_templates($this, $this->loc);
$gc = new geoCountry();
$countries = $gc->find('all');
$gr = new geoRegion();
$regions = $gr->find('all');
assign_to_template(array(
'config'=>$this->config,
'pullable_modules'=>$pullable_modules,
'views'=>$views,
'countries'=>$countries,
'regions'=>$regions,
'title'=>static::displayname()
));
} | CWE-74 | 1 |
public function remove()
{
$this->checkCSRFParam();
$project = $this->getProject();
$category = $this->getCategory();
if ($this->categoryModel->remove($category['id'])) {
$this->flash->success(t('Category removed successfully.'));
} else {
$this->flash->failure(t('Unable to remove this category.'));
}
$this->response->redirect($this->helper->url->to('CategoryController', 'index', array('project_id' => $project['id'])));
} | CWE-200 | 10 |
public static function isPublic($s) {
if ($s == null) {
return false;
}
while ($s->public && $s->parent > 0) {
$s = new section($s->parent);
}
$lineage = (($s->public) ? 1 : 0);
return $lineage;
}
| CWE-74 | 1 |
foreach ($days as $event) {
if (empty($event->eventdate->date) || ($viewrange == 'upcoming' && $event->eventdate->date < time()))
break;
if (empty($event->eventstart))
$event->eventstart = $event->eventdate->date;
$extitem[] = $event;
}
| CWE-74 | 1 |
private function getCategory()
{
$category = $this->categoryModel->getById($this->request->getIntegerParam('category_id'));
if (empty($category)) {
throw new PageNotFoundException();
}
return $category;
} | CWE-200 | 10 |
public function delete() {
global $db;
/* The global constants can be overriden by passing appropriate params */
//sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet
// $require_login = empty($this->params['require_login']) ? COMMENTS_REQUIRE_LOGIN : $this->params['require_login'];
// $require_approval = empty($this->params['require_approval']) ? COMMENTS_REQUIRE_APPROVAL : $this->params['require_approval'];
// $require_notification = empty($this->params['require_notification']) ? COMMENTS_REQUIRE_NOTIFICATION : $this->params['require_notification'];
// $notification_email = empty($this->params['notification_email']) ? COMMENTS_NOTIFICATION_EMAIL : $this->params['notification_email'];
if (empty($this->params['id'])) {
flash('error', gt('Missing id for the comment you would like to delete'));
expHistory::back();
}
// delete the comment
$comment = new expComment($this->params['id']);
$comment->delete();
// delete the association too
$db->delete($comment->attachable_table, 'expcomments_id='.$this->params['id']);
// send the user back where they came from.
expHistory::back();
} | CWE-74 | 1 |
private function getSwimlane()
{
$swimlane = $this->swimlaneModel->getById($this->request->getIntegerParam('swimlane_id'));
if (empty($swimlane)) {
throw new PageNotFoundException();
}
return $swimlane;
} | CWE-200 | 10 |
$temp_result_value = str_replace( $search, $v, $subject );
$rendered_values[] = $temp_result_value;
}
return [
implode( $delimiter, $rendered_values ),
'noparse' => false,
'isHTML' => false
];
} | CWE-400 | 2 |
function test_allowed_anon_comments() {
add_filter( 'xmlrpc_allow_anonymous_comments', '__return_true' );
$comment_args = array(
1,
'',
'',
self::$post->ID,
array(
'author' => 'WordPress',
'author_email' => '[email protected]',
'content' => 'Test Anon Comments',
),
);
$result = $this->myxmlrpcserver->wp_newComment( $comment_args );
$this->assertNotIXRError( $result );
$this->assertInternalType( 'int', $result );
} | CWE-862 | 8 |
public function testAuthCheckAuthFails()
{
$GLOBALS['cfg']['Server']['auth_swekey_config'] = 'testConfigSwekey';
$GLOBALS['server'] = 1;
$_REQUEST['old_usr'] = '';
$_REQUEST['pma_username'] = '';
$_COOKIE['pmaServer-1'] = 'pmaServ1';
$_COOKIE['pmaUser-1'] = 'pmaUser1';
$_COOKIE['pma_iv-1'] = base64_encode('testiv09testiv09');
$GLOBALS['cfg']['blowfish_secret'] = 'secret';
$_SESSION['last_access_time'] = 1;
$_SESSION['last_valid_captcha'] = true;
$GLOBALS['cfg']['LoginCookieValidity'] = 0;
$_SESSION['last_access_time'] = -1;
// mock for blowfish function
$this->object = $this->getMockBuilder('AuthenticationCookie')
->disableOriginalConstructor()
->setMethods(array('authFails'))
->getMock();
$this->object->expects($this->once())
->method('authFails');
$this->assertFalse(
$this->object->authCheck()
);
$this->assertTrue(
$GLOBALS['no_activity']
);
} | CWE-200 | 10 |
public static function referenceFixtures() {
return array(
'campaign' => array ('Campaign', '.CampaignMailingBehaviorTest'),
'lists' => 'X2List',
'credentials' => 'Credentials',
'users' => 'User',
'profile' => array('Profile','.marketing')
);
} | CWE-20 | 0 |
public static function _date2timestamp( $datetime, $wtz=null ) {
if( !isset( $datetime['hour'] )) $datetime['hour'] = 0;
if( !isset( $datetime['min'] )) $datetime['min'] = 0;
if( !isset( $datetime['sec'] )) $datetime['sec'] = 0;
if( empty( $wtz ) && ( !isset( $datetime['tz'] ) || empty( $datetime['tz'] )))
return mktime( $datetime['hour'], $datetime['min'], $datetime['sec'], $datetime['month'], $datetime['day'], $datetime['year'] );
$output = $offset = 0;
if( empty( $wtz )) {
if( iCalUtilityFunctions::_isOffset( $datetime['tz'] )) {
$offset = iCalUtilityFunctions::_tz2offset( $datetime['tz'] ) * -1;
$wtz = 'UTC';
}
else
$wtz = $datetime['tz'];
}
if(( 'Z' == $wtz ) || ( 'GMT' == strtoupper( $wtz )))
$wtz = 'UTC';
try {
$strdate = sprintf( '%04d-%02d-%02d %02d:%02d:%02d', $datetime['year'], $datetime['month'], $datetime['day'], $datetime['hour'], $datetime['min'], $datetime['sec'] );
$d = new DateTime( $strdate, new DateTimeZone( $wtz ));
if( 0 != $offset ) // adjust for offset
$d->modify( $offset.' seconds' );
$output = $d->format( 'U' );
unset( $d );
}
catch( Exception $e ) {
$output = mktime( $datetime['hour'], $datetime['min'], $datetime['sec'], $datetime['month'], $datetime['day'], $datetime['year'] );
}
return $output;
}
| CWE-74 | 1 |
public function register()
{
JSession::checkToken('post') or jexit(JText::_('JINVALID_TOKEN'));
// Get the application
$app = JFactory::getApplication();
// Get the form data.
$data = $this->input->post->get('user', array(), 'array');
// Get the model and validate the data.
$model = $this->getModel('Registration', 'UsersModel');
$form = $model->getForm();
if (!$form)
{
JError::raiseError(500, $model->getError());
return false;
}
$return = $model->validate($form, $data);
// Check for errors.
if ($return === false)
{
// Get the validation messages.
$errors = $model->getErrors();
// Push up to three validation messages out to the user.
for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++)
{
if ($errors[$i] instanceof Exception)
{
$app->enqueueMessage($errors[$i]->getMessage(), 'notice');
continue;
}
$app->enqueueMessage($errors[$i], 'notice');
}
// Save the data in the session.
$app->setUserState('users.registration.form.data', $data);
// Redirect back to the registration form.
$this->setRedirect('index.php?option=com_users&view=registration');
return false;
}
// Finish the registration.
$return = $model->register($data);
// Check for errors.
if ($return === false)
{
// Save the data in the session.
$app->setUserState('users.registration.form.data', $data);
// Redirect back to the registration form.
$message = JText::sprintf('COM_USERS_REGISTRATION_SAVE_FAILED', $model->getError());
$this->setRedirect('index.php?option=com_users&view=registration', $message, 'error');
return false;
}
// Flush the data from the session.
$app->setUserState('users.registration.form.data', null);
return true;
} | CWE-20 | 0 |
public function toolbar() {
// global $user;
$menu = array();
$dirs = array(
BASE.'framework/modules/administration/menus',
BASE.'themes/'.DISPLAY_THEME.'/modules/administration/menus'
);
foreach ($dirs as $dir) {
if (is_readable($dir)) {
$dh = opendir($dir);
while (($file = readdir($dh)) !== false) {
if (substr($file,-4,4) == '.php' && is_readable($dir.'/'.$file) && is_file($dir.'/'.$file)) {
$menu[substr($file,0,-4)] = include($dir.'/'.$file);
if (empty($menu[substr($file,0,-4)])) unset($menu[substr($file,0,-4)]);
}
}
}
}
// sort the top level menus alphabetically by filename
ksort($menu);
$sorted = array();
foreach($menu as $m) $sorted[] = $m;
// slingbar position
if (isset($_COOKIE['slingbar-top'])){
$top = $_COOKIE['slingbar-top'];
} else {
$top = SLINGBAR_TOP;
}
assign_to_template(array(
'menu'=>(bs3()) ? $sorted : json_encode($sorted),
"top"=>$top
));
} | CWE-74 | 1 |
public static function upload_user_avatar() {
$file = $_FILES['lp-upload-avatar'];
$upload_dir = learn_press_user_profile_picture_upload_dir();
add_filter( 'upload_dir', array( __CLASS__, '_user_avatar_upload_dir' ), 10000 );
$result = wp_handle_upload(
$file,
array(
'test_form' => false,
)
);
remove_filter( 'upload_dir', array( __CLASS__, '_user_avatar_upload_dir' ), 10000 );
if ( is_array( $result ) ) {
$result['name'] = $upload_dir['subdir'] . '/' . basename( $result['file'] );
unset( $result['file'] );
} else {
$result = array(
'error' => __( 'Profile picture upload failed', 'learnpress' ),
);
}
learn_press_send_json( $result );
} | CWE-610 | 17 |
public function fromData($data, $filename)
{
if ($data === null) {
return;
}
$tempPath = temp_path(basename($filename));
FileHelper::put($tempPath, $data);
$file = $this->fromFile($tempPath);
FileHelper::delete($tempPath);
return $file;
} | CWE-362 | 18 |
public static function parseAndTrimExport($str, $isHTML = false) { //�Death from above�? �
//echo "1<br>"; eDebug($str);
$str = str_replace("�", "’", $str);
$str = str_replace("�", "‘", $str);
$str = str_replace("�", "®", $str);
$str = str_replace("�", "-", $str);
$str = str_replace("�", "—", $str);
$str = str_replace("�", "”", $str);
$str = str_replace("�", "“", $str);
$str = str_replace("\r\n", " ", $str);
$str = str_replace("\t", " ", $str);
$str = str_replace(",", "\,", $str);
$str = str_replace("�", "¼", $str);
$str = str_replace("�", "½", $str);
$str = str_replace("�", "¾", $str);
if (!$isHTML) {
$str = str_replace('\"', """, $str);
$str = str_replace('"', """, $str);
} else {
$str = str_replace('"', '""', $str);
}
//$str = htmlspecialchars($str);
//$str = utf8_encode($str);
$str = trim(str_replace("�", "™", $str));
//echo "2<br>"; eDebug($str,die);
return $str;
} | CWE-74 | 1 |
public function scopeSearch(Builder $query, array $search = [])
{
if (empty($search)) {
return $query;
}
if (!array_intersect(array_keys($search), $this->searchable)) {
return $query;
}
return $query->where($search);
} | CWE-287 | 4 |
function updateObject($object, $table, $where=null, $identifier='id', $is_revisioned=false) {
if ($is_revisioned) {
$object->revision_id++;
//if ($table=="text") eDebug($object);
$res = $this->insertObject($object, $table);
//if ($table=="text") eDebug($object,true);
$this->trim_revisions($table, $object->$identifier, WORKFLOW_REVISION_LIMIT);
return $res;
}
$sql = "UPDATE " . $this->prefix . "$table SET ";
foreach (get_object_vars($object) as $var => $val) {
//We do not want to save any fields that start with an '_'
//if($is_revisioned && $var=='revision_id') $val++;
if ($var{0} != '_') {
if (is_array($val) || is_object($val)) {
$val = serialize($val);
$sql .= "`$var`='".$val."',";
} else {
$sql .= "`$var`='" . $this->escapeString($val) . "',";
}
}
}
$sql = substr($sql, 0, -1) . " WHERE ";
if ($where != null)
$sql .= $this->injectProof($where);
else
$sql .= "`" . $identifier . "`=" . $object->$identifier;
//if ($table == 'text') eDebug($sql,true);
$res = (@mysqli_query($this->connection, $sql) != false);
return $res;
} | CWE-74 | 1 |
function edit() {
global $user;
/* The global constants can be overriden by passing appropriate params */
//sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet
$require_login = empty($this->params['require_login']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];
$require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];
$require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];
$notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];
if (empty($this->params['formtitle']))
{
if (empty($this->params['id']))
{
$formtitle = gt("Add New Note");
}
else
{
$formtitle = gt("Edit Note");
}
}
else
{
$formtitle = $this->params['formtitle'];
}
$id = empty($this->params['id']) ? null : $this->params['id'];
$simpleNote = new expSimpleNote($id);
//FIXME here is where we might sanitize the note before displaying/editing it
assign_to_template(array(
'simplenote'=>$simpleNote,
'user'=>$user,
'require_login'=>$require_login,
'require_approval'=>$require_approval,
'require_notification'=>$require_notification,
'notification_email'=>$notification_email,
'formtitle'=>$formtitle,
'content_type'=>$this->params['content_type'],
'content_id'=>$this->params['content_id'],
'tab'=>empty($this->params['tab'])?0:$this->params['tab']
));
} | CWE-74 | 1 |
static function description() { return gt("Places navigation links/menus on the page."); }
| CWE-74 | 1 |
public static function DragnDropReRank2() {
global $router, $db;
$id = $router->params['id'];
$page = new section($id);
$old_rank = $page->rank;
$old_parent = $page->parent;
$new_rank = $router->params['position'] + 1; // rank
$new_parent = intval($router->params['parent']);
$db->decrement($page->tablename, 'rank', 1, 'rank>' . $old_rank . ' AND parent=' . $old_parent); // close in hole
$db->increment($page->tablename, 'rank', 1, 'rank>=' . $new_rank . ' AND parent=' . $new_parent); // make room
$params = array();
$params['parent'] = $new_parent;
$params['rank'] = $new_rank;
$page->update($params);
self::checkForSectionalAdmins($id);
expSession::clearAllUsersSessionCache('navigation');
}
| CWE-74 | 1 |
function productFeed() {
// global $db;
//check query password to avoid DDOS
/*
* condition = new
* description
* id - SKU
* link
* price
* title
* brand - manufacturer
* image link - fullsized image, up to 10, comma seperated
* product type - category - "Electronics > Audio > Audio Accessories MP3 Player Accessories","Health & Beauty > Healthcare > Biometric Monitors > Pedometers"
*/
$out = '"id","condition","description","like","price","title","brand","image link","product type"' . chr(13) . chr(10);
$p = new product();
$prods = $p->find('all', 'parent_id=0 AND ');
//$prods = $db->selectObjects('product','parent_id=0 AND');
} | CWE-74 | 1 |
$text = preg_replace($exp, '', $text);
}
// Primary expression to filter out tags
$exp = '/(?:^|\s|\.)(#\w+[-\w]+\w+|#\w+)(?:$|[^\'"])/u';
$matches = array();
preg_match_all($exp, $text, $matches);
return $matches;
} | CWE-20 | 0 |
public function validate() {
global $db;
// check for an sef url field. If it exists make sure it's valid and not a duplicate
//this needs to check for SEF URLS being turned on also: TODO
if (property_exists($this, 'sef_url') && !(in_array('sef_url', $this->do_not_validate))) {
if (empty($this->sef_url)) $this->makeSefUrl();
if (!isset($this->validates['is_valid_sef_name']['sef_url'])) $this->validates['is_valid_sef_name']['sef_url'] = array();
if (!isset($this->validates['uniqueness_of']['sef_url'])) $this->validates['uniqueness_of']['sef_url'] = array();
}
// safeguard again loc data not being pass via forms...sometimes this happens when you're in a router
// mapped view and src hasn't been passed in via link to the form
if (isset($this->id) && empty($this->location_data)) {
$loc = $db->selectValue($this->tablename, 'location_data', 'id=' . $this->id);
if (!empty($loc)) $this->location_data = $loc;
}
// run the validation as defined in the models
if (!isset($this->validates)) return true;
$messages = array();
$post = empty($_POST) ? array() : expString::sanitize($_POST);
foreach ($this->validates as $validation=> $field) {
foreach ($field as $key=> $value) {
$fieldname = is_numeric($key) ? $value : $key;
$opts = is_numeric($key) ? array() : $value;
$ret = expValidator::$validation($fieldname, $this, $opts);
if (!is_bool($ret)) {
$messages[] = $ret;
expValidator::setErrorField($fieldname);
unset($post[$fieldname]);
}
}
}
if (count($messages) >= 1) expValidator::failAndReturnToForm($messages, $post);
} | CWE-74 | 1 |
recyclebin::sendToRecycleBin($loc, $parent);
//FIXME if we delete the module & sectionref the module completely disappears
// if (class_exists($secref->module)) {
// $modclass = $secref->module;
// //FIXME: more module/controller glue code
// if (expModules::controllerExists($modclass)) {
// $modclass = expModules::getControllerClassName($modclass);
// $mod = new $modclass($loc->src);
// $mod->delete_instance();
// } else {
// $mod = new $modclass();
// $mod->deleteIn($loc);
// }
// }
}
// $db->delete('sectionref', 'section=' . $parent);
$db->delete('section', 'parent=' . $parent);
}
| CWE-74 | 1 |
$this->markTestSkipped('Function openssl_random_pseudo_bytes need LibreSSL version >=2.1.5 or Windows system on server');
}
}
static::$functions = $functions;
// test various string lengths
for ($length = 1; $length < 64; $length++) {
$key1 = $this->security->generateRandomKey($length);
$this->assertInternalType('string', $key1);
$this->assertEquals($length, strlen($key1));
$key2 = $this->security->generateRandomKey($length);
$this->assertInternalType('string', $key2);
$this->assertEquals($length, strlen($key2));
if ($length >= 7) { // avoid random test failure, short strings are likely to collide
$this->assertNotEquals($key1, $key2);
}
}
// test for /dev/urandom, reading larger data to see if loop works properly
$length = 1024 * 1024;
$key1 = $this->security->generateRandomKey($length);
$this->assertInternalType('string', $key1);
$this->assertEquals($length, strlen($key1));
$key2 = $this->security->generateRandomKey($length);
$this->assertInternalType('string', $key2);
$this->assertEquals($length, strlen($key2));
$this->assertNotEquals($key1, $key2);
// force /dev/urandom reading loop to deal with chunked data
// the above test may have read everything in one run.
// not sure if this can happen in real life but if it does
// we should be prepared
static::$fopen = fopen('php://memory', 'rwb');
$length = 1024 * 1024;
$key1 = $this->security->generateRandomKey($length);
$this->assertInternalType('string', $key1);
$this->assertEquals($length, strlen($key1));
} | CWE-330 | 12 |
public function testLogout()
{
$GLOBALS['cfg']['Server']['auth_swekey_config'] = '';
$GLOBALS['cfg']['CaptchaLoginPrivateKey'] = '';
$GLOBALS['cfg']['CaptchaLoginPublicKey'] = '';
$_REQUEST['old_usr'] = 'pmaolduser';
$GLOBALS['cfg']['LoginCookieDeleteAll'] = false;
$GLOBALS['cfg']['Servers'] = array(1);
$GLOBALS['server'] = 1;
$_COOKIE['pmaPass-1'] = 'test';
$this->object->authCheck();
$this->assertFalse(
isset($_COOKIE['pmaPass-1'])
);
} | CWE-200 | 10 |
private function isWindows()
{
return DIRECTORY_SEPARATOR !== '/';
} | CWE-330 | 12 |
$escapedArgument .= '^%"'.substr($part, 1, -1).'"^%';
} else {
// escape trailing backslash
if ('\\' === substr($part, -1)) {
$part .= '\\';
}
$quote = true;
$escapedArgument .= $part;
}
}
if ($quote) {
$escapedArgument = '"'.$escapedArgument.'"';
}
return $escapedArgument;
} | CWE-77 | 14 |
} elseif (!empty($this->params['src'])) {
if ($this->params['src'] == $loc->src) {
$this->config = $config->config;
break;
}
}
}
| CWE-74 | 1 |
private function userCanSeeUserGroups($project_id)
{
$project = $this->project_manager->getProject($project_id);
$user = $this->user_manager->getCurrentUser();
ProjectAuthorization::userCanAccessProject($user, $project, new URLVerification());
return true;
} | CWE-863 | 11 |
private static function verifySignature($signature, $input, $key, $algo = 'HS256')
{
switch ($algo) {
case'HS256':
case'HS384':
case'HS512':
return JWT::sign($input, $key, $algo) === $signature;
case 'RS256':
return (boolean) openssl_verify($input, $signature, $key, OPENSSL_ALGO_SHA256);
case 'RS384':
return (boolean) openssl_verify($input, $signature, $key, OPENSSL_ALGO_SHA384);
case 'RS512':
return (boolean) openssl_verify($input, $signature, $key, OPENSSL_ALGO_SHA512);
default:
throw new Exception("Unsupported or invalid signing algorithm.");
}
} | CWE-20 | 0 |
$link = str_replace(URL_FULL, '', makeLink(array('section' => $section->id)));
| CWE-74 | 1 |
public function actionGetItems(){
$sql = 'SELECT id, name as value FROM x2_opportunities WHERE name LIKE :qterm ORDER BY name ASC';
$command = Yii::app()->db->createCommand($sql);
$qterm = $_GET['term'].'%';
$command->bindParam(":qterm", $qterm, PDO::PARAM_STR);
$result = $command->queryAll();
echo CJSON::encode($result);
Yii::app()->end();
} | CWE-20 | 0 |
$query->whereExists(function ($permissionQuery) use (&$tableDetails, $action) {
/** @var Builder $permissionQuery */
$permissionQuery->select(['role_id'])->from('joint_permissions')
->whereColumn('joint_permissions.entity_id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
->whereColumn('joint_permissions.entity_type', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
->where('action', '=', $action)
->whereIn('role_id', $this->getCurrentUserRoles())
->where(function (QueryBuilder $query) {
$this->addJointHasPermissionCheck($query, $this->currentUser()->id);
});
});
}); | CWE-863 | 11 |
function XMLRPCaddImageGroupToComputerGroup($imageGroup, $computerGroup){
$imageid = getResourceGroupID("image/$imageGroup");
$compid = getResourceGroupID("computer/$computerGroup");
if($imageid && $compid){
$tmp = getUserResources(array("imageAdmin"),
array("manageMapping"), 1);
$imagegroups = $tmp['image'];
$tmp = getUserResources(array("computerAdmin"),
array("manageMapping"), 1);
$computergroups = $tmp['computer'];
if(array_key_exists($compid, $computergroups) &&
array_key_exists($imageid, $imagegroups)){
$mapping = getResourceMapping("image", "computer",
$imageid,
$compid);
if(!array_key_exists($imageid, $mapping) ||
!array_key_exists($compid, $mapping[$imageid])){
$query = "INSERT INTO resourcemap "
. "(resourcegroupid1, "
. "resourcetypeid1, "
. "resourcegroupid2, "
. "resourcetypeid2) "
. "VALUES ($imageid, "
. "13, "
. "$compid, "
. "12)";
doQuery($query, 101);
}
return array('status' => 'success');
} else {
return array('status' => 'error',
'errorcode' => 84,
'errormsg' => 'cannot access computer and/or image group');
}
} else {
return array('status' => 'error',
'errorcode' => 83,
'errormsg' => 'invalid resource group name');
}
} | CWE-20 | 0 |
function _setupMcrypt()
{
$this->_clearBuffers();
$this->enchanged = $this->dechanged = true;
if (!isset($this->enmcrypt)) {
static $mcrypt_modes = array(
self::MODE_CTR => 'ctr',
self::MODE_ECB => MCRYPT_MODE_ECB,
self::MODE_CBC => MCRYPT_MODE_CBC,
self::MODE_CFB => 'ncfb',
self::MODE_OFB => MCRYPT_MODE_NOFB,
self::MODE_STREAM => MCRYPT_MODE_STREAM,
);
$this->demcrypt = mcrypt_module_open($this->cipher_name_mcrypt, '', $mcrypt_modes[$this->mode], '');
$this->enmcrypt = mcrypt_module_open($this->cipher_name_mcrypt, '', $mcrypt_modes[$this->mode], '');
// we need the $ecb mcrypt resource (only) in MODE_CFB with enableContinuousBuffer()
// to workaround mcrypt's broken ncfb implementation in buffered mode
// see: {@link http://phpseclib.sourceforge.net/cfb-demo.phps}
if ($this->mode == self::MODE_CFB) {
$this->ecb = mcrypt_module_open($this->cipher_name_mcrypt, '', MCRYPT_MODE_ECB, '');
}
} // else should mcrypt_generic_deinit be called?
if ($this->mode == self::MODE_CFB) {
mcrypt_generic_init($this->ecb, $this->key, str_repeat("\0", $this->block_size));
}
} | CWE-200 | 10 |
$backup = ['sys' => $GLOBALS['TYPO3_CONF_VARS']['SYS'], 'server' => $_SERVER]; | CWE-20 | 0 |
public function search_external() {
// global $db, $user;
global $db;
$sql = "select DISTINCT(a.id) as id, a.source as source, a.firstname as firstname, a.middlename as middlename, a.lastname as lastname, a.organization as organization, a.email as email ";
$sql .= "from " . $db->prefix . "external_addresses as a "; //R JOIN " .
//$db->prefix . "billingmethods as bm ON bm.addresses_id=a.id ";
$sql .= " WHERE match (a.firstname,a.lastname,a.email,a.organization) against ('" . $this->params['query'] .
"*' IN BOOLEAN MODE) ";
$sql .= "order by match (a.firstname,a.lastname,a.email,a.organization) against ('" . $this->params['query'] . "*' IN BOOLEAN MODE) ASC LIMIT 12";
$res = $db->selectObjectsBySql($sql);
foreach ($res as $key=>$record) {
$res[$key]->title = $record->firstname . ' ' . $record->lastname;
}
//eDebug($sql);
$ar = new expAjaxReply(200, gt('Here\'s the items you wanted'), $res);
$ar->send();
} | CWE-74 | 1 |
public function editAlt() {
global $user;
$file = new expFile($this->params['id']);
if ($user->id==$file->poster || $user->isAdmin()) {
$file->alt = $this->params['newValue'];
$file->save();
$ar = new expAjaxReply(200, gt('Your alt was updated successfully'), $file);
} else {
$ar = new expAjaxReply(300, gt("You didn't create this file, so you can't edit it."));
}
$ar->send();
echo json_encode($file); //FIXME we exit before hitting this
} | CWE-74 | 1 |
Subsets and Splits