diff --git "a/train.jsonl" "b/train.jsonl" --- "a/train.jsonl" +++ "b/train.jsonl" @@ -1,4554 +1,4551 @@ -{"code": "\t\tpublic function removeRemote($name)\n\t\t{\n\t\t\t$this->run('remote', 'remove', $name);\n\t\t\treturn $this;\n\t\t}", "label_name": "CWE-77", "label": "77"} -{"code": " public function enable()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $swimlane_id = $this->request->getIntegerParam('swimlane_id');\n\n if ($this->swimlaneModel->enable($project['id'], $swimlane_id)) {\n $this->flash->success(t('Swimlane updated successfully.'));\n } else {\n $this->flash->failure(t('Unable to update this swimlane.'));\n }\n\n $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public function manage_messages() {\n expHistory::set('manageable', $this->params);\n \n $page = new expPaginator(array(\n\t\t\t'model'=>'order_status_messages',\n\t\t\t'where'=>1,\n 'limit'=>10,\n\t\t\t'order'=>'body',\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->params['controller'],\n 'action'=>$this->params['action'],\n\t\t\t//'columns'=>array('Name'=>'title')\n ));\n\n //eDebug($page);\n\t\tassign_to_template(array(\n 'page'=>$page\n ));\n }", "label_name": "CWE-74", "label": "74"} -{"code": "\tpublic function update_version() {\n\t // get the current version\n\t $hv = new help_version();\n\t $current_version = $hv->find('first', 'is_current=1');\n\t \n\t // check to see if the we have a new current version and unset the old current version.\n\t if (!empty($this->params['is_current'])) {\n//\t $db->sql('UPDATE '.DB_TABLE_PREFIX.'_help_version set is_current=0');\n help_version::clearHelpVersion();\n\t }\n\t expSession::un_set('help-version');\n\n\t // save the version\n\t $id = empty($this->params['id']) ? null : $this->params['id'];\n\t $version = new help_version();\n\t // if we don't have a current version yet so we will force this one to be it\n\t if (empty($current_version->id)) $this->params['is_current'] = 1;\n\t $version->update($this->params);\n\t \n\t // if this is a new version we need to copy over docs\n\t if (empty($id)) {\n\t self::copydocs($current_version->id, $version->id);\t \n\t }\n // let's update the search index to reflect the current help version\n searchController::spider();\n\n\t flash('message', gt('Saved help version').' '.$version->version);\n\t expHistory::back();\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": " $date->delete(); // event automatically deleted if all assoc eventdates are deleted\r\n }\r\n expHistory::back();\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " ->where('owned_by', '=', $userIdToCheck);\n });\n }", "label_name": "CWE-863", "label": "863"} -{"code": " function addDiscountToCart() {\n// global $user, $order;\n global $order;\n //lookup discount to see if it's real and valid, and not already in our cart\n //this will change once we allow more than one coupon code\n\n $discount = new discounts();\n $discount = $discount->getCouponByName($this->params['coupon_code']);\n\n if (empty($discount)) {\n flash('error', gt(\"This discount code you entered does not exist.\"));\n //redirect_to(array('controller'=>'cart', 'action'=>'checkout')); \n expHistory::back();\n }\n\n //check to see if it's in our cart already\n if ($this->isDiscountInCart($discount->id)) {\n flash('error', gt(\"This discount code is already in your cart.\"));\n //redirect_to(array('controller'=>'cart', 'action'=>'checkout'));\n expHistory::back();\n }\n\n //this should really be reworked, as it shoudn't redirect directly and not return\n $validateDiscountMessage = $discount->validateDiscount();\n if ($validateDiscountMessage == \"\") {\n //if all good, add to cart, otherwise it will have redirected\n $od = new order_discounts();\n $od->orders_id = $order->id;\n $od->discounts_id = $discount->id;\n $od->coupon_code = $discount->coupon_code;\n $od->title = $discount->title;\n $od->body = $discount->body;\n $od->save();\n // set this to just the discount applied via this coupon?? if so, when though? $od->discount_total = ??;\n flash('message', gt(\"The discount code has been applied to your cart.\"));\n } else {\n flash('error', $validateDiscountMessage);\n }\n //redirect_to(array('controller'=>'cart', 'action'=>'checkout')); \n expHistory::back();\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\tpublic static function dplChapterParserFunction( &$parser, $text = '', $heading = ' ', $maxLength = -1, $page = '?page?', $link = 'default', $trim = false ) {\n\t\t$parser->addTrackingCategory( 'dplchapter-parserfunc-tracking-category' );\n\t\t$output = \\DPL\\LST::extractHeadingFromText( $parser, $page, '?title?', $text, $heading, '', $sectionHeading, true, $maxLength, $link, $trim );\n\t\treturn $output[0];\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": "\tpublic function __construct() {\n\t\t$this->setRichness( Config::getSetting( 'functionalRichness' ) );\n\n\t\tif ( \\DynamicPageListHooks::isLikeIntersection() ) {\n\t\t\t$this->data['ordermethod'] = [\n\t\t\t\t'default'\t=> 'categoryadd',\n\t\t\t\t'values'\t=> [\n\t\t\t\t\t'categoryadd',\n\t\t\t\t\t'lastedit',\n\t\t\t\t\t'none'\n\t\t\t\t]\n\t\t\t];\n\t\t\t$this->data['order'] = [\n\t\t\t\t'default'\t=> 'descending',\n\t\t\t\t'values'\t=> [\n\t\t\t\t\t'ascending',\n\t\t\t\t\t'descending'\n\t\t\t\t]\n\t\t\t];\n\t\t\t$this->data['mode'] = [\n\t\t\t\t'default'\t=> 'unordered',\n\t\t\t\t'values'\t=> [\n\t\t\t\t\t'none',\n\t\t\t\t\t'ordered',\n\t\t\t\t\t'unordered'\n\t\t\t\t]\n\t\t\t];\n\t\t\t$this->data['userdateformat'] = [\n\t\t\t\t'default' => 'Y-m-d: '\n\t\t\t];\n\t\t\t$this->data['allowcachedresults']['default'] = 'true';\n\t\t}\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": "\tfunction unlockTables() {\n $sql = \"UNLOCK TABLES\";\n \n $res = mysqli_query($this->connection, $sql);\n return $res;\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public static function validateNumber(\n $path,\n $values,\n $allow_neg,\n $allow_zero,\n $max_value,\n $error_string\n ) {\n if ($values[$path] === '') {\n return '';\n }\n\n if (intval($values[$path]) != $values[$path]\n || (! $allow_neg && $values[$path] < 0)\n || (! $allow_zero && $values[$path] == 0)\n || $values[$path] > $max_value\n ) {\n return $error_string;\n }\n\n return '';\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public function approve_submit() {\n global $history;\n \n if (empty($this->params['id'])) {\n flash('error', gt('No ID supplied for comment to approve'));\n $lastUrl = expHistory::getLast('editable');\n }\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n $require_login = empty($this->params['require_login']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];\n $require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];\n $require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n $notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];\n \n $simplenote = new expSimpleNote($this->params['id']);\n //FIXME here is where we might sanitize the note before approving it\n $simplenote->body = $this->params['body'];\n $simplenote->approved = $this->params['approved'];\n $simplenote->save();\n \n $lastUrl = makelink($history->history[$history->history['lasts']['type']][count($history->history[$history->history['lasts']['type']])-1]['params']);\n if (!empty($this->params['tab']))\n {\n $lastUrl .= \"#\".$this->params['tab'];\n }\n redirect_to($lastUrl);\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function confirm()\n {\n $project = $this->getProject();\n $swimlane = $this->getSwimlane();\n\n $this->response->html($this->helper->layout->project('swimlane/remove', array(\n 'project' => $project,\n 'swimlane' => $swimlane,\n )));\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public function event()\n {\n $project = $this->getProject();\n $values = $this->request->getValues();\n\n if (empty($values['action_name']) || empty($values['project_id'])) {\n return $this->create();\n }\n\n return $this->response->html($this->template->render('action_creation/event', array(\n 'values' => $values,\n 'project' => $project,\n 'available_actions' => $this->actionManager->getAvailableActions(),\n 'events' => $this->actionManager->getCompatibleEvents($values['action_name']),\n )));\n }", "label_name": "CWE-200", "label": "200"} -{"code": " $comments->records[$key]->avatar = $db->selectObject('user_avatar',\"user_id='\".$record->poster.\"'\");\n }\n\n if (empty($this->params['config']['disable_nested_comments'])) $comments->records = self::arrangecomments($comments->records);\n // eDebug($sql, true);\n \n // count the unapproved comments\n if ($require_approval == 1 && $user->isAdmin()) {\n $sql = 'SELECT count(com.id) as c FROM '.$db->prefix.'expComments com ';\n $sql .= 'JOIN '.$db->prefix.'content_expComments cnt ON com.id=cnt.expcomments_id ';\n $sql .= 'WHERE cnt.content_id='.$this->params['content_id'].\" AND cnt.content_type='\".$this->params['content_type'].\"' \";\n $sql .= 'AND com.approved=0';\n $unapproved = $db->countObjectsBySql($sql);\n } else {\n $unapproved = 0;\n } \n \n $this->config = $this->params['config'];\n $type = !empty($this->params['type']) ? $this->params['type'] : gt('Comment');\n $ratings = !empty($this->params['ratings']) ? true : false;\n\n assign_to_template(array(\n 'comments'=>$comments,\n 'config'=>$this->params['config'],\n 'unapproved'=>$unapproved,\n\t\t\t'content_id'=>$this->params['content_id'], \n\t\t\t'content_type'=>$this->params['content_type'],\n\t\t\t'user'=>$user,\n\t\t\t'hideform'=>$this->params['hideform'],\n\t\t\t'hidecomments'=>$this->params['hidecomments'],\n\t\t\t'title'=>$this->params['title'],\n\t\t\t'formtitle'=>$this->params['formtitle'],\n 'type'=>$type,\n 'ratings'=>$ratings,\n 'require_login'=>$require_login,\n 'require_approval'=>$require_approval,\n 'require_notification'=>$require_notification,\n 'notification_email'=>$notification_email,\n\t\t));\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": " public static function canImportData() {\r\n return true;\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": "\tprivate static function dumpParsedRefs( $parser, $label ) {\n\t\t// if (!preg_match(\"/Query Q/\",$parser->mTitle->getText())) return '';\n\t\techo '
parser mLinks: ';\n\t\tob_start();\n\t\tvar_dump( $parser->getOutput()->mLinks );\n\t\t$a = ob_get_contents();\n\t\tob_end_clean();\n\t\techo htmlspecialchars( $a, ENT_QUOTES );\n\t\techo '
';\n\t\techo '
parser mTemplates: ';\n\t\tob_start();\n\t\tvar_dump( $parser->getOutput()->mTemplates );\n\t\t$a = ob_get_contents();\n\t\tob_end_clean();\n\t\techo htmlspecialchars( $a, ENT_QUOTES );\n\t\techo '
';\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " public function testIsExpiredReturnsTrueIfCompiledFileDoesntExist()\n {\n $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__);\n $files->shouldReceive('exists')->once()->with(__DIR__.'/'.sha1('foo').'.php')->andReturn(false);\n $this->assertTrue($compiler->isExpired('foo'));\n }", "label_name": "CWE-327", "label": "327"} -{"code": "\tfunction manage() {\n\t global $db;\n\t \n\t expHistory::set('manageable', $this->params);\n//\t $classes = array();\n $dir = BASE.\"framework/modules/ecommerce/billingcalculators\";\n if (is_readable($dir)) {\n $dh = opendir($dir);\n while (($file = readdir($dh)) !== false) {\n if (is_file(\"$dir/$file\") && substr(\"$dir/$file\", -4) == \".php\") {\n include_once(\"$dir/$file\");\n $classname = substr($file, 0, -4);\n $id = $db->selectValue('billingcalculator', 'id', 'calculator_name=\"'.$classname.'\"');\n if (empty($id)) {\n// $calobj = null;\n $calcobj = new $classname();\n if ($calcobj->isSelectable() == true) {\n $obj = new billingcalculator(array(\n 'title'=>$calcobj->name(),\n// 'user_title'=>$calcobj->title,\n 'body'=>$calcobj->description(), \n 'calculator_name'=>$classname,\n 'enabled'=>false));\n $obj->save();\n }\n }\n }\n }\n }\n \n $bcalc = new billingcalculator();\n $calculators = $bcalc->find('all');\n assign_to_template(array(\n 'calculators'=>$calculators\n ));\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": " function captureAuthorization() {\n //eDebug($this->params,true);\n $order = new order($this->params['id']);\n /*eDebug($this->params); \n //eDebug($order,true);*/\n //eDebug($order,true);\n //$billing = new billing();\n\n //eDebug($billing, true);\n //$billing->calculator = new $calcname($order->billingmethod[0]->billingcalculator_id);\n $calc = $order->billingmethod[0]->billingcalculator->calculator;\n $calc->config = $order->billingmethod[0]->billingcalculator->config;\n\n //$calc = new $calc-\n //eDebug($calc,true);\n if (!method_exists($calc, 'delayed_capture')) {\n flash('error', gt('The Billing Calculator does not support delayed capture'));\n expHistory::back();\n }\n\n $result = $calc->delayed_capture($order->billingmethod[0], $this->params['capture_amt'], $order);\n\n if (empty($result->errorCode)) {\n flash('message', gt('The authorized payment was successfully captured'));\n expHistory::back();\n\n } else {\n flash('error', gt('An error was encountered while capturing the authorized payment.') . '

' . $result->message);\n expHistory::back();\n }\n }", "label_name": "CWE-74", "label": "74"} -{"code": " function fread($handle, $length)\n {\n if (\\yiiunit\\framework\\base\\SecurityTest::$fread !== null) {\n return \\yiiunit\\framework\\base\\SecurityTest::$fread;\n }\n if (\\yiiunit\\framework\\base\\SecurityTest::$fopen !== null) {\n return $length < 8 ? \\str_repeat('s', $length) : 'test1234';\n }\n\n return \\fread($handle, $length);\n }", "label_name": "CWE-330", "label": "330"} -{"code": " static function displayname() {\n return gt(\"e-Commerce Category Manager\");\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function confirm()\n {\n $project = $this->getProject();\n\n $this->response->html($this->helper->layout->project('column/remove', array(\n 'column' => $this->columnModel->getById($this->request->getIntegerParam('column_id')),\n 'project' => $project,\n )));\n }", "label_name": "CWE-200", "label": "200"} -{"code": " function checkPassword($username, $password)\n {\n $doUser = OA_Dal::factoryDO('users');\n $doUser->username = strtolower($username);\n $doUser->password = md5($password);\n $doUser->find();\n\n if ($doUser->fetch()) {\n return $doUser;\n } else {\n return false;\n }\n }", "label_name": "CWE-287", "label": "287"} -{"code": "\tpublic static function init( $settings = false ) {\n\t\tif ( $settings === false ) {\n\t\t\tglobal $wgDplSettings;\n\n\t\t\t$settings = $wgDplSettings;\n\t\t}\n\n\t\tif ( !is_array( $settings ) ) {\n\t\t\tthrow new MWException( __METHOD__ . \": Invalid settings passed.\" );\n\t\t}\n\n\t\tself::$settings = array_merge( self::$settings, $settings );\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": "\t\t\tVariables::setVar( [ '', '', $argName, $argValue ] );\n\t\t\tif ( defined( 'ExtVariables::VERSION' ) ) {\n\t\t\t\t\\ExtVariables::get( $this->parser )->setVarValue( $argName, $argValue );\n\t\t\t}\n\t\t}\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " public function __construct(\n AuthManager $auth,\n Encrypter $encrypter,\n Google2FA $google2FA,\n Repository $config,\n CacheRepository $cache,\n RecoveryTokenRepository $recoveryTokenRepository,\n UserRepositoryInterface $repository\n ) {\n parent::__construct($auth, $config);\n\n $this->google2FA = $google2FA;\n $this->cache = $cache;\n $this->repository = $repository;\n $this->encrypter = $encrypter;\n $this->recoveryTokenRepository = $recoveryTokenRepository;\n }", "label_name": "CWE-287", "label": "287"} -{"code": " $link = str_replace(URL_FULL, '', makeLink(array('section' => $section->id)));\r", "label_name": "CWE-74", "label": "74"} -{"code": " public function showUnpublished() {\n expHistory::set('viewable', $this->params);\n \n // setup the where clause for looking up records.\n $where = parent::aggregateWhereClause();\n $where = \"((unpublish != 0 AND unpublish < \".time().\") OR (publish > \".time().\")) AND \".$where;\n if (isset($this->config['only_featured'])) $where .= ' AND is_featured=1';\n\n $page = new expPaginator(array(\n 'model'=>'news',\n 'where'=>$where,\n 'limit'=>25,\n 'order'=>'unpublish',\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->baseclassname,\n 'action'=>$this->params['action'],\n 'src'=>$this->loc->src,\n 'columns'=>array(\n gt('Title')=>'title',\n gt('Published On')=>'publish',\n gt('Status')=>'unpublish'\n ),\n ));\n \n assign_to_template(array(\n 'page'=>$page\n ));\n }", "label_name": "CWE-74", "label": "74"} -{"code": " $input = ['name' => 'ldap', 'rootdn_passwd' => $password];", "label_name": "CWE-327", "label": "327"} -{"code": " public static function parseAndTrimImport($str, $isHTML = false) { //\ufffdDeath from above\ufffd? \ufffd\n //echo \"1
\"; eDebug($str);\n// global $db;\n\n $str = str_replace(\"\ufffd\", \"’\", $str);\n $str = str_replace(\"\ufffd\", \"‘\", $str);\n $str = str_replace(\"\ufffd\", \"®\", $str);\n $str = str_replace(\"\ufffd\", \"-\", $str);\n $str = str_replace(\"\ufffd\", \"—\", $str);\n $str = str_replace(\"\ufffd\", \"”\", $str);\n $str = str_replace(\"\ufffd\", \"“\", $str);\n $str = str_replace(\"\\r\\n\", \" \", $str);\n $str = str_replace(\"\\,\", \",\", $str);\n $str = str_replace('\"\"', '\"', $str); //do this no matter what...in case someone added a quote in a non HTML field\n if (!$isHTML) {\n //if HTML, then leave the single quotes alone, otheriwse replace w/ special Char \n $str = str_replace('\"', \""\", $str);\n }\n $str = str_replace(\"\ufffd\", \"¼\", $str);\n $str = str_replace(\"\ufffd\", \"½\", $str);\n $str = str_replace(\"\ufffd\", \"¾\", $str);\n //$str = htmlspecialchars($str);\n //$str = utf8_encode($str);\n// if (DB_ENGINE=='mysqli') {\n//\t $str = @mysqli_real_escape_string($db->connection,trim(str_replace(\"\ufffd\", \"™\", $str)));\n// } elseif(DB_ENGINE=='mysql') {\n// $str = @mysql_real_escape_string(trim(str_replace(\"\ufffd\", \"™\", $str)),$db->connection);\n// } else {\n//\t $str = trim(str_replace(\"\ufffd\", \"™\", $str));\n// }\n $str = @expString::escape(trim(str_replace(\"\ufffd\", \"™\", $str)));\n //echo \"2
\"; eDebug($str,die);\n return $str;\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function testFirstTrustedProxyIsSetAsRemote()\n {\n $expectedSubRequest = Request::create('/');\n $expectedSubRequest->headers->set('Surrogate-Capability', 'abc=\"ESI/1.0\"');\n $expectedSubRequest->server->set('REMOTE_ADDR', '1.1.1.1');\n\n if (Request::getTrustedHeaderName(Request::HEADER_CLIENT_IP)) {\n $expectedSubRequest->headers->set('x-forwarded-for', array('127.0.0.1'));\n $expectedSubRequest->server->set('HTTP_X_FORWARDED_FOR', '127.0.0.1');\n }\n\n Request::setTrustedProxies(array('1.1.1.1'));\n\n $strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest($expectedSubRequest));\n\n $request = Request::create('/');\n $request->headers->set('Surrogate-Capability', 'abc=\"ESI/1.0\"');\n $strategy->render('/', $request);\n\n Request::setTrustedProxies(array());\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\tpublic function test_valid_comment_0_content() {\n\t\t$result = $this->myxmlrpcserver->wp_newComment(\n\t\t\tarray(\n\t\t\t\t1,\n\t\t\t\t'administrator',\n\t\t\t\t'administrator',\n\t\t\t\tself::$post->ID,\n\t\t\t\tarray(\n\t\t\t\t\t'content' => '0',\n\t\t\t\t),\n\t\t\t)\n\t\t);\n\n\t\t$this->assertNotIXRError( $result );\n\t}", "label_name": "CWE-862", "label": "862"} -{"code": " foreach ($flatArray as $key => $value) {\n $pattern = '/' . $key . '([^.]|$)/';\n if (preg_match($pattern, $expression, $matches)) {\n\n switch (gettype($flatArray[$key])) {\n case 'boolean':\n $expression = str_replace($key, $flatArray[$key] ? 'true' : 'false', $expression);\n break;\n case 'NULL':\n $expression = str_replace($key, 'false', $expression);\n break;\n case 'string':\n $expression = str_replace($key, '\"' . $flatArray[$key] . '\"', $expression);\n break;\n case 'object':\n $expression = self::executeClosure($expression, $key, $flatArray[$key], $flatArray);\n break;\n default:\n $expression = str_replace($key, $flatArray[$key], $expression);\n break;\n }\n $bool = eval(\"return $expression;\");\n }\n }", "label_name": "CWE-74", "label": "74"} -{"code": "\tfunction show_vendor () {\n\t\t$vendor = new vendor();\n\t\t\n\t\tif(isset($this->params['id'])) {\n\t\t\t$vendor = $vendor->find('first', 'id =' .$this->params['id']);\n\t\t\t$vendor_title = $vendor->title;\n\t\t\t$state = new geoRegion($vendor->state);\n\t\t\t$vendor->state = $state->name;\n\t\t\t//Removed unnecessary fields\n\t\t\tunset(\n $vendor->title,\n $vendor->table,\n $vendor->tablename,\n $vendor->classname,\n $vendor->identifier\n );\n\t\t\n\t\t\tassign_to_template(array(\n 'vendor_title' => $vendor_title,\n 'vendor'=>$vendor\n ));\n\t\t}\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": " public static function getIconName($module)\n {\n return isset(static::$iconNames[$module])\n ? static::$iconNames[$module]\n : strtolower(str_replace('_', '-', $module));\n }", "label_name": "CWE-863", "label": "863"} -{"code": " function reparent_standalone() {\r\n $standalone = $this->section->find($this->params['page']);\r\n if ($standalone) {\r\n $standalone->parent = $this->params['parent'];\r\n $standalone->update();\r\n expSession::clearAllUsersSessionCache('navigation');\r\n expHistory::back();\r\n } else {\r\n notfoundController::handle_not_found();\r\n }\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public function isLocal() {\n $localhosts = array('::1', '127.0.0.1', '0.0.0.0');\n return (\n in_array(server::get('SERVER_ADDR'), $localhosts) ||\n server::get('SERVER_NAME') == 'localhost' ||\n str::endsWith(server::get('SERVER_NAME'), '.localhost') ||\n str::endsWith(server::get('SERVER_NAME'), '.test')\n );\n }", "label_name": "CWE-346", "label": "346"} -{"code": " public function Hello($host = '') {\n $this->error = null; // so no confusion is caused\n\n if(!$this->connected()) {\n $this->error = array(\n \"error\" => \"Called Hello() without being connected\");\n return false;\n }\n\n // if hostname for HELO was not specified send default\n if(empty($host)) {\n // determine appropriate default to send to server\n $host = \"localhost\";\n }\n\n // Send extended hello first (RFC 2821)\n if(!$this->SendHello(\"EHLO\", $host)) {\n if(!$this->SendHello(\"HELO\", $host)) {\n return false;\n }\n }\n\n return true;\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\tpublic static function getStylesheet($styleName)\n\t{\n\t\t// Get custom stylesheet, of the default stylesheet if the custom stylesheet does not exist\n\t\t$stylesheet = get_option($styleName, '');\n\n\t\tif (strlen($stylesheet) <= 0)\n\t\t{\n\t\t\t$stylesheetFile = SlideshowPluginMain::getPluginPath() . DIRECTORY_SEPARATOR . 'style' . DIRECTORY_SEPARATOR . 'SlideshowPlugin' . DIRECTORY_SEPARATOR . $styleName . '.css';\n\n\t\t\tif (!file_exists($stylesheetFile))\n\t\t\t{\n\t\t\t\t$stylesheetFile = SlideshowPluginMain::getPluginPath() . DIRECTORY_SEPARATOR . 'style' . DIRECTORY_SEPARATOR . 'SlideshowPlugin' . DIRECTORY_SEPARATOR . 'style-light.css';\n\t\t\t}\n\n\t\t\t// Get contents of stylesheet\n\t\t\tob_start();\n\t\t\tinclude($stylesheetFile);\n\t\t\t$stylesheet .= ob_get_clean();\n\t\t}\n\n\t\t// Replace the URL placeholders with actual URLs and add a unique identifier to separate stylesheets\n\t\t$stylesheet = str_replace('%plugin-url%', SlideshowPluginMain::getPluginUrl(), $stylesheet);\n\t\t$stylesheet = str_replace('%site-url%', get_bloginfo('url'), $stylesheet);\n\t\t$stylesheet = str_replace('%stylesheet-url%', get_stylesheet_directory_uri(), $stylesheet);\n\t\t$stylesheet = str_replace('%template-url%', get_template_directory_uri(), $stylesheet);\n\t\t$stylesheet = str_replace('.slideshow_container', '.slideshow_container_' . $styleName, $stylesheet);\n\n\t\treturn $stylesheet;\n\t}", "label_name": "CWE-200", "label": "200"} -{"code": " public static function getHelpVersionId($version) {\n global $db;\n\n return $db->selectValue('help_version', 'id', 'version=\"'.$version.'\"');\n }", "label_name": "CWE-74", "label": "74"} -{"code": "function XMLRPCblockAllocation($imageid, $start, $end, $numMachines,\n $usergroupid, $ignoreprivileges=0) {\n\tglobal $user, $xmlrpcBlockAPIUsers;\n\tif(! in_array($user['id'], $xmlrpcBlockAPIUsers)) {\n\t\treturn array('status' => 'error',\n\t\t 'errorcode' => 34,\n\t\t 'errormsg' => 'access denied for managing block allocations');\n\t}\n\t$ownerid = getUserlistID('vclreload@Local');\n\t$name = \"API:$start\";\n\t$managementnodes = getManagementNodes('future');\n\tif(empty($managementnodes)) {\n\t\treturn array('status' => 'error',\n\t\t 'errorcode' => 12,\n\t\t 'errormsg' => 'could not allocate a management node to handle block allocation');\n\t}\n\t$mnid = array_rand($managementnodes);\n\t$query = \"INSERT INTO blockRequest \"\n\t . \"(name, \"\n\t . \"imageid, \"\n\t . \"numMachines, \"\n\t . \"groupid, \"\n\t . \"repeating, \"\n\t . \"ownerid, \"\n\t . \"admingroupid, \"\n\t . \"managementnodeid, \"\n\t . \"expireTime, \"\n\t . \"status) \"\n\t . \"VALUES \"\n\t . \"('$name', \"\n\t . \"$imageid, \"\n\t . \"$numMachines, \"\n\t . \"$usergroupid, \"\n\t . \"'list', \"\n\t . \"$ownerid, \"\n\t . \"0, \"\n\t . \"$mnid, \"\n\t . \"'$end', \"\n\t . \"'accepted')\";\n\tdoQuery($query, 101);\n\t$brid = dbLastInsertID();\n\t$query = \"INSERT INTO blockTimes \"\n\t . \"(blockRequestid, \"\n\t . \"start, \"\n\t . \"end) \"\n\t . \"VALUES \"\n\t . \"($brid, \"\n\t . \"'$start', \"\n\t . \"'$end')\";\n\tdoQuery($query, 101);\n\t$btid = dbLastInsertID();\n\t$return = XMLRPCprocessBlockTime($btid, $ignoreprivileges);\n\t$return['blockTimesid'] = $btid;\n\treturn $return;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "\tpublic function addMessage( $errorId ) {\n\t\t$args = func_get_args();\n\t\t$args = array_map( 'htmlspecialchars', $args );\n\t\treturn call_user_func_array( [ $this, 'msg' ], $args );\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": "\tpublic function paramRules() {\n\t\treturn array(\n\t\t\t'title' => Yii::t('studio',$this->title),\n\t\t\t'info' => Yii::t('studio',$this->info),\n\t\t\t'modelRequired' => 'Contacts',\n\t\t\t'options' => array(\n\t\t\t\tarray(\n 'name'=>'listId',\n 'label'=>Yii::t('studio','List'),\n 'type'=>'link',\n 'linkType'=>'X2List',\n 'linkSource'=>Yii::app()->createUrl(\n\t\t\t\t\t CActiveRecord::model('X2List')->autoCompleteSource\n\t\t\t\t )\n ),\n\t\t\t));\n\t}", "label_name": "CWE-20", "label": "20"} -{"code": "function adodb_addslashes($s)\n{\n\t$len = strlen($s);\n\tif ($len == 0) return \"''\";\n\tif (strncmp($s,\"'\",1) === 0 && substr($s,$len-1) == \"'\") return $s; // already quoted\n\n\treturn \"'\".addslashes($s).\"'\";\n}", "label_name": "CWE-287", "label": "287"} -{"code": "\tpublic function manage_versions() {\n\t expHistory::set('manageable', $this->params);\n\t \n\t $hv = new help_version();\n\t $current_version = $hv->find('first', 'is_current=1');\n\t \n\t $sql = 'SELECT hv.*, COUNT(h.title) AS num_docs FROM '.DB_TABLE_PREFIX.'_help h ';\n\t $sql .= 'RIGHT JOIN '.DB_TABLE_PREFIX.'_help_version hv ON h.help_version_id=hv.id GROUP BY hv.version';\n\n\t $page = new expPaginator(array(\n 'sql'=>$sql,\n 'limit'=>30,\n 'order' => (isset($this->params['order']) ? $this->params['order'] : 'version'),\n 'dir' => (isset($this->params['dir']) ? $this->params['dir'] : 'DESC'),\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->baseclassname,\n 'action'=>$this->params['action'],\n 'src'=>$this->loc->src,\n 'columns'=>array(\n gt('Version')=>'version',\n gt('Title')=>'title',\n gt('Current')=>'is_current',\n gt('# of Docs')=>'num_docs'\n ),\n ));\n\t \n\t assign_to_template(array(\n 'current_version'=>$current_version,\n 'page'=>$page\n ));\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": " public function gc($force = false, $expiredOnly = true)\n {\n if ($force || mt_rand(0, 1000000) < $this->gcProbability) {\n $this->gcRecursive($this->cachePath, $expiredOnly);\n }\n }", "label_name": "CWE-330", "label": "330"} -{"code": " private function isWindows()\n {\n return DIRECTORY_SEPARATOR !== '/';\n }", "label_name": "CWE-330", "label": "330"} -{"code": "\tpublic function loginForm( WebRequest $request ) { // Step 13\n\t\t$out = $this->getOutput();\n\t\t$username = $request->getVal('username');\n\t\t$codes = SOA2Login::codes( $username );\n\t\t$out->addHTML(Html::openElement('form', [ 'method' => 'POST' ]));\n\t\t$out->addHTML(Html::hidden('username', $username));\n\t\t$out->addHTML(Html::hidden('token', $codes['csrf'])); // Step 14\n\t\t$profile = Html::element(\n\t\t\t'a',\n\t\t\t[\n\t\t\t\t'href' => sprintf(SOA2_PROFILE_URL, urlencode($username)),\n\t\t\t\t'target' => '_new'\n\t\t\t],\n\t\t\twfMessage('soa2-your-profile')->plain()\n\t\t);\n\t\t// Step 16\n\t\t$out->addHTML(Html::rawElement(\n\t\t\t'p', [],\n\t\t\twfMessage('soa2-vercode-explanation')->rawParams($profile)->parse()\n\t\t));\n\t\t$out->addHTML(Html::rawElement('p', [], Html::element(\n\t\t\t'code', [], $codes['code']\n\t\t)));\n\t\t$out->addHTML(Html::rawElement('p', [], Html::submitButton(\n\t\t\twfMessage('soa2-login')->plain(), []\n\t\t)));\n\t\t$out->addHTML(Html::closeElement('form'));\n\t}", "label_name": "CWE-863", "label": "863"} -{"code": " public function testRenderWithTrustedHeaderDisabled()\n {\n Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, '');\n\n $strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest(Request::create('/')));\n $this->assertSame('foo', $strategy->render('/', Request::create('/'))->getContent());\n }", "label_name": "CWE-20", "label": "20"} -{"code": " $banner->increaseImpressions();\n }\n }\n \n // assign banner to the template and show it!\n assign_to_template(array(\n 'banners'=>$banners\n ));\n }", "label_name": "CWE-74", "label": "74"} -{"code": " function preview()\n {\n if ($this->params['id'] == 0) { // we want the default editor\n $demo = new stdClass();\n $demo->id = 0;\n $demo->name = \"Default\";\n if ($this->params['editor'] == 'ckeditor') {\n $demo->skin = 'kama';\n } elseif ($this->params['editor'] == 'tinymce') {\n $demo->skin = 'lightgray';\n }\n } else {\n $demo = self::getEditorSettings($this->params['id'], expString::escape($this->params['editor']));\n }\n assign_to_template(\n array(\n 'demo' => $demo,\n 'editor' => $this->params['editor']\n )\n );\n }", "label_name": "CWE-200", "label": "200"} -{"code": "\tfunction test_valid_comment() {\n\t\t$result = $this->myxmlrpcserver->wp_newComment(\n\t\t\tarray(\n\t\t\t\t1,\n\t\t\t\t'administrator',\n\t\t\t\t'administrator',\n\t\t\t\tself::$post->ID,\n\t\t\t\tarray(\n\t\t\t\t\t'content' => rand_str( 100 ),\n\t\t\t\t),\n\t\t\t)\n\t\t);\n\n\t\t$this->assertNotIXRError( $result );\n\t}", "label_name": "CWE-862", "label": "862"} -{"code": "\tprotected function parseImageUrlWithPath( $article ) {\n\t\t$imageUrl = '';\n\t\tif ( $article instanceof \\DPL\\Article ) {\n\t\t\tif ( $article->mNamespace == NS_FILE ) {\n\t\t\t\t// calculate URL for existing images\n\t\t\t\t// $img = Image::newFromName($article->mTitle->getText());\n\t\t\t\t$img = wfFindFile( \\Title::makeTitle( NS_FILE, $article->mTitle->getText() ) );\n\t\t\t\tif ( $img && $img->exists() ) {\n\t\t\t\t\t$imageUrl = $img->getURL();\n\t\t\t\t} else {\n\t\t\t\t\t$fileTitle = \\Title::makeTitleSafe( NS_FILE, $article->mTitle->getDBKey() );\n\t\t\t\t\t$imageUrl = \\RepoGroup::singleton()->getLocalRepo()->newFile( $fileTitle )->getPath();\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t$title = \\Title::newfromText( 'File:' . $article );\n\t\t\tif ( $title !== null ) {\n\t\t\t\t$fileTitle = \\Title::makeTitleSafe( 6, $title->getDBKey() );\n\t\t\t\t$imageUrl = \\RepoGroup::singleton()->getLocalRepo()->newFile( $fileTitle )->getPath();\n\t\t\t}\n\t\t}\n\n\t\t//@TODO: Check this preg_replace. Probably only works for stock file repositories. --Alexia\n\t\t$imageUrl = preg_replace( '~^.*images/(.*)~', '\\1', $imageUrl );\n\n\t\treturn $imageUrl;\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " $description = \"User (\" . $this->User->id . \"): \" . $this->Auth->user('email');\n $fieldsResult = \"Password changed.\";\n }\n\n // query\n $this->Log = ClassRegistry::init('Log');\n $this->Log->create();\n $this->Log->save(array(\n 'org' => $this->Auth->user('Organisation')['name'],\n 'model' => $model,\n 'model_id' => $modelId,\n 'email' => $this->Auth->user('email'),\n 'action' => $action,\n 'title' => $description,\n 'change' => isset($fieldsResult) ? $fieldsResult : ''));\n\n // write to syslogd as well\n App::import('Lib', 'SysLog.SysLog');\n $syslog = new SysLog();\n if (isset($fieldsResult) && $fieldsResult) {\n $syslog->write('notice', $description . ' -- ' . $action . ' -- ' . $fieldsResult);\n } else {\n $syslog->write('notice', $description . ' -- ' . $action);\n }\n }", "label_name": "CWE-269", "label": "269"} -{"code": " public function configure() {\n $this->config['defaultbanner'] = array();\n if (!empty($this->config['defaultbanner_id'])) {\n $this->config['defaultbanner'][] = new expFile($this->config['defaultbanner_id']);\n } \n\t parent::configure();\n\t $banners = $this->banner->find('all', null, 'companies_id');\n\t assign_to_template(array(\n 'banners'=>$banners,\n 'title'=>static::displayname()\n ));\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": " private function getTaskLink()\n {\n $link = $this->taskLinkModel->getById($this->request->getIntegerParam('link_id'));\n\n if (empty($link)) {\n throw new PageNotFoundException();\n }\n\n return $link;\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public function testNotRemoveAuthorizationHeaderOnRedirect()\n {\n $mock = new MockHandler([\n new Response(302, ['Location' => 'http://example.com/2']),\n static function (RequestInterface $request) {\n self::assertTrue($request->hasHeader('Authorization'));\n return new Response(200);\n }\n ]);\n $handler = HandlerStack::create($mock);\n $client = new Client(['handler' => $handler]);\n $client->get('http://example.com?a=b', ['auth' => ['testuser', 'testpass']]);\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public function testGetDropdownConnect($params, $expected, $session_params = []) {\n $this->login();\n\n $bkp_params = [];\n //set session params if any\n if (count($session_params)) {\n foreach ($session_params as $param => $value) {\n if (isset($_SESSION[$param])) {\n $bkp_params[$param] = $_SESSION[$param];\n }\n $_SESSION[$param] = $value;\n }\n }\n\n $params['_idor_token'] = \\Session::getNewIDORToken($params['itemtype'] ?? '');\n\n $result = \\Dropdown::getDropdownConnect($params, false);\n\n //reset session params before executing test\n if (count($session_params)) {\n foreach ($session_params as $param => $value) {\n if (isset($bkp_params[$param])) {\n $_SESSION[$param] = $bkp_params[$param];\n } else {\n unset($_SESSION[$param]);\n }\n }\n }\n\n $this->array($result)->isIdenticalTo($expected);\n }", "label_name": "CWE-862", "label": "862"} -{"code": "\tpublic static function generate_location_json( ) {\r\n\t\t/* TODO: Try to track modification?\r\n\t\tif ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {\r\n\t\t\t$http_time = strtotime( $_SERVER['HTTP_IF_MODIFIED_SINCE'] );\r\n\t\t\t$mod_time = strtotime( $post->post_modified_gmt . ' GMT' );\r\n\t\t\tif ($mod_time <= $http_time) {\r\n\t\t\t\treturn status_header(304); // Not modified\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tstatus_header(200);\r\n\t\theader( 'Last-Modified: ' . mysql2date( 'D, d M Y H:i:s', $post->post_modified_gmt, false ) . ' GMT' );\r\n\t\theader( 'Content-type: text/xml; charset='.get_settings('blog_charset'), true);\r\n\t\theader( 'Cache-control: max-age=300, must-revalidate', true);\r\n\t\theader( 'Expires: ' . gmdate( 'D, d M Y H:i:s', time() + 300 ) . \" GMT\" );\r\n\t\theader( 'Pragma:' );\r\n\t\t */\r\n\t\tstatus_header(200);\r\n\t\theader('Content-type: application/json; charset='.get_option('blog_charset'), true);\r\n\t\theader('Cache-Control: no-cache;', true);\r\n\t\theader('Expires: -1;', true);\r\n\r\n\t\t$json = GeoMashup::get_locations_json($_REQUEST);\r\n\t\tif ( isset( $_REQUEST['callback'] ) )\r\n\t\t\t$json = $_REQUEST['callback'] . '(' . $json . ')';\r\n\t\techo $json;\r\n\t}\r", "label_name": "CWE-20", "label": "20"} -{"code": " public function searchAdmin(){\n $criteria = new CDbCriteria;\n return $this->searchBase($criteria);\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public static function decode($jwt, $key = null, $verify = true)\n {\n $tks = explode('.', $jwt);\n\n if (count($tks) != 3) {\n throw new Exception('Wrong number of segments');\n }\n\n list($headb64, $payloadb64, $cryptob64) = $tks;\n\n if (null === ($header = json_decode(JWT::urlsafeB64Decode($headb64)))) {\n throw new Exception('Invalid segment encoding');\n }\n\n if (null === $payload = json_decode(JWT::urlsafeB64Decode($payloadb64))) {\n throw new Exception('Invalid segment encoding');\n }\n\n $sig = JWT::urlsafeB64Decode($cryptob64);\n\n if ($verify) {\n if (empty($header->alg)) {\n throw new DomainException('Empty algorithm');\n }\n\n if (!JWT::verifySignature($sig, \"$headb64.$payloadb64\", $key, $header->alg)) {\n throw new UnexpectedValueException('Signature verification failed');\n }\n }\n\n return $payload;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function settings_save() {\n AuthUser::load();\n if (!AuthUser::isLoggedIn()) {\n redirect(get_url('login'));\n } else if (!AuthUser::hasPermission('admin_edit')) {\n Flash::set('error', __('You do not have permission to access the requested page!'));\n redirect(get_url());\n }\n \n if (!isset($_POST['settings'])) {\n Flash::set('error', 'File Manager - ' . __('form was not posted.'));\n redirect(get_url('plugin/file_manager/settings'));\n } else {\n $settings = $_POST['settings'];\n\n if ($settings['umask'] == 0)\n $settings['umask'] = 0;\n elseif (!preg_match('/^0?[0-7]{3}$/', $settings['umask']))\n $settings['umask'] = 0;\n if (strlen($settings['umask']) === 3)\n $settings['umask'] = '0' . $settings['umask'];\n elseif (strlen($settings['umask']) !== 4 && $settings['umask'] != 0)\n $settings['umask'] = 0;\n\n if (!preg_match('/^0?[0-7]{3}$/', $settings['dirmode']))\n $settings['dirmode'] = '0755';\n if (strlen($settings['dirmode']) === 3)\n $settings['dirmode'] = '0' . $settings['dirmode'];\n\n if (!preg_match('/^0?[0-7]{3}$/', $settings['filemode']))\n $settings['filemode'] = '0755';\n if (strlen($settings['filemode']) === 3)\n $settings['filemode'] = '0' . $settings['filemode'];\n }\n\n if (Plugin::setAllSettings($settings, 'file_manager'))\n Flash::setNow('success', 'File Manager - ' . __('plugin settings saved.'));\n else\n Flash::setNow('error', 'File Manager - ' . __('plugin settings not saved!'));\n\n $this->display('file_manager/views/settings', array('settings' => $settings));\n }", "label_name": "CWE-20", "label": "20"} -{"code": " foreach ($matches[1] as $index => $body) {\n $parts = explode('_', $body);\n $fileID = $parts[0];\n $hash = $parts[1];\n try {\n $file = erLhcoreClassModelChatFile::fetch($fileID);\n if (is_object($file) && $hash == $file->security_hash) {\n\n $url = (erLhcoreClassSystem::$httpsMode == true ? 'https:' : 'http:') . '//' . $_SERVER['HTTP_HOST'] . erLhcoreClassDesign::baseurldirect('file/downloadfile') . \"/{$file->id}/{$hash}\";\n\n $media[] = array(\n 'id' => $file->id,\n 'size' => $file->size,\n 'upload_name' => $file->upload_name,\n 'type' => $file->type,\n 'extension' => $file->extension,\n 'hash' => $hash,\n 'url' => $url,\n );\n\n $msg_text_cleaned = str_replace($matches[0][$index],'',$msg_text_cleaned);\n }\n\n } catch (Exception $e) {\n\n }\n }", "label_name": "CWE-116", "label": "116"} -{"code": " $this->subtaskTimeTrackingModel->logEndTime($subtaskId, $this->userSession->getId());\n $this->subtaskTimeTrackingModel->updateTaskTimeTracking($task['id']);\n }", "label_name": "CWE-200", "label": "200"} -{"code": " function searchName() {\r\n return gt(\"Calendar Event\");\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public function testGetFilteredEventsDataProvider () {\n TestingAuxLib::loadX2NonWebUser ();\n TestingAuxLib::suLogin ('testuser');\n Yii::app()->settings->historyPrivacy = null;\n $profile = Profile::model()->findByAttributes(array('username' => 'testuser'));\n $retVal = Events::getFilteredEventsDataProvider ($profile, true, null, false);\n $dataProvider = $retVal['dataProvider'];\n $events = $dataProvider->getData ();\n $expectedEvents = Events::getEvents (0, 0, count ($events), $profile);\n\n // verify events from getData\n $this->assertEquals (\n Yii::app()->db->createCommand (\"\n select id\n from x2_events\n where user='testuser' or visibility\n order by timestamp desc, id desc\n \")->queryColumn (),\n array_map (\n function ($event) { return $event->id; }, \n $expectedEvents['events']\n )\n );\n\n // ensure that getFilteredEventsDataProvider returns same events as getData\n $this->assertEquals (\n array_map (\n function ($event) { return $event->id; }, \n $expectedEvents['events']\n ),\n array_map (\n function ($event) { return $event->id; }, \n $events\n )\n );\n TestingAuxLib::restoreX2WebUser ();\n }", "label_name": "CWE-20", "label": "20"} -{"code": " $modelNames[ucfirst($module->name)] = self::getModelTitle($modelName);\n }\n asort ($modelNames);\n if ($criteria !== null) {\n return $modelNames;\n } else {\n self::$_modelNames = $modelNames;\n }\n }\n return self::$_modelNames;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function IsSendmail() {\n if (!stristr(ini_get('sendmail_path'), 'sendmail')) {\n $this->Sendmail = '/var/qmail/bin/sendmail';\n }\n $this->Mailer = 'sendmail';\n }", "label_name": "CWE-20", "label": "20"} -{"code": " static function isSearchable() {\r\n return true;\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " protected function getBodyTagAttributes()\n {\n $formEngineParameters = [];\n $parameters = parent::getBodyTagAttributes();\n\n $formEngineParameters['fieldChangeFunc'] = $this->parameters['fieldChangeFunc'];\n $formEngineParameters['fieldChangeFuncHash'] = GeneralUtility::hmac(serialize($this->parameters['fieldChangeFunc']));\n\n $parameters['data-add-on-params'] .= HttpUtility::buildQueryString(['P' => $formEngineParameters], '&');\n\n return $parameters;\n }", "label_name": "CWE-327", "label": "327"} -{"code": " public function enable()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $swimlane_id = $this->request->getIntegerParam('swimlane_id');\n\n if ($this->swimlaneModel->enable($project['id'], $swimlane_id)) {\n $this->flash->success(t('Swimlane updated successfully.'));\n } else {\n $this->flash->failure(t('Unable to update this swimlane.'));\n }\n\n $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public function beforeSave () {\n $valid = parent::beforeSave ();\n if ($valid) {\n $table = Yii::app()->db->schema->tables[$this->myTableName];\n $existing = array_key_exists($this->fieldName, $table->columns) && \n $table->columns[$this->fieldName] instanceof CDbColumnSchema;\n if($existing){ \n $valid = $this->modifyColumn();\n }\n }\n return $valid;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function AddCC($address, $name = '') {\n return $this->AddAnAddress('cc', $address, $name);\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public static function canView($section) {\r\n global $db;\r\n\r\n if ($section == null) {\r\n return false;\r\n }\r\n if ($section->public == 0) {\r\n // Not a public section. Check permissions.\r\n return expPermissions::check('view', expCore::makeLocation('navigation', '', $section->id));\r\n } else { // Is public. check parents.\r\n if ($section->parent <= 0) {\r\n // Out of parents, and since we are still checking, we haven't hit a private section.\r\n return true;\r\n } else {\r\n $s = $db->selectObject('section', 'id=' . $section->parent);\r\n return self::canView($s);\r\n }\r\n }\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": "\tfunction lockTable($table,$lockType=\"WRITE\") {\n $sql = \"LOCK TABLES `\" . $this->prefix . \"$table` $lockType\";\n \n $res = mysqli_query($this->connection, $sql); \n return $res;\n }", "label_name": "CWE-74", "label": "74"} -{"code": " function captureAuthorization() {\n //eDebug($this->params,true);\n $order = new order($this->params['id']);\n /*eDebug($this->params); \n //eDebug($order,true);*/\n //eDebug($order,true);\n //$billing = new billing();\n\n //eDebug($billing, true);\n //$billing->calculator = new $calcname($order->billingmethod[0]->billingcalculator_id);\n $calc = $order->billingmethod[0]->billingcalculator->calculator;\n $calc->config = $order->billingmethod[0]->billingcalculator->config;\n\n //$calc = new $calc-\n //eDebug($calc,true);\n if (!method_exists($calc, 'delayed_capture')) {\n flash('error', gt('The Billing Calculator does not support delayed capture'));\n expHistory::back();\n }\n\n $result = $calc->delayed_capture($order->billingmethod[0], $this->params['capture_amt'], $order);\n\n if (empty($result->errorCode)) {\n flash('message', gt('The authorized payment was successfully captured'));\n expHistory::back();\n\n } else {\n flash('error', gt('An error was encountered while capturing the authorized payment.') . '

' . $result->message);\n expHistory::back();\n }\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function create_file() {\n if (!AuthUser::hasPermission('file_manager_mkfile')) {\n Flash::set('error', __('You do not have sufficient permissions to create a file.'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n \n // CSRF checks\n if (isset($_POST['csrf_token'])) {\n $csrf_token = $_POST['csrf_token'];\n if (!SecureToken::validateToken($csrf_token, BASE_URL.'plugin/file_manager/create_file')) {\n Flash::set('error', __('Invalid CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n }\n else {\n Flash::set('error', __('No CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n\n $data = $_POST['file'];\n\n $path = str_replace('..', '', $data['path']);\n $filename = str_replace('..', '', $data['name']);\n $file = FILES_DIR . DS . $path . DS . $filename;\n\n if (file_put_contents($file, '') !== false) {\n $mode = Plugin::getSetting('filemode', 'file_manager');\n chmod($file, octdec($mode));\n } else {\n Flash::set('error', __('File :name has not been created!', array(':name' => $filename)));\n }\n redirect(get_url('plugin/file_manager/browse/' . $path));\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public static function returnChildrenAsJSON() {\r\n global $db;\r\n\r\n //$nav = section::levelTemplate(intval($_REQUEST['id'], 0));\r\n $id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;\r\n $nav = $db->selectObjects('section', 'parent=' . $id, 'rank');\r\n //FIXME $manage_all is moot w/ cascading perms now?\r\n $manage_all = false;\r\n if (expPermissions::check('manage', expCore::makeLocation('navigation', '', $id))) {\r\n $manage_all = true;\r\n }\r\n //FIXME recode to use foreach $key=>$value\r\n $navcount = count($nav);\r\n for ($i = 0; $i < $navcount; $i++) {\r\n if ($manage_all || expPermissions::check('manage', expCore::makeLocation('navigation', '', $nav[$i]->id))) {\r\n $nav[$i]->manage = 1;\r\n $view = true;\r\n } else {\r\n $nav[$i]->manage = 0;\r\n $view = $nav[$i]->public ? true : expPermissions::check('view', expCore::makeLocation('navigation', '', $nav[$i]->id));\r\n }\r\n $nav[$i]->link = expCore::makeLink(array('section' => $nav[$i]->id), '', $nav[$i]->sef_name);\r\n if (!$view) unset($nav[$i]);\r\n }\r\n $nav= array_values($nav);\r\n// $nav[$navcount - 1]->last = true;\r\n if (count($nav)) $nav[count($nav) - 1]->last = true;\r\n// echo expJavascript::ajaxReply(201, '', $nav);\r\n $ar = new expAjaxReply(201, '', $nav);\r\n $ar->send();\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " protected function registerBackendPermissions()\n {\n BackendAuth::registerCallback(function ($manager) {\n $manager->registerPermissions('October.System', [\n 'system.manage_updates' => [\n 'label' => 'system::lang.permissions.manage_software_updates',\n 'tab' => 'system::lang.permissions.name'\n ],\n 'system.access_logs' => [\n 'label' => 'system::lang.permissions.access_logs',\n 'tab' => 'system::lang.permissions.name'\n ],\n 'system.manage_mail_settings' => [\n 'label' => 'system::lang.permissions.manage_mail_settings',\n 'tab' => 'system::lang.permissions.name'\n ],\n 'system.manage_mail_templates' => [\n 'label' => 'system::lang.permissions.manage_mail_templates',\n 'tab' => 'system::lang.permissions.name'\n ]\n ]);\n });\n }", "label_name": "CWE-269", "label": "269"} -{"code": " function showallSubcategories() {\n// global $db;\n\n expHistory::set('viewable', $this->params);\n// $parent = isset($this->params['cat']) ? $this->params['cat'] : expSession::get('catid');\n $catid = expSession::get('catid');\n $parent = !empty($catid) ? $catid : (!empty($this->params['cat']) ? $this->params['cat'] : 0);\n $category = new storeCategory($parent);\n $categories = $category->getEcomSubcategories();\n $ancestors = $category->pathToNode();\n assign_to_template(array(\n 'categories' => $categories,\n 'ancestors' => $ancestors,\n 'category' => $category\n ));\n }", "label_name": "CWE-20", "label": "20"} -{"code": " protected function generateVerifyCode()\n {\n if ($this->minLength > $this->maxLength) {\n $this->maxLength = $this->minLength;\n }\n if ($this->minLength < 3) {\n $this->minLength = 3;\n }\n if ($this->maxLength > 20) {\n $this->maxLength = 20;\n }\n $length = mt_rand($this->minLength, $this->maxLength);\n\n $letters = 'bcdfghjklmnpqrstvwxyz';\n $vowels = 'aeiou';\n $code = '';\n for ($i = 0; $i < $length; ++$i) {\n if ($i % 2 && mt_rand(0, 10) > 2 || !($i % 2) && mt_rand(0, 10) > 9) {\n $code .= $vowels[mt_rand(0, 4)];\n } else {\n $code .= $letters[mt_rand(0, 20)];\n }\n }\n\n return $code;\n }", "label_name": "CWE-330", "label": "330"} -{"code": " print_r($single_error);\n }\n\n echo '';\n }", "label_name": "CWE-20", "label": "20"} -{"code": " $emails[$u->email] = trim(user::getUserAttribution($u->id));\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": "\tprotected function replaceTagCount( $tag, $nr ) {\n\t\treturn str_replace( '%NR%', $nr, $tag );\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " public function getFileContent($file, $identifier)\n {\n $resource = sprintf('hg cat -r %s %s', ProcessExecutor::escape($identifier), ProcessExecutor::escape($file));\n $this->process->execute($resource, $content, $this->repoDir);\n\n if (!trim($content)) {\n return null;\n }\n\n return $content;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " $cLoc = serialize(expCore::makeLocation('container','@section' . $page->id));\r\n $ret .= scan_container($cLoc, $page->id);\r\n $ret .= scan_page($page->id);\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public function getViewFileParams () {\n if (!isset ($this->_viewFileParams)) {\n $this->_viewFileParams = array_merge (\n parent::getViewFileParams (),\n array (\n 'chartType' => $this->chartType,\n\t\t\t 'chartSettingsDataProvider' => self::getChartSettingsProvider (\n $this->chartType),\n 'eventTypes' =>\n array ('all'=>Yii::t('app', 'All Events')) + Events::$eventLabels,\n 'socialSubtypes' => json_decode (\n\t\t\t Dropdowns::model()->findByPk(113)->options,true),\n 'visibilityFilters' => array (\n '1'=>'Public',\n '0'=>'Private',\n ),\n 'suppressChartSettings' => false,\n 'chartType' => 'usersChart',\n 'widgetUID' => $this->widgetUID,\n 'metricTypes' => User::getUserOptions (),\n )\n );\n }\n return $this->_viewFileParams;\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\tpublic function manage_versions() {\n\t expHistory::set('manageable', $this->params);\n\t \n\t $hv = new help_version();\n\t $current_version = $hv->find('first', 'is_current=1');\n\t \n\t $sql = 'SELECT hv.*, COUNT(h.title) AS num_docs FROM '.DB_TABLE_PREFIX.'_help h ';\n\t $sql .= 'RIGHT JOIN '.DB_TABLE_PREFIX.'_help_version hv ON h.help_version_id=hv.id GROUP BY hv.version';\n\n\t $page = new expPaginator(array(\n 'sql'=>$sql,\n 'limit'=>30,\n 'order' => (isset($this->params['order']) ? $this->params['order'] : 'version'),\n 'dir' => (isset($this->params['dir']) ? $this->params['dir'] : 'DESC'),\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->baseclassname,\n 'action'=>$this->params['action'],\n 'src'=>$this->loc->src,\n 'columns'=>array(\n gt('Version')=>'version',\n gt('Title')=>'title',\n gt('Current')=>'is_current',\n gt('# of Docs')=>'num_docs'\n ),\n ));\n\t \n\t assign_to_template(array(\n 'current_version'=>$current_version,\n 'page'=>$page\n ));\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": " public static function validatePMAStorage($path, $values)\n {\n $result = array(\n 'Server_pmadb' => '',\n 'Servers/1/controluser' => '',\n 'Servers/1/controlpass' => ''\n );\n $error = false;\n\n if ($values['Servers/1/pmadb'] == '') {\n return $result;\n }\n\n $result = array();\n if ($values['Servers/1/controluser'] == '') {\n $result['Servers/1/controluser'] = __(\n 'Empty phpMyAdmin control user while using phpMyAdmin configuration '\n . 'storage!'\n );\n $error = true;\n }\n if ($values['Servers/1/controlpass'] == '') {\n $result['Servers/1/controlpass'] = __(\n 'Empty phpMyAdmin control user password while using phpMyAdmin '\n . 'configuration storage!'\n );\n $error = true;\n }\n if (! $error) {\n $test = static::testDBConnection(\n $values['Servers/1/connect_type'],\n $values['Servers/1/host'], $values['Servers/1/port'],\n $values['Servers/1/socket'], $values['Servers/1/controluser'],\n $values['Servers/1/controlpass'], 'Server_pmadb'\n );\n if ($test !== true) {\n $result = array_merge($result, $test);\n }\n }\n return $result;\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public function delete() {\n if (!AuthUser::hasPermission('file_manager_delete')) {\n Flash::set('error', __('You do not have sufficient permissions to delete a file or directory.'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n\n $paths = func_get_args();\n\n $file = urldecode(join('/', $paths));\n \n // CSRF checks\n if (isset($_GET['csrf_token'])) {\n $csrf_token = $_GET['csrf_token'];\n if (!SecureToken::validateToken($csrf_token, BASE_URL.'plugin/file_manager/delete/'.$file)) {\n Flash::set('error', __('Invalid CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n }\n else {\n Flash::set('error', __('No CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n\n $file = FILES_DIR . '/' . str_replace('..', '', $file);\n $filename = array_pop($paths);\n $paths = join('/', $paths);\n\n if (is_file($file)) {\n if (!unlink($file))\n Flash::set('error', __('Permission denied!'));\n }\n else {\n if (!$this->_rrmdir($file))\n Flash::set('error', __('Permission denied!'));\n }\n\n redirect(get_url('plugin/file_manager/browse/' . $paths));\n }", "label_name": "CWE-20", "label": "20"} -{"code": " $payment->write();\n $i++;\n }\n\n // Ugly hack to set the money amount\n $this->payment->Status = 'Created';\n $this->payment->setAmount($total);\n\n // If not everything was refunded, the payment should still have the \"Captured\" status\n if ($total > 0) {\n $endStatus = 'Captured';\n }\n }\n\n parent::markCompleted($endStatus, $serviceResponse, $gatewayMessage);\n if ($endStatus === 'Captured') {\n $this->createMessage(Message\\PartiallyRefundedResponse::class, $gatewayMessage);\n } else {\n $this->createMessage(Message\\RefundedResponse::class, $gatewayMessage);\n }\n\n ErrorHandling::safeExtend($this->payment, 'onRefunded', $serviceResponse);\n }", "label_name": "CWE-436", "label": "436"} -{"code": " public function testAuthCheckDecryptPassword()\n {\n $GLOBALS['cfg']['Server']['auth_swekey_config'] = 'testConfigSwekey';\n $GLOBALS['server'] = 1;\n $_REQUEST['old_usr'] = '';\n $_REQUEST['pma_username'] = '';\n $_COOKIE['pmaServer-1'] = 'pmaServ1';\n $_COOKIE['pmaUser-1'] = 'pmaUser1';\n $_COOKIE['pmaPass-1'] = 'pmaPass1';\n $_COOKIE['pma_iv-1'] = base64_encode('testiv09testiv09');\n $GLOBALS['cfg']['blowfish_secret'] = 'secret';\n $_SESSION['last_valid_captcha'] = true;\n $_SESSION['last_access_time'] = time() - 1000;\n $GLOBALS['cfg']['LoginCookieValidity'] = 1440;\n\n // mock for blowfish function\n $this->object = $this->getMockBuilder('AuthenticationCookie')\n ->disableOriginalConstructor()\n ->setMethods(array('cookieDecrypt'))\n ->getMock();\n\n $this->object->expects($this->at(1))\n ->method('cookieDecrypt')\n ->will($this->returnValue(\"\\xff(blank)\"));\n\n $this->assertTrue(\n $this->object->authCheck()\n );\n\n $this->assertTrue(\n $GLOBALS['from_cookie']\n );\n\n $this->assertEquals(\n '',\n $GLOBALS['PHP_AUTH_PW']\n );\n\n }", "label_name": "CWE-200", "label": "200"} -{"code": " foreach ($days as $event) {\r\n if (empty($event->eventdate->date) || ($viewrange == 'upcoming' && $event->eventdate->date < time()))\r\n break;\r\n if (empty($event->eventstart))\r\n $event->eventstart = $event->eventdate->date;\r\n $extitem[] = $event;\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": "function GoodAuthDigestTestController($serverPort) {\n $args = array('Authorization' => 'Digest username=\"admin\", ' .\n 'realm=\"Restricted area\", nonce=\"564a12611dae8\", ' .\n 'uri=\"/test_auth_digest.php\", cnonce=\"MjIyMTg1\", nc=00000001, ' .\n 'qop=\"auth\", response=\"e544aaed06917adea3e5c74dd49f0e32\", ' .\n 'opaque=\"cdce8a5c95a1427d74df7acbf41c9ce0\"');\n var_dump(request(php_uname('n'), $serverPort, \"test_auth_digest.php\",\n [], [], $args));\n}", "label_name": "CWE-668", "label": "668"} -{"code": " public function activate_address()\n {\n global $db, $user;\n\n $object = new stdClass();\n $object->id = $this->params['id'];\n $db->setUniqueFlag($object, 'addresses', $this->params['is_what'], \"user_id=\" . $user->id);\n flash(\"message\", gt(\"Successfully updated address.\"));\n expHistory::back(); \n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function confirm()\n {\n $task = $this->getTask();\n $subtask = $this->getSubtask();\n\n $this->response->html($this->template->render('subtask/remove', array(\n 'subtask' => $subtask,\n 'task' => $task,\n )));\n }", "label_name": "CWE-200", "label": "200"} -{"code": "\tstatic public function getPriorityText($_lng, $_priority = 0)\n\t{\n\t\tswitch($_priority)\n\t\t{\n\t\t\tcase 1:\n\t\t\t\treturn $_lng['ticket']['high'];\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\treturn $_lng['ticket']['normal'];\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn $_lng['ticket']['low'];\n\t\t\t\tbreak;\n\t\t}\n\t}", "label_name": "CWE-732", "label": "732"} -{"code": "\tpublic function update_version() {\n\t // get the current version\n\t $hv = new help_version();\n\t $current_version = $hv->find('first', 'is_current=1');\n\t \n\t // check to see if the we have a new current version and unset the old current version.\n\t if (!empty($this->params['is_current'])) {\n//\t $db->sql('UPDATE '.DB_TABLE_PREFIX.'_help_version set is_current=0');\n help_version::clearHelpVersion();\n\t }\n\t expSession::un_set('help-version');\n\n\t // save the version\n\t $id = empty($this->params['id']) ? null : $this->params['id'];\n\t $version = new help_version();\n\t // if we don't have a current version yet so we will force this one to be it\n\t if (empty($current_version->id)) $this->params['is_current'] = 1;\n\t $version->update($this->params);\n\t \n\t // if this is a new version we need to copy over docs\n\t if (empty($id)) {\n\t self::copydocs($current_version->id, $version->id);\t \n\t }\n // let's update the search index to reflect the current help version\n searchController::spider();\n\n\t flash('message', gt('Saved help version').' '.$version->version);\n\t expHistory::back();\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": " $rndString = function ($len = 10) {\n $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n $randomString = '';\n for ($i = 0; $i < $len; $i++) {\n $randomString .= $characters[rand(0, strlen($characters) - 1)];\n }\n\n return $randomString;\n };", "label_name": "CWE-330", "label": "330"} -{"code": " public function actionGetItems(){\n // We need to select the id both as 'id' and 'value' in order to correctly populate the association form.\n $sql = 'SELECT id, id as value FROM x2_services WHERE id LIKE :qterm ORDER BY id ASC';\n $command = Yii::app()->db->createCommand($sql);\n $qterm = $_GET['term'].'%';\n $command->bindParam(\":qterm\", $qterm, PDO::PARAM_STR);\n $result = $command->queryAll();\n echo CJSON::encode($result);\n exit;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " $ds = self::connectToServer($replicate[\"host\"], $replicate[\"port\"],\n $ldap_method['rootdn'],\n Toolbox::decrypt($ldap_method['rootdn_passwd'], GLPIKEY),\n $ldap_method['use_tls'], $ldap_method['deref_option']);\n\n // Test with login and password of the user\n if (!$ds\n && !empty($login)) {\n $ds = self::connectToServer($replicate[\"host\"], $replicate[\"port\"], $login,\n $password, $ldap_method['use_tls'],\n $ldap_method['deref_option']);\n }\n if ($ds) {\n return $ds;\n }\n }\n }", "label_name": "CWE-327", "label": "327"} -{"code": " public function confirm()\n {\n $project = $this->getProject();\n $tag_id = $this->request->getIntegerParam('tag_id');\n $tag = $this->tagModel->getById($tag_id);\n\n $this->response->html($this->template->render('project_tag/remove', array(\n 'tag' => $tag,\n 'project' => $project,\n )));\n }", "label_name": "CWE-200", "label": "200"} -{"code": " foreach ($project_templates as $project_template) {\n if ((int) $project_template->getGroupId() === \\Project::ADMIN_PROJECT_ID) {\n continue;\n }\n $company_templates[] = new CompanyTemplate($project_template, $this->glyph_finder);\n }", "label_name": "CWE-863", "label": "863"} -{"code": "\tprivate static function thumb($source_path, $thumb_path){\n\t\tini_set('memory_limit', '128M');\n\n\t\t$source_details = getimagesize($source_path);\n\t\t$source_w = $source_details[0];\n\t\t$source_h = $source_details[1];\n\n\t\tif($source_w > $source_h){\n\t\t\t$new_w = self::THUMB_W;\n\t\t\t$new_h = intval($source_h * $new_w / $source_w);\n\t\t} else {\n\t\t\t$new_h = self::THUMB_H;\n\t\t\t$new_w = intval($source_w * $new_h / $source_h);\n\t\t}\n\n\t\tswitch($source_details[2]){\n\t\t\tcase IMAGETYPE_GIF:\n\t\t\t\t$imgt = \"imagegif\";\n\t\t\t\t$imgcreatefrom = \"imagecreatefromgif\";\n\t\t\t\tbreak;\n\n\t\t\tcase IMAGETYPE_JPEG:\n\t\t\t\t$imgt = \"imagejpeg\";\n\t\t\t\t$imgcreatefrom = \"imagecreatefromjpeg\";\n\t\t\t\tbreak;\n\n\t\t\tcase IMAGETYPE_PNG:\n\t\t\t\t$imgt = \"imagepng\";\n\t\t\t\t$imgcreatefrom = \"imagecreatefrompng\";\n\t\t\t\tbreak;\n\n\t\t\tcase IMAGETYPE_WEBP:\n\t\t\t\t$imgt = \"imagewebp\";\n\t\t\t\t$imgcreatefrom = \"imagecreatefromwebp\";\n\t\t\t\tbreak;\n\n\t\t\tcase IMAGETYPE_WBMP:\n\t\t\t\t$imgt = \"imagewbmp\";\n\t\t\t\t$imgcreatefrom = \"imagecreatefromwbmp\";\n\t\t\t\tbreak;\n\n\t\t\tcase IMAGETYPE_BMP:\n\t\t\t\t$imgt = \"imagebmp\";\n\t\t\t\t$imgcreatefrom = \"imagecreatefrombmp\";\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\treturn false;\n\t\t}\n\n\t\t$old_image = $imgcreatefrom($source_path);\n\t\t$new_image = imagecreatetruecolor($new_w, $new_h);\n\t\timagecopyresampled($new_image, $old_image, 0, 0, 0, 0, $new_w, $new_h, $source_w, $source_h);\n\n\t\t$new_image = self::fix_orientation($source_path, $new_image);\n\t\t$old_image = self::fix_orientation($source_path, $old_image);\n\n\t\t$imgt($new_image, $thumb_path);\n\t\t$imgt($old_image, $source_path);\n\t\treturn true;\n\t}", "label_name": "CWE-20", "label": "20"} -{"code": " function update_optiongroup_master() {\n global $db;\n\n $id = empty($this->params['id']) ? null : $this->params['id'];\n $og = new optiongroup_master($id);\n $oldtitle = $og->title;\n $og->update($this->params);\n \n // if the title of the master changed we should update the option groups that are already using it.\n if ($oldtitle != $og->title) {\n $db->sql('UPDATE '.$db->prefix.'optiongroup SET title=\"'.$og->title.'\" WHERE title=\"'.$oldtitle.'\"');\n }\n \n expHistory::back();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function manage() {\n expHistory::set('manageable', $this->params);\n \n // build out a SQL query that gets all the data we need and is sortable.\n $sql = 'SELECT b.*, c.title as companyname, f.expfiles_id as file_id ';\n $sql .= 'FROM '.DB_TABLE_PREFIX.'_banner b, '.DB_TABLE_PREFIX.'_companies c , '.DB_TABLE_PREFIX.'_content_expFiles f ';\n $sql .= 'WHERE b.companies_id = c.id AND (b.id = f.content_id AND f.content_type=\"banner\")';\n\t\t\n\t\t$page = new expPaginator(array(\n\t\t\t'model'=>'banner',\n\t\t\t'sql'=>$sql,\n\t\t\t'order'=>'title',\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->params['controller'],\n 'action'=>$this->params['action'],\n 'src'=>$this->loc->src,\n\t\t\t'columns'=>array(\n gt('Title')=>'title',\n gt('Company')=>'companyname',\n gt('Impressions')=>'impressions',\n gt('Clicks')=>'clicks'\n )\n ));\n\n\t\tassign_to_template(array(\n 'page'=>$page\n ));\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function saveconfig() {\n global $db;\n\n if (empty($this->params['id'])) return false;\n $calcname = $db->selectValue('shippingcalculator', 'calculator_name', 'id='.$this->params['id']);\n $calc = new $calcname($this->params['id']);\n $conf = serialize($calc->parseConfig($this->params)); \n $calc->update(array('config'=>$conf));\n expHistory::back();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " $masteroption->delete();\n }\n \n // delete the mastergroup\n $db->delete('optiongroup', 'optiongroup_master_id='.$mastergroup->id);\n $mastergroup->delete();\n \n expHistory::back();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " protected function prepareImport($model, $csvName) {\n $this->openX2 ('/admin/importModels?model='.ucfirst($model));\n $csv = implode(DIRECTORY_SEPARATOR, array(\n Yii::app()->basePath,\n 'tests',\n 'data',\n 'csvs',\n $csvName\n ));\n $this->type ('data', $csv);\n $this->clickAndWait (\"dom=document.querySelector ('input[type=\\\"submit\\\"]')\");\n $this->assertCsvUploaded ($csv);\n }", "label_name": "CWE-20", "label": "20"} -{"code": " private function _getMetaTags()\n {\n $retval = '';\n $retval .= '';\n $retval .= '';\n $retval .= '';\n if (! $GLOBALS['cfg']['AllowThirdPartyFraming']) {\n $retval .= '';\n }\n return $retval;\n }", "label_name": "CWE-200", "label": "200"} -{"code": " static function searchUser(AuthLDAP $authldap) {\n\n if (self::connectToServer($authldap->getField('host'), $authldap->getField('port'),\n $authldap->getField('rootdn'),\n Toolbox::decrypt($authldap->getField('rootdn_passwd'), GLPIKEY),\n $authldap->getField('use_tls'),\n $authldap->getField('deref_option'))) {\n self::showLdapUsers();\n\n } else {\n echo \"
\".__('Unable to connect to the LDAP directory');\n }\n }", "label_name": "CWE-327", "label": "327"} -{"code": " function manage() {\n expHistory::set('viewable', $this->params);\n // $category = new storeCategory();\n // $categories = $category->getFullTree();\n // \n // // foreach($categories as $i=>$val){\n // // if (!empty($this->values) && in_array($val->id,$this->values)) {\n // // $this->tags[$i]->value = true;\n // // } else {\n // // $this->tags[$i]->value = false;\n // // }\n // // $this->tags[$i]->draggable = $this->draggable; \n // // $this->tags[$i]->checkable = $this->checkable; \n // // }\n //\n // $obj = json_encode($categories); \n }", "label_name": "CWE-74", "label": "74"} -{"code": " public static function parentPlaceholder($section = '')\n {\n if (! isset(static::$parentPlaceholder[$section])) {\n static::$parentPlaceholder[$section] = '##parent-placeholder-'.sha1($section).'##';\n }\n\n return static::$parentPlaceholder[$section];\n }", "label_name": "CWE-327", "label": "327"} -{"code": " function insertObject($object, $table) {\n //if ($table==\"text\") eDebug($object,true); \n $sql = \"INSERT INTO `\" . $this->prefix . \"$table` (\";\n $values = \") VALUES (\";\n foreach (get_object_vars($object) as $var => $val) {\n //We do not want to save any fields that start with an '_'\n if ($var{0} != '_') {\n $sql .= \"`$var`,\";\n if ($values != \") VALUES (\") {\n $values .= \",\";\n }\n $values .= \"'\" . $this->escapeString($val) . \"'\";\n }\n }\n $sql = substr($sql, 0, -1) . substr($values, 0) . \")\";\n //if($table=='text')eDebug($sql,true);\n if (@mysqli_query($this->connection, $sql) != false) {\n $id = mysqli_insert_id($this->connection);\n return $id;\n } else\n return 0;\n }", "label_name": "CWE-74", "label": "74"} -{"code": " function edit() {\r\n global $template;\r\n\r\n parent::edit();\r\n $allforms = array();\r\n $allforms[\"\"] = gt('Disallow Feedback');\r\n // calculate which event date is the one being edited\r\n $event_key = 0;\r\n foreach ($template->tpl->tpl_vars['record']->value->eventdate as $key=>$d) {\r\n \t if ($d->id == $this->params['date_id']) $event_key = $key;\r\n \t}\r\n\r\n assign_to_template(array(\r\n 'allforms' => array_merge($allforms, expTemplate::buildNameList(\"forms\", \"event/email\", \"tpl\", \"[!_]*\")),\r\n 'checked_date' => !empty($this->params['date_id']) ? $this->params['date_id'] : null,\r\n 'event_key' => $event_key,\r\n ));\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public static function parseAndTrim($str, $isHTML = false) { //\ufffdDeath from above\ufffd? \ufffd\n //echo \"1
\"; eDebug($str);\n// global $db;\n\n $str = str_replace(\"\ufffd\", \"’\", $str);\n $str = str_replace(\"\ufffd\", \"‘\", $str);\n $str = str_replace(\"\ufffd\", \"®\", $str);\n $str = str_replace(\"\ufffd\", \"-\", $str);\n $str = str_replace(\"\ufffd\", \"—\", $str);\n $str = str_replace(\"\ufffd\", \"”\", $str);\n $str = str_replace(\"\ufffd\", \"“\", $str);\n $str = str_replace(\"\\r\\n\", \" \", $str);\n //$str = str_replace(\",\",\"\\,\",$str); \n\n $str = str_replace('\\\"', \""\", $str);\n $str = str_replace('\"', \""\", $str);\n $str = str_replace(\"\ufffd\", \"¼\", $str);\n $str = str_replace(\"\ufffd\", \"½\", $str);\n $str = str_replace(\"\ufffd\", \"¾\", $str);\n //$str = htmlspecialchars($str);\n //$str = utf8_encode($str);\n// if (DB_ENGINE=='mysqli') {\n//\t $str = @mysqli_real_escape_string($db->connection,trim(str_replace(\"\ufffd\", \"™\", $str)));\n// } elseif(DB_ENGINE=='mysql') {\n// $str = @mysql_real_escape_string(trim(str_replace(\"\ufffd\", \"™\", $str)),$db->connection);\n// } else {\n//\t $str = trim(str_replace(\"\ufffd\", \"™\", $str));\n// }\n $str = @expString::escape(trim(str_replace(\"\ufffd\", \"™\", $str)));\n //echo \"2
\"; eDebug($str,die);\n return $str;\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function getBranches()\n {\n if (null === $this->branches) {\n $branches = array();\n $bookmarks = array();\n\n $this->process->execute('hg branches', $output, $this->repoDir);\n foreach ($this->process->splitLines($output) as $branch) {\n if ($branch && Preg::isMatch('(^([^\\s]+)\\s+\\d+:([a-f0-9]+))', $branch, $match)) {\n $branches[$match[1]] = $match[2];\n }\n }\n\n $this->process->execute('hg bookmarks', $output, $this->repoDir);\n foreach ($this->process->splitLines($output) as $branch) {\n if ($branch && Preg::isMatch('(^(?:[\\s*]*)([^\\s]+)\\s+\\d+:(.*)$)', $branch, $match)) {\n $bookmarks[$match[1]] = $match[2];\n }\n }\n\n // Branches will have preference over bookmarks\n $this->branches = array_merge($bookmarks, $branches);\n }\n\n return $this->branches;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " private function getCategory()\n {\n $category = $this->categoryModel->getById($this->request->getIntegerParam('category_id'));\n\n if (empty($category)) {\n throw new PageNotFoundException();\n }\n\n return $category;\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public function getBranches()\n {\n if (null === $this->branches) {\n $branches = array();\n\n $this->process->execute('git branch --no-color --no-abbrev -v', $output, $this->repoDir);\n foreach ($this->process->splitLines($output) as $branch) {\n if ($branch && !Preg::isMatch('{^ *[^/]+/HEAD }', $branch)) {\n if (Preg::isMatch('{^(?:\\* )? *(\\S+) *([a-f0-9]+)(?: .*)?$}', $branch, $match)) {\n $branches[$match[1]] = $match[2];\n }\n }\n }\n\n $this->branches = $branches;\n }\n\n return $this->branches;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function getDisplayName ($plural=true) {\n return Yii::t('contacts', '{contact} List|{contact} Lists', array(\n (int) $plural,\n '{contact}' => Modules::displayName(false, 'Contacts'),\n ));\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function save_change_password() {\n global $user;\n\n $isuser = ($this->params['uid'] == $user->id) ? 1 : 0;\n\n if (!$user->isAdmin() && !$isuser) {\n flash('error', gt('You do not have permissions to change this users password.'));\n expHistory::back();\n }\n\n if (($isuser && empty($this->params['password'])) || (!empty($this->params['password']) && $user->password != user::encryptPassword($this->params['password']))) {\n flash('error', gt('The current password you entered is not correct.'));\n expHistory::returnTo('editable');\n }\n //eDebug($user);\n $u = new user($this->params['uid']);\n\n $ret = $u->setPassword($this->params['new_password1'], $this->params['new_password2']);\n //eDebug($u, true);\n if (is_string($ret)) {\n flash('error', $ret);\n expHistory::returnTo('editable');\n } else {\n $params = array();\n $params['is_admin'] = !empty($u->is_admin);\n $params['is_acting_admin'] = !empty($u->is_acting_admin);\n $u->update($params);\n }\n\n if (!$isuser) {\n flash('message', gt('The password for') . ' ' . $u->username . ' ' . gt('has been changed.'));\n } else {\n $user->password = $u->password;\n flash('message', gt('Your password has been changed.'));\n }\n expHistory::back();\n }", "label_name": "CWE-74", "label": "74"} -{"code": "\tpublic function assets_path($file = NULL, $path = NULL, $module = NULL, $absolute = NULL)\n\t{\n\t\t$cache = '';\n\t\tif (!isset($absolute)) $absolute = $this->assets_absolute_path;\n\t\t\n\t\t$CI = $this->_get_assets_config();\n\t\tif ($this->asset_append_cache_timestamp AND in_array($path, $this->asset_append_cache_timestamp) AND !empty($file))\n\t\t{\n\t\t\t$q_str = (strpos($file, '?') === FALSE) ? '?' : '&';\n\t\t\t$cache = $q_str.'c='.strtotime($this->assets_last_updated);\n\t\t}\n\t\n\t\t// if it is an absolute path already provided, then we just return it without any caching\n\t\tif (!$this->_is_local_path($file))\n\t\t{\n\t\t\treturn $file.$cache;\n\t\t}\n\t\t\n\t\t$assets_folders = $this->assets_folders;\n\n\t\t$asset_type = (!empty($assets_folders[$path])) ? $assets_folders[$path] : $CI->config->item($path);\n\n\t\t// if absolute path, then we just return that\n\t\tif (!$this->_is_local_path($this->assets_path))\n\t\t{\n\t\t\treturn $this->assets_path.$asset_type.$file.$cache;\n\t\t}\n\n\t\t$assets_path = $this->_get_assets_path($module);\n\t\t\n\t\t$path = WEB_PATH.$assets_path.$asset_type.$file.$cache;\n\n\t\tif ($absolute)\n\t\t{\n\t\t\t$protocol = ($_SERVER[\"SERVER_PORT\"] == 443) ? \"https://\" : \"http://\";\n\t\t\t$path = $protocol.$_SERVER['HTTP_HOST'].$path;\n\t\t}\n\t\treturn $path;\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": " function import() {\r\n $pullable_modules = expModules::listInstalledControllers($this->baseclassname);\r\n $modules = new expPaginator(array(\r\n 'records' => $pullable_modules,\r\n 'controller' => $this->loc->mod,\r\n 'action' => $this->params['action'],\r\n 'order' => isset($this->params['order']) ? $this->params['order'] : 'section',\r\n 'dir' => isset($this->params['dir']) ? $this->params['dir'] : '',\r\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\r\n 'columns' => array(\r\n gt('Title') => 'title',\r\n gt('Page') => 'section'\r\n ),\r\n ));\r\n\r\n assign_to_template(array(\r\n 'modules' => $modules,\r\n ));\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " function searchCategory() {\r\n return gt('Event');\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": "\tstatic function convertUTF($string) {\n\t\treturn $string = str_replace('?', '', htmlspecialchars($string, ENT_IGNORE, 'UTF-8'));\n\t} ", "label_name": "CWE-74", "label": "74"} -{"code": "function twig_array_reduce(Environment $env, $array, $arrow, $initial = null)\n{\n if (!$arrow instanceof Closure && $env->hasExtension('\\Twig\\Extension\\SandboxExtension') && $env->getExtension('\\Twig\\Extension\\SandboxExtension')->isSandboxed()) {\n throw new RuntimeError('The callable passed to the \"reduce\" filter must be a Closure in sandbox mode.');\n }\n\n if (!\\is_array($array)) {\n if (!$array instanceof \\Traversable) {\n throw new RuntimeError(sprintf('The \"reduce\" filter only works with arrays or \"Traversable\", got \"%s\" as first argument.', \\gettype($array)));\n }\n\n $array = iterator_to_array($array);\n }\n\n return array_reduce($array, $arrow, $initial);\n}", "label_name": "CWE-74", "label": "74"} -{"code": " function insertObject($object, $table) {\n //if ($table==\"text\") eDebug($object,true); \n $sql = \"INSERT INTO `\" . $this->prefix . \"$table` (\";\n $values = \") VALUES (\";\n foreach (get_object_vars($object) as $var => $val) {\n //We do not want to save any fields that start with an '_'\n if ($var{0} != '_') {\n $sql .= \"`$var`,\";\n if ($values != \") VALUES (\") {\n $values .= \",\";\n }\n $values .= \"'\" . $this->escapeString($val) . \"'\";\n }\n }\n $sql = substr($sql, 0, -1) . substr($values, 0) . \")\";\n //if($table=='text')eDebug($sql,true);\n if (@mysqli_query($this->connection, $sql) != false) {\n $id = mysqli_insert_id($this->connection);\n return $id;\n } else\n return 0;\n }", "label_name": "CWE-74", "label": "74"} -{"code": " function generateAutoLoginLink($params){\n\n $dataRequest = array();\n $dataRequestAppend = array();\n\n // Destination ID\n if (isset($params['r'])){\n $dataRequest['r'] = $params['r'];\n $dataRequestAppend[] = '/(r)/'.rawurlencode(base64_encode($params['r']));\n }\n\n // User ID\n if (isset($params['u']) && is_numeric($params['u'])){\n $dataRequest['u'] = $params['u'];\n $dataRequestAppend[] = '/(u)/'.rawurlencode($params['u']);\n }\n\n // Username\n if (isset($params['l'])){\n $dataRequest['l'] = $params['l'];\n $dataRequestAppend[] = '/(l)/'.rawurlencode($params['l']);\n }\n\n if (!isset($params['l']) && !isset($params['u'])) {\n throw new Exception('Username or User ID has to be provided');\n }\n\n $ts = time() + $params['t'];\n\n // Expire time for link\n if (isset($params['t'])) {\n $dataRequest['t'] = $ts;\n $dataRequestAppend[] = '/(t)/'.rawurlencode($ts);\n }\n\n $hashValidation = sha1($params['secret_hash'].sha1($params['secret_hash'].implode(',', $dataRequest)));\n\n return $_SERVER['HTTP_HOST'] . erLhcoreClassDesign::baseurldirect(\"user/autologin\") . \"/{$hashValidation}\".implode('', $dataRequestAppend);\n }", "label_name": "CWE-116", "label": "116"} -{"code": "\tfunction getTextColumns($table) {\n\t\t$sql = \"SHOW COLUMNS FROM \" . $this->prefix.$table . \" WHERE type = 'text' OR type like 'varchar%'\";\n\t\t$res = @mysqli_query($this->connection, $sql);\n\t\tif ($res == null)\n return array();\n\t\t$records = array();\n\t\twhile($row = mysqli_fetch_object($res)) {\n\t\t\t$records[] = $row->Field;\n\t\t}\n\t\t\n\t\treturn $records;\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": " public function update() {\n\n //populate the alt tag field if the user didn't\n if (empty($this->params['alt'])) $this->params['alt'] = $this->params['title'];\n \n // call expController update to save the image\n parent::update();\n }", "label_name": "CWE-74", "label": "74"} -{"code": "\tpublic function save_user() {\r\n\t\tif ( empty( $_POST['user_id'] ) ) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\t$user_id = $_POST['user_id'];\r\n\r\n\t\tif ( !is_numeric( $user_id ) ) {\r\n\t\t\treturn $user_id;\r\n\t\t}\r\n\r\n\t\tif ( !current_user_can( 'edit_user', $user_id ) ) {\r\n\t\t\treturn $user_id;\r\n\t\t}\r\n\r\n\t\treturn $this->save_posted_object_location( $user_id );\r\n\t}\r", "label_name": "CWE-20", "label": "20"} -{"code": " public function safePath($filename = 'data.csv'){\n return implode(DIRECTORY_SEPARATOR, array(\n Yii::app()->basePath,\n 'data',\n $filename\n ));\n }", "label_name": "CWE-20", "label": "20"} -{"code": " $db->insertObject($obj, 'expeAlerts_subscribers');\n }\n \n $count = count($this->params['ealerts']);\n \n if ($count > 0) {\n flash('message', gt(\"Your subscriptions have been updated. You are now subscriber to\").\" \".$count.' '.gt('E-Alerts.'));\n } else {\n flash('error', gt(\"You have been unsubscribed from all E-Alerts.\"));\n }\n \n expHistory::back();\n }", "label_name": "CWE-74", "label": "74"} -{"code": "\tpublic static function dumpArray( $arg ) {\n\t\t$numargs = count( $arg );\n\t\tif ( $numargs < 3 ) {\n\t\t\treturn '';\n\t\t}\n\t\t$var = trim( $arg[2] );\n\t\t$text = \" array {$var} = {\";\n\t\t$n = 0;\n\t\tif ( array_key_exists( $var, self::$memoryArray ) ) {\n\t\t\tforeach ( self::$memoryArray[$var] as $value ) {\n\t\t\t\tif ( $n++ > 0 ) {\n\t\t\t\t\t$text .= ', ';\n\t\t\t\t}\n\t\t\t\t$text .= \"{$value}\";\n\t\t\t}\n\t\t}\n\t\treturn $text . \"}\\n\";\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " $bool = self::evaluateTypedCondition($array, $expression);\n\n if (!$bool) {\n $hit->parentNode->removeChild($hit);\n } else {\n $hit->removeAttribute('n-if');\n }\n }\n return $doc->saveHTML();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function editTitle() {\n global $user;\n $file = new expFile($this->params['id']);\n if ($user->id==$file->poster || $user->isAdmin()) {\n $file->title = $this->params['newValue'];\n $file->save();\n $ar = new expAjaxReply(200, gt('Your title was updated successfully'), $file);\n } else {\n $ar = new expAjaxReply(300, gt(\"You didn't create this file, so you can't edit it.\"));\n }\n $ar->send();\n } ", "label_name": "CWE-74", "label": "74"} -{"code": " $navs[$i]->link = expCore::makeLink(array('section' => $navs[$i]->id), '', $navs[$i]->sef_name);\r\n if (!$view) {\r\n// unset($navs[$i]); //FIXME this breaks jstree if we remove a parent and not the child\r\n $attr = new stdClass();\r\n $attr->class = 'hidden'; // bs3 class to hide elements\r\n $navs[$i]->li_attr = $attr;\r\n }\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": "\tpublic function test_empty_content_multiple_spaces() {\n\t\t$result = $this->myxmlrpcserver->wp_newComment(\n\t\t\tarray(\n\t\t\t\t1,\n\t\t\t\t'administrator',\n\t\t\t\t'administrator',\n\t\t\t\tself::$post->ID,\n\t\t\t\tarray(\n\t\t\t\t\t'content' => ' ',\n\t\t\t\t),\n\t\t\t)\n\t\t);\n\n\t\t$this->assertIXRError( $result );\n\t\t$this->assertSame( 403, $result->code );\n\t}", "label_name": "CWE-862", "label": "862"} -{"code": " public function testRemoveAuthorizationHeaderOnRedirect()\n {\n $mock = new MockHandler([\n new Response(302, ['Location' => 'http://test.com']),\n static function (RequestInterface $request) {\n self::assertFalse($request->hasHeader('Authorization'));\n return new Response(200);\n }\n ]);\n $handler = HandlerStack::create($mock);\n $client = new Client(['handler' => $handler]);\n $client->get('http://example.com?a=b', ['auth' => ['testuser', 'testpass']]);\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public function handle($stanza, $parent = false)\n {\n $message = $stanza->forwarded->message;\n\n $jid = explode('/',(string)$message->attributes()->from);\n $to = current(explode('/',(string)$message->attributes()->to));\n\n if($message->composing)\n $this->event('composing', array($jid[0], $to));\n if($message->paused)\n $this->event('paused', array($jid[0], $to));\n if($message->gone)\n $this->event('gone', array($jid[0], $to));\n\n if($message->body || $message->subject) {\n $m = new \\Modl\\Message;\n $m->set($message, $stanza->forwarded);\n\n if(!preg_match('#^\\?OTR#', $m->body)) {\n $md = new \\Modl\\MessageDAO;\n $md->set($m);\n\n $this->pack($m);\n $this->deliver();\n }\n }\n }", "label_name": "CWE-346", "label": "346"} -{"code": " function searchByModelForm() {\n // get the search terms\n $terms = $this->params['search_string'];\n\n $sql = \"model like '%\" . $terms . \"%'\";\n\n $limit = !empty($this->config['limit']) ? $this->config['limit'] : 10;\n $page = new expPaginator(array(\n 'model' => 'product',\n 'where' => $sql,\n 'limit' => !empty($this->config['pagination_default']) ? $this->config['pagination_default'] : $limit,\n 'order' => 'title',\n 'dir' => 'DESC',\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller' => $this->params['controller'],\n 'action' => $this->params['action'],\n 'columns' => array(\n gt('Model #') => 'model',\n gt('Product Name') => 'title',\n gt('Price') => 'base_price'\n ),\n ));\n\n assign_to_template(array(\n 'page' => $page,\n 'terms' => $terms\n ));\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function approve() {\n expHistory::set('editable', $this->params);\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n $require_login = empty($this->params['require_login']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];\n $require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];\n $require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n $notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];\n \n if (empty($this->params['id'])) {\n flash('error', gt('No ID supplied for note to approve'));\n $lastUrl = expHistory::getLast('editable');\n }\n \n $simplenote = new expSimpleNote($this->params['id']);\n assign_to_template(array(\n 'simplenote'=>$simplenote,\n 'require_login'=>$require_login,\n 'require_approval'=>$require_approval,\n 'require_notification'=>$require_notification,\n 'notification_email'=>$notification_email,\n 'tab'=>$this->params['tab']\n ));\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public static function getModelTypes($assoc = false) {\n $modelTypes = Yii::app()->db->createCommand()\n ->selectDistinct('modelName')\n ->from('x2_fields')\n ->where('modelName!=\"Calendar\"')\n ->order('modelName ASC')\n ->queryColumn();\n\n if ($assoc === true) {\n return array_combine($modelTypes, array_map(function($term) {\n return Yii::t('app', X2Model::getModelTitle($term));\n }, $modelTypes));\n }\n $modelTypes = array_map(function($term) {\n return Yii::t('app', $term);\n }, $modelTypes);\n return $modelTypes;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function SetFrom($address, $name = '', $auto = 1) {\n $address = trim($address);\n $name = trim(preg_replace('/[\\r\\n]+/', '', $name)); //Strip breaks and trim\n if (!$this->ValidateAddress($address)) {\n $this->SetError($this->Lang('invalid_address').': '. $address);\n if ($this->exceptions) {\n throw new phpmailerException($this->Lang('invalid_address').': '.$address);\n }\n if ($this->SMTPDebug) {\n $this->edebug($this->Lang('invalid_address').': '.$address);\n }\n return false;\n }\n $this->From = $address;\n $this->FromName = $name;\n if ($auto) {\n if (empty($this->ReplyTo)) {\n $this->AddAnAddress('Reply-To', $address, $name);\n }\n if (empty($this->Sender)) {\n $this->Sender = $address;\n }\n }\n return true;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " protected function renderImageByImagick($code)\n {\n $backColor = $this->transparent ? new \\ImagickPixel('transparent') : new \\ImagickPixel('#' . str_pad(dechex($this->backColor), 6, 0, STR_PAD_LEFT));\n $foreColor = new \\ImagickPixel('#' . str_pad(dechex($this->foreColor), 6, 0, STR_PAD_LEFT));\n\n $image = new \\Imagick();\n $image->newImage($this->width, $this->height, $backColor);\n\n $draw = new \\ImagickDraw();\n $draw->setFont($this->fontFile);\n $draw->setFontSize(30);\n $fontMetrics = $image->queryFontMetrics($draw, $code);\n\n $length = strlen($code);\n $w = (int) $fontMetrics['textWidth'] - 8 + $this->offset * ($length - 1);\n $h = (int) $fontMetrics['textHeight'] - 8;\n $scale = min(($this->width - $this->padding * 2) / $w, ($this->height - $this->padding * 2) / $h);\n $x = 10;\n $y = round($this->height * 27 / 40);\n for ($i = 0; $i < $length; ++$i) {\n $draw = new \\ImagickDraw();\n $draw->setFont($this->fontFile);\n $draw->setFontSize((int) (mt_rand(26, 32) * $scale * 0.8));\n $draw->setFillColor($foreColor);\n $image->annotateImage($draw, $x, $y, mt_rand(-10, 10), $code[$i]);\n $fontMetrics = $image->queryFontMetrics($draw, $code[$i]);\n $x += (int) $fontMetrics['textWidth'] + $this->offset;\n }\n\n $image->setImageFormat('png');\n return $image->getImageBlob();\n }", "label_name": "CWE-330", "label": "330"} -{"code": "function barcode_print($code, $encoding=\"ANY\", $scale = 2 ,$mode = \"png\")\n{\n // DOLCHANGE LDR Add log\n dol_syslog(\"barcode.lib.php::barcode_print $code $encoding $scale $mode\");\n\n $bars=barcode_encode($code,$encoding);\n\n if (! $bars)\n {\n // DOLCHANGE LDR Return error message instead of array\n $error='Bad Value '.$code.' for encoding '.$encoding;\n dol_syslog('barcode.lib.php::barcode_print '.$error, LOG_ERR);\n return $error;\n }\n if (! $mode) $mode=\"png\";\n //if (preg_match(\"/^(text|txt|plain)$/i\",$mode)) print barcode_outtext($bars['text'],$bars['bars']);\n //elseif (preg_match(\"/^(html|htm)$/i\",$mode)) print barcode_outhtml($bars['text'],$bars['bars'], $scale,0, 0);\n //else\n barcode_outimage($bars['text'], $bars['bars'], $scale, $mode);\n return $bars;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "\t\t\t\t$fieldPickListValues[$value] = \\App\\Language::translate($value, $this->getModuleName(),false,false);\n\t\t\t}\n\t\t\t// Protection against deleting a value that does not exist on the list\n\t\t\tif ('picklist' === $fieldDataType) {\n\t\t\t\t$fieldValue = $this->get('fieldvalue');\n\t\t\t\tif (!empty($fieldValue) && !isset($fieldPickListValues[$fieldValue])) {\n\t\t\t\t\t$fieldPickListValues[$fieldValue] = \\App\\Language::translate($fieldValue, $this->getModuleName(),false,false);\n\t\t\t\t\t$this->set('isEditableReadOnly', true);\n\t\t\t\t}\n\t\t\t}\n\t\t} elseif (method_exists($this->getUITypeModel(), 'getPicklistValues')) {", "label_name": "CWE-20", "label": "20"} -{"code": " public function remove()\n {\n $project = $this->getProject();\n $this->checkCSRFParam();\n $column_id = $this->request->getIntegerParam('column_id');\n\n if ($this->columnModel->remove($column_id)) {\n $this->flash->success(t('Column removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this column.'));\n }\n\n $this->response->redirect($this->helper->url->to('ColumnController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-200", "label": "200"} -{"code": " fwrite(STDERR, sprintf(\"%2d %s ==> %s\\n\", $i + 1, $test, var_export($result, true)));", "label_name": "CWE-330", "label": "330"} -{"code": "\t\t\t\t$path = Helpers::isAbsolute($item) ? $item : ($this->getRepositoryPath() . DIRECTORY_SEPARATOR . $item);\n\n\t\t\t\tif (!file_exists($path)) {\n\t\t\t\t\tthrow new GitException(\"The path at '$item' does not represent a valid file.\");\n\t\t\t\t}\n\n\t\t\t\t$this->run('add', $item);\n\t\t\t}", "label_name": "CWE-77", "label": "77"} -{"code": "\tpublic static function endReset( &$parser, $text ) {\n\t\tif ( !self::$createdLinks['resetdone'] ) {\n\t\t\tself::$createdLinks['resetdone'] = true;\n\t\t\tforeach ( $parser->getOutput()->mCategories as $key => $val ) {\n\t\t\t\tif ( array_key_exists( $key, self::$fixedCategories ) ) {\n\t\t\t\t\tself::$fixedCategories[$key] = $val;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// $text .= self::dumpParsedRefs($parser,\"before final reset\");\n\t\t\tif ( self::$createdLinks['resetLinks'] ) {\n\t\t\t\t$parser->getOutput()->mLinks = [];\n\t\t\t}\n\t\t\tif ( self::$createdLinks['resetCategories'] ) {\n\t\t\t\t$parser->getOutput()->mCategories = self::$fixedCategories;\n\t\t\t}\n\t\t\tif ( self::$createdLinks['resetTemplates'] ) {\n\t\t\t\t$parser->getOutput()->mTemplates = [];\n\t\t\t}\n\t\t\tif ( self::$createdLinks['resetImages'] ) {\n\t\t\t\t$parser->getOutput()->mImages = [];\n\t\t\t}\n\t\t\t// $text .= self::dumpParsedRefs( $parser, 'after final reset' );\n\t\t\tself::$fixedCategories = [];\n\t\t}\n\t\treturn true;\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " public function addTags($tags) {\n $result = false;\n $addedTags = array();\n\n foreach ((array) $tags as $tagName) {\n if (empty($tagName))\n continue;\n if (!in_array($tagName, $this->getTags())) { // check for duplicate tag\n $tag = new Tags;\n $tag->tag = '#' . ltrim($tagName, '#');\n $tag->itemId = $this->getOwner()->id;\n $tag->type = get_class($this->getOwner());\n $tag->taggedBy = Yii::app()->getSuName();\n $tag->timestamp = time();\n $tag->itemName = $this->getOwner()->name;\n\n if ($tag->save()) {\n $this->_tags[] = $tag->tag; // update tag cache\n $addedTags[] = $tagName;\n $result = true;\n } else {\n throw new CHttpException(422, 'Failed saving tag due to errors: ' . json_encode($tag->errors));\n }\n }\n }\n if ($this->flowTriggersEnabled)\n X2Flow::trigger('RecordTagAddTrigger', array(\n 'model' => $this->getOwner(),\n 'tags' => $addedTags,\n ));\n\n return $result;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function __construct(\n CartService $cartService,\n int $defaultTtl,\n bool $httpCacheEnabled,\n MaintenanceModeResolver $maintenanceModeResolver\n ) {\n $this->cartService = $cartService;\n $this->defaultTtl = $defaultTtl;\n $this->httpCacheEnabled = $httpCacheEnabled;\n $this->maintenanceResolver = $maintenanceModeResolver;\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public function showall() {\n expHistory::set('viewable', $this->params);\n // figure out if should limit the results\n if (isset($this->params['limit'])) {\n $limit = $this->params['limit'] == 'none' ? null : $this->params['limit'];\n } else {\n $limit = (isset($this->config['limit']) && $this->config['limit'] != '') ? $this->config['limit'] : 10;\n } \n $order = isset($this->config['order']) ? $this->config['order'] : 'publish DESC';\n\n // pull the news posts from the database\n $items = $this->news->find('all', $this->aggregateWhereClause(), $order);\n\n // merge in any RSS news and perform the sort and limit the number of posts we return to the configured amount.\n if (!empty($this->config['pull_rss'])) $items = $this->mergeRssData($items);\n \n // setup the pagination object to paginate the news stories.\n $page = new expPaginator(array(\n 'records'=>$items,\n 'limit'=>$limit,\n 'order'=>$order,\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->params['controller'],\n 'action'=>$this->params['action'],\n 'src'=>$this->loc->src,\n 'view'=>empty($this->params['view']) ? null : $this->params['view']\n ));\n \n assign_to_template(array(\n 'page'=>$page,\n 'items'=>$page->records,\n 'rank'=>($order==='rank')?1:0,\n 'params'=>$this->params,\n ));\n }", "label_name": "CWE-74", "label": "74"} -{"code": "\tfunction manage () {\n\t expHistory::set('viewable', $this->params);\n\t\t\n\t\t$vendor = new vendor();\n\t\t$vendors = $vendor->find('all');\n\t\tif(!empty($this->params['vendor'])) {\n\t\t\t$purchase_orders = $this->purchase_order->find('all', 'vendor_id=' . $this->params['vendor']);\n\t\t} else {\n\t\t\t$purchase_orders = $this->purchase_order->find('all');\n\t\t}\n\t\t\n\t\tassign_to_template(array(\n 'purchase_orders'=>$purchase_orders,\n 'vendors' => $vendors,\n 'vendor_id' => @$this->params['vendor']\n ));\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": " function import() {\r\n $pullable_modules = expModules::listInstalledControllers($this->baseclassname);\r\n $modules = new expPaginator(array(\r\n 'records' => $pullable_modules,\r\n 'controller' => $this->loc->mod,\r\n 'action' => $this->params['action'],\r\n 'order' => isset($this->params['order']) ? $this->params['order'] : 'section',\r\n 'dir' => isset($this->params['dir']) ? $this->params['dir'] : '',\r\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\r\n 'columns' => array(\r\n gt('Title') => 'title',\r\n gt('Page') => 'section'\r\n ),\r\n ));\r\n\r\n assign_to_template(array(\r\n 'modules' => $modules,\r\n ));\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public function testRemoveCurlAuthorizationOptionsOnRedirect($auth)\n {\n if (!defined('\\CURLOPT_HTTPAUTH')) {\n self::markTestSkipped('ext-curl is required for this test');\n }\n\n $mock = new MockHandler([\n new Response(302, ['Location' => 'http://test.com']),\n static function (RequestInterface $request, $options) {\n self::assertFalse(\n isset($options['curl'][\\CURLOPT_HTTPAUTH]),\n 'curl options still contain CURLOPT_HTTPAUTH entry'\n );\n self::assertFalse(\n isset($options['curl'][\\CURLOPT_USERPWD]),\n 'curl options still contain CURLOPT_USERPWD entry'\n );\n return new Response(200);\n }\n ]);\n $handler = HandlerStack::create($mock);\n $client = new Client(['handler' => $handler]);\n $client->get('http://example.com?a=b', ['auth' => ['testuser', 'testpass', $auth]]);\n }", "label_name": "CWE-200", "label": "200"} -{"code": "\tpublic static function setupMigration( Parser &$parser ) {\n\t\t$parser->setHook( 'Intersection', [ __CLASS__, 'intersectionTag' ] );\n\t\t$parser->addTrackingCategory( 'dpl-intersection-tracking-category' );\n\n\t\tself::init();\n\n\t\treturn true;\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " private function resolveTrustedProxy()\n {\n if (!$trustedProxies = Request::getTrustedProxies()) {\n return '127.0.0.1';\n }\n\n $firstTrustedProxy = reset($trustedProxies);\n\n return false !== ($i = strpos($firstTrustedProxy, '/')) ? substr($firstTrustedProxy, 0, $i) : $firstTrustedProxy;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public static function getTemplateHierarchyFlat($parent, $depth = 1) {\r\n global $db;\r\n\r\n $arr = array();\r\n $kids = $db->selectObjects('section_template', 'parent=' . $parent, 'rank');\r\n//\t\t$kids = expSorter::sort(array('array'=>$kids,'sortby'=>'rank', 'order'=>'ASC'));\r\n for ($i = 0, $iMax = count($kids); $i < $iMax; $i++) {\r\n $page = $kids[$i];\r\n $page->depth = $depth;\r\n $page->first = ($i == 0 ? 1 : 0);\r\n $page->last = ($i == count($kids) - 1 ? 1 : 0);\r\n $arr[] = $page;\r\n $arr = array_merge($arr, self::getTemplateHierarchyFlat($page->id, $depth + 1));\r\n }\r\n return $arr;\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": "\tprivate function _allrevisionsbefore( $option ) {\n\t\t$this->addTable( 'revision_actor_temp', 'rev' );\n\t\t$this->addSelect(\n\t\t\t[\n\t\t\t\t'rev.revactor_rev',\n\t\t\t\t'rev.revactor_timestamp'\n\t\t\t]\n\t\t);\n\t\t$this->addOrderBy( 'rev.revactor_rev' );\n\t\t$this->setOrderDir( 'DESC' );\n\t\t$this->addWhere(\n\t\t\t[\n\t\t\t\t$this->tableNames['page'] . '.page_id = rev.revactor_page',\n\t\t\t\t'rev.revactor_timestamp < ' . $this->convertTimestamp( $option )\n\t\t\t]\n\t\t);\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": "\tpublic function behaviors() {\n\t\treturn array_merge(parent::behaviors(),array(\n\t\t\t'X2LinkableBehavior'=>array(\n\t\t\t\t'class'=>'X2LinkableBehavior',\n\t\t\t\t'module'=>'marketing'\n\t\t\t),\n\t\t\t'ERememberFiltersBehavior' => array(\n\t\t\t\t'class'=>'application.components.ERememberFiltersBehavior',\n\t\t\t\t'defaults'=>array(),\n\t\t\t\t'defaultStickOnClear'=>false\n\t\t\t)\n\t\t));\n\t}", "label_name": "CWE-20", "label": "20"} -{"code": " $body = str_replace(array(\"\\n\"), \"
\", $body);\r\n } else {\r\n // It's going elsewhere (doesn't like quoted-printable)\r\n $body = str_replace(array(\"\\n\"), \" -- \", $body);\r\n }\r\n $title = $items[$i]->title;\r\n\r\n $msg .= \"BEGIN:VEVENT\\n\";\r\n $msg .= $dtstart . $dtend;\r\n $msg .= \"UID:\" . $items[$i]->date_id . \"\\n\";\r\n $msg .= \"DTSTAMP:\" . date(\"Ymd\\THis\", time()) . \"Z\\n\";\r\n if ($title) {\r\n $msg .= \"SUMMARY:$title\\n\";\r\n }\r\n if ($body) {\r\n $msg .= \"DESCRIPTION;ENCODING=QUOTED-PRINTABLE:\" . $body . \"\\n\";\r\n }\r\n //\tif($link_url) { $msg .= \"URL: $link_url\\n\";}\r\n if (!empty($this->config['usecategories'])) {\r\n if (!empty($items[$i]->expCat[0]->title)) {\r\n $msg .= \"CATEGORIES:\".$items[$i]->expCat[0]->title.\"\\n\";\r\n } else {\r\n $msg .= \"CATEGORIES:\".$this->config['uncat'].\"\\n\";\r\n }\r\n }\r\n $msg .= \"END:VEVENT\\n\";\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": "\tfunction __construct() {\n\t\t$this->mDb = GlobalNewFilesHooks::getGlobalDB( DB_REPLICA, 'gnf_files' );\n\n\t\tif ( $this->getRequest()->getText( 'sort', 'files_date' ) == 'files_date' ) {\n\t\t\t$this->mDefaultDirection = IndexPager::DIR_DESCENDING;\n\t\t} else {\n\t\t\t$this->mDefaultDirection = IndexPager::DIR_ASCENDING;\n\t\t}\n\n\t\tparent::__construct( $this->getContext() );\n\t}", "label_name": "CWE-20", "label": "20"} -{"code": " public function confirm()\n {\n $project = $this->getProject();\n\n $this->response->html($this->helper->layout->project('column/remove', array(\n 'column' => $this->columnModel->getById($this->request->getIntegerParam('column_id')),\n 'project' => $project,\n )));\n }", "label_name": "CWE-200", "label": "200"} -{"code": " $query->whereExists(function ($permissionQuery) use (&$tableDetails, $action) {\n /** @var Builder $permissionQuery */\n $permissionQuery->select(['role_id'])->from('joint_permissions')\n ->whereColumn('joint_permissions.entity_id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])\n ->whereColumn('joint_permissions.entity_type', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])\n ->where('action', '=', $action)\n ->whereIn('role_id', $this->getCurrentUserRoles())\n ->where(function (QueryBuilder $query) {\n $this->addJointHasPermissionCheck($query, $this->currentUser()->id);\n });\n });", "label_name": "CWE-863", "label": "863"} -{"code": " public function confirm()\n {\n $project = $this->getProject();\n $category = $this->getCategory();\n\n $this->response->html($this->helper->layout->project('category/remove', array(\n 'project' => $project,\n 'category' => $category,\n )));\n }", "label_name": "CWE-200", "label": "200"} -{"code": " static function author() {\r\n return \"Dave Leffler\";\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " protected function forceChangePassword()\n {\n if (!Yii::$app->user->isMustChangePasswordUrl()) {\n return Yii::$app->getResponse()->redirect(Url::toRoute(Yii::$app->user->mustChangePasswordRoute));\n }\n }", "label_name": "CWE-863", "label": "863"} -{"code": " $rst[$key] = self::parseAndTrim($st, $unescape);\n }\n return $rst;\n }\n\n $str = str_replace(\"
\",\" \",$str);\n $str = str_replace(\"
\",\" \",$str);\n $str = str_replace(\"
\",\" \",$str);\n $str = str_replace(\"
\",\" \",$str);\n $str = str_replace(\"\\r\\n\",\" \",$str);\n $str = str_replace('\"',\""\",$str);\n $str = str_replace(\"'\",\"'\",$str);\n $str = str_replace(\"\u2019\",\"’\",$str);\n $str = str_replace(\"\u2018\",\"‘\",$str);\n $str = str_replace(\"\u00ae\",\"®\",$str);\n $str = str_replace(\"\u2013\",\"-\", $str);\n $str = str_replace(\"\u2014\",\"—\", $str);\n $str = str_replace(\"\u201d\",\"”\", $str);\n $str = str_replace(\"\u201c\",\"“\", $str);\n $str = str_replace(\"\u00bc\",\"¼\",$str);\n $str = str_replace(\"\u00bd\",\"½\",$str);\n $str = str_replace(\"\u00be\",\"¾\",$str);\n\t\t$str = str_replace(\"\u2122\",\"™\", $str);\n\t\t$str = trim($str);\n\t\t\n if ($unescape) {\n\t\t\t$str = stripcslashes($str); \n\t\t} else {\n\t $str = addslashes($str);\n }\n\n return $str;\n }", "label_name": "CWE-74", "label": "74"} -{"code": "\t\tpublic function setRemoteUrl($name, $url, array $params = NULL)\n\t\t{\n\t\t\t$this->run('remote', 'set-url', $params, $name, $url);\n\t\t\treturn $this;\n\t\t}", "label_name": "CWE-77", "label": "77"} -{"code": "function wp_validate_redirect($location, $default = '') {\n\t$location = trim( $location );\n\t// browsers will assume 'http' is your protocol, and will obey a redirect to a URL starting with '//'\n\tif ( substr($location, 0, 2) == '//' )\n\t\t$location = 'http:' . $location;\n\n\t// In php 5 parse_url may fail if the URL query part contains http://, bug #38143\n\t$test = ( $cut = strpos($location, '?') ) ? substr( $location, 0, $cut ) : $location;\n\n\t// @-operator is used to prevent possible warnings in PHP < 5.3.3.\n\t$lp = @parse_url($test);\n\n\t// Give up if malformed URL\n\tif ( false === $lp )\n\t\treturn $default;\n\n\t// Allow only http and https schemes. No data:, etc.\n\tif ( isset($lp['scheme']) && !('http' == $lp['scheme'] || 'https' == $lp['scheme']) )\n\t\treturn $default;\n\n\t// Reject if certain components are set but host is not. This catches urls like https:host.com for which parse_url does not set the host field.\n\tif ( ! isset( $lp['host'] ) && ( isset( $lp['scheme'] ) || isset( $lp['user'] ) || isset( $lp['pass'] ) || isset( $lp['port'] ) ) ) {\n\t\treturn $default;\n\t}\n\n\t// Reject malformed components parse_url() can return on odd inputs.\n\tforeach ( array( 'user', 'pass', 'host' ) as $component ) {\n\t\tif ( isset( $lp[ $component ] ) && strpbrk( $lp[ $component ], ':/?#@' ) ) {\n\t\t\treturn $default;\n\t\t}\n\t}\n\n\t$wpp = parse_url(home_url());\n\n\t/**\n\t * Filters the whitelist of hosts to redirect to.\n\t *\n\t * @since 2.3.0\n\t *\n\t * @param array $hosts An array of allowed hosts.\n\t * @param bool|string $host The parsed host; empty if not isset.\n\t */\n\t$allowed_hosts = (array) apply_filters( 'allowed_redirect_hosts', array($wpp['host']), isset($lp['host']) ? $lp['host'] : '' );\n\n\tif ( isset($lp['host']) && ( !in_array($lp['host'], $allowed_hosts) && $lp['host'] != strtolower($wpp['host'])) )\n\t\t$location = $default;\n\n\treturn $location;\n}", "label_name": "CWE-20", "label": "20"} -{"code": " public static function parseAndTrimImport($str, $isHTML = false) { //\ufffdDeath from above\ufffd? \ufffd\n //echo \"1
\"; eDebug($str);\n// global $db;\n\n $str = str_replace(\"\ufffd\", \"’\", $str);\n $str = str_replace(\"\ufffd\", \"‘\", $str);\n $str = str_replace(\"\ufffd\", \"®\", $str);\n $str = str_replace(\"\ufffd\", \"-\", $str);\n $str = str_replace(\"\ufffd\", \"—\", $str);\n $str = str_replace(\"\ufffd\", \"”\", $str);\n $str = str_replace(\"\ufffd\", \"“\", $str);\n $str = str_replace(\"\\r\\n\", \" \", $str);\n $str = str_replace(\"\\,\", \",\", $str);\n $str = str_replace('\"\"', '\"', $str); //do this no matter what...in case someone added a quote in a non HTML field\n if (!$isHTML) {\n //if HTML, then leave the single quotes alone, otheriwse replace w/ special Char \n $str = str_replace('\"', \""\", $str);\n }\n $str = str_replace(\"\ufffd\", \"¼\", $str);\n $str = str_replace(\"\ufffd\", \"½\", $str);\n $str = str_replace(\"\ufffd\", \"¾\", $str);\n //$str = htmlspecialchars($str);\n //$str = utf8_encode($str);\n// if (DB_ENGINE=='mysqli') {\n//\t $str = @mysqli_real_escape_string($db->connection,trim(str_replace(\"\ufffd\", \"™\", $str)));\n// } elseif(DB_ENGINE=='mysql') {\n// $str = @mysql_real_escape_string(trim(str_replace(\"\ufffd\", \"™\", $str)),$db->connection);\n// } else {\n//\t $str = trim(str_replace(\"\ufffd\", \"™\", $str));\n// }\n $str = @expString::escape(trim(str_replace(\"\ufffd\", \"™\", $str)));\n //echo \"2
\"; eDebug($str,die);\n return $str;\n }", "label_name": "CWE-74", "label": "74"} -{"code": "function cron_dbmanager_backup() {\n\tglobal $wpdb;\n\t$backup_options = get_option('dbmanager_options');\n\t$backup_email = stripslashes($backup_options['backup_email']);\n\tif(intval($backup_options['backup_period']) > 0) {\n\t\t$backup = array();\n\t\t$backup['date'] = current_time('timestamp');\n\t\t$backup['mysqldumppath'] = $backup_options['mysqldumppath'];\n\t\t$backup['mysqlpath'] = $backup_options['mysqlpath'];\n\t\t$backup['path'] = $backup_options['path'];\n\t\t$backup['password'] = str_replace('$', '\\$', DB_PASSWORD);\n\t\t$backup['host'] = DB_HOST;\n\t\t$backup['port'] = '';\n\t\t$backup['sock'] = '';\n\t\tif(strpos(DB_HOST, ':') !== false) {\n\t\t\t$db_host = explode(':', DB_HOST);\n\t\t\t$backup['host'] = $db_host[0];\n\t\t\tif(intval($db_host[1]) != 0) {\n\t\t\t\t$backup['port'] = ' --port=\"'.intval($db_host[1]).'\"';\n\t\t\t} else {\n\t\t\t\t$backup['sock'] = ' --socket=\"'.$db_host[1].'\"';\n\t\t\t}\n\t\t}\n\t\t$backup['command'] = '';\n\t\t$brace = (substr(PHP_OS, 0, 3) == 'WIN') ? '\"' : '';\n\t\tif(intval($backup_options['backup_gzip']) == 1) {\n\t\t\t$backup['filename'] = $backup['date'].'_-_'.DB_NAME.'.sql.gz';\n\t\t\t$backup['filepath'] = $backup['path'].'/'.$backup['filename'];\n\t\t\t$backup['command'] = $brace.$backup['mysqldumppath'].$brace.' --force --host=\"'.$backup['host'].'\" --user=\"'.DB_USER.'\" --password=\"'.$backup['password'].'\"'.$backup['port'].$backup['sock'].' --add-drop-table --skip-lock-tables '.DB_NAME.' | gzip > '.$brace.$backup['filepath'].$brace;\n\t\t} else {\n\t\t\t$backup['filename'] = $backup['date'].'_-_'.DB_NAME.'.sql';\n\t\t\t$backup['filepath'] = $backup['path'].'/'.$backup['filename'];\n\t\t\t$backup['command'] = $brace.$backup['mysqldumppath'].$brace.' --force --host=\"'.$backup['host'].'\" --user=\"'.DB_USER.'\" --password=\"'.$backup['password'].'\"'.$backup['port'].$backup['sock'].' --add-drop-table --skip-lock-tables '.DB_NAME.' > '.$brace.$backup['filepath'].$brace;\n\t\t}\n\t\texecute_backup($backup['command']);\n\t\tif( !empty( $backup_email ) )\n\t\t{\n\t\t\tdbmanager_email_backup( $backup_email, $backup['filepath'] );\n\t\t}\n\t}\n\treturn;\n}", "label_name": "CWE-20", "label": "20"} -{"code": " public function Turn() {\n $this->error = array(\"error\" => \"This method, TURN, of the SMTP \".\n \"is not implemented\");\n if($this->do_debug >= 1) {\n $this->edebug(\"SMTP -> NOTICE: \" . $this->error[\"error\"] . $this->CRLF . '
');\n }\n return false;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " foreach ($elem[2] as $field) {\n echo '\n \n    '.$field[1].' :\n ';\n if ($field[3] === \"masked\") {\n echo '\n
';\n } else {\n echo '\n
';\n }\n echo '\n \n ';\n }", "label_name": "CWE-269", "label": "269"} -{"code": "\t\t} elseif ( $rowSize > 0 ) {\n\t\t\t// repeat row header after n lines of output\n\t\t\t$nstart = 0;\n\t\t\t$nsize = $rowSize;\n\t\t\t$count = count( $articles );\n\t\t\t$output .= '{|' . $rowColFormat . \"\\n|\\n\";\n\t\t\tdo {\n\t\t\t\tif ( $nstart + $nsize > $count ) {\n\t\t\t\t\t$nsize = $count - $nstart;\n\t\t\t\t}\n\t\t\t\t$output .= $lister->formatList( $articles, $nstart, $nsize );\n\t\t\t\t$output .= \"\\n|-\\n|\\n\";\n\t\t\t\t$nstart = $nstart + $nsize;\n\t\t\t\tif ( $nstart >= $count ) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} while ( true );\n\t\t\t$output .= \"\\n|}\\n\";\n\t\t} else {", "label_name": "CWE-400", "label": "400"} -{"code": " $files[$key]->save();\n }\n \n// eDebug($files,true);\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function Connect ($host, $port = false, $tval = 30) {\n // Are we already connected?\n if ($this->connected) {\n return true;\n }\n\n /*\n On Windows this will raise a PHP Warning error if the hostname doesn't exist.\n Rather than supress it with @fsockopen, let's capture it cleanly instead\n */\n\n set_error_handler(array(&$this, 'catchWarning'));\n\n // Connect to the POP3 server\n $this->pop_conn = fsockopen($host, // POP3 Host\n $port, // Port #\n $errno, // Error Number\n $errstr, // Error Message\n $tval); // Timeout (seconds)\n\n // Restore the error handler\n restore_error_handler();\n\n // Does the Error Log now contain anything?\n if ($this->error && $this->do_debug >= 1) {\n $this->displayErrors();\n }\n\n // Did we connect?\n if ($this->pop_conn == false) {\n // It would appear not...\n $this->error = array(\n 'error' => \"Failed to connect to server $host on port $port\",\n 'errno' => $errno,\n 'errstr' => $errstr\n );\n\n if ($this->do_debug >= 1) {\n $this->displayErrors();\n }\n\n return false;\n }\n\n // Increase the stream time-out\n\n // Check for PHP 4.3.0 or later\n if (version_compare(phpversion(), '5.0.0', 'ge')) {\n stream_set_timeout($this->pop_conn, $tval, 0);\n } else {\n // Does not work on Windows\n if (substr(PHP_OS, 0, 3) !== 'WIN') {\n socket_set_timeout($this->pop_conn, $tval, 0);\n }\n }\n\n // Get the POP3 server response\n $pop3_response = $this->getResponse();\n\n // Check for the +OK\n if ($this->checkResponse($pop3_response)) {\n // The connection is established and the POP3 server is talking\n $this->connected = true;\n return true;\n }\n return false;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " foreach ($nodes as $node) {\r\n if ((($perm == 'view' && $node->public == 1) || expPermissions::check($perm, expCore::makeLocation('navigation', '', $node->id))) && !in_array($node->id, $ignore_ids)) {\r\n if ($node->active == 1) {\r\n $text = str_pad('', ($depth + ($full ? 1 : 0)) * 3, '.', STR_PAD_LEFT) . $node->name;\r\n } else {\r\n $text = str_pad('', ($depth + ($full ? 1 : 0)) * 3, '.', STR_PAD_LEFT) . '(' . $node->name . ')';\r\n }\r\n $ar[$node->id] = $text;\r\n foreach (self::levelDropdownControlArray($node->id, $depth + 1, $ignore_ids, $full, $perm, $addstandalones, $addinternalalias) as $id => $text) {\r\n $ar[$id] = $text;\r\n }\r\n }\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public function editAlt() {\n global $user; \n $file = new expFile($this->params['id']);\n if ($user->id==$file->poster || $user->isAdmin()) {\n $file->alt = $this->params['newValue'];\n $file->save();\n $ar = new expAjaxReply(200, gt('Your alt was updated successfully'), $file);\n } else {\n $ar = new expAjaxReply(300, gt(\"You didn't create this file, so you can't edit it.\"));\n }\n $ar->send();\n echo json_encode($file); //FIXME we exit before hitting this\n } ", "label_name": "CWE-74", "label": "74"} -{"code": "function check_file_dir_name($label) {\n if (empty($label) || preg_match('/[^A-Za-z0-9_.-]/', $label))\n die(xlt(\"ERROR: The following variable contains invalid characters\").\": \". attr($label));\n}", "label_name": "CWE-116", "label": "116"} -{"code": " private function __pullEvent($eventId, &$successes, &$fails, $eventModel, $server, $user, $jobId)\n {\n $event = $eventModel->downloadEventFromServer(\n $eventId,\n $server\n );\n if (!empty($event)) {\n if ($this->__checkIfEventIsBlockedBeforePull($event)) {\n return false;\n }\n $event = $this->__updatePulledEventBeforeInsert($event, $server, $user);\n if (!$this->__checkIfEventSaveAble($event)) {\n $fails[$eventId] = __('Empty event detected.');\n } else {\n $this->__checkIfPulledEventExistsAndAddOrUpdate($event, $eventId, $successes, $fails, $eventModel, $server, $user, $jobId);\n }\n } else {\n // error\n $fails[$eventId] = __('failed downloading the event') . ': ' . json_encode($event);\n }\n return true;\n }", "label_name": "CWE-269", "label": "269"} -{"code": "\t\t\t\t\t$parser->getOutput()->mTemplates[$nsp] = array_diff_assoc( $parser->getOutput()->mTemplates[$nsp], self::$createdLinks[1][$nsp] );\n\t\t\t\t\t// echo (\"
 elim: parser  Tpls [$nsp] nachher = \". count($parser->getOutput()->mTemplates[$nsp])\t .\"
\\n\");\n\t\t\t\t\tif ( count( $parser->getOutput()->mTemplates[$nsp] ) == 0 ) {\n\t\t\t\t\t\tunset( $parser->getOutput()->mTemplates[$nsp] );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}", "label_name": "CWE-400", "label": "400"} -{"code": "\tpublic function addTable( $table, $alias ) {\n\t\tif ( empty( $table ) ) {\n\t\t\tthrow new \\MWException( __METHOD__ . ': An empty table name was passed.' );\n\t\t}\n\t\tif ( empty( $alias ) || is_numeric( $alias ) ) {\n\t\t\tthrow new \\MWException( __METHOD__ . ': An empty or numeric table alias was passed.' );\n\t\t}\n\t\tif ( !isset( $this->tables[$alias] ) ) {\n\t\t\t$this->tables[$alias] = $this->DB->tableName( $table );\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " function showByModel() {\n global $order, $template, $db;\n\n expHistory::set('viewable', $this->params);\n $product = new product();\n $model = $product->find(\"first\", 'model=\"' . $this->params['model'] . '\"');\n //eDebug($model);\n $product_type = new $model->product_type($model->id);\n //eDebug($product_type);\n $tpl = $product_type->getForm('show');\n if (!empty($tpl)) $template = new controllertemplate($this, $tpl);\n //eDebug($template);\n $this->grabConfig(); // grab the global config\n assign_to_template(array(\n 'config' => $this->config,\n 'product' => $product_type,\n 'last_category' => $order->lastcat\n ));\n }", "label_name": "CWE-20", "label": "20"} -{"code": "function XMLRPCaddImageGroupToComputerGroup($imageGroup, $computerGroup){\n $imageid = getResourceGroupID(\"image/$imageGroup\");\n $compid = getResourceGroupID(\"computer/$computerGroup\");\n if($imageid && $compid){\n $tmp = getUserResources(array(\"imageAdmin\"),\n array(\"manageMapping\"), 1);\n $imagegroups = $tmp['image'];\n $tmp = getUserResources(array(\"computerAdmin\"),\n array(\"manageMapping\"), 1);\n $computergroups = $tmp['computer'];\n\n if(array_key_exists($compid, $computergroups) &&\n array_key_exists($imageid, $imagegroups)){\n $mapping = getResourceMapping(\"image\", \"computer\",\n $imageid,\n $compid);\n if(!array_key_exists($imageid, $mapping) ||\n !array_key_exists($compid, $mapping[$imageid])){\n $query = \"INSERT INTO resourcemap \"\n . \"(resourcegroupid1, \"\n\t\t\t . \"resourcetypeid1, \"\n\t\t\t . \"resourcegroupid2, \"\n\t\t\t . \"resourcetypeid2) \"\n\t\t\t . \"VALUES ($imageid, \"\n\t\t\t . \"13, \"\n\t\t\t . \"$compid, \"\n\t\t\t . \"12)\";\n doQuery($query, 101);\n }\n return array('status' => 'success');\n } else {\n return array('status' => 'error',\n 'errorcode' => 84,\n 'errormsg' => 'cannot access computer and/or image group');\n }\n } else {\n return array('status' => 'error',\n 'errorcode' => 83,\n 'errormsg' => 'invalid resource group name');\n }\n}", "label_name": "CWE-20", "label": "20"} -{"code": " public static function isPublic($s) {\r\n if ($s == null) {\r\n return false;\r\n }\r\n while ($s->public && $s->parent > 0) {\r\n $s = new section($s->parent);\r\n }\r\n $lineage = (($s->public) ? 1 : 0);\r\n return $lineage;\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": "function PMA_secureSession()\n{\n // prevent session fixation and XSS\n // (better to use session_status() if available)\n if ((PMA_PHP_INT_VERSION >= 50400 && session_status() === PHP_SESSION_ACTIVE)\n || (PMA_PHP_INT_VERSION < 50400 && session_id() !== '')\n ) {\n session_regenerate_id(true);\n }\n $_SESSION[' PMA_token '] = md5(uniqid(rand(), true));\n}", "label_name": "CWE-200", "label": "200"} -{"code": " $newret = recyclebin::restoreFromRecycleBin($iLoc, $page_id);\r\n if (!empty($newret)) $ret .= $newret . '
';\r\n if ($iLoc->mod == 'container') {\r\n $ret .= scan_container($container->internal, $page_id);\r\n }\r\n }\r\n return $ret;\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public function scopeSearch(Builder $query, array $search = [])\n {\n if (empty($search)) {\n return $query;\n }\n\n if (!array_intersect(array_keys($search), $this->searchable)) {\n return $query;\n }\n\n return $query->where($search);\n }", "label_name": "CWE-287", "label": "287"} -{"code": " public function actionGetItems() {\n $sql = 'SELECT id, name as value FROM x2_accounts WHERE name LIKE :qterm ORDER BY name ASC';\n $command = Yii::app()->db->createCommand($sql);\n $qterm = $_GET['term'] . '%';\n $command->bindParam(\":qterm\", $qterm, PDO::PARAM_STR);\n $result = $command->queryAll();\n echo CJSON::encode($result);\n exit;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function getDisplayName ($plural=true) {\n return Yii::t('marketing', 'Web Form');\n }", "label_name": "CWE-20", "label": "20"} -{"code": " function edit() {\r\n global $template;\r\n\r\n parent::edit();\r\n $allforms = array();\r\n $allforms[\"\"] = gt('Disallow Feedback');\r\n // calculate which event date is the one being edited\r\n $event_key = 0;\r\n foreach ($template->tpl->tpl_vars['record']->value->eventdate as $key=>$d) {\r\n \t if ($d->id == $this->params['date_id']) $event_key = $key;\r\n \t}\r\n\r\n assign_to_template(array(\r\n 'allforms' => array_merge($allforms, expTemplate::buildNameList(\"forms\", \"event/email\", \"tpl\", \"[!_]*\")),\r\n 'checked_date' => !empty($this->params['date_id']) ? $this->params['date_id'] : null,\r\n 'event_key' => $event_key,\r\n ));\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " $value = str_replace($originalName, $cleanedName, $value);\n }\n unset($value);\n }\n $result = hash_equals(GeneralUtility::hmac(serialize($fieldChangeFunctions)), $this->parameters['fieldChangeFuncHash']);\n }\n return $result;\n }", "label_name": "CWE-327", "label": "327"} -{"code": " $query->whereExists(function ($permissionQuery) use (&$tableDetails, $morphClass) {\n /** @var Builder $permissionQuery */\n $permissionQuery->select('id')->from('joint_permissions')\n ->whereColumn('joint_permissions.entity_id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])\n ->where('entity_type', '=', $morphClass)\n ->where('action', '=', 'view')\n ->whereIn('role_id', $this->getCurrentUserRoles())\n ->where(function (QueryBuilder $query) {\n $this->addJointHasPermissionCheck($query, $this->currentUser()->id);\n });\n });", "label_name": "CWE-863", "label": "863"} -{"code": " protected function assertNoPHPErrors () {\n\t\t$this->assertElementNotPresent('css=.xdebug-error');\n\t\t$this->assertElementNotPresent('css=#x2-php-error');\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function activate_discount(){ \n if (isset($this->params['id'])) {\n $discount = new discounts($this->params['id']);\n $discount->update($this->params);\n //if ($discount->discountulator->hasConfig() && empty($discount->config)) {\n //flash('messages', $discount->discountulator->name().' requires configuration. Please do so now.');\n //redirect_to(array('controller'=>'billing', 'action'=>'configure', 'id'=>$discount->id));\n //}\n }\n \n expHistory::back();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function get_view_config() {\n global $template;\n \n // set paths we will search in for the view\n $paths = array(\n BASE.'themes/'.DISPLAY_THEME.'/modules/common/views/file/configure',\n BASE.'framework/modules/common/views/file/configure',\n );\n\n foreach ($paths as $path) {\n $view = $path.'/'.$this->params['view'].'.tpl';\n if (is_readable($view)) {\n if (bs(true)) {\n $bstrapview = $path.'/'.$this->params['view'].'.bootstrap.tpl';\n if (file_exists($bstrapview)) {\n $view = $bstrapview;\n }\n }\n if (bs3(true)) {\n $bstrapview = $path.'/'.$this->params['view'].'.bootstrap3.tpl';\n if (file_exists($bstrapview)) {\n $view = $bstrapview;\n }\n }\n $template = new controllertemplate($this, $view);\n $ar = new expAjaxReply(200, 'ok');\n\t\t $ar->send();\n }\n }\n }", "label_name": "CWE-74", "label": "74"} -{"code": " $sloc = expCore::makeLocation('navigation', null, $section->id);\r\n // remove any manage permissions for this page and it's children\r\n // $db->delete('userpermission', \"module='navigationController' AND internal=\".$section->id);\r\n // $db->delete('grouppermission', \"module='navigationController' AND internal=\".$section->id);\r\n foreach ($allusers as $uid) {\r\n $u = user::getUserById($uid);\r\n expPermissions::grant($u, 'manage', $sloc);\r\n }\r\n foreach ($allgroups as $gid) {\r\n $g = group::getGroupById($gid);\r\n expPermissions::grantGroup($g, 'manage', $sloc);\r\n }\r\n }\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": "\tprivate function _addlasteditor( $option ) {\n\t\t//Addlasteditor can not be used with addauthor.\n\t\tif ( !isset( $this->parametersProcessed['addauthor'] ) || !$this->parametersProcessed['addauthor'] ) {\n\t\t\t$this->addTable( 'revision_actor_temp', 'rev' );\n\t\t\t$this->addWhere(\n\t\t\t\t[\n\t\t\t\t\t$this->tableNames['page'] . '.page_id = rev.revactor_page',\n\t\t\t\t\t'rev.revactor_timestamp = (SELECT MAX(rev_aux_max.revactor_timestamp) FROM ' . $this->tableNames['revision_actor_temp'] . ' AS rev_aux_max WHERE rev_aux_max.revactor_page = rev.revactor_page)'\n\t\t\t\t]\n\t\t\t);\n\t\t\t$this->_adduser( null, 'rev' );\n\t\t}\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " public static function parseAndTrimExport($str, $isHTML = false) { //\ufffdDeath from above\ufffd? \ufffd\n //echo \"1
\"; eDebug($str); \n\n $str = str_replace(\"\ufffd\", \"’\", $str);\n $str = str_replace(\"\ufffd\", \"‘\", $str);\n $str = str_replace(\"\ufffd\", \"®\", $str);\n $str = str_replace(\"\ufffd\", \"-\", $str);\n $str = str_replace(\"\ufffd\", \"—\", $str);\n $str = str_replace(\"\ufffd\", \"”\", $str);\n $str = str_replace(\"\ufffd\", \"“\", $str);\n $str = str_replace(\"\\r\\n\", \" \", $str);\n $str = str_replace(\"\\t\", \" \", $str);\n $str = str_replace(\",\", \"\\,\", $str);\n $str = str_replace(\"\ufffd\", \"¼\", $str);\n $str = str_replace(\"\ufffd\", \"½\", $str);\n $str = str_replace(\"\ufffd\", \"¾\", $str);\n\n if (!$isHTML) {\n $str = str_replace('\\\"', \""\", $str);\n $str = str_replace('\"', \""\", $str);\n } else {\n $str = str_replace('\"', '\"\"', $str);\n }\n\n //$str = htmlspecialchars($str);\n //$str = utf8_encode($str);\n $str = trim(str_replace(\"\ufffd\", \"™\", $str));\n //echo \"2
\"; eDebug($str,die);\n return $str;\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function show()\n {\n $task = $this->getTask();\n $subtask = $this->getSubtask();\n\n $this->response->html($this->template->render('subtask_restriction/show', array(\n 'status_list' => array(\n SubtaskModel::STATUS_TODO => t('Todo'),\n SubtaskModel::STATUS_DONE => t('Done'),\n ),\n 'subtask_inprogress' => $this->subtaskStatusModel->getSubtaskInProgress($this->userSession->getId()),\n 'subtask' => $subtask,\n 'task' => $task,\n )));\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public function actionAppendTag() {\n if (isset($_POST['Type'], $_POST['Id'], $_POST['Tag']) &&\n preg_match('/^[\\w\\d_-]+$/', $_POST['Type'])) {\n\n if (!class_exists($_POST['Type'])) {\n echo 'false';\n return;\n }\n $model = X2Model::model($_POST['Type'])->findByPk($_POST['Id']);\n echo $model->addTags($_POST['Tag']);\n exit;\n if ($model !== null && $model->addTags($_POST['Tag'])) {\n echo 'true';\n return;\n }\n }\n echo 'false';\n }", "label_name": "CWE-20", "label": "20"} -{"code": " function manage() {\r\n global $db, $router, $user;\r\n\r\n expHistory::set('manageable', $router->params);\r\n assign_to_template(array(\r\n 'canManageStandalones' => self::canManageStandalones(),\r\n 'sasections' => $db->selectObjects('section', 'parent=-1'),\r\n 'user' => $user,\r\n// 'canManagePagesets' => $user->isAdmin(),\r\n// 'templates' => $db->selectObjects('section_template', 'parent=0'),\r\n ));\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": "function invalidTestController($port) {\n $host = php_uname('n');\n\n $filename = __DIR__.'/request-doesnotexist.dat';\n $file = fopen($filename, 'rb');\n $req_dat = fread($file, filesize($filename));\n fclose($file);\n\n // Repeat the data three times, to make it invalid. This particular bytestream\n // (and ones like it -- repeat 3 times!) in particular used to tickle a\n // use-after-free in the FastCGI support.\n $req_dat = $req_dat . $req_dat . $req_dat;\n\n $sock = fsockopen($host, $port);\n fwrite($sock, $req_dat);\n fclose($sock);\n\n // Should still be able to recover and respond to a request over the port on a\n // new TCP connection.\n echo request($host, $port, 'hello.php');\n echo \"\\n\";\n}", "label_name": "CWE-668", "label": "668"} -{"code": " $count += $db->dropTable($basename);\n }\n \n flash('message', gt('Deleted').' '.$count.' '.gt('unused tables').'.');\n expHistory::back();\n }", "label_name": "CWE-74", "label": "74"} -{"code": "\t\tpublic function createBranch($name, $checkout = FALSE)\n\t\t{\n\t\t\t// git branch $name\n\t\t\t$this->run('branch', $name);\n\n\t\t\tif ($checkout) {\n\t\t\t\t$this->checkout($name);\n\t\t\t}\n\n\t\t\treturn $this;\n\t\t}", "label_name": "CWE-77", "label": "77"} -{"code": " public function testAuthCheckAuthFails()\n {\n $GLOBALS['cfg']['Server']['auth_swekey_config'] = 'testConfigSwekey';\n $GLOBALS['server'] = 1;\n $_REQUEST['old_usr'] = '';\n $_REQUEST['pma_username'] = '';\n $_COOKIE['pmaServer-1'] = 'pmaServ1';\n $_COOKIE['pmaUser-1'] = 'pmaUser1';\n $_COOKIE['pma_iv-1'] = base64_encode('testiv09testiv09');\n $GLOBALS['cfg']['blowfish_secret'] = 'secret';\n $_SESSION['last_access_time'] = 1;\n $_SESSION['last_valid_captcha'] = true;\n $GLOBALS['cfg']['LoginCookieValidity'] = 0;\n $_SESSION['last_access_time'] = -1;\n // mock for blowfish function\n $this->object = $this->getMockBuilder('AuthenticationCookie')\n ->disableOriginalConstructor()\n ->setMethods(array('authFails'))\n ->getMock();\n\n $this->object->expects($this->once())\n ->method('authFails');\n\n $this->assertFalse(\n $this->object->authCheck()\n );\n\n $this->assertTrue(\n $GLOBALS['no_activity']\n );\n }", "label_name": "CWE-200", "label": "200"} -{"code": "\tpublic function actionView($id) {\n\t\t$model = CActiveRecord::model('Docs')->findByPk($id);\n if (!$this->checkPermissions($model, 'view')) $this->denied ();\n\n\t\tif(isset($model)){\n\t\t\t$permissions=explode(\", \",$model->editPermissions);\n\t\t\tif(in_array(Yii::app()->user->getName(),$permissions))\n\t\t\t\t$editFlag=true;\n\t\t\telse\n\t\t\t\t$editFlag=false;\n\t\t}\n\t\t//echo $model->visibility;exit;\n\t\tif (!isset($model) ||\n\t\t\t !(($model->visibility==1 ||\n\t\t\t\t($model->visibility==0 && $model->createdBy==Yii::app()->user->getName())) ||\n\t\t\t\tYii::app()->params->isAdmin|| $editFlag))\n\t\t\t$this->redirect(array('/docs/docs/index'));\n\n // add doc to user's recent item list\n User::addRecentItem('d', $id, Yii::app()->user->getId());\n X2Flow::trigger('RecordViewTrigger',array('model'=>$model));\n\t\t$this->render('view', array(\n\t\t\t'model' => $model,\n\t\t));\n\t}", "label_name": "CWE-20", "label": "20"} -{"code": " public function testHttpCacheIsSetAsATrustedProxy(array $existing, array $expected)\n {\n Request::setTrustedProxies($existing);\n\n $this->setNextResponse();\n $this->request('GET', '/', array('REMOTE_ADDR' => '10.0.0.1'));\n\n $this->assertEquals($expected, Request::getTrustedProxies());\n\n Request::setTrustedProxies(array());\n }", "label_name": "CWE-20", "label": "20"} -{"code": " $src = substr($ref->source, strlen($prefix)) . $section->id;\r\n if (call_user_func(array($ref->module, 'hasContent'))) {\r\n $oloc = expCore::makeLocation($ref->module, $ref->source);\r\n $nloc = expCore::makeLocation($ref->module, $src);\r\n if ($ref->module != \"container\") {\r\n call_user_func(array($ref->module, 'copyContent'), $oloc, $nloc);\r\n } else {\r\n call_user_func(array($ref->module, 'copyContent'), $oloc, $nloc, $section->id);\r\n }\r\n }\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": "\tprivate function _maxrevisions( $option ) {\n\t\t$this->addWhere( \"((SELECT count(rev_aux3.revactor_page) FROM {$this->tableNames['revision_actor_temp']} AS rev_aux3 WHERE rev_aux3.revactor_page = {$this->tableNames['page']}.page_id) <= {$option})\" );\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " public function IsMail() {\n $this->Mailer = 'mail';\n }", "label_name": "CWE-20", "label": "20"} -{"code": "function XMLRPCendRequest($requestid) {\n\tglobal $user;\n\t$requestid = processInputData($requestid, ARG_NUMERIC);\n\t$userRequests = getUserRequests('all', $user['id']);\n\t$found = 0;\n\tforeach($userRequests as $req) {\n\t\tif($req['id'] == $requestid) {\n\t\t\t$request = getRequestInfo($requestid);\n\t\t\t$found = 1;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif(! $found)\n\t\treturn array('status' => 'error',\n\t\t 'errorcode' => 1,\n\t\t 'errormsg' => 'unknown requestid');\n\n\tdeleteRequest($request);\n\treturn array('status' => 'success');\n}", "label_name": "CWE-20", "label": "20"} -{"code": " private static function retrieveClosurePattern($pure, $closureName)\n {\n $pattern = '/';\n if (!$pure) {\n $pattern .= preg_quote(self::$registeredDelimiters[0]) . \"\\s*\";\n }\n $pattern .= \"$closureName\\(([a-z0-9,\\.\\s]+)\\)\";\n if (!$pure) {\n $pattern .= \"\\s*\" . preg_quote(self::$registeredDelimiters[1]);\n }\n return $pattern . \"/i\";\n }", "label_name": "CWE-74", "label": "74"} -{"code": "\tpublic function approve_toggle() {\n\t if (empty($this->params['id'])) return;\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n// $require_login = empty($this->params['require_login']) ? COMMENTS_REQUIRE_LOGIN : $this->params['require_login'];\n// $require_approval = empty($this->params['require_approval']) ? COMMENTS_REQUIRE_APPROVAL : $this->params['require_approval'];\n// $require_notification = empty($this->params['require_notification']) ? COMMENTS_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n// $notification_email = empty($this->params['notification_email']) ? COMMENTS_NOTIFICATION_EMAIL : $this->params['notification_email'];\n\n\t $comment = new expComment($this->params['id']);\n\t $comment->approved = $comment->approved == 1 ? 0 : 1;\n\t if ($comment->approved) {\n\t\t $this->sendApprovalNotification($comment,$this->params);\n\t }\n\t $comment->save();\n\t expHistory::back();\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": "\tpublic function Set($_var = '', $_value = '', $_vartrusted = false, $_valuetrusted = false) {\n\n\t\tif ($_var != ''\n\t\t\t&& $_value != ''\n\t\t) {\n\t\t\tif (!$_vartrusted) {\n\t\t\t\t$_var = strip_tags($_var);\n\t\t\t}\n\n\t\t\tif (!$_valuetrusted) {\n\t\t\t\t$_value = strip_tags($_value, '
');\n\t\t\t}\n\n\t\t\tif (strtolower($_var) == 'message'\n\t\t\t\t|| strtolower($_var) == 'subject'\n\t\t\t) {\n\t\t\t\t$_value = $this->convertLatin1ToHtml($_value);\n\t\t\t}\n\n\t\t\t$this->t_data[$_var] = $_value;\n\t\t}\n\t}", "label_name": "CWE-732", "label": "732"} -{"code": " public function confirm()\n {\n $project = $this->getProject();\n $tag_id = $this->request->getIntegerParam('tag_id');\n $tag = $this->tagModel->getById($tag_id);\n\n $this->response->html($this->template->render('project_tag/remove', array(\n 'tag' => $tag,\n 'project' => $project,\n )));\n }", "label_name": "CWE-200", "label": "200"} -{"code": "\t\t\tforeach ( $option as $_option ) {\n\t\t\t\t//Parameter functions return true or false. The full parameter data will be passed into the Query object later.\n\t\t\t\tif ( $this->parameters->$parameter( $_option ) === false ) {\n\t\t\t\t\t//Do not build this into the output just yet. It will be collected at the end.\n\t\t\t\t\t$this->logger->addMessage( \\DynamicPageListHooks::WARN_WRONGPARAM, $parameter, $_option );\n\t\t\t\t}\n\t\t\t}", "label_name": "CWE-400", "label": "400"} -{"code": " public function destroy(Appointment $appointment)\n {\n if (!auth()->user()->can(\"appointment-create\")) {\n return response(\"Access denied\", 403);\n }\n\n $deleted = $appointment->delete();\n if ($deleted) {\n return response(\"Success\");\n }\n return response(\"Error\", 503);\n }", "label_name": "CWE-862", "label": "862"} -{"code": "\tpublic function setHeadListAttributes( $attributes ) {\n\t\t$this->headListAttributes = \\Sanitizer::fixTagAttributes( $attributes, 'ul' );\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": "\tfunction unlockTables() {\n $sql = \"UNLOCK TABLES\";\n \n $res = mysqli_query($this->connection, $sql);\n return $res;\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function manage() {\n expHistory::set('viewable', $this->params);\n \n $page = new expPaginator(array(\n\t\t\t'model'=>'order_status',\n\t\t\t'where'=>1,\n 'limit'=>10,\n\t\t\t'order'=>'rank',\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->params['controller'],\n 'action'=>$this->params['action'],\n //'columns'=>array('Name'=>'title')\n ));\n\n\t\tassign_to_template(array(\n 'page'=>$page\n ));\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function testAuthCheckDecryptUser()\n {\n $GLOBALS['cfg']['Server']['auth_swekey_config'] = 'testConfigSwekey';\n $GLOBALS['server'] = 1;\n $_REQUEST['old_usr'] = '';\n $_REQUEST['pma_username'] = '';\n $_COOKIE['pmaServer-1'] = 'pmaServ1';\n $_COOKIE['pmaUser-1'] = 'pmaUser1';\n $_COOKIE['pma_iv-1'] = base64_encode('testiv09testiv09');\n $GLOBALS['cfg']['blowfish_secret'] = 'secret';\n $_SESSION['last_access_time'] = '';\n $_SESSION['last_valid_captcha'] = true;\n\n // mock for blowfish function\n $this->object = $this->getMockBuilder('AuthenticationCookie')\n ->disableOriginalConstructor()\n ->setMethods(array('cookieDecrypt'))\n ->getMock();\n\n $this->object->expects($this->once())\n ->method('cookieDecrypt')\n ->will($this->returnValue('testBF'));\n\n $this->assertFalse(\n $this->object->authCheck()\n );\n\n $this->assertEquals(\n 'testBF',\n $GLOBALS['PHP_AUTH_USER']\n );\n }", "label_name": "CWE-200", "label": "200"} -{"code": "\tpublic function __construct( $title, $namespace ) {\n\t\t$this->mTitle = $title;\n\t\t$this->mNamespace = $namespace;\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " private function runCallback() {\n foreach ($this->records as &$record) {\n if (isset($record->ref_type)) {\n $refType = $record->ref_type;\n if (class_exists($record->ref_type)) {\n $type = new $refType();\n $classinfo = new ReflectionClass($type);\n if ($classinfo->hasMethod('paginationCallback')) {\n $item = new $type($record->original_id);\n $item->paginationCallback($record);\n }\n }\n }\n } \n }", "label_name": "CWE-74", "label": "74"} -{"code": " $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn];", "label_name": "CWE-863", "label": "863"} -{"code": "\tpublic static function dplNumParserFunction( &$parser, $text = '' ) {\n\t\t$parser->addTrackingCategory( 'dplnum-parserfunc-tracking-category' );\n\t\t$num = str_replace( ' ', ' ', $text );\n\t\t$num = str_replace( ' ', ' ', $text );\n\t\t$num = preg_replace( '/([0-9])([.])([0-9][0-9]?[^0-9,])/', '\\1,\\3', $num );\n\t\t$num = preg_replace( '/([0-9.]+),([0-9][0-9][0-9])\\s*Mrd/', '\\1\\2 000000 ', $num );\n\t\t$num = preg_replace( '/([0-9.]+),([0-9][0-9])\\s*Mrd/', '\\1\\2 0000000 ', $num );\n\t\t$num = preg_replace( '/([0-9.]+),([0-9])\\s*Mrd/', '\\1\\2 00000000 ', $num );\n\t\t$num = preg_replace( '/\\s*Mrd/', '000000000 ', $num );\n\t\t$num = preg_replace( '/([0-9.]+),([0-9][0-9][0-9])\\s*Mio/', '\\1\\2 000 ', $num );\n\t\t$num = preg_replace( '/([0-9.]+),([0-9][0-9])\\s*Mio/', '\\1\\2 0000 ', $num );\n\t\t$num = preg_replace( '/([0-9.]+),([0-9])\\s*Mio/', '\\1\\2 00000 ', $num );\n\t\t$num = preg_replace( '/\\s*Mio/', '000000 ', $num );\n\t\t$num = preg_replace( '/[. ]/', '', $num );\n\t\t$num = preg_replace( '/^[^0-9]+/', '', $num );\n\t\t$num = preg_replace( '/[^0-9].*/', '', $num );\n\t\treturn $num;\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " public function gc($force = false)\n {\n if ($force || mt_rand(0, 1000000) < $this->gcProbability) {\n $this->db->createCommand()\n ->delete($this->cacheTable, '[[expire]] > 0 AND [[expire]] < ' . time())\n ->execute();\n }\n }", "label_name": "CWE-330", "label": "330"} -{"code": " public function execute(&$params){\n $action = new Actions;\n $action->associationType = lcfirst(get_class($params['model']));\n $action->associationId = $params['model']->id;\n $action->subject = $this->parseOption('subject', $params);\n $action->actionDescription = $this->parseOption('description', $params);\n if($params['model']->hasAttribute('assignedTo'))\n $action->assignedTo = $params['model']->assignedTo;\n if($params['model']->hasAttribute('priority'))\n $action->priority = $params['model']->priority;\n if($params['model']->hasAttribute('visibility'))\n $action->visibility = $params['model']->visibility;\n\n if ($action->save()) {\n return array (\n true,\n Yii::t('studio', \"View created action: \").$action->getLink ()\n );\n } else {\n return array(false, array_shift($action->getErrors()));\n }\n\n }", "label_name": "CWE-20", "label": "20"} -{"code": " foreach($item->attributes as $name => $value)\n if ($name !== 'id' && $name !== 'listId')\n $copy->$name = $value;\n $lineItems[] = $copy;\n }\n return $lineItems;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function testXForwarderForHeaderForForwardedRequests($xForwardedFor, $expected)\n {\n $this->setNextResponse();\n $server = array('REMOTE_ADDR' => '10.0.0.1');\n if (false !== $xForwardedFor) {\n $server['HTTP_X_FORWARDED_FOR'] = $xForwardedFor;\n }\n $this->request('GET', '/', $server);\n\n $this->assertEquals($expected, $this->kernel->getBackendRequest()->headers->get('X-Forwarded-For'));\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public static function _date2timestamp( $datetime, $wtz=null ) {\r\n if( !isset( $datetime['hour'] )) $datetime['hour'] = 0;\r\n if( !isset( $datetime['min'] )) $datetime['min'] = 0;\r\n if( !isset( $datetime['sec'] )) $datetime['sec'] = 0;\r\n if( empty( $wtz ) && ( !isset( $datetime['tz'] ) || empty( $datetime['tz'] )))\r\n return mktime( $datetime['hour'], $datetime['min'], $datetime['sec'], $datetime['month'], $datetime['day'], $datetime['year'] );\r\n $output = $offset = 0;\r\n if( empty( $wtz )) {\r\n if( iCalUtilityFunctions::_isOffset( $datetime['tz'] )) {\r\n $offset = iCalUtilityFunctions::_tz2offset( $datetime['tz'] ) * -1;\r\n $wtz = 'UTC';\r\n }\r\n else\r\n $wtz = $datetime['tz'];\r\n }\r\n if(( 'Z' == $wtz ) || ( 'GMT' == strtoupper( $wtz )))\r\n $wtz = 'UTC';\r\n try {\r\n $strdate = sprintf( '%04d-%02d-%02d %02d:%02d:%02d', $datetime['year'], $datetime['month'], $datetime['day'], $datetime['hour'], $datetime['min'], $datetime['sec'] );\r\n $d = new DateTime( $strdate, new DateTimeZone( $wtz ));\r\n if( 0 != $offset ) // adjust for offset\r\n $d->modify( $offset.' seconds' );\r\n $output = $d->format( 'U' );\r\n unset( $d );\r\n }\r\n catch( Exception $e ) {\r\n $output = mktime( $datetime['hour'], $datetime['min'], $datetime['sec'], $datetime['month'], $datetime['day'], $datetime['year'] );\r\n }\r\n return $output;\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " function reset_stats() {\n// global $db;\n\n // reset the counters\n// $db->sql ('UPDATE '.$db->prefix.'banner SET impressions=0 WHERE 1');\n banner::resetImpressions();\n// $db->sql ('UPDATE '.$db->prefix.'banner SET clicks=0 WHERE 1');\n banner::resetClicks();\n \n // let the user know we did stuff. \n flash('message', gt(\"Banner statistics reset.\"));\n expHistory::back();\n }", "label_name": "CWE-74", "label": "74"} -{"code": "\tpublic function editspeed() {\n global $db;\n\n if (empty($this->params['id'])) return false;\n $calcname = $db->selectValue('shippingcalculator', 'calculator_name', 'id='.$this->params['id']);\n $calc = new $calcname($this->params['id']);\n assign_to_template(array(\n 'calculator'=>$calc\n ));\n\t\t\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function getDisplayName ($plural=true) {\n return Yii::t('users', '{user}', array(\n '{user}' => Modules::displayName($plural, 'Users'),\n ));\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\tstatic function convertXMLFeedSafeChar($str) {\n\t\t$str = str_replace(\"
\",\"\",$str);\n $str = str_replace(\"
\",\"\",$str);\n $str = str_replace(\"
\",\"\",$str);\n $str = str_replace(\"
\",\"\",$str);\n $str = str_replace(\""\",'\"',$str);\n $str = str_replace(\"'\",\"'\",$str);\n $str = str_replace(\"’\",\"'\",$str);\n $str = str_replace(\"‘\",\"'\",$str); \n $str = str_replace(\"®\",\"\",$str);\n $str = str_replace(\"\ufffd\",\"-\", $str);\n $str = str_replace(\"\ufffd\",\"-\", $str); \n $str = str_replace(\"\ufffd\", '\"', $str);\n $str = str_replace(\"”\",'\"', $str);\n $str = str_replace(\"\ufffd\", '\"', $str);\n $str = str_replace(\"“\",'\"', $str);\n $str = str_replace(\"\\r\\n\",\" \",$str); \n $str = str_replace(\"\ufffd\",\" 1/4\",$str);\n $str = str_replace(\"¼\",\" 1/4\", $str);\n $str = str_replace(\"\ufffd\",\" 1/2\",$str);\n $str = str_replace(\"½\",\" 1/2\",$str);\n $str = str_replace(\"\ufffd\",\" 3/4\",$str);\n $str = str_replace(\"¾\",\" 3/4\",$str);\n $str = str_replace(\"\ufffd\", \"(TM)\", $str);\n $str = str_replace(\"™\",\"(TM)\", $str);\n $str = str_replace(\"®\",\"(R)\", $str);\n $str = str_replace(\"\ufffd\",\"(R)\",$str); \n $str = str_replace(\"&\",\"&\",$str); \n\t\t$str = str_replace(\">\",\">\",$str); \t\t\n return trim($str);\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": "\t\tpublic function merge($branch, $options = NULL)\n\t\t{\n\t\t\t$this->run('merge', $options, $branch);\n\t\t\treturn $this;\n\t\t}", "label_name": "CWE-77", "label": "77"} -{"code": " public function showall() {\n expHistory::set('viewable', $this->params);\n $limit = (isset($this->config['limit']) && $this->config['limit'] != '') ? $this->config['limit'] : 10;\n if (!empty($this->params['view']) && ($this->params['view'] == 'showall_accordion' || $this->params['view'] == 'showall_tabbed')) {\n $limit = '0';\n }\n $order = isset($this->config['order']) ? $this->config['order'] : \"rank\";\n $page = new expPaginator(array(\n 'model'=>'photo',\n 'where'=>$this->aggregateWhereClause(),\n 'limit'=>$limit,\n 'order'=>$order,\n 'categorize'=>empty($this->config['usecategories']) ? false : $this->config['usecategories'],\n 'uncat'=>!empty($this->config['uncat']) ? $this->config['uncat'] : gt('Not Categorized'),\n 'groups'=>!isset($this->params['gallery']) ? array() : array($this->params['gallery']),\n 'grouplimit'=>!empty($this->params['view']) && $this->params['view'] == 'showall_galleries' ? 1 : null,\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->baseclassname,\n 'action'=>$this->params['action'],\n 'src'=>$this->loc->src,\n 'columns'=>array(\n gt('Title')=>'title'\n ),\n ));\n \n assign_to_template(array(\n 'page'=>$page,\n 'params'=>$this->params,\n ));\n }", "label_name": "CWE-74", "label": "74"} -{"code": "\tpublic function setItemAttributes( $attributes ) {\n\t\t$this->itemAttributes = \\Sanitizer::fixTagAttributes( $attributes, 'li' );\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " public static function checkPermissions($permission,$location) {\r\n global $exponent_permissions_r, $router;\r\n\r\n // only applies to the 'manage' method\r\n if (empty($location->src) && empty($location->int) && (!empty($router->params['action']) && $router->params['action'] == 'manage') || strpos($router->current_url, 'action=manage') !== false) {\r\n if (!empty($exponent_permissions_r['navigation'])) foreach ($exponent_permissions_r['navigation'] as $page) {\r\n foreach ($page as $pageperm) {\r\n if (!empty($pageperm['manage'])) return true;\r\n }\r\n }\r\n }\r\n return false;\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $action = $this->actionModel->getById($this->request->getIntegerParam('action_id'));\n\n if (! empty($action) && $this->actionModel->remove($action['id'])) {\n $this->flash->success(t('Action removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this action.'));\n }\n\n $this->response->redirect($this->helper->url->to('ActionController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-200", "label": "200"} -{"code": " function update_optiongroup_master() {\n global $db;\n\n $id = empty($this->params['id']) ? null : $this->params['id'];\n $og = new optiongroup_master($id);\n $oldtitle = $og->title;\n $og->update($this->params);\n \n // if the title of the master changed we should update the option groups that are already using it.\n if ($oldtitle != $og->title) {\n $db->sql('UPDATE '.$db->prefix.'optiongroup SET title=\"'.$og->title.'\" WHERE title=\"'.$oldtitle.'\"');\n }\n \n expHistory::back();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public static function validateServer($path, $values)\n {\n $result = array(\n 'Server' => '',\n 'Servers/1/user' => '',\n 'Servers/1/SignonSession' => '',\n 'Servers/1/SignonURL' => ''\n );\n $error = false;\n if ($values['Servers/1/auth_type'] == 'config'\n && empty($values['Servers/1/user'])\n ) {\n $result['Servers/1/user'] = __(\n 'Empty username while using [kbd]config[/kbd] authentication method!'\n );\n $error = true;\n }\n if ($values['Servers/1/auth_type'] == 'signon'\n && empty($values['Servers/1/SignonSession'])\n ) {\n $result['Servers/1/SignonSession'] = __(\n 'Empty signon session name '\n . 'while using [kbd]signon[/kbd] authentication method!'\n );\n $error = true;\n }\n if ($values['Servers/1/auth_type'] == 'signon'\n && empty($values['Servers/1/SignonURL'])\n ) {\n $result['Servers/1/SignonURL'] = __(\n 'Empty signon URL while using [kbd]signon[/kbd] authentication '\n . 'method!'\n );\n $error = true;\n }\n\n if (! $error && $values['Servers/1/auth_type'] == 'config') {\n $password = $values['Servers/1/nopassword'] ? null\n : $values['Servers/1/password'];\n $test = static::testDBConnection(\n $values['Servers/1/connect_type'],\n $values['Servers/1/host'],\n $values['Servers/1/port'],\n $values['Servers/1/socket'],\n $values['Servers/1/user'],\n $password,\n 'Server'\n );\n if ($test !== true) {\n $result = array_merge($result, $test);\n }\n }\n return $result;\n }", "label_name": "CWE-200", "label": "200"} -{"code": " static function author() {\r\n return \"Dave Leffler\";\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " $files[$key]->save();\n }\n \n// eDebug($files,true);\n }", "label_name": "CWE-74", "label": "74"} -{"code": "\tpublic function admin_print_scripts( $not_used ) {\r\n\t\t// Load any uploaded KML into the search map - only works with browser uploader\r\n\t\t\r\n\t\t// See if wp_upload_handler found uploaded KML\r\n\t\t$kml_url = get_transient( 'gm_uploaded_kml_url' );\r\n\t\tif (strlen($kml_url) > 0) {\r\n\t\t\t// Load the KML in the location editor\r\n\t\t\techo '\r\n\t\t\t\t';\r\n\t\t\tdelete_transient( 'gm_uploaded_kml_url' );\r\n\t\t}\r\n\t}\r", "label_name": "CWE-20", "label": "20"} -{"code": "\tpublic function approve_toggle() {\n\t if (empty($this->params['id'])) return;\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n// $require_login = empty($this->params['require_login']) ? COMMENTS_REQUIRE_LOGIN : $this->params['require_login'];\n// $require_approval = empty($this->params['require_approval']) ? COMMENTS_REQUIRE_APPROVAL : $this->params['require_approval'];\n// $require_notification = empty($this->params['require_notification']) ? COMMENTS_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n// $notification_email = empty($this->params['notification_email']) ? COMMENTS_NOTIFICATION_EMAIL : $this->params['notification_email'];\n\n\t $comment = new expComment($this->params['id']);\n\t $comment->approved = $comment->approved == 1 ? 0 : 1;\n\t if ($comment->approved) {\n\t\t $this->sendApprovalNotification($comment,$this->params);\n\t }\n\t $comment->save();\n\t expHistory::back();\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": "\tpublic function fixsessions() {\n\t global $db;\n\n//\t\t$test = $db->sql('CHECK TABLE '.$db->prefix.'sessionticket');\n\t\t$fix = $db->sql('REPAIR TABLE '.$db->prefix.'sessionticket');\n\t\tflash('message', gt('Sessions Table was Repaired'));\n\t\texpHistory::back();\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": " public function Disconnect () {\n $this->sendString('QUIT');\n\n fclose($this->pop_conn);\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function validate() {\n global $db;\n // check for an sef url field. If it exists make sure it's valid and not a duplicate\n //this needs to check for SEF URLS being turned on also: TODO\n\n if (property_exists($this, 'sef_url') && !(in_array('sef_url', $this->do_not_validate))) {\n if (empty($this->sef_url)) $this->makeSefUrl();\n if (!isset($this->validates['is_valid_sef_name']['sef_url'])) $this->validates['is_valid_sef_name']['sef_url'] = array();\n if (!isset($this->validates['uniqueness_of']['sef_url'])) $this->validates['uniqueness_of']['sef_url'] = array();\n }\n\n // safeguard again loc data not being pass via forms...sometimes this happens when you're in a router\n // mapped view and src hasn't been passed in via link to the form \n if (isset($this->id) && empty($this->location_data)) {\n $loc = $db->selectValue($this->tablename, 'location_data', 'id=' . $this->id);\n if (!empty($loc)) $this->location_data = $loc;\n }\n\n // run the validation as defined in the models\n if (!isset($this->validates)) return true;\n $messages = array();\n $post = empty($_POST) ? array() : expString::sanitize($_POST);\n foreach ($this->validates as $validation=> $field) {\n foreach ($field as $key=> $value) {\n $fieldname = is_numeric($key) ? $value : $key;\n $opts = is_numeric($key) ? array() : $value;\n $ret = expValidator::$validation($fieldname, $this, $opts);\n if (!is_bool($ret)) {\n $messages[] = $ret;\n expValidator::setErrorField($fieldname);\n unset($post[$fieldname]);\n }\n }\n }\n\n if (count($messages) >= 1) expValidator::failAndReturnToForm($messages, $post);\n }", "label_name": "CWE-74", "label": "74"} -{"code": "\tprivate function _qualitypages( $option ) {\n\t\tif ( function_exists( 'efLoadFlaggedRevs' ) ) {\n\t\t\t//Do not add this again if 'stablepages' has already added it.\n\t\t\tif ( !$this->parametersProcessed['stablepages'] ) {\n\t\t\t\t$this->addJoin(\n\t\t\t\t\t'flaggedpages',\n\t\t\t\t\t[\n\t\t\t\t\t\t\"LEFT JOIN\",\n\t\t\t\t\t\t\"page_id = fp_page_id\"\n\t\t\t\t\t]\n\t\t\t\t);\n\t\t\t}\n\t\t\tswitch ( $option ) {\n\t\t\t\tcase 'only':\n\t\t\t\t\t$this->addWhere( 'fp_quality >= 1' );\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'exclude':\n\t\t\t\t\t$this->addWhere( 'fp_quality = 0' );\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": "\tpublic function getPurchaseOrderByJSON() {\n\n\t\tif(!empty($this->params['vendor'])) {\n\t\t\t$purchase_orders = $this->purchase_order->find('all', 'vendor_id=' . $this->params['vendor']);\n\t\t} else {\n\t\t\t$purchase_orders = $this->purchase_order->find('all');\n\t\t}\n\n\t\techo json_encode($purchase_orders);\n\t}", "label_name": "CWE-20", "label": "20"} -{"code": " function edit_section() {\r\n global $db, $user;\r\n\r\n $parent = new section($this->params['parent']);\r\n if (empty($parent->id)) $parent->id = 0;\r\n assign_to_template(array(\r\n 'haveStandalone' => ($db->countObjects('section', 'parent=-1') && $parent->id >= 0),\r\n 'parent' => $parent,\r\n 'isAdministrator' => $user->isAdmin(),\r\n ));\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": "\tfunction edit() {\n\t if (empty($this->params['content_id'])) {\n\t flash('message',gt('An error occurred: No content id set.'));\n expHistory::back(); \n\t } \n /* The global constants can be overridden by passing appropriate params */\n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n// $require_login = empty($this->params['require_login']) ? COMMENTS_REQUIRE_LOGIN : $this->params['require_login'];\n// $require_approval = empty($this->params['require_approval']) ? COMMENTS_REQUIRE_APPROVAL : $this->params['require_approval'];\n// $require_notification = empty($this->params['require_notification']) ? COMMENTS_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n// $notification_email = empty($this->params['notification_email']) ? COMMENTS_NOTIFICATION_EMAIL : $this->params['notification_email'];\n \n \n\t $id = empty($this->params['id']) ? null : $this->params['id'];\n\t $comment = new expComment($id);\n //FIXME here is where we might sanitize the comment before displaying/editing it\n\t\tassign_to_template(array(\n\t\t 'content_id'=>$this->params['content_id'],\n 'content_type'=>$this->params['content_type'],\n\t\t 'comment'=>$comment\n\t\t));\n\t}\t", "label_name": "CWE-74", "label": "74"} -{"code": " public function saveConfig() { \n if (!empty($this->params['aggregate']) || !empty($this->params['pull_rss'])) {\n if ($this->params['order'] == 'rank ASC') {\n expValidator::failAndReturnToForm(gt('User defined ranking is not allowed when aggregating or pull RSS data feeds.'), $this->params);\n }\n }\n \n parent::saveConfig();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " foreach ($allusers as $uid) {\r\n $u = user::getUserById($uid);\r\n expPermissions::grant($u, 'manage', $sloc);\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": "function getUserGroupID($name, $affilid=DEFAULT_AFFILID) {\n\t$query = \"SELECT id \"\n\t . \"FROM usergroup \"\n\t . \"WHERE name = '$name' AND \"\n\t . \"affiliationid = $affilid\";\n\t$qh = doQuery($query, 300);\n\tif($row = mysql_fetch_row($qh)) {\n\t\treturn $row[0];\n\t}\n\t$query = \"INSERT INTO usergroup \"\n\t . \"(name, \"\n\t . \"affiliationid, \"\n\t . \"custom, \"\n\t . \"courseroll) \"\n\t . \"VALUES \"\n\t . \"('$name', \"\n\t . \"$affilid, \"\n\t . \"0, \"\n\t . \"0)\";\n\tdoQuery($query, 301);\n\t$qh = doQuery(\"SELECT LAST_INSERT_ID() FROM usergroup\", 302);\n\tif(! $row = mysql_fetch_row($qh)) {\n\t\tabort(303);\n\t}\n\treturn $row[0];\n}", "label_name": "CWE-20", "label": "20"} -{"code": " function columnUpdate($table, $col, $val, $where=1) { \n $res = @mysqli_query($this->connection, \"UPDATE `\" . $this->prefix . \"$table` SET `$col`='\" . $val . \"' WHERE $where\");\n /*if ($res == null)\n return array();\n $objects = array();\n for ($i = 0; $i < mysqli_num_rows($res); $i++)\n $objects[] = mysqli_fetch_object($res);*/\n //return $objects;\n }", "label_name": "CWE-74", "label": "74"} -{"code": " function delete_recurring() {\r\n $item = $this->event->find('first', 'id=' . $this->params['id']);\r\n if ($item->is_recurring == 1) { // need to give user options\r\n expHistory::set('editable', $this->params);\r\n assign_to_template(array(\r\n 'checked_date' => $this->params['date_id'],\r\n 'event' => $item,\r\n ));\r\n } else { // Process a regular delete\r\n $item->delete();\r\n }\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": "\t \t\tself::$collectedInfo[$params['name']] = array('definition' => $params, 'value' => $_FILES[$params['name']]);\r\n\t \t}\r\n\r\n \t} else {\r\n \t\tif (isset(self::$collectedInfo[$params['name']]['value'])){\r\n \t\t\t$valueContent = self::$collectedInfo[$params['name']]['value'];\r\n \t\t\t$downloadLink = \"id.'/'.self::$collectedObject->hash.'/'.$params['name'].\"\\\">Download (\".htmlspecialchars($valueContent['name']).\")\";\r\n \t\t}\r\n \t}\r\n \t\r\n \treturn \"{$downloadLink}\";\r\n }\r", "label_name": "CWE-116", "label": "116"} -{"code": " public function testCheckHTTP()\n {\n if (! function_exists('curl_init')) {\n $this->markTestSkipped('Missing curl extension!');\n }\n $this->assertTrue(\n $this->object->checkHTTP(\"http://www.phpmyadmin.net/test/data\")\n );\n $this->assertContains(\n \"TEST DATA\",\n $this->object->checkHTTP(\"http://www.phpmyadmin.net/test/data\", true)\n );\n $this->assertFalse(\n $this->object->checkHTTP(\"http://www.phpmyadmin.net/test/nothing\")\n );\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function testDecrypt($expected, $key, $string) {\n $this->string(\\Toolbox::decrypt($string, $key))->isIdenticalTo($expected);\n }", "label_name": "CWE-327", "label": "327"} -{"code": "\t\tpublic function createTag($name, $options = NULL)\n\t\t{\n\t\t\t$this->run('tag', $options, $name);\n\t\t\treturn $this;\n\t\t}", "label_name": "CWE-77", "label": "77"} -{"code": " protected function createSubRequest($uri, Request $request)\n {\n $cookies = $request->cookies->all();\n $server = $request->server->all();\n\n // Override the arguments to emulate a sub-request.\n // Sub-request object will point to localhost as client ip and real client ip\n // will be included into trusted header for client ip\n try {\n if ($trustedHeaderName = Request::getTrustedHeaderName(Request::HEADER_CLIENT_IP)) {\n $currentXForwardedFor = $request->headers->get($trustedHeaderName, '');\n\n $server['HTTP_'.$trustedHeaderName] = ($currentXForwardedFor ? $currentXForwardedFor.', ' : '').$request->getClientIp();\n }\n } catch (\\InvalidArgumentException $e) {\n // Do nothing\n }\n\n $server['REMOTE_ADDR'] = $this->resolveTrustedProxy();\n\n unset($server['HTTP_IF_MODIFIED_SINCE']);\n unset($server['HTTP_IF_NONE_MATCH']);\n\n $subRequest = Request::create($uri, 'get', array(), $cookies, array(), $server);\n if ($request->headers->has('Surrogate-Capability')) {\n $subRequest->headers->set('Surrogate-Capability', $request->headers->get('Surrogate-Capability'));\n }\n\n if ($session = $request->getSession()) {\n $subRequest->setSession($session);\n }\n\n return $subRequest;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function update_discount() {\n $id = empty($this->params['id']) ? null : $this->params['id'];\n $discount = new discounts($id);\n // find required shipping method if needed\n if ($this->params['required_shipping_calculator_id'] > 0) {\n $this->params['required_shipping_method'] = $this->params['required_shipping_methods'][$this->params['required_shipping_calculator_id']];\n } else {\n $this->params['required_shipping_calculator_id'] = 0;\n }\n \n $discount->update($this->params);\n expHistory::back();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " static function isSearchable() { return true; }\r", "label_name": "CWE-74", "label": "74"} -{"code": "\tpublic function setSectionSeparators( ?array $separators ) {\n\t\t$this->sectionSeparators = (array)$separators ?? [];\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " public function urlProvider()\n {\n return array(\n array('http://till:test@svn.example.org/', $this->getCmd(\" --username 'till' --password 'test' \")),\n array('http://svn.apache.org/', ''),\n array('svn://johndoe@example.org', $this->getCmd(\" --username 'johndoe' --password '' \")),\n );\n }", "label_name": "CWE-77", "label": "77"} -{"code": " public function breadcrumb() {\r\n global $sectionObj;\r\n\r\n expHistory::set('viewable', $this->params);\r\n $id = $sectionObj->id;\r\n $current = null;\r\n // Show not only the location of a page in the hierarchy but also the location of a standalone page\r\n $current = new section($id);\r\n if ($current->parent == -1) { // standalone page\r\n $navsections = section::levelTemplate(-1, 0);\r\n foreach ($navsections as $section) {\r\n if ($section->id == $id) {\r\n $current = $section;\r\n break;\r\n }\r\n }\r\n } else {\r\n $navsections = section::levelTemplate(0, 0);\r\n foreach ($navsections as $section) {\r\n if ($section->id == $id) {\r\n $current = $section;\r\n break;\r\n }\r\n }\r\n }\r\n assign_to_template(array(\r\n 'sections' => $navsections,\r\n 'current' => $current,\r\n ));\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " static function testLDAPConnection($auths_id, $replicate_id = -1) {\n\n $config_ldap = new self();\n $res = $config_ldap->getFromDB($auths_id);\n\n // we prevent some delay...\n if (!$res) {\n return false;\n }\n\n //Test connection to a replicate\n if ($replicate_id != -1) {\n $replicate = new AuthLdapReplicate();\n $replicate->getFromDB($replicate_id);\n $host = $replicate->fields[\"host\"];\n $port = $replicate->fields[\"port\"];\n\n } else {\n //Test connection to a master ldap server\n $host = $config_ldap->fields['host'];\n $port = $config_ldap->fields['port'];\n }\n $ds = self::connectToServer($host, $port, $config_ldap->fields['rootdn'],\n Toolbox::decrypt($config_ldap->fields['rootdn_passwd'], GLPIKEY),\n $config_ldap->fields['use_tls'],\n $config_ldap->fields['deref_option']);\n if ($ds) {\n return true;\n }\n return false;\n }", "label_name": "CWE-327", "label": "327"} -{"code": "\tpublic static function getSetting( $setting ) {\n\t\treturn ( array_key_exists( $setting, self::$settings ) ? self::$settings[$setting] : null );\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": "\tpublic static function getSubcategories( $categoryName, $depth = 1 ) {\n\t\t$DB = wfGetDB( DB_REPLICA, 'dpl' );\n\n\t\tif ( $depth > 2 ) {\n\t\t\t//Hard constrain depth because lots of recursion is bad.\n\t\t\t$depth = 2;\n\t\t}\n\t\t$categories = [];\n\t\t$result = $DB->select(\n\t\t\t[ 'page', 'categorylinks' ],\n\t\t\t[ 'page_title' ],\n\t\t\t[\n\t\t\t\t'page_namespace'\t\t=> intval( NS_CATEGORY ),\n\t\t\t\t'categorylinks.cl_to'\t=> str_replace( ' ', '_', $categoryName )\n\t\t\t],\n\t\t\t__METHOD__,\n\t\t\t[ 'DISTINCT' ],\n\t\t\t[\n\t\t\t\t'categorylinks' => [\n\t\t\t\t\t'INNER JOIN',\n\t\t\t\t\t'page.page_id = categorylinks.cl_from'\n\t\t\t\t]\n\t\t\t]\n\t\t);\n\t\twhile ( $row = $result->fetchRow() ) {\n\t\t\t$categories[] = $row['page_title'];\n\t\t\tif ( $depth > 1 ) {\n\t\t\t\t$categories = array_merge( $categories, self::getSubcategories( $row['page_title'], $depth - 1 ) );\n\t\t\t}\n\t\t}\n\t\t$categories = array_unique( $categories );\n\t\t$DB->freeResult( $result );\n\t\treturn $categories;\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " public function settings_save() {\n AuthUser::load();\n if (!AuthUser::isLoggedIn()) {\n redirect(get_url('login'));\n } else if (!AuthUser::hasPermission('admin_edit')) {\n Flash::set('error', __('You do not have permission to access the requested page!'));\n redirect(get_url());\n }\n \n if (!isset($_POST['settings'])) {\n Flash::set('error', 'File Manager - ' . __('form was not posted.'));\n redirect(get_url('plugin/file_manager/settings'));\n } else {\n $settings = $_POST['settings'];\n\n if ($settings['umask'] == 0)\n $settings['umask'] = 0;\n elseif (!preg_match('/^0?[0-7]{3}$/', $settings['umask']))\n $settings['umask'] = 0;\n if (strlen($settings['umask']) === 3)\n $settings['umask'] = '0' . $settings['umask'];\n elseif (strlen($settings['umask']) !== 4 && $settings['umask'] != 0)\n $settings['umask'] = 0;\n\n if (!preg_match('/^0?[0-7]{3}$/', $settings['dirmode']))\n $settings['dirmode'] = '0755';\n if (strlen($settings['dirmode']) === 3)\n $settings['dirmode'] = '0' . $settings['dirmode'];\n\n if (!preg_match('/^0?[0-7]{3}$/', $settings['filemode']))\n $settings['filemode'] = '0755';\n if (strlen($settings['filemode']) === 3)\n $settings['filemode'] = '0' . $settings['filemode'];\n }\n\n if (Plugin::setAllSettings($settings, 'file_manager'))\n Flash::setNow('success', 'File Manager - ' . __('plugin settings saved.'));\n else\n Flash::setNow('error', 'File Manager - ' . __('plugin settings not saved!'));\n\n $this->display('file_manager/views/settings', array('settings' => $settings));\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public static function validateRegex($path, $values)\n {\n $result = array($path => '');\n\n if ($values[$path] == '') {\n return $result;\n }\n\n static::testPHPErrorMsg();\n\n $matches = array();\n // in libraries/ListDatabase.php _checkHideDatabase(),\n // a '/' is used as the delimiter for hide_db\n preg_match('/' . $values[$path] . '/', '', $matches);\n\n static::testPHPErrorMsg(false);\n\n if (isset($php_errormsg)) {\n $error = preg_replace('/^preg_match\\(\\): /', '', $php_errormsg);\n return array($path => $error);\n }\n\n return $result;\n }", "label_name": "CWE-200", "label": "200"} -{"code": " static function decrypt($string, $key) {\n\n $result = '';\n $string = base64_decode($string);\n\n for ($i=0; $igetProject();\n $values = $this->request->getValues();\n\n if (empty($values['action_name']) || empty($values['project_id']) || empty($values['event_name'])) {\n $this->create();\n return;\n }\n\n $action = $this->actionManager->getAction($values['action_name']);\n $action_params = $action->getActionRequiredParameters();\n\n if (empty($action_params)) {\n $this->doCreation($project, $values + array('params' => array()));\n }\n\n $projects_list = $this->projectUserRoleModel->getActiveProjectsByUser($this->userSession->getId());\n unset($projects_list[$project['id']]);\n\n $this->response->html($this->template->render('action_creation/params', array(\n 'values' => $values,\n 'action_params' => $action_params,\n 'columns_list' => $this->columnModel->getList($project['id']),\n 'users_list' => $this->projectUserRoleModel->getAssignableUsersList($project['id']),\n 'projects_list' => $projects_list,\n 'colors_list' => $this->colorModel->getList(),\n 'categories_list' => $this->categoryModel->getList($project['id']),\n 'links_list' => $this->linkModel->getList(0, false),\n 'priorities_list' => $this->projectTaskPriorityModel->getPriorities($project),\n 'project' => $project,\n 'available_actions' => $this->actionManager->getAvailableActions(),\n 'swimlane_list' => $this->swimlaneModel->getList($project['id']),\n 'events' => $this->actionManager->getCompatibleEvents($values['action_name']),\n )));\n }", "label_name": "CWE-200", "label": "200"} -{"code": " function fopen($filename, $mode)\n {\n if (\\yiiunit\\framework\\base\\SecurityTest::$fopen !== null) {\n return \\yiiunit\\framework\\base\\SecurityTest::$fopen;\n }\n\n return \\fopen($filename, $mode);\n }", "label_name": "CWE-330", "label": "330"} -{"code": " $count += $db->dropTable($basename);\n }\n \n flash('message', gt('Deleted').' '.$count.' '.gt('unused tables').'.');\n expHistory::back();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function __construct(Project $project)\n {\n parent::__construct('Project #' . $project->getID() . ' is not active and is not a template');\n $this->project = $project;\n }", "label_name": "CWE-863", "label": "863"} -{"code": " array_push($stack, $node);\n }\n }\n return array(\n 'status' => 'success',\n 'nodes' => $nodes);\n } else {\n return array(\n 'status' => 'error',\n 'errorcode' => 56,\n 'errormsg' => 'User cannot access node content');\n }\n}", "label_name": "CWE-20", "label": "20"} -{"code": "\tprivate function _addfirstcategorydate( $option ) {\n\t\t//@TODO: This should be programmatically determining which categorylink table to use instead of assuming the first one.\n\t\t$this->addSelect(\n\t\t\t[\n\t\t\t\t'cl_timestamp'\t=> \"DATE_FORMAT(cl1.cl_timestamp, '%Y%m%d%H%i%s')\"\n\t\t\t]\n\t\t);\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " private function decryptContentEncryptionKey($private_key_or_secret) {\n switch ($this->header['alg']) {\n case 'RSA1_5':\n $rsa = $this->rsa($private_key_or_secret, RSA::ENCRYPTION_PKCS1);\n $this->content_encryption_key = $rsa->decrypt($this->jwe_encrypted_key);\n break;\n case 'RSA-OAEP':\n $rsa = $this->rsa($private_key_or_secret, RSA::ENCRYPTION_OAEP);\n $this->content_encryption_key = $rsa->decrypt($this->jwe_encrypted_key);\n break;\n case 'dir':\n $this->content_encryption_key = $private_key_or_secret;\n break;\n case 'A128KW':\n case 'A256KW':\n case 'ECDH-ES':\n case 'ECDH-ES+A128KW':\n case 'ECDH-ES+A256KW':\n throw new JOSE_Exception_UnexpectedAlgorithm('Algorithm not supported');\n default:\n throw new JOSE_Exception_UnexpectedAlgorithm('Unknown algorithm');\n }\n if (!$this->content_encryption_key) {\n # NOTE:\n # Not to disclose timing difference between CEK decryption error and others.\n # Mitigating Bleichenbacher Attack on PKCS#1 v1.5\n # ref.) http://inaz2.hatenablog.com/entry/2016/01/26/222303\n $this->generateContentEncryptionKey(null);\n }\n }", "label_name": "CWE-200", "label": "200"} -{"code": "function XMLRPCremoveNode($nodeID){\n require_once(\".ht-inc/privileges.php\");\n global $user;\n if(!in_array(\"nodeAdmin\", $user['privileges'])){\n return array(\n 'status' => 'error',\n 'errorcode' => 56,\n 'errormsg' => 'User cannot administer nodes');\n }\n if(!checkUserHasPriv(\"nodeAdmin\", $user['id'], $nodeID)){\n return array(\n 'status' => 'error',\n 'errorcode' => 57,\n 'errormsg' => 'User cannot edit this node');\n }\n $nodes = recurseGetChildren($nodeID);\n array_push($nodes, $nodeID);\n $deleteNodes = implode(',', $nodes);\n $query = \"DELETE FROM privnode \"\n . \"WHERE id IN ($deleteNodes)\";\n doQuery($query, 345);\n return array(\n 'status' => 'success');\n}", "label_name": "CWE-20", "label": "20"} -{"code": " public static function isPublic($s) {\r\n if ($s == null) {\r\n return false;\r\n }\r\n while ($s->public && $s->parent > 0) {\r\n $s = new section($s->parent);\r\n }\r\n $lineage = (($s->public) ? 1 : 0);\r\n return $lineage;\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " $object->size = convert_size($cur->getSize());\n $object->mtime = date('D, j M, Y', $cur->getMTime());\n list($object->perms, $object->chmod) = $this->_getPermissions($cur->getPerms());\n \n // Find the file type\n $object->type = $this->_getFileType($cur);\n\n // make the link depending on if it's a file or a dir\n if ($cur->isDir()) {\n $object->link = 'path . $object->name) . '\">' . $object->name . '';\n } else {\n $object->link = 'path . $object->name . (endsWith($object->name, URL_SUFFIX) ? '?has_url_suffix=1' : '')) . '\">' . $object->name . '';\n }\n\n $files[$object->name] = $object;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " protected function checkTrustedHostPattern()\n {\n if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['trustedHostsPattern'] === GeneralUtility::ENV_TRUSTED_HOSTS_PATTERN_ALLOW_ALL) {\n $this->messageQueue->enqueue(new FlashMessage(\n 'Trusted hosts pattern is configured to allow all header values. Check the pattern defined in Admin'\n . ' Tools -> Settings -> Configure Installation-Wide Options -> System -> trustedHostsPattern'\n . ' and adapt it to expected host value(s).',\n 'Trusted hosts pattern is insecure',\n FlashMessage::WARNING\n ));\n } else {\n if (GeneralUtility::hostHeaderValueMatchesTrustedHostsPattern($_SERVER['HTTP_HOST'])) {\n $this->messageQueue->enqueue(new FlashMessage(\n '',\n 'Trusted hosts pattern is configured to allow current host value.'\n ));\n } else {\n $this->messageQueue->enqueue(new FlashMessage(\n 'The trusted hosts pattern will be configured to allow all header values. This is because your $SERVER_NAME:$SERVER_PORT'\n . ' is \"' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'] . '\" while your HTTP_HOST is \"'\n . $_SERVER['HTTP_HOST'] . '\". Check the pattern defined in Admin'\n . ' Tools -> Settings -> Configure Installation-Wide Options -> System -> trustedHostsPattern'\n . ' and adapt it to expected host value(s).',\n 'Trusted hosts pattern mismatch',\n FlashMessage::ERROR\n ));\n }\n }\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public static function navtojson() {\r\n return json_encode(self::navhierarchy());\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " protected function setUp()\n {\n static::$functions = [];\n static::$fopen = null;\n static::$fread = null;\n parent::setUp();\n $this->security = new ExposedSecurity();\n $this->security->derivationIterations = 1000; // speed up test running\n }", "label_name": "CWE-330", "label": "330"} -{"code": "\tprivate static function init() {\n\t\t\\DPL\\Config::init();\n\n\t\tif ( !isset( self::$createdLinks ) ) {\n\t\t\tself::$createdLinks = [\n\t\t\t\t'resetLinks' => false,\n\t\t\t\t'resetTemplates' => false,\n\t\t\t\t'resetCategories' => false,\n\t\t\t\t'resetImages' => false,\n\t\t\t\t'resetdone' => false,\n\t\t\t\t'elimdone' => false\n\t\t\t];\n\t\t}\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": "\tfunction test_username_avoids_anon_flow() {\n\t\tadd_filter( 'xmlrpc_allow_anonymous_comments', '__return_true' );\n\n\t\t$comment_args = array(\n\t\t\t1,\n\t\t\t'administrator',\n\t\t\t'administrator',\n\t\t\tself::$post->ID,\n\t\t\tarray(\n\t\t\t\t'author' => 'WordPress',\n\t\t\t\t'author_email' => 'noreply at wordpress.org',\n\t\t\t\t'content' => 'Test Anon Comments',\n\t\t\t),\n\t\t);\n\n\t\t$result = $this->myxmlrpcserver->wp_newComment( $comment_args );\n\t\t$comment = get_comment( $result );\n\t\t$user_id = get_user_by( 'login', 'administrator' )->ID;\n\n\t\t$this->assertSame( $user_id, (int) $comment->user_id );\n\t}", "label_name": "CWE-862", "label": "862"} -{"code": " private function isWindows()\n {\n return DIRECTORY_SEPARATOR !== '/';\n }", "label_name": "CWE-330", "label": "330"} -{"code": " protected function get_remote_contents(&$url, $timeout = 30, $redirect_max = 5, $ua = 'Mozilla/5.0', $fp = null)\n {\n $method = (function_exists('curl_exec') && !ini_get('safe_mode') && !ini_get('open_basedir')) ? 'curl_get_contents' : 'fsock_get_contents';\n return $this->$method($url, $timeout, $redirect_max, $ua, $fp);\n }", "label_name": "CWE-200", "label": "200"} -{"code": " protected function generateVerifyCode()\n {\n if ($this->minLength > $this->maxLength) {\n $this->maxLength = $this->minLength;\n }\n if ($this->minLength < 3) {\n $this->minLength = 3;\n }\n if ($this->maxLength > 20) {\n $this->maxLength = 20;\n }\n $length = mt_rand($this->minLength, $this->maxLength);\n\n $letters = 'bcdfghjklmnpqrstvwxyz';\n $vowels = 'aeiou';\n $code = '';\n for ($i = 0; $i < $length; ++$i) {\n if ($i % 2 && mt_rand(0, 10) > 2 || !($i % 2) && mt_rand(0, 10) > 9) {\n $code .= $vowels[mt_rand(0, 4)];\n } else {\n $code .= $letters[mt_rand(0, 20)];\n }\n }\n\n return $code;\n }", "label_name": "CWE-330", "label": "330"} -{"code": " function process_subsections($parent_section, $subtpl) {\r\n global $db, $router;\r\n\r\n $section = new stdClass();\r\n $section->parent = $parent_section->id;\r\n $section->name = $subtpl->name;\r\n $section->sef_name = $router->encode($section->name);\r\n $section->subtheme = $subtpl->subtheme;\r\n $section->active = $subtpl->active;\r\n $section->public = $subtpl->public;\r\n $section->rank = $subtpl->rank;\r\n $section->page_title = $subtpl->page_title;\r\n $section->keywords = $subtpl->keywords;\r\n $section->description = $subtpl->description;\r\n $section->id = $db->insertObject($section, 'section');\r\n self::process_section($section, $subtpl);\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " function searchName() { return gt('Webpage'); }\r", "label_name": "CWE-74", "label": "74"} -{"code": " private function checkAuthenticationTag() {\n if ($this->authentication_tag === $this->calculateAuthenticationTag()) {\n return true;\n } else {\n throw new JOSE_Exception_UnexpectedAlgorithm('Invalid authentication tag');\n }\n }", "label_name": "CWE-200", "label": "200"} -{"code": "\tstatic function convertUTF($string) {\n\t\treturn $string = str_replace('?', '', htmlspecialchars($string, ENT_IGNORE, 'UTF-8'));\n\t} ", "label_name": "CWE-74", "label": "74"} -{"code": " public function __get($var) {\r\n\r\n switch ($var) {\r\n\r\n case 'configuration_array':\r\n $this->configuration_array = array();\r\n if ($this->configuration != ''){\r\n $jsonData = json_decode($this->configuration,true);\r\n if ($jsonData !== null) {\r\n $this->configuration_array = $jsonData;\r\n } else {\r\n $this->configuration_array = array();\r\n }\r\n }\r\n return $this->configuration_array;\r\n break;\r\n\r\n case 'name_support':\r\n return $this->name_support = $this->nick;\r\n break;\r\n\r\n case 'has_photo':\r\n return $this->filename != '';\r\n break;\r\n\r\n case 'has_photo_avatar':\r\n return $this->filename != '' || $this->avatar != '';\r\n break;\r\n\r\n case 'photo_path':\r\n $this->photo_path = ($this->filepath != '' ? '//' . $_SERVER['HTTP_HOST'] . erLhcoreClassSystem::instance()->wwwDir() : erLhcoreClassSystem::instance()->wwwImagesDir() ) .'/'. $this->filepath . $this->filename;\r\n return $this->photo_path;\r\n break;\r\n\r\n case 'file_path_server':\r\n return $this->filepath . $this->filename;\r\n break;\r\n\r\n default:\r\n break;\r\n }\r\n }\r", "label_name": "CWE-116", "label": "116"} -{"code": "\tprivate function _adduser( $option, $tableAlias = '' ) {\n\t\t$tableAlias = ( !empty( $tableAlias ) ? $tableAlias . '.' : '' );\n\t\t$this->addSelect(\n\t\t\t[\n\t\t\t\t$tableAlias . 'revactor_actor',\n\t\t\t]\n\t\t);\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " static function isSearchable() {\r\n return true;\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " PMA_sendHeaderLocation($GLOBALS['cfg']['Server']['LogoutURL']);\n } else {\n PMA_sendHeaderLocation($GLOBALS['cfg']['Server']['SignonURL']);\n }\n\n if (!defined('TESTSUITE')) {\n exit();\n } else {\n return false;\n }\n }", "label_name": "CWE-200", "label": "200"} -{"code": "\tprivate function _notuses( $option ) {\n\t\tif ( count( $option ) > 0 ) {\n\t\t\t$where = $this->tableNames['page'] . '.page_id NOT IN (SELECT ' . $this->tableNames['templatelinks'] . '.tl_from FROM ' . $this->tableNames['templatelinks'] . ' WHERE (';\n\t\t\t$ors = [];\n\t\t\tforeach ( $option as $linkGroup ) {\n\t\t\t\tforeach ( $linkGroup as $link ) {\n\t\t\t\t\t$_or = '(' . $this->tableNames['templatelinks'] . '.tl_namespace=' . intval( $link->getNamespace() );\n\t\t\t\t\tif ( $this->parameters->getParameter( 'ignorecase' ) ) {\n\t\t\t\t\t\t$_or .= ' AND LOWER(CAST(' . $this->tableNames['templatelinks'] . '.tl_title AS char))=LOWER(' . $this->DB->addQuotes( $link->getDbKey() ) . '))';\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$_or .= ' AND ' . $this->tableNames['templatelinks'] . '.tl_title=' . $this->DB->addQuotes( $link->getDbKey() ) . ')';\n\t\t\t\t\t}\n\t\t\t\t\t$ors[] = $_or;\n\t\t\t\t}\n\t\t\t}\n\t\t\t$where .= implode( ' OR ', $ors ) . '))';\n\t\t}\n\t\t$this->addWhere( $where );\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " public function AddAddress($address, $name = '') {\n return $this->AddAnAddress('to', $address, $name);\n }", "label_name": "CWE-20", "label": "20"} -{"code": "function current_user_get_bug_filter( $p_project_id = null ) {\n\t$f_filter_string = gpc_get_string( 'filter', '' );\n\t$t_filter = '';\n\n\tif( !is_blank( $f_filter_string ) ) {\n\t\tif( is_numeric( $f_filter_string ) ) {\n\t\t\t$t_token = token_get_value( TOKEN_FILTER );\n\t\t\tif( null != $t_token ) {\n\t\t\t\t$t_filter = json_decode( $t_token, true );\n\t\t\t}\n\t\t} else {\n\t\t\t$t_filter = json_decode( $f_filter_string, true );\n\t\t}\n\t\t$t_filter = filter_ensure_valid_filter( $t_filter );\n\t} else if( !filter_is_cookie_valid() ) {\n\t\t$t_filter = filter_get_default();\n\t} else {\n\t\t$t_user_id = auth_get_current_user_id();\n\t\t$t_filter = user_get_bug_filter( $t_user_id, $p_project_id );\n\t}\n\n\treturn $t_filter;\n}", "label_name": "CWE-200", "label": "200"} -{"code": " private function isWindows()\n {\n return DIRECTORY_SEPARATOR !== '/';\n }", "label_name": "CWE-330", "label": "330"} -{"code": " function edit_option_master() {\n expHistory::set('editable', $this->params);\n \n $params = isset($this->params['id']) ? $this->params['id'] : $this->params;\n $record = new option_master($params); \n assign_to_template(array(\n 'record'=>$record\n ));\n }", "label_name": "CWE-74", "label": "74"} -{"code": " private static function verifySignature($signature, $input, $key, $algo = 'HS256')\n {\n switch ($algo) {\n case'HS256':\n case'HS384':\n case'HS512':\n return JWT::sign($input, $key, $algo) === $signature;\n\n case 'RS256':\n return (boolean) openssl_verify($input, $signature, $key, OPENSSL_ALGO_SHA256);\n\n case 'RS384':\n return (boolean) openssl_verify($input, $signature, $key, OPENSSL_ALGO_SHA384);\n\n case 'RS512':\n return (boolean) openssl_verify($input, $signature, $key, OPENSSL_ALGO_SHA512);\n\n default:\n throw new Exception(\"Unsupported or invalid signing algorithm.\");\n }\n }", "label_name": "CWE-20", "label": "20"} -{"code": " function columnUpdate($table, $col, $val, $where=1) { \n $res = @mysqli_query($this->connection, \"UPDATE `\" . $this->prefix . \"$table` SET `$col`='\" . $val . \"' WHERE $where\");\n /*if ($res == null)\n return array();\n $objects = array();\n for ($i = 0; $i < mysqli_num_rows($res); $i++)\n $objects[] = mysqli_fetch_object($res);*/\n //return $objects;\n }", "label_name": "CWE-74", "label": "74"} -{"code": " $module_views[$key]['name'] = gt($value['name']);\n }\n\n // look for a config form for this module's current view \n// $controller->loc->mod = expModules::getControllerClassName($controller->loc->mod);\n //check to see if hcview was passed along, indicating a hard-coded module\n// if (!empty($controller->params['hcview'])) {\n// $viewname = $controller->params['hcview'];\n// } else {\n// $viewname = $db->selectValue('container', 'view', \"internal='\".serialize($controller->loc).\"'\");\n// }\n// $viewconfig = $viewname.'.config';\n// foreach ($modpaths as $path) {\n// if (file_exists($path.'/'.$viewconfig)) {\n// $fileparts = explode('_', $viewname);\n// if ($fileparts[0]=='show'||$fileparts[0]=='showall') array_shift($fileparts);\n// $module_views[$viewname]['name'] = ucwords(implode(' ', $fileparts)).' '.gt('View Configuration');\n// $module_views[$viewname]['file'] =$path.'/'.$viewconfig;\n// }\n// }\n \n // sort the views highest to lowest by filename\n // we are reverse sorting now so our array merge\n // will overwrite property..we will run array_reverse\n // when we're finished to get them back in the right order\n krsort($common_views);\n krsort($module_views);\n\n if (!empty($moduleconfig)) $common_views = array_merge($common_views, $moduleconfig);\n $views = array_merge($common_views, $module_views);\n $views = array_reverse($views);\n\n return $views;\n}", "label_name": "CWE-74", "label": "74"} -{"code": " public function remove()\n {\n $project = $this->getProject();\n $this->checkCSRFParam();\n $column_id = $this->request->getIntegerParam('column_id');\n\n if ($this->columnModel->remove($column_id)) {\n $this->flash->success(t('Column removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this column.'));\n }\n\n $this->response->redirect($this->helper->url->to('ColumnController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-200", "label": "200"} -{"code": " static function description() {\r\n return \"Manage events and schedules, and optionally publish them.\";\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": "\tpublic function formatItem( Article $article, $pageText = null ) {\n\t\tglobal $wgLang;\n\n\t\t$item = '';\n\n\t\t// DPL Article, not MediaWiki.\n\t\t$date = $article->getDate();\n\t\tif ( $date !== null ) {\n\t\t\t$item .= $date . ' ';\n\t\t\tif ( $article->mRevision !== null ) {\n\t\t\t\t$item .= '[{{fullurl:' . $article->mTitle . '|oldid=' . $article->mRevision . '}} ' . htmlspecialchars( $article->mTitle ) . ']';\n\t\t\t} else {\n\t\t\t\t$item .= $article->mLink;\n\t\t\t}\n\t\t} else {\n\t\t\t// output the link to the article\n\t\t\t$item .= $article->mLink;\n\t\t}\n\n\t\tif ( $article->mSize != null ) {\n\t\t\t$byte = 'B';\n\t\t\t$pageLength = $wgLang->formatNum( $article->mSize );\n\t\t\t$item .= \" [{$pageLength} {$byte}]\";\n\t\t}\n\n\t\tif ( $article->mCounter !== null ) {\n\t\t\t$contLang = MediaWikiServices::getInstance()->getContentLanguage();\n\n\t\t\t$item .= ' ' . $contLang->getDirMark() . '(' . wfMessage( 'hitcounters-nviews', $wgLang->formatNum( $article->mCounter ) )->escaped() . ')';\n\t\t}\n\n\t\tif ( $article->mUserLink !== null ) {\n\t\t\t$item .= ' . . [[User:' . $article->mUser . '|' . $article->mUser . ']]';\n\t\t\tif ( $article->mComment != '' ) {\n\t\t\t\t$item .= ' { ' . $article->mComment . ' }';\n\t\t\t}\n\t\t}\n\n\t\tif ( $article->mContributor !== null ) {\n\t\t\t$item .= ' . . [[User:' . $article->mContributor . '|' . $article->mContributor . \" $article->mContrib]]\";\n\t\t}\n\n\t\tif ( !empty( $article->mCategoryLinks ) ) {\n\t\t\t$item .= ' . . ' . wfMessage( 'categories' ) . ': ' . implode( ' | ', $article->mCategoryLinks ) . '';\n\t\t}\n\n\t\tif ( $this->getParameters()->getParameter( 'addexternallink' ) && $article->mExternalLink !== null ) {\n\t\t\t$item .= ' \u2192 ' . $article->mExternalLink;\n\t\t}\n\n\t\tif ( $pageText !== null ) {\n\t\t\t//Include parsed/processed wiki markup content after each item before the closing tag.\n\t\t\t$item .= $pageText;\n\t\t}\n\n\t\t$item = $this->getItemStart() . $item . $this->getItemEnd();\n\n\t\t$item = $this->replaceTagParameters( $item, $article );\n\n\t\treturn $item;\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": "\tfunction selectBillingOptions() {\n\t\t\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": "\t\t\t$cols = explode( '}:', $label );\n\t\t\tif ( count( $cols ) <= 1 ) {\n\t\t\t\tif ( array_key_exists( $t, $_tableRow ) ) {\n\t\t\t\t\t$tableRow[$groupNr] = $_tableRow[$t];\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t$n = count( explode( ':', $cols[1] ) );\n\t\t\t\t$colNr = -1;\n\t\t\t\t$t--;\n\t\t\t\tfor ( $i = 1; $i <= $n; $i++ ) {\n\t\t\t\t\t$colNr++;\n\t\t\t\t\t$t++;\n\t\t\t\t\tif ( array_key_exists( $t, $_tableRow ) ) {\n\t\t\t\t\t\t$tableRow[$groupNr . '.' . $colNr] = $_tableRow[$t];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn $tableRow;\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " public function actionDeleteDropdown() {\n $dropdowns = Dropdowns::model()->findAll();\n\n if (isset($_POST['dropdown'])) {\n if ($_POST['dropdown'] != Actions::COLORS_DROPDOWN_ID) {\n $model = Dropdowns::model()->findByPk($_POST['dropdown']);\n $model->delete();\n $this->redirect('manageDropDowns');\n }\n }\n\n $this->render('deleteDropdowns', array(\n 'dropdowns' => $dropdowns,\n ));\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function save() {\n $data = $_POST['file'];\n\n // security (remove all ..)\n $data['name'] = str_replace('..', '', $data['name']);\n $file = FILES_DIR . DS . $data['name'];\n \n // CSRF checks\n if (isset($_POST['csrf_token'])) {\n $csrf_token = $_POST['csrf_token'];\n if (!SecureToken::validateToken($csrf_token, BASE_URL.'plugin/file_manager/save/'.$data['name'])) {\n Flash::set('error', __('Invalid CSRF token found!'));\n redirect(get_url('plugin/file_manager/view/'.$data['name']));\n }\n }\n else {\n Flash::set('error', __('No CSRF token found!'));\n redirect(get_url('plugin/file_manager/view/'.$data['name']));\n }\n \n if (file_exists($file)) {\n if (file_put_contents($file, $data['content']) !== false) {\n Flash::set('success', __('File has been saved with success!'));\n } else {\n Flash::set('error', __('File is not writable! File has not been saved!'));\n }\n } else {\n if (file_put_contents($file, $data['content'])) {\n Flash::set('success', __('File :name has been created with success!', array(':name' => $data['name'])));\n } else {\n Flash::set('error', __('Directory is not writable! File has not been saved!'));\n }\n }\n\n // save and quit or save and continue editing ?\n if (isset($_POST['commit'])) {\n redirect(get_url('plugin/file_manager/browse/' . substr($data['name'], 0, strrpos($data['name'], '/'))));\n } else {\n redirect(get_url('plugin/file_manager/view/' . $data['name'] . (endsWith($data['name'], URL_SUFFIX) ? '?has_url_suffix=1' : '')));\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\tpublic static function newFromStyle( $style, \\DPL\\Parameters $parameters, \\Parser $parser ) {\n\t\t$style = strtolower( $style );\n\t\tswitch ( $style ) {\n\t\t\tcase 'category':\n\t\t\t\t$class = 'CategoryList';\n\t\t\t\tbreak;\n\t\t\tcase 'definition':\n\t\t\t\t$class = 'DefinitionList';\n\t\t\t\tbreak;\n\t\t\tcase 'gallery':\n\t\t\t\t$class = 'GalleryList';\n\t\t\t\tbreak;\n\t\t\tcase 'inline':\n\t\t\t\t$class = 'InlineList';\n\t\t\t\tbreak;\n\t\t\tcase 'ordered':\n\t\t\t\t$class = 'OrderedList';\n\t\t\t\tbreak;\n\t\t\tcase 'subpage':\n\t\t\t\t$class = 'SubPageList';\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\tcase 'unordered':\n\t\t\t\t$class = 'UnorderedList';\n\t\t\t\tbreak;\n\t\t\tcase 'userformat':\n\t\t\t\t$class = 'UserFormatList';\n\t\t\t\tbreak;\n\t\t}\n\t\t$class = '\\DPL\\Lister\\\\' . $class;\n\n\t\treturn new $class( $parameters, $parser );\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": "\tprivate function _lastrevisionbefore( $option ) {\n\t\t$this->addTable( 'revision_actor_temp', 'rev' );\n\t\t$this->addSelect( [ 'rev.revactor_rev', 'rev.revactor_timestamp' ] );\n\t\t// tell the query optimizer not to look at rows that the following subquery will filter out anyway\n\t\t$this->addWhere(\n\t\t\t[\n\t\t\t\t$this->tableNames['page'] . '.page_id = rev.revactor_page',\n\t\t\t\t'rev.revactor_timestamp < ' . $this->convertTimestamp( $option )\n\t\t\t]\n\t\t);\n\t\t$this->addWhere(\n\t\t\t[\n\t\t\t\t$this->tableNames['page'] . '.page_id = rev.revactor_page',\n\t\t\t\t'rev.revactor_timestamp = (SELECT MAX(rev_aux_bef.revactor_timestamp) FROM ' . $this->tableNames['revision_actor_temp'] . ' AS rev_aux_bef WHERE rev_aux_bef.revactor_page=rev.revactor_page AND rev_aux_bef.revactor_timestamp < ' . $this->convertTimestamp( $option ) . ')'\n\t\t\t]\n\t\t);\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " static function description() { return gt(\"Places navigation links/menus on the page.\"); }\r", "label_name": "CWE-74", "label": "74"} -{"code": "\tprivate function _notlastmodifiedby( $option ) {\n\t\t$user = new \\User;\n\t\t$this->addWhere( $this->DB->addQuotes( $user->newFromName( $option )->getActorId() ) . ' != (SELECT revactor_actor FROM ' . $this->tableNames['revision_actor_temp'] . ' WHERE ' . $this->tableNames['revision_actor_temp'] . '.revactor_page=page_id ORDER BY ' . $this->tableNames['revision_actor_temp'] . '.revactor_timestamp DESC LIMIT 1)' );\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": "\tpublic function check(&$params){\n $tags = $this->config['options']['tags']['value'];\n $tags = is_array($tags) ? $tags : Tags::parseTags($tags, true);\n if(!empty($tags) && isset($params['tags'])){ // Check passed params to be sure they're set\n if(!is_array($params['tags'])){\n $params['tags'] = explode(',', $params['tags']);\n }\n $params['tags'] = array_map(function($item){ \n return preg_replace('/^#/','', $item); \n }, $params['tags']);\n\n // must have at least 1 tag in the list:\n if(count(array_intersect($params['tags'], $tags)) > 0){\n return $this->checkConditions($params);\n }else{\n return array(false, Yii::t('studio','No tags on the record matched those in the tag trigger criteria.'));\n }\n }else{ // config is invalid or record has no tags (tags are not optional)\n return array(false, empty($tags) ? Yii::t('studio','No tags in the trigger criteria!') : Yii::t('studio','Tags parameter missing!'));\n }\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function configure() {\n $this->config['defaultbanner'] = array();\n if (!empty($this->config['defaultbanner_id'])) {\n $this->config['defaultbanner'][] = new expFile($this->config['defaultbanner_id']);\n } \n\t parent::configure();\n\t $banners = $this->banner->find('all', null, 'companies_id');\n\t assign_to_template(array(\n 'banners'=>$banners,\n 'title'=>static::displayname()\n ));\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": " public static function navtojson() {\r\n return json_encode(self::navhierarchy());\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " function addDiscountToCart() {\n// global $user, $order;\n global $order;\n //lookup discount to see if it's real and valid, and not already in our cart\n //this will change once we allow more than one coupon code\n\n $discount = new discounts();\n $discount = $discount->getCouponByName($this->params['coupon_code']);\n\n if (empty($discount)) {\n flash('error', gt(\"This discount code you entered does not exist.\"));\n //redirect_to(array('controller'=>'cart', 'action'=>'checkout')); \n expHistory::back();\n }\n\n //check to see if it's in our cart already\n if ($this->isDiscountInCart($discount->id)) {\n flash('error', gt(\"This discount code is already in your cart.\"));\n //redirect_to(array('controller'=>'cart', 'action'=>'checkout'));\n expHistory::back();\n }\n\n //this should really be reworked, as it shoudn't redirect directly and not return\n $validateDiscountMessage = $discount->validateDiscount();\n if ($validateDiscountMessage == \"\") {\n //if all good, add to cart, otherwise it will have redirected\n $od = new order_discounts();\n $od->orders_id = $order->id;\n $od->discounts_id = $discount->id;\n $od->coupon_code = $discount->coupon_code;\n $od->title = $discount->title;\n $od->body = $discount->body;\n $od->save();\n // set this to just the discount applied via this coupon?? if so, when though? $od->discount_total = ??;\n flash('message', gt(\"The discount code has been applied to your cart.\"));\n } else {\n flash('error', $validateDiscountMessage);\n }\n //redirect_to(array('controller'=>'cart', 'action'=>'checkout')); \n expHistory::back();\n }", "label_name": "CWE-20", "label": "20"} -{"code": " $module_views[$key]['name'] = gt($value['name']);\n }\n\n // look for a config form for this module's current view \n// $controller->loc->mod = expModules::getControllerClassName($controller->loc->mod);\n //check to see if hcview was passed along, indicating a hard-coded module\n// if (!empty($controller->params['hcview'])) {\n// $viewname = $controller->params['hcview'];\n// } else {\n// $viewname = $db->selectValue('container', 'view', \"internal='\".serialize($controller->loc).\"'\");\n// }\n// $viewconfig = $viewname.'.config';\n// foreach ($modpaths as $path) {\n// if (file_exists($path.'/'.$viewconfig)) {\n// $fileparts = explode('_', $viewname);\n// if ($fileparts[0]=='show'||$fileparts[0]=='showall') array_shift($fileparts);\n// $module_views[$viewname]['name'] = ucwords(implode(' ', $fileparts)).' '.gt('View Configuration');\n// $module_views[$viewname]['file'] =$path.'/'.$viewconfig;\n// }\n// }\n \n // sort the views highest to lowest by filename\n // we are reverse sorting now so our array merge\n // will overwrite property..we will run array_reverse\n // when we're finished to get them back in the right order\n krsort($common_views);\n krsort($module_views);\n\n if (!empty($moduleconfig)) $common_views = array_merge($common_views, $moduleconfig);\n $views = array_merge($common_views, $module_views);\n $views = array_reverse($views);\n\n return $views;\n}", "label_name": "CWE-74", "label": "74"} -{"code": " protected function getComment()\n {\n $comment = $this->commentModel->getById($this->request->getIntegerParam('comment_id'));\n\n if (empty($comment)) {\n throw new PageNotFoundException();\n }\n\n if (! $this->userSession->isAdmin() && $comment['user_id'] != $this->userSession->getId()) {\n throw new AccessForbiddenException();\n }\n\n return $comment;\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public function chmod() {\n if (!AuthUser::hasPermission('file_manager_chmod')) {\n Flash::set('error', __('You do not have sufficient permissions to change the permissions on a file or directory.'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n\n // CSRF checks\n if (isset($_POST['csrf_token'])) {\n $csrf_token = $_POST['csrf_token'];\n if (!SecureToken::validateToken($csrf_token, BASE_URL.'plugin/file_manager/chmod')) {\n Flash::set('error', __('Invalid CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n }\n else {\n Flash::set('error', __('No CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n \n $data = $_POST['file'];\n $data['name'] = str_replace('..', '', $data['name']);\n $file = FILES_DIR . '/' . $data['name'];\n\n if (file_exists($file)) {\n if (@!chmod($file, octdec($data['mode'])))\n Flash::set('error', __('Permission denied!'));\n }\n else {\n Flash::set('error', __('File or directory not found!'));\n }\n\n $path = substr($data['name'], 0, strrpos($data['name'], '/'));\n redirect(get_url('plugin/file_manager/browse/' . $path));\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\t\t\t\t$item = trim( $item );\n\t\t\t\tif ( strpos( $item, '|-' ) === 0 ) {\n\t\t\t\t\t$item = explode( '|-', $item, 2 );\n\t\t\t\t\tif ( count( $item ) == 2 ) {\n\t\t\t\t\t\t$item = $item[1];\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$rowsKey[$index] = $item;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif ( strlen( $item ) > 0 ) {\n\t\t\t\t\t$word = explode( \"\\n|\", $item );\n\t\t\t\t\tif ( isset( $word[0] ) && empty( $word[0] ) ) {\n\t\t\t\t\t\tarray_shift( $word );\n\t\t\t\t\t}\n\t\t\t\t\tif ( isset( $word[abs( $sortColumn ) - 1] ) ) {\n\t\t\t\t\t\t$test = trim( $word[abs( $sortColumn ) - 1] );\n\t\t\t\t\t\tif ( strpos( $test, '|' ) > 0 ) {\n\t\t\t\t\t\t\t$test = trim( explode( '|', $test )[1] );\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$rowsKey[$index] = $test;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t$this->sort($rowsKey, $sortColumn);\n\t\t\t$newItems = [];\n\t\t\tforeach ( $rowsKey as $index => $val ) {\n\t\t\t\t$newItems[] = $items[$index];\n\t\t\t}\n\t\t\t$items = $newItems;\n\t\t}\n\n\t\treturn $this->listStart . $this->implodeItems( $items ) . $this->listEnd;\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " public function getItems2 (\n $prefix='', $page=0, $limit=20, $valueAttr='name', $nameAttr='name') {\n\n $modelClass = get_class ($this->owner);\n $model = CActiveRecord::model ($modelClass);\n $table = $model->tableName ();\n $offset = intval ($page) * intval ($limit);\n\n AuxLib::coerceToArray ($valueAttr);\n $modelClass::checkThrowAttrError (array_merge ($valueAttr, array ($nameAttr)));\n $params = array ();\n if ($prefix !== '') {\n $params[':prefix'] = $prefix . '%';\n }\n $offset = abs ((int) $offset);\n $limit = abs ((int) $limit);\n $command = Yii::app()->db->createCommand (\"\n SELECT \" . implode (',', $valueAttr) . \", $nameAttr as __name\n FROM $table\n WHERE \" . ($prefix === '' ? \n '1=1' : ($nameAttr . ' LIKE :prefix')\n ) . \"\n ORDER BY __name\n LIMIT $offset, $limit\n \");", "label_name": "CWE-20", "label": "20"} -{"code": " public function gc($force = false)\n {\n if ($force || mt_rand(0, 1000000) < $this->gcProbability) {\n $this->db->createCommand()\n ->delete($this->cacheTable, '[[expire]] > 0 AND [[expire]] < ' . time())\n ->execute();\n }\n }", "label_name": "CWE-330", "label": "330"} -{"code": " function process_subsections($parent_section, $subtpl) {\r\n global $db, $router;\r\n\r\n $section = new stdClass();\r\n $section->parent = $parent_section->id;\r\n $section->name = $subtpl->name;\r\n $section->sef_name = $router->encode($section->name);\r\n $section->subtheme = $subtpl->subtheme;\r\n $section->active = $subtpl->active;\r\n $section->public = $subtpl->public;\r\n $section->rank = $subtpl->rank;\r\n $section->page_title = $subtpl->page_title;\r\n $section->keywords = $subtpl->keywords;\r\n $section->description = $subtpl->description;\r\n $section->id = $db->insertObject($section, 'section');\r\n self::process_section($section, $subtpl);\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": "\tpublic function getPurchaseOrderByJSON() {\n\t\t\n\t\tif(!empty($this->params['vendor'])) {\n\t\t\t$purchase_orders = $this->purchase_order->find('all', 'vendor_id=' . $this->params['vendor']);\n\t\t} else {\n\t\t\t$purchase_orders = $this->purchase_order->find('all');\n\t\t}\n\t\t\n\t\techo json_encode($purchase_orders);\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": " function showByModel() {\n global $order, $template, $db;\n\n expHistory::set('viewable', $this->params);\n $product = new product();\n $model = $product->find(\"first\", 'model=\"' . $this->params['model'] . '\"');\n //eDebug($model);\n $product_type = new $model->product_type($model->id);\n //eDebug($product_type);\n $tpl = $product_type->getForm('show');\n if (!empty($tpl)) $template = new controllertemplate($this, $tpl);\n //eDebug($template);\n $this->grabConfig(); // grab the global config\n assign_to_template(array(\n 'config' => $this->config,\n 'product' => $product_type,\n 'last_category' => $order->lastcat\n ));\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\t\tforeach($return as $index => $value) {\n\t\t\tif(! is_string($value))\n\t\t\t\t$return[$index] = $defaultvalue;\n\t\t\telseif($addslashes)\n\t\t\t\t$return[$index] = addslashes($value);\n\t\t}", "label_name": "CWE-20", "label": "20"} -{"code": " self::removeLevel($kid->id);\r\n }\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " $newret = recyclebin::restoreFromRecycleBin($iLoc, $page_id);\r\n if (!empty($newret)) $ret .= $newret . '
';\r\n if ($iLoc->mod == 'container') {\r\n $ret .= scan_container($container->internal, $page_id);\r\n }\r\n }\r\n return $ret;\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " function edit_order_item() {\n $oi = new orderitem($this->params['id'], true, true);\n if (empty($oi->id)) {\n flash('error', gt('Order item doesn\\'t exist.'));\n expHistory::back();\n }\n $oi->user_input_fields = expUnserialize($oi->user_input_fields);\n $params['options'] = $oi->opts;\n $params['user_input_fields'] = $oi->user_input_fields;\n $oi->product = new product($oi->product->id, true, true);\n if ($oi->product->parent_id != 0) {\n $parProd = new product($oi->product->parent_id);\n //$oi->product->optiongroup = $parProd->optiongroup; \n $oi->product = $parProd;\n }\n //FIXME we don't use selectedOpts?\n// $oi->selectedOpts = array();\n// if (!empty($oi->opts)) {\n// foreach ($oi->opts as $opt) {\n// $option = new option($opt[0]);\n// $og = new optiongroup($option->optiongroup_id);\n// if (!isset($oi->selectedOpts[$og->id]) || !is_array($oi->selectedOpts[$og->id]))\n// $oi->selectedOpts[$og->id] = array($option->id);\n// else\n// array_push($oi->selectedOpts[$og->id], $option->id);\n// }\n// }\n //eDebug($oi->selectedOpts);\n\n assign_to_template(array(\n 'oi' => $oi,\n 'params' => $params\n ));\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function settings() {\n AuthUser::load();\n if (!AuthUser::isLoggedIn()) {\n redirect(get_url('login'));\n } else if (!AuthUser::hasPermission('admin_edit')) {\n Flash::set('error', __('You do not have permission to access the requested page!'));\n redirect(get_url());\n }\n \n $settings = Plugin::getAllSettings('file_manager');\n\n if (!$settings) {\n Flash::set('error', 'Files - ' . __('unable to retrieve plugin settings.'));\n return;\n }\n\n $this->display('file_manager/views/settings', array('settings' => $settings));\n }", "label_name": "CWE-20", "label": "20"} -{"code": " function selectObjectBySql($sql) {\n //$logFile = \"C:\\\\xampp\\\\htdocs\\\\supserg\\\\tmp\\\\queryLog.txt\";\n //$lfh = fopen($logFile, 'a');\n //fwrite($lfh, $sql . \"\\n\"); \n //fclose($lfh); \n $res = @mysqli_query($this->connection, $this->injectProof($sql));\n if ($res == null)\n return null;\n return mysqli_fetch_object($res);\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function actionGetItems(){\n $sql = 'SELECT id, name as value, subject FROM x2_bug_reports WHERE name LIKE :qterm ORDER BY name ASC';\n $command = Yii::app()->db->createCommand($sql);\n $qterm = $_GET['term'].'%';\n $command->bindParam(\":qterm\", $qterm, PDO::PARAM_STR);\n $result = $command->queryAll();\n echo CJSON::encode($result); exit;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " foreach ($evs as $key=>$event) {\r\n if ($condense) {\r\n $eventid = $event->id;\r\n $multiday_event = array_filter($events, create_function('$event', 'global $eventid; return $event->id === $eventid;'));\r\n if (!empty($multiday_event)) {\r\n unset($evs[$key]);\r\n continue;\r\n }\r\n }\r\n $evs[$key]->eventstart += $edate->date;\r\n $evs[$key]->eventend += $edate->date;\r\n $evs[$key]->date_id = $edate->id;\r\n if (!empty($event->expCat)) {\r\n $catcolor = empty($event->expCat[0]->color) ? null : trim($event->expCat[0]->color);\r\n// if (substr($catcolor,0,1)=='#') $catcolor = '\" style=\"color:'.$catcolor.';';\r\n $evs[$key]->color = $catcolor;\r\n }\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public function confirm()\n {\n $project = $this->getProject();\n $filter = $this->customFilterModel->getById($this->request->getIntegerParam('filter_id'));\n\n $this->response->html($this->helper->layout->project('custom_filter/remove', array(\n 'project' => $project,\n 'filter' => $filter,\n 'title' => t('Remove a custom filter')\n )));\n }", "label_name": "CWE-200", "label": "200"} -{"code": " protected function markCompleted($endStatus, ServiceResponse $serviceResponse, $gatewayMessage)\n {\n parent::markCompleted($endStatus, $serviceResponse, $gatewayMessage);\n $this->createMessage(Message\\CreateCardResponse::class, $gatewayMessage);\n ErrorHandling::safeExtend($this->payment, 'onCardCreated', $serviceResponse);\n }", "label_name": "CWE-436", "label": "436"} -{"code": "\tpublic static function onParserFirstCallInit( Parser &$parser ) {\n\t\tself::init();\n\n\t\t//DPL offers the same functionality as Intersection. So we register the tag in case LabeledSection Extension is not installed so that the section markers are removed.\n\t\tif ( \\DPL\\Config::getSetting( 'handleSectionTag' ) ) {\n\t\t\t$parser->setHook( 'section', [ __CLASS__, 'dplTag' ] );\n\t\t}\n\n\t\t$parser->setHook( 'DPL', [ __CLASS__, 'dplTag' ] );\n\t\t$parser->setHook( 'DynamicPageList', [ __CLASS__, 'intersectionTag' ] );\n\n\t\t$parser->setFunctionHook( 'dpl', [ __CLASS__, 'dplParserFunction' ] );\n\t\t$parser->setFunctionHook( 'dplnum', [ __CLASS__, 'dplNumParserFunction' ] );\n\t\t$parser->setFunctionHook( 'dplvar', [ __CLASS__, 'dplVarParserFunction' ] );\n\t\t$parser->setFunctionHook( 'dplreplace', [ __CLASS__, 'dplReplaceParserFunction' ] );\n\t\t$parser->setFunctionHook( 'dplchapter', [ __CLASS__, 'dplChapterParserFunction' ] );\n\t\t$parser->setFunctionHook( 'dplmatrix', [ __CLASS__, 'dplMatrixParserFunction' ] );\n\n\t\treturn true;\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": "\tpublic function setListAttributes( $attributes ) {\n\t\t$this->listAttributes = \\Sanitizer::fixTagAttributes( $attributes, 'ul' );\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": "\tfunction manage () {\n\t expHistory::set('viewable', $this->params);\n\t\t\n\t\t$vendor = new vendor();\n\t\t$vendors = $vendor->find('all');\n\t\tif(!empty($this->params['vendor'])) {\n\t\t\t$purchase_orders = $this->purchase_order->find('all', 'vendor_id=' . $this->params['vendor']);\n\t\t} else {\n\t\t\t$purchase_orders = $this->purchase_order->find('all');\n\t\t}\n\t\t\n\t\tassign_to_template(array(\n 'purchase_orders'=>$purchase_orders,\n 'vendors' => $vendors,\n 'vendor_id' => @$this->params['vendor']\n ));\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": " public function getDisplayName ($plural=true) {\n $moduleName = X2Model::getModuleName (get_class ($this));\n return Modules::displayName ($plural, $moduleName);\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\t\tpublic static function save_uploaded_user_avatar() {\n\t\t\t$avatar_data = wp_parse_args(\n\t\t\t\tLP_Request::get( 'lp-user-avatar-crop' ),\n\t\t\t\tarray(\n\t\t\t\t\t'name' => '',\n\t\t\t\t\t'width' => '',\n\t\t\t\t\t'height' => '',\n\t\t\t\t\t'points' => '',\n\t\t\t\t\t'nonce' => '',\n\t\t\t\t)\n\t\t\t);\n\n\t\t\t$current_user_id = get_current_user_id();\n\n\t\t\tif ( ! wp_verify_nonce( $avatar_data['nonce'], 'save-uploaded-profile-' . $current_user_id ) ) {\n\t\t\t\tdie( 'ERROR VERIFY NONCE!' );\n\t\t\t}\n\n\t\t\t$url = learn_press_update_user_profile_avatar();\n\t\t\tif ( $url ) {\n\t\t\t\t$user = learn_press_get_current_user();\n\n\t\t\t\tlearn_press_send_json(\n\t\t\t\t\tarray(\n\t\t\t\t\t\t'success' => true,\n\t\t\t\t\t\t'avatar' => sprintf( '', $url ),\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\t};\n\n\t\t\twp_die();\n\t\t}", "label_name": "CWE-610", "label": "610"} -{"code": " public function testIpAddressOfRangedTrustedProxyIsSetAsRemote()\n {\n $expectedSubRequest = Request::create('/');\n $expectedSubRequest->headers->set('Surrogate-Capability', 'abc=\"ESI/1.0\"');\n $expectedSubRequest->server->set('REMOTE_ADDR', '1.1.1.1');\n $expectedSubRequest->headers->set('x-forwarded-for', array('127.0.0.1'));\n $expectedSubRequest->server->set('HTTP_X_FORWARDED_FOR', '127.0.0.1');\n\n Request::setTrustedProxies(array('1.1.1.1/24'));\n\n $strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest($expectedSubRequest));\n\n $request = Request::create('/');\n $request->headers->set('Surrogate-Capability', 'abc=\"ESI/1.0\"');\n $strategy->render('/', $request);\n\n Request::setTrustedProxies(array());\n }", "label_name": "CWE-20", "label": "20"} -{"code": " function edit_freeform() {\r\n $section = isset($this->params['id']) ? $this->section->find($this->params['id']) : new section($this->params);\r\n if ($section->parent == -1) {\r\n notfoundController::handle_not_found();\r\n exit;\r\n } // doesn't work for standalone pages\r\n if (empty($section->id)) {\r\n $section->public = 1;\r\n if (!isset($section->parent)) {\r\n // This is another precaution. The parent attribute\r\n // should ALWAYS be set by the caller.\r\n //FJD - if that's the case, then we should die.\r\n notfoundController::handle_not_authorized();\r\n exit;\r\n //$section->parent = 0;\r\n }\r\n }\r\n assign_to_template(array(\r\n 'section' => $section,\r\n 'glyphs' => self::get_glyphs(),\r\n ));\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public function searchNew() {\n global $db, $user;\n //$this->params['query'] = str_ireplace('-','\\-',$this->params['query']);\n $sql = \"select DISTINCT(p.id) as id, p.title, model, sef_url, f.id as fileid, \";\n $sql .= \"match (p.title,p.model,p.body) against ('\" . $this->params['query'] . \"*' IN BOOLEAN MODE) as relevance, \";\n $sql .= \"CASE when p.model like '\" . $this->params['query'] . \"%' then 1 else 0 END as modelmatch, \";\n $sql .= \"CASE when p.title like '%\" . $this->params['query'] . \"%' then 1 else 0 END as titlematch \";\n $sql .= \"from \" . $db->prefix . \"product as p INNER JOIN \" .\n $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 .\n \"expFiles as f ON cef.expFiles_id = f.id WHERE \";\n if (!$user->isAdmin()) $sql .= '(p.active_type=0 OR p.active_type=1) AND ';\n $sql .= \" match (p.title,p.model,p.body) against ('\" . $this->params['query'] . \"*' IN BOOLEAN MODE) AND p.parent_id=0 \";\n $sql .= \" HAVING relevance > 0 \";\n //$sql .= \"GROUP BY p.id \"; \n $sql .= \"order by modelmatch,titlematch,relevance desc LIMIT 10\";\n\n eDebug($sql);\n $res = $db->selectObjectsBySql($sql);\n eDebug($res, true);\n $ar = new expAjaxReply(200, gt('Here\\'s the items you wanted'), $res);\n $ar->send();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public static function canView($section) {\r\n global $db;\r\n\r\n if ($section == null) {\r\n return false;\r\n }\r\n if ($section->public == 0) {\r\n // Not a public section. Check permissions.\r\n return expPermissions::check('view', expCore::makeLocation('navigation', '', $section->id));\r\n } else { // Is public. check parents.\r\n if ($section->parent <= 0) {\r\n // Out of parents, and since we are still checking, we haven't hit a private section.\r\n return true;\r\n } else {\r\n $s = $db->selectObject('section', 'id=' . $section->parent);\r\n return self::canView($s);\r\n }\r\n }\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": "\tfunction test_anon_comments_require_email() {\n\t\tadd_filter( 'xmlrpc_allow_anonymous_comments', '__return_true' );\n\n\t\t$comment_args = array(\n\t\t\t1,\n\t\t\t'',\n\t\t\t'',\n\t\t\tself::$post->ID,\n\t\t\tarray(\n\t\t\t\t'author' => 'WordPress',\n\t\t\t\t'author_email' => 'noreply at wordpress.org',\n\t\t\t\t'content' => 'Test Anon Comments',\n\t\t\t),\n\t\t);\n\n\t\t$result = $this->myxmlrpcserver->wp_newComment( $comment_args );\n\t\t$this->assertIXRError( $result );\n\t\t$this->assertSame( 403, $result->code );\n\t}", "label_name": "CWE-862", "label": "862"} -{"code": " public function pending() {\n// global $db;\n \n // make sure we have what we need.\n if (empty($this->params['id'])) expQueue::flashAndFlow('error', gt('Your subscriber ID was not supplied.'));\n\n // find the subscriber and their pending subscriptions\n $ealerts = expeAlerts::getPendingBySubscriber($this->params['id']);\n $subscriber = new subscribers($this->params['id']);\n \n // render the template\n assign_to_template(array(\n 'subscriber'=>$subscriber,\n 'ealerts'=>$ealerts\n ));\n }", "label_name": "CWE-74", "label": "74"} -{"code": " $db->updateObject($value, 'section');\r\n }\r\n $db->updateObject($moveSec, 'section');\r\n //handle re-ranking of previous parent\r\n $oldSiblings = $db->selectObjects(\"section\", \"parent=\" . $oldParent . \" AND rank>\" . $oldRank . \" ORDER BY rank\");\r\n $rerank = 1;\r\n foreach ($oldSiblings as $value) {\r\n if ($value->id != $moveSec->id) {\r\n $value->rank = $rerank;\r\n $db->updateObject($value, 'section');\r\n $rerank++;\r\n }\r\n }\r\n if ($oldParent != $moveSec->parent) {\r\n //we need to re-rank the children of the parent that the moving section has just left\r\n $childOfLastMove = $db->selectObjects(\"section\", \"parent=\" . $oldParent . \" ORDER BY rank\");\r\n for ($i = 0, $iMax = count($childOfLastMove); $i < $iMax; $i++) {\r\n $childOfLastMove[$i]->rank = $i;\r\n $db->updateObject($childOfLastMove[$i], 'section');\r\n }\r\n }\r\n }\r\n }\r\n self::checkForSectionalAdmins($move);\r\n expSession::clearAllUsersSessionCache('navigation');\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public function testPOSTForRegularUser()\n {\n $post_resource = json_encode([\n 'label' => 'Test Request 9747 regular user',\n 'shortname' => 'test9747-regular-user',\n 'description' => 'Test of Request 9747 for REST API Project Creation',\n 'is_public' => true,\n 'template_id' => 100,\n ]);\n\n $response = $this->getResponseByName(\n REST_TestDataBuilder::TEST_USER_2_NAME,\n $this->request_factory->createRequest(\n 'POST',\n 'projects'\n )->withBody(\n $this->stream_factory->createStream($post_resource)\n )\n );\n\n self::assertEquals(201, $response->getStatusCode());\n\n $create_project_id = json_decode($response->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR)['id'];\n\n $this->removeAdminFromProjectMembers(\n $create_project_id,\n REST_TestDataBuilder::TEST_USER_2_NAME,\n );\n }", "label_name": "CWE-863", "label": "863"} -{"code": " foreach ($events as $event) {\r\n $extevents[$date][] = $event;\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " function edit_order_item() {\n $oi = new orderitem($this->params['id'], true, true);\n if (empty($oi->id)) {\n flash('error', gt('Order item doesn\\'t exist.'));\n expHistory::back();\n }\n $oi->user_input_fields = expUnserialize($oi->user_input_fields);\n $params['options'] = $oi->opts;\n $params['user_input_fields'] = $oi->user_input_fields;\n $oi->product = new product($oi->product->id, true, true);\n if ($oi->product->parent_id != 0) {\n $parProd = new product($oi->product->parent_id);\n //$oi->product->optiongroup = $parProd->optiongroup; \n $oi->product = $parProd;\n }\n //FIXME we don't use selectedOpts?\n// $oi->selectedOpts = array();\n// if (!empty($oi->opts)) {\n// foreach ($oi->opts as $opt) {\n// $option = new option($opt[0]);\n// $og = new optiongroup($option->optiongroup_id);\n// if (!isset($oi->selectedOpts[$og->id]) || !is_array($oi->selectedOpts[$og->id]))\n// $oi->selectedOpts[$og->id] = array($option->id);\n// else\n// array_push($oi->selectedOpts[$og->id], $option->id);\n// }\n// }\n //eDebug($oi->selectedOpts);\n\n assign_to_template(array(\n 'oi' => $oi,\n 'params' => $params\n ));\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function testCompilePathIsProperlyCreated()\n {\n $compiler = new BladeCompiler($this->getFiles(), __DIR__);\n $this->assertEquals(__DIR__.'/'.sha1('foo').'.php', $compiler->getCompiledPath('foo'));\n }", "label_name": "CWE-327", "label": "327"} -{"code": " public function rules()\n {\n return [\n 'name' => 'required',\n 'email' => 'required|email',\n 'address' => '',\n 'primary_number' => 'numeric',\n 'secondary_number' => 'numeric',\n 'password' => 'sometimes',\n 'password_confirmation' => 'sometimes',\n 'image_path' => '',\n 'departments' => 'required'\n ];\n }", "label_name": "CWE-862", "label": "862"} -{"code": " function searchByModelForm() {\n // get the search terms\n $terms = $this->params['search_string'];\n\n $sql = \"model like '%\" . $terms . \"%'\";\n\n $limit = !empty($this->config['limit']) ? $this->config['limit'] : 10;\n $page = new expPaginator(array(\n 'model' => 'product',\n 'where' => $sql,\n 'limit' => !empty($this->config['pagination_default']) ? $this->config['pagination_default'] : $limit,\n 'order' => 'title',\n 'dir' => 'DESC',\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller' => $this->params['controller'],\n 'action' => $this->params['action'],\n 'columns' => array(\n gt('Model #') => 'model',\n gt('Product Name') => 'title',\n gt('Price') => 'base_price'\n ),\n ));\n\n assign_to_template(array(\n 'page' => $page,\n 'terms' => $terms\n ));\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\t\t\t\t\t\t\t\t\t\tunset($sql, $parameters, $row);\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t//download compressed file\n\t\t\t\t\t\t\t\tif (@sizeof($email_files) != 0) {\n\n\t\t\t\t\t\t\t\t\t//define compressed file name\n\t\t\t\t\t\t\t\t\t\t$compressed_filename = 'emails_'.date('Ymd_His').'.zip';\n\n\t\t\t\t\t\t\t\t\t//compress email files\n\t\t\t\t\t\t\t\t\t\t$command = 'zip -mj '.$_SESSION['server']['temp']['dir'].'/'.$compressed_filename.' '.implode(' ', $email_files).' 2>&1';\n\t\t\t\t\t\t\t\t\t\texec($command, $response, $restore_errlevel);\n\t\t\t\t\t\t\t\t\t\tunset($command);\n\n\t\t\t\t\t\t\t\t\t//push download\n\t\t\t\t\t\t\t\t\t\tif (file_exists($_SESSION['server']['temp']['dir'].'/'.$compressed_filename)) {\n\n\t\t\t\t\t\t\t\t\t\t\t//open file\n\t\t\t\t\t\t\t\t\t\t\t\tsession_cache_limiter('public');\n\t\t\t\t\t\t\t\t\t\t\t\t$fd = fopen($_SESSION['server']['temp']['dir'].'/'.$compressed_filename, 'rb');\n\n\t\t\t\t\t\t\t\t\t\t\t//set headers\n\t\t\t\t\t\t\t\t\t\t\t\theader(\"Content-Type: application/zip\");\n\t\t\t\t\t\t\t\t\t\t\t\theader('Content-Disposition: attachment; filename=\"'.$compressed_filename.'\"');\n\t\t\t\t\t\t\t\t\t\t\t\theader(\"Cache-Control: no-cache, must-revalidate\"); // HTTP/1.1\n\t\t\t\t\t\t\t\t\t\t\t\theader(\"Expires: Sat, 26 Jul 1997 05:00:00 GMT\"); // Date in the past\n\t\t\t\t\t\t\t\t\t\t\t\theader(\"Content-Length: \".filesize($_SESSION['server']['temp']['dir'].'/'.$compressed_filename));\n\n\t\t\t\t\t\t\t\t\t\t\t//output file content\n\t\t\t\t\t\t\t\t\t\t\t\tob_clean();\n\t\t\t\t\t\t\t\t\t\t\t\tfpassthru($fd);\n\t\t\t\t\t\t\t\t\t\t\t\tfclose($fd);\n\n\t\t\t\t\t\t\t\t\t\t\t//remove compressed file\n\t\t\t\t\t\t\t\t\t\t\t\t@unlink($_SESSION['server']['temp']['dir'].'/'.$compressed_filename);\n\t\t\t\t\t\t\t\t\t\t\t\texit;\n\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t}\n\n\t\t} //method", "label_name": "CWE-77", "label": "77"} -{"code": " public static function getHelpVersionId($version) {\n global $db;\n\n return $db->selectValue('help_version', 'id', 'version=\"'.$version.'\"');\n }", "label_name": "CWE-74", "label": "74"} -{"code": " $navs[$i]->link = expCore::makeLink(array('section' => $navs[$i]->id), '', $navs[$i]->sef_name);\r\n if (!$view) {\r\n// unset($navs[$i]); //FIXME this breaks jstree if we remove a parent and not the child\r\n $attr = new stdClass();\r\n $attr->class = 'hidden'; // bs3 class to hide elements\r\n $navs[$i]->li_attr = $attr;\r\n }\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public function IsSMTP() {\n $this->Mailer = 'smtp';\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\tfunction __construct() {\n\t\tparent::__construct( 'GlobalNewFiles' );\n\t}", "label_name": "CWE-20", "label": "20"} -{"code": " public function Connect($host, $port = 0, $tval = 30) {\n // set the error val to null so there is no confusion\n $this->error = null;\n\n // make sure we are __not__ connected\n if($this->connected()) {\n // already connected, generate error\n $this->error = array(\"error\" => \"Already connected to a server\");\n return false;\n }\n\n if(empty($port)) {\n $port = $this->SMTP_PORT;\n }\n\n // connect to the smtp server\n $this->smtp_conn = @fsockopen($host, // the host of the server\n $port, // the port to use\n $errno, // error number if any\n $errstr, // error message if any\n $tval); // give up after ? secs\n // verify we connected properly\n if(empty($this->smtp_conn)) {\n $this->error = array(\"error\" => \"Failed to connect to server\",\n \"errno\" => $errno,\n \"errstr\" => $errstr);\n if($this->do_debug >= 1) {\n $this->edebug(\"SMTP -> ERROR: \" . $this->error[\"error\"] . \": $errstr ($errno)\" . $this->CRLF . '
');\n }\n return false;\n }\n\n // SMTP server can take longer to respond, give longer timeout for first read\n // Windows does not have support for this timeout function\n if(substr(PHP_OS, 0, 3) != \"WIN\") {\n $max = ini_get('max_execution_time');\n if ($max != 0 && $tval > $max) { // don't bother if unlimited\n @set_time_limit($tval);\n }\n stream_set_timeout($this->smtp_conn, $tval, 0);\n }\n\n // get any announcement\n $announce = $this->get_lines();\n\n if($this->do_debug >= 2) {\n $this->edebug(\"SMTP -> FROM SERVER:\" . $announce . $this->CRLF . '
');\n }\n\n return true;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " function addDiscountToCart() {\n// global $user, $order;\n global $order;\n //lookup discount to see if it's real and valid, and not already in our cart\n //this will change once we allow more than one coupon code\n\n $discount = new discounts();\n $discount = $discount->getCouponByName($this->params['coupon_code']);\n\n if (empty($discount)) {\n flash('error', gt(\"This discount code you entered does not exist.\"));\n //redirect_to(array('controller'=>'cart', 'action'=>'checkout')); \n expHistory::back();\n }\n\n //check to see if it's in our cart already\n if ($this->isDiscountInCart($discount->id)) {\n flash('error', gt(\"This discount code is already in your cart.\"));\n //redirect_to(array('controller'=>'cart', 'action'=>'checkout'));\n expHistory::back();\n }\n\n //this should really be reworked, as it shoudn't redirect directly and not return\n $validateDiscountMessage = $discount->validateDiscount();\n if ($validateDiscountMessage == \"\") {\n //if all good, add to cart, otherwise it will have redirected\n $od = new order_discounts();\n $od->orders_id = $order->id;\n $od->discounts_id = $discount->id;\n $od->coupon_code = $discount->coupon_code;\n $od->title = $discount->title;\n $od->body = $discount->body;\n $od->save();\n // set this to just the discount applied via this coupon?? if so, when though? $od->discount_total = ??;\n flash('message', gt(\"The discount code has been applied to your cart.\"));\n } else {\n flash('error', $validateDiscountMessage);\n }\n //redirect_to(array('controller'=>'cart', 'action'=>'checkout')); \n expHistory::back();\n }", "label_name": "CWE-20", "label": "20"} -{"code": " function configure() {\n expHistory::set('editable', $this->params);\n // little bit of trickery so that that categories can have their own configs\n \n $this->loc->src = \"@globalstoresettings\";\n $config = new expConfig($this->loc);\n $this->config = $config->config;\n $pullable_modules = expModules::listInstalledControllers($this->baseclassname, $this->loc);\n $views = expTemplate::get_config_templates($this, $this->loc);\n \n $gc = new geoCountry(); \n $countries = $gc->find('all');\n \n $gr = new geoRegion(); \n $regions = $gr->find('all');\n \n assign_to_template(array(\n 'config'=>$this->config,\n 'pullable_modules'=>$pullable_modules,\n 'views'=>$views,\n 'countries'=>$countries,\n 'regions'=>$regions,\n 'title'=>static::displayname()\n ));\n } ", "label_name": "CWE-74", "label": "74"} -{"code": " public function testSmtpConnect()\n {\n $this->Mail->SMTPDebug = 4; //Show connection-level errors\n $this->assertTrue($this->Mail->smtpConnect(), 'SMTP single connect failed');\n $this->Mail->smtpClose();\n $this->Mail->Host = \"ssl://localhost:12345;tls://localhost:587;10.10.10.10:54321;localhost:12345;10.10.10.10\";\n $this->assertFalse($this->Mail->smtpConnect(), 'SMTP bad multi-connect succeeded');\n $this->Mail->smtpClose();\n $this->Mail->Host = \"localhost:12345;10.10.10.10:54321;\" . $_REQUEST['mail_host'];\n $this->assertTrue($this->Mail->smtpConnect(), 'SMTP multi-connect failed');\n $this->Mail->smtpClose();\n $this->Mail->Host = \" localhost:12345 ; \" . $_REQUEST['mail_host'] . ' ';\n $this->assertTrue($this->Mail->smtpConnect(), 'SMTP hosts with stray spaces failed');\n $this->Mail->smtpClose();\n $this->Mail->Host = $_REQUEST['mail_host'];\n //Need to pick a harmless option so as not cause problems of its own! socket:bind doesn't work with Travis-CI\n $this->assertTrue(\n $this->Mail->smtpConnect(array('ssl' => array('verify_depth' => 10))),\n 'SMTP connect with options failed'\n );\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function approve() {\n expHistory::set('editable', $this->params);\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n $require_login = empty($this->params['require_login']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];\n $require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];\n $require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n $notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];\n \n if (empty($this->params['id'])) {\n flash('error', gt('No ID supplied for note to approve'));\n $lastUrl = expHistory::getLast('editable');\n }\n \n $simplenote = new expSimpleNote($this->params['id']);\n assign_to_template(array(\n 'simplenote'=>$simplenote,\n 'require_login'=>$require_login,\n 'require_approval'=>$require_approval,\n 'require_notification'=>$require_notification,\n 'notification_email'=>$notification_email,\n 'tab'=>$this->params['tab']\n ));\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function testAuthHeader()\n {\n $restoreInstance = PMA\\libraries\\Response::getInstance();\n\n $mockResponse = $this->getMockBuilder('PMA\\libraries\\Response')\n ->disableOriginalConstructor()\n ->setMethods(array('isAjax', 'headersSent', 'header'))\n ->getMock();\n\n $mockResponse->expects($this->once())\n ->method('isAjax')\n ->with()\n ->will($this->returnValue(false));\n\n $mockResponse->expects($this->any())\n ->method('headersSent')\n ->with()\n ->will($this->returnValue(false));\n\n $mockResponse->expects($this->once())\n ->method('header')\n ->with('Location: http://www.phpmyadmin.net/logout' . ((SID) ? '?' . SID : ''));", "label_name": "CWE-200", "label": "200"} -{"code": "\tfunction token($str) {\n\t\t$fw=$this->fw;\n\t\t$str=trim(preg_replace('/\\{\\{(.+?)\\}\\}/s',trim('\\1'),\n\t\t\t$fw->compile($str)));\n\t\tif (preg_match('/^(.+)(?split(trim($parts[2],\"\\xC2\\xA0\")) as $func)\n\t\t\t\t$str=((empty($this->filter[$cmd=$func]) &&\n\t\t\t\t\tfunction_exists($cmd)) ||\n\t\t\t\t\tis_string($cmd=$this->filter($func)))?\n\t\t\t\t\t$cmd.'('.$str.')':\n\t\t\t\t\t'Base::instance()->'.\n\t\t\t\t\t\t'call($this->filter(\\''.$func.'\\'),['.$str.'])';\n\t\t}\n\t\treturn $str;\n\t}", "label_name": "CWE-20", "label": "20"} -{"code": " public function SendAndMail($from) {\n $this->error = null; // so no confusion is caused\n\n if(!$this->connected()) {\n $this->error = array(\n \"error\" => \"Called SendAndMail() without being connected\");\n return false;\n }\n\n fputs($this->smtp_conn,\"SAML FROM:\" . $from . $this->CRLF);\n\n $rply = $this->get_lines();\n $code = substr($rply,0,3);\n\n if($this->do_debug >= 2) {\n $this->edebug(\"SMTP -> FROM SERVER:\" . $rply . $this->CRLF . '
');\n }\n\n if($code != 250) {\n $this->error =\n array(\"error\" => \"SAML not accepted from server\",\n \"smtp_code\" => $code,\n \"smtp_msg\" => substr($rply,4));\n if($this->do_debug >= 1) {\n $this->edebug(\"SMTP -> ERROR: \" . $this->error[\"error\"] . \": \" . $rply . $this->CRLF . '
');\n }\n return false;\n }\n return true;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function rename() {\n if (!AuthUser::hasPermission('file_manager_rename')) {\n Flash::set('error', __('You do not have sufficient permissions to rename this file or directory.'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n \n // CSRF checks\n if (isset($_POST['csrf_token'])) {\n $csrf_token = $_POST['csrf_token'];\n if (!SecureToken::validateToken($csrf_token, BASE_URL.'plugin/file_manager/rename')) {\n Flash::set('error', __('Invalid CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n }\n else {\n Flash::set('error', __('No CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n\n $data = $_POST['file'];\n\n $data['current_name'] = str_replace('..', '', $data['current_name']);\n $data['new_name'] = str_replace('..', '', $data['new_name']);\n\n // Clean filenames\n $data['new_name'] = preg_replace('/ /', '_', $data['new_name']);\n $data['new_name'] = preg_replace('/[^a-z0-9_\\-\\.]/i', '', $data['new_name']);\n\n $path = substr($data['current_name'], 0, strrpos($data['current_name'], '/'));\n $file = FILES_DIR . '/' . $data['current_name'];\n\n // Check another file doesn't already exist with same name\n if (file_exists(FILES_DIR . '/' . $path . '/' . $data['new_name'])) {\n Flash::set('error', __('A file or directory with that name already exists!'));\n redirect(get_url('plugin/file_manager/browse/' . $path));\n }\n\n if (file_exists($file)) {\n if (!rename($file, FILES_DIR . '/' . $path . '/' . $data['new_name']))\n Flash::set('error', __('Permission denied!'));\n }\n else {\n Flash::set('error', __('File or directory not found!' . $file));\n }\n\n redirect(get_url('plugin/file_manager/browse/' . $path));\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\tprivate function readData() {\n\n\t\tif (isset($this->tid)\n\t\t\t&& $this->tid != - 1\n\t\t) {\n\t\t\t$_ticket_stmt = Database::prepare('\n\t\t\t\tSELECT * FROM `' . TABLE_PANEL_TICKETS . '` WHERE `id` = :tid'\n\t\t\t);\n\t\t\t$_ticket = Database::pexecute_first($_ticket_stmt, array('tid' => $this->tid));\n\n\t\t\t$this->Set('customer', $_ticket['customerid'], true, false);\n\t\t\t$this->Set('admin', $_ticket['adminid'], true, false);\n\t\t\t$this->Set('subject', $_ticket['subject'], true, false);\n\t\t\t$this->Set('category', $_ticket['category'], true, false);\n\t\t\t$this->Set('priority', $_ticket['priority'], true, false);\n\t\t\t$this->Set('message', $_ticket['message'], true, false);\n\t\t\t$this->Set('dt', $_ticket['dt'], true, false);\n\t\t\t$this->Set('lastchange', $_ticket['lastchange'], true, false);\n\t\t\t$this->Set('ip', $_ticket['ip'], true, false);\n\t\t\t$this->Set('status', $_ticket['status'], true, false);\n\t\t\t$this->Set('lastreplier', $_ticket['lastreplier'], true, false);\n\t\t\t$this->Set('by', $_ticket['by'], true, false);\n\t\t\t$this->Set('answerto', $_ticket['answerto'], true, false);\n\t\t\t$this->Set('archived', $_ticket['archived'], true, false);\n\t\t}\n\t}", "label_name": "CWE-732", "label": "732"} -{"code": "\tprivate function _createdby( $option ) {\n\t\t$this->addTable( 'revision', 'creation_rev' );\n\t\t$this->addTable( 'revision_actor_temp', 'creation_rev_actor' );\n\t\t$this->_adduser( null, 'creation_rev_actor' );\n\t\t$user = new \\User;\n\n\t\t$this->addWhere(\n\t\t\t[\n\t\t\t\t$this->DB->addQuotes( $user->newFromName( $option )->getActorId() ) . ' = creation_rev_actor.revactor_actor',\n\t\t\t\t'creation_rev_actor.revactor_page = page_id',\n\t\t\t\t'creation_rev.rev_parent_id = 0'\n\t\t\t]\n\t\t);\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " $criteria->addCondition (\n 'user IN (' .\n 'SELECT DISTINCT b.username ' .\n 'FROM x2_group_to_user a JOIN x2_group_to_user b ' .\n 'ON a.groupId=b.groupId ' .\n 'WHERE a.username=:getAccessCriteria_username' .\n ') OR (user = :getAccessCriteria_username)');\n } else { // default history privacy (public or assigned)\n $criteria->addCondition (\"(user=:getAccessCriteria_username OR visibility=1)\");\n }\n }\n\n if ($profile) {\n $criteria->params[':getAccessCriteria_profileUsername'] = $profile->username;\n /* only show events associated with current profile which current user has\n permission to see */\n $criteria->addCondition (\"user=:getAccessCriteria_profileUsername\");\n if (!Yii::app()->params->isAdmin) {\n $criteria->addCondition (\"visibility=1\");\n }\n }\n return $criteria;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " private function runCallback() {\n foreach ($this->records as &$record) {\n if (isset($record->ref_type)) {\n $refType = $record->ref_type;\n if (class_exists($record->ref_type)) {\n $type = new $refType();\n $classinfo = new ReflectionClass($type);\n if ($classinfo->hasMethod('paginationCallback')) {\n $item = new $type($record->original_id);\n $item->paginationCallback($record);\n }\n }\n }\n } \n }", "label_name": "CWE-74", "label": "74"} -{"code": "\tpublic function setTableSortMethod($method = null) {\n\t\t$this->tableSortMethod = $method === null ? 'standard' : $method;\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " public static function parseAndTrimExport($str, $isHTML = false) { //\ufffdDeath from above\ufffd? \ufffd\n //echo \"1
\"; eDebug($str); \n\n $str = str_replace(\"\ufffd\", \"’\", $str);\n $str = str_replace(\"\ufffd\", \"‘\", $str);\n $str = str_replace(\"\ufffd\", \"®\", $str);\n $str = str_replace(\"\ufffd\", \"-\", $str);\n $str = str_replace(\"\ufffd\", \"—\", $str);\n $str = str_replace(\"\ufffd\", \"”\", $str);\n $str = str_replace(\"\ufffd\", \"“\", $str);\n $str = str_replace(\"\\r\\n\", \" \", $str);\n $str = str_replace(\"\\t\", \" \", $str);\n $str = str_replace(\",\", \"\\,\", $str);\n $str = str_replace(\"\ufffd\", \"¼\", $str);\n $str = str_replace(\"\ufffd\", \"½\", $str);\n $str = str_replace(\"\ufffd\", \"¾\", $str);\n\n if (!$isHTML) {\n $str = str_replace('\\\"', \""\", $str);\n $str = str_replace('\"', \""\", $str);\n } else {\n $str = str_replace('\"', '\"\"', $str);\n }\n\n //$str = htmlspecialchars($str);\n //$str = utf8_encode($str);\n $str = trim(str_replace(\"\ufffd\", \"™\", $str));\n //echo \"2
\"; eDebug($str,die);\n return $str;\n }", "label_name": "CWE-74", "label": "74"} -{"code": " protected function fixupImportedAttributes($modelName, X2Model &$model) {\n if ($modelName === 'Contacts' || $modelName === 'X2Leads')\n $this->fixupImportedContactName ($model);\n\n if ($modelName === 'Actions' && isset($model->associationType))\n $this->reconstructImportedActionAssoc($model);\n\n if ($model->hasAttribute('visibility')) {\n // Nobody every remembers to set visibility... set it for them\n if(empty($model->visibility) && ($model->visibility !== 0 && $model->visibility !== \"0\")\n || $model->visibility == 'Public') {\n $model->visibility = 1;\n } elseif($model->visibility == 'Private')\n $model->visibility = 0;\n }\n // If date fields were provided, do not create new values for them\n if (!empty($model->createDate) || !empty($model->lastUpdated) ||\n !empty($model->lastActivity)) {\n $now = time();\n if (empty($model->createDate))\n $model->createDate = $now;\n if (empty($model->lastUpdated))\n $model->lastUpdated = $now;\n if ($model->hasAttribute('lastActivity') && empty($model->lastActivity))\n $model->lastActivity = $now;\n }\n if($_SESSION['leadRouting'] == 1){\n $assignee = $this->getNextAssignee();\n if($assignee == \"Anyone\")\n $assignee = \"\";\n $model->assignedTo = $assignee;\n }\n // Loop through our override and set the manual data\n foreach($_SESSION['override'] as $attr => $val){\n $model->$attr = $val;\n }\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function admin_delete($id = null)\n {\n if (!$this->request->is('post') && !$this->request->is('delete')) {\n throw new MethodNotAllowedException(__('Action not allowed, post or delete request expected.'));\n }\n if (!$this->_isAdmin()) {\n throw new Exception('Administrators only.');\n }\n $this->User->id = $id;\n $conditions = array('User.id' => $id);\n if (!$this->_isSiteAdmin()) {\n $conditions['org_id'] = $this->Auth->user('org_id');\n }\n $user = $this->User->find('first', array(\n 'conditions' => $conditions,\n 'recursive' => -1\n ));\n if (empty($user)) {\n throw new NotFoundException(__('Invalid user'));\n }\n $fieldsDescrStr = 'User (' . $id . '): ' . $user['User']['email'];\n if ($this->User->delete($id)) {\n $this->__extralog(\"delete\", $fieldsDescrStr, '');\n if ($this->_isRest()) {\n return $this->RestResponse->saveSuccessResponse('User', 'admin_delete', $id, $this->response->type(), 'User deleted.');\n } else {\n $this->Flash->success(__('User deleted'));\n $this->redirect(array('action' => 'index'));\n }\n }\n $this->Flash->error(__('User was not deleted'));\n $this->redirect(array('action' => 'index'));\n }", "label_name": "CWE-269", "label": "269"} -{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $tag_id = $this->request->getIntegerParam('tag_id');\n $tag = $this->tagModel->getById($tag_id);\n\n if ($tag['project_id'] != $project['id']) {\n throw new AccessForbiddenException();\n }\n\n if ($this->tagModel->remove($tag_id)) {\n $this->flash->success(t('Tag removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this tag.'));\n }\n\n $this->response->redirect($this->helper->url->to('ProjectTagController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-200", "label": "200"} -{"code": " static function description() {\r\n return \"Manage events and schedules, and optionally publish them.\";\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public function testRemoveCurlAuthorizationOptionsOnRedirect($auth)\n {\n if (!defined('\\CURLOPT_HTTPAUTH')) {\n self::markTestSkipped('ext-curl is required for this test');\n }\n\n $mock = new MockHandler([\n new Response(302, ['Location' => 'http://test.com']),\n static function (RequestInterface $request, $options) {\n self::assertFalse(\n isset($options['curl'][\\CURLOPT_HTTPAUTH]),\n 'curl options still contain CURLOPT_HTTPAUTH entry'\n );\n self::assertFalse(\n isset($options['curl'][\\CURLOPT_USERPWD]),\n 'curl options still contain CURLOPT_USERPWD entry'\n );\n return new Response(200);\n }\n ]);\n $handler = HandlerStack::create($mock);\n $client = new Client(['handler' => $handler]);\n $client->get('http://example.com?a=b', ['auth' => ['testuser', 'testpass', $auth]]);\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public function onKernelResponse(ResponseEvent $event)\n {\n if (!$event->isMainRequest()) {\n return;\n }\n\n $request = $event->getRequest();\n\n if (!$request->hasSession() || !$request->attributes->get('_security_firewall_run', false)) {\n return;\n }\n\n if ($this->dispatcher) {\n $this->dispatcher->removeListener(KernelEvents::RESPONSE, [$this, 'onKernelResponse']);\n }\n $this->registered = false;\n $session = $request->getSession();\n $sessionId = $session->getId();\n $usageIndexValue = $session instanceof Session ? $usageIndexReference = &$session->getUsageIndex() : null;\n $token = $this->tokenStorage->getToken();\n\n if (null === $token || $this->trustResolver->isAnonymous($token)) {\n if ($request->hasPreviousSession()) {\n $session->remove($this->sessionKey);\n }\n } else {\n $session->set($this->sessionKey, serialize($token));\n\n if (null !== $this->logger) {\n $this->logger->debug('Stored the security token in the session.', ['key' => $this->sessionKey]);\n }\n }\n\n if ($this->sessionTrackerEnabler && $session->getId() === $sessionId) {\n $usageIndexReference = $usageIndexValue;\n }\n }", "label_name": "CWE-287", "label": "287"} -{"code": "\tfunction edit_vendor() {\n\t\t$vendor = new vendor();\n\t\t\n\t\tif(isset($this->params['id'])) {\n\t\t\t$vendor = $vendor->find('first', 'id =' .$this->params['id']);\n\t\t\tassign_to_template(array(\n 'vendor'=>$vendor\n ));\n\t\t}\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": " public function confirm() {\n global $db;\n \n // make sure we have what we need.\n if (empty($this->params['key'])) expQueue::flashAndFlow('error', gt('The security key for account was not supplied.'));\n if (empty($this->params['id'])) expQueue::flashAndFlow('error', gt('The subscriber id for account was not supplied.'));\n \n // verify the id/key pair \n $id = $db->selectValue('subscribers','id', 'id='.$this->params['id'].' AND hash=\"'.$this->params['key'].'\"');\n if (empty($id)) expQueue::flashAndFlow('error', gt('We could not find any subscriptions matching the ID and Key you provided.'));\n \n // activate this users pending subscriptions\n $sub = new stdClass();\n $sub->enabled = 1;\n $db->updateObject($sub, 'expeAlerts_subscribers', 'subscribers_id='.$id);\n \n // find the users active subscriptions\n $ealerts = expeAlerts::getBySubscriber($id);\n assign_to_template(array(\n 'ealerts'=>$ealerts\n ));\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function theme_switch() {\n if (!expUtil::isReallyWritable(BASE.'framework/conf/config.php')) { // we can't write to the config.php file\n flash('error',gt('The file /framework/conf/config.php is NOT Writeable. You will be unable to change the theme.'));\n }\n \texpSettings::change('DISPLAY_THEME_REAL', $this->params['theme']);\n\t expSession::set('display_theme',$this->params['theme']);\n\t $sv = isset($this->params['sv'])?$this->params['sv']:'';\n\t if (strtolower($sv)=='default') {\n\t $sv = '';\n\t }\n\t expSettings::change('THEME_STYLE_REAL',$sv);\n\t expSession::set('theme_style',$sv);\n\t expDatabase::install_dbtables(); // update tables to include any custom definitions in the new theme\n\n // $message = (MINIFY != 1) ? \"Exponent is now minifying Javascript and CSS\" : \"Exponent is no longer minifying Javascript and CSS\" ;\n // flash('message',$message);\n\t $message = gt(\"You have selected the\").\" '\".$this->params['theme'].\"' \".gt(\"theme\");\n\t if ($sv != '') {\n\t\t $message .= ' '.gt('with').' '.$this->params['sv'].' '.gt('style variation');\n\t }\n\t flash('message',$message);\n// expSession::un_set('framework');\n expSession::set('force_less_compile', 1);\n// expTheme::removeSmartyCache();\n expSession::clearAllUsersSessionCache();\n \texpHistory::returnTo('manageable');\n }\t", "label_name": "CWE-74", "label": "74"} -{"code": "\t\tpublic function fetch($remote = NULL, array $params = NULL)\n\t\t{\n\t\t\t$this->run('fetch', $remote, $params);\n\t\t\treturn $this;\n\t\t}", "label_name": "CWE-77", "label": "77"} -{"code": "\tpublic static function newFromStyle( $style, \\DPL\\Parameters $parameters ) {\n\t\t$style = strtolower( $style );\n\t\tswitch ( $style ) {\n\t\t\tcase 'definition':\n\t\t\t\t$class = 'DefinitionHeading';\n\t\t\t\tbreak;\n\t\t\tcase 'h1':\n\t\t\tcase 'h2':\n\t\t\tcase 'h3':\n\t\t\tcase 'h4':\n\t\t\tcase 'h5':\n\t\t\tcase 'h6':\n\t\t\tcase 'header':\n\t\t\t\t$class = 'TieredHeading';\n\t\t\t\tbreak;\n\t\t\tcase 'ordered':\n\t\t\t\t$class = 'OrderedHeading';\n\t\t\t\tbreak;\n\t\t\tcase 'unordered':\n\t\t\t\t$class = 'UnorderedHeading';\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn null;\n\t\t\t\tbreak;\n\t\t}\n\t\t$class = '\\DPL\\Heading\\\\' . $class;\n\n\t\treturn new $class( $parameters );\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " $date->delete(); // event automatically deleted if all assoc eventdates are deleted\r\n }\r\n expHistory::back();\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public function rules() {\n $parentRules = parent::rules();\n $parentRules[] = array(\n 'firstName,lastName', 'required', 'on' => 'webForm');\n return $parentRules;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function testGetEventsPublicProfile(){\n TestingAuxLib::loadX2NonWebUser ();\n TestingAuxLib::suLogin ('testuser');\n\n Yii::app()->settings->historyPrivacy = null;\n $lastEventId=0;\n $lastTimestamp=0;\n $myProfile = Profile::model()->findByAttributes(array('username' => 'testuser2'));\n $events=Events::getEvents(\n $lastEventId,$lastTimestamp,null,$myProfile, false);\n $this->assertEquals (\n array_map (\n function ($event) { return $event->id; }, \n Events::model ()->findAllByAttributes (array (\n 'user' => 'testuser2',\n 'visibility' => 1 \n ))\n ),\n array_map (function ($event) { return $event->id; }, $events['events']));\n\n TestingAuxLib::restoreX2WebUser ();\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function clearTags() {\n $this->_tags = array(); // clear tag cache\n\n return (bool) CActiveRecord::model('Tags')->deleteAllByAttributes(array(\n 'type' => get_class($this->getOwner()),\n 'itemId' => $this->getOwner()->id)\n );\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public static function getHelpVersion($version_id) {\n global $db;\n\n return $db->selectValue('help_version', 'version', 'id=\"'.$version_id.'\"');\n }", "label_name": "CWE-74", "label": "74"} -{"code": " function manage() {\n expHistory::set('viewable', $this->params);\n // $category = new storeCategory();\n // $categories = $category->getFullTree();\n // \n // // foreach($categories as $i=>$val){\n // // if (!empty($this->values) && in_array($val->id,$this->values)) {\n // // $this->tags[$i]->value = true;\n // // } else {\n // // $this->tags[$i]->value = false;\n // // }\n // // $this->tags[$i]->draggable = $this->draggable; \n // // $this->tags[$i]->checkable = $this->checkable; \n // // }\n //\n // $obj = json_encode($categories); \n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function Reset() {\n $this->error = null; // so no confusion is caused\n\n if(!$this->connected()) {\n $this->error = array(\n \"error\" => \"Called Reset() without being connected\");\n return false;\n }\n\n fputs($this->smtp_conn,\"RSET\" . $this->CRLF);\n\n $rply = $this->get_lines();\n $code = substr($rply,0,3);\n\n if($this->do_debug >= 2) {\n $this->edebug(\"SMTP -> FROM SERVER:\" . $rply . $this->CRLF . '
');\n }\n\n if($code != 250) {\n $this->error =\n array(\"error\" => \"RSET failed\",\n \"smtp_code\" => $code,\n \"smtp_msg\" => substr($rply,4));\n if($this->do_debug >= 1) {\n $this->edebug(\"SMTP -> ERROR: \" . $this->error[\"error\"] . \": \" . $rply . $this->CRLF . '
');\n }\n return false;\n }\n\n return true;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function actionGetItems(){\n $sql = 'SELECT id, name as value FROM x2_opportunities WHERE name LIKE :qterm ORDER BY name ASC';\n $command = Yii::app()->db->createCommand($sql);\n $qterm = $_GET['term'].'%';\n $command->bindParam(\":qterm\", $qterm, PDO::PARAM_STR);\n $result = $command->queryAll();\n echo CJSON::encode($result);\n Yii::app()->end();\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function confirm()\n {\n $project = $this->getProject();\n\n $this->response->html($this->helper->layout->project('action/remove', array(\n 'action' => $this->actionModel->getById($this->request->getIntegerParam('action_id')),\n 'available_events' => $this->eventManager->getAll(),\n 'available_actions' => $this->actionManager->getAvailableActions(),\n 'project' => $project,\n 'title' => t('Remove an action')\n )));\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public function shouldRun(DateTime $date)\n {\n global $timedate;\n\n $runDate = clone $date;\n $this->handleTimeZone($runDate);\n\n $cron = Cron\\CronExpression::factory($this->schedule);\n if (empty($this->last_run) && $cron->isDue($runDate)) {\n return true;\n }\n\n $lastRun = $this->last_run ? $timedate->fromDb($this->last_run) : $timedate->fromDb($this->date_entered);\n \n $this->handleTimeZone($lastRun);\n $next = $cron->getNextRunDate($lastRun);\n\n return $next <= $runDate;\n }", "label_name": "CWE-287", "label": "287"} -{"code": " private function mail_passthru($to, $subject, $body, $header, $params) {\n if ( ini_get('safe_mode') || !($this->UseSendmailOptions) ) {\n $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header);\n } else {\n $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header, $params);\n }\n return $rt;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function recipient($toaddr)\n {\n return $this->sendCommand(\n 'RCPT TO',\n 'RCPT TO:<' . $toaddr . '>',\n array(250, 251)\n );\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function buildControl() {\r\n $control = new colorcontrol();\r\n if (!empty($this->params['value'])) $control->value = $this->params['value'];\r\n if ($this->params['value'][0] != '#') $this->params['value'] = '#' . $this->params['value'];\r\n $control->default = $this->params['value'];\r\n if (!empty($this->params['hide'])) $control->hide = $this->params['hide'];\r\n if (isset($this->params['flip'])) $control->flip = $this->params['flip'];\r\n $this->params['name'] = !empty($this->params['name']) ? $this->params['name'] : '';\r\n $control->name = $this->params['name'];\r\n $this->params['id'] = !empty($this->params['id']) ? $this->params['id'] : '';\r\n $control->id = isset($this->params['id']) && $this->params['id'] != \"\" ? $this->params['id'] : \"\";\r\n //echo $control->id;\r\n if (empty($control->id)) $control->id = $this->params['name'];\r\n if (empty($control->name)) $control->name = $this->params['id'];\r\n\r\n // attempt to translate the label\r\n if (!empty($this->params['label'])) {\r\n $this->params['label'] = gt($this->params['label']);\r\n } else {\r\n $this->params['label'] = null;\r\n }\r\n echo $control->toHTML($this->params['label'], $this->params['name']);\r\n// $ar = new expAjaxReply(200, gt('The control was created'), json_encode(array('data'=>$code)));\r\n// $ar->send();\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public function testOnKernelResponseWithoutSession()\n {\n $tokenStorage = new TokenStorage();\n $tokenStorage->setToken(new UsernamePasswordToken('test1', 'pass1', 'phpunit'));\n $request = new Request();\n $request->attributes->set('_security_firewall_run', true);\n $session = new Session(new MockArraySessionStorage());\n $request->setSession($session);\n\n $event = new ResponseEvent(\n $this->createMock(HttpKernelInterface::class),\n $request,\n HttpKernelInterface::MAIN_REQUEST,\n new Response()\n );\n\n $listener = new ContextListener($tokenStorage, [], 'session', null, new EventDispatcher());\n $listener->onKernelResponse($event);\n\n $this->assertTrue($session->isStarted());\n }", "label_name": "CWE-287", "label": "287"} -{"code": "\tpublic function editspeed() {\n global $db;\n\n if (empty($this->params['id'])) return false;\n $calcname = $db->selectValue('shippingcalculator', 'calculator_name', 'id='.$this->params['id']);\n $calc = new $calcname($this->params['id']);\n assign_to_template(array(\n 'calculator'=>$calc\n ));\n\t\t\n }", "label_name": "CWE-74", "label": "74"} -{"code": "\tprivate function setDefaults() {\n\t\t$this->setParameter( 'defaulttemplatesuffix', '.default' );\n\n\t\t$parameters = $this->getParametersForRichness();\n\t\tforeach ( $parameters as $parameter ) {\n\t\t\tif ( $this->getData( $parameter )['default'] !== null && !( $this->getData( $parameter )['default'] === false && $this->getData( $parameter )['boolean'] === true ) ) {\n\t\t\t\tif ( $parameter == 'debug' ) {\n\t\t\t\t\t\\DynamicPageListHooks::setDebugLevel( $this->getData( $parameter )['default'] );\n\t\t\t\t}\n\t\t\t\t$this->setParameter( $parameter, $this->getData( $parameter )['default'] );\n\t\t\t}\n\t\t}\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " function edit_optiongroup_master() {\n expHistory::set('editable', $this->params);\n \n $id = isset($this->params['id']) ? $this->params['id'] : null;\n $record = new optiongroup_master($id); \n assign_to_template(array(\n 'record'=>$record\n ));\n }", "label_name": "CWE-74", "label": "74"} -{"code": " function scan_page($parent_id) {\r\n global $db;\r\n\r\n $sections = $db->selectObjects('section','parent=' . $parent_id);\r\n $ret = '';\r\n foreach ($sections as $page) {\r\n $cLoc = serialize(expCore::makeLocation('container','@section' . $page->id));\r\n $ret .= scan_container($cLoc, $page->id);\r\n $ret .= scan_page($page->id);\r\n }\r\n return $ret;\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " $layout[$loc] = array_merge($layout[$loc],$data);\n }\n }\n }\n return $layout;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " $src = substr($ref->source, strlen($prefix)) . $section->id;\r\n if (call_user_func(array($ref->module, 'hasContent'))) {\r\n $oloc = expCore::makeLocation($ref->module, $ref->source);\r\n $nloc = expCore::makeLocation($ref->module, $src);\r\n if ($ref->module != \"container\") {\r\n call_user_func(array($ref->module, 'copyContent'), $oloc, $nloc);\r\n } else {\r\n call_user_func(array($ref->module, 'copyContent'), $oloc, $nloc, $section->id);\r\n }\r\n }\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": "\tpublic function setMultiSectionSeparators( ?array $separators ) {\n\t\t$this->multiSectionSeparators = (array)$separators ?? [];\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " public function theme_switch() {\n if (!expUtil::isReallyWritable(BASE.'framework/conf/config.php')) { // we can't write to the config.php file\n flash('error',gt('The file /framework/conf/config.php is NOT Writeable. You will be unable to change the theme.'));\n }\n \texpSettings::change('DISPLAY_THEME_REAL', $this->params['theme']);\n\t expSession::set('display_theme',$this->params['theme']);\n\t $sv = isset($this->params['sv'])?$this->params['sv']:'';\n\t if (strtolower($sv)=='default') {\n\t $sv = '';\n\t }\n\t expSettings::change('THEME_STYLE_REAL',$sv);\n\t expSession::set('theme_style',$sv);\n\t expDatabase::install_dbtables(); // update tables to include any custom definitions in the new theme\n\n // $message = (MINIFY != 1) ? \"Exponent is now minifying Javascript and CSS\" : \"Exponent is no longer minifying Javascript and CSS\" ;\n // flash('message',$message);\n\t $message = gt(\"You have selected the\").\" '\".$this->params['theme'].\"' \".gt(\"theme\");\n\t if ($sv != '') {\n\t\t $message .= ' '.gt('with').' '.$this->params['sv'].' '.gt('style variation');\n\t }\n\t flash('message',$message);\n// expSession::un_set('framework');\n expSession::set('force_less_compile', 1);\n// expTheme::removeSmartyCache();\n expSession::clearAllUsersSessionCache();\n \texpHistory::returnTo('manageable');\n }\t", "label_name": "CWE-74", "label": "74"} -{"code": "\tfunction formatValue( $name, $value ) {\n\t\t$row = $this->mCurrentRow;\n\n\t\t$wiki = $row->files_dbname;\n\n\t\tswitch ( $name ) {\n\t\t\tcase 'files_timestamp':\n\t\t\t\t$formatted = htmlspecialchars( $this->getLanguage()->userTimeAndDate( $row->files_timestamp, $this->getUser() ) );\n\t\t\t\tbreak;\n\t\t\tcase 'files_dbname':\n\t\t\t\t$formatted = $row->files_dbname;\n\t\t\t\tbreak;\n\t\t\tcase 'files_url':\n\t\t\t\t$formatted = \"files_url}\\\" style=\\\"width:135px;height:135px;\\\">\";\n\t\t\t\tbreak;\n\t\t\tcase 'files_name':\n\t\t\t\t$formatted = \"files_page}\\\">{$row->files_name}\";\n\t\t\t\tbreak;\n\t\t\tcase 'files_user':\n\t\t\t\t$formatted = \"files_user}\\\">{$row->files_user}\";\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\t$formatted = \"Unable to format $name\";\n\t\t\t\tbreak;\n\t\t}\n\n\t\treturn $formatted;\n\t}", "label_name": "CWE-20", "label": "20"} -{"code": " public function approve_submit() {\n global $history;\n \n if (empty($this->params['id'])) {\n flash('error', gt('No ID supplied for comment to approve'));\n $lastUrl = expHistory::getLast('editable');\n }\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n $require_login = empty($this->params['require_login']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];\n $require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];\n $require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n $notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];\n \n $simplenote = new expSimpleNote($this->params['id']);\n //FIXME here is where we might sanitize the note before approving it\n $simplenote->body = $this->params['body'];\n $simplenote->approved = $this->params['approved'];\n $simplenote->save();\n \n $lastUrl = makelink($history->history[$history->history['lasts']['type']][count($history->history[$history->history['lasts']['type']])-1]['params']);\n if (!empty($this->params['tab']))\n {\n $lastUrl .= \"#\".$this->params['tab'];\n }\n redirect_to($lastUrl);\n }", "label_name": "CWE-74", "label": "74"} -{"code": " $fileName = ltrim(dirname($fileName) . '/' . basename($fileName, '.js'), '/.');\n if (empty($fileName)) {\n continue;\n }\n $templateBase = $inflector->filter(array(\n 'module' => $moduleName,\n 'controller' => $controllerName,\n 'file' => $fileName)\n );\n\n $templateExtend = $inflector->filter(array(\n 'module' => $moduleName,\n 'controller' => $this->Request()->getControllerName(),\n 'file' => $fileName)\n );\n if ($this->View()->templateExists($templateBase)) {\n $template .= '{include file=\"' . $templateBase. '\"}' . \"\\n\";\n }\n if ($this->View()->templateExists($templateExtend)) {\n $template .= '{include file=\"' . $templateExtend. '\"}' . \"\\n\";\n }\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function rules()\n {\n return [\n 'name' => 'required',\n 'email' => 'required|email',\n 'address' => '',\n 'primary_number' => 'numeric',\n 'secondary_number' => 'numeric',\n 'password' => 'required|min:5|confirmed',\n 'password_confirmation' => 'required|min:5',\n 'image_path' => '',\n 'roles' => 'required',\n 'departments' => 'required'\n ];\n }", "label_name": "CWE-862", "label": "862"} -{"code": " public function execute(&$params){\n $options = &$this->config['options'];\n\n $event = new Events;\n $notif = new Notification;\n\n $user = $this->parseOption('user', $params);\n\n $type = $this->parseOption('type', $params);\n\n if($type === 'auto'){\n if(!isset($params['model']))\n return array (false, '');\n $notif->modelType = get_class($params['model']);\n $notif->modelId = $params['model']->id;\n $notif->type = $this->getNotifType();\n\n $event->associationType = get_class($params['model']);\n $event->associationId = $params['model']->id;\n $event->type = $this->getEventType();\n if($params['model']->hasAttribute('visibility'))\n $event->visibility = $params['model']->visibility;\n // $event->user = $this->parseOption('user',$params);\n } else{\n $text = $this->parseOption('text', $params);\n\n $notif->type = 'custom';\n $notif->text = $text;\n\n $event->type = 'feed';\n $event->subtype = $type;\n $event->text = $text;\n if($user == 'auto' && isset($params['model']) && \n $params['model']->hasAttribute('assignedTo') && \n !empty($params['model']->assignedTo)){\n\n $event->user = $params['model']->assignedTo;\n }elseif(!empty($user)){\n $event->user = $user;\n }else{\n $event->user = 'admin';\n }\n }\n if(!$this->parseOption('createNotif', $params)) {\n if (!$notif->save()) {\n return array(false, array_shift($notif->getErrors()));\n }\n }\n\n if ($event->save()) {\n return array (true, \"\");\n } else {\n return array(false, array_shift($event->getErrors()));\n }\n\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\tpublic function attributeLabels() {\n\t\treturn array(\n\t\t\t'actionId' => Yii::t('actions','Action ID'),\n\t\t\t'text' => Yii::t('actions','Action Text'),\n\t\t);\n\t}", "label_name": "CWE-20", "label": "20"} -{"code": " public function logout()\n {\n if ($this->Session->check('Auth.User')) {\n $this->__extralog(\"logout\");\n }\n $this->Flash->info(__('Good-Bye'));\n $user = $this->User->find('first', array(\n 'conditions' => array(\n 'User.id' => $this->Auth->user('id')\n ),\n 'recursive' => -1\n ));\n unset($user['User']['password']);\n $user['User']['action'] = 'logout';\n $this->User->save($user['User'], true, array('id'));\n $this->redirect($this->Auth->logout());\n }", "label_name": "CWE-269", "label": "269"} -{"code": " public function putAction(Request $request)\n {\n $this->checkArguments($request);\n $user = $this->tokenStorage->getToken()->getUser();\n $this->userManager->save($request->request->all(), $request->get('locale'), $user->getId(), true);\n\n $user->setFirstName($request->get('firstName'));\n $user->setLastName($request->get('lastName'));\n\n $this->objectManager->flush();\n\n $view = View::create($user);\n\n $context = new Context();\n $context->setGroups(['profile']);\n\n $view->setContext($context);\n\n return $this->viewHandler->handle($view);\n }", "label_name": "CWE-269", "label": "269"} -{"code": " protected function getFile()\n {\n $task_id = $this->request->getIntegerParam('task_id');\n $file_id = $this->request->getIntegerParam('file_id');\n $model = 'projectFileModel';\n\n if ($task_id > 0) {\n $model = 'taskFileModel';\n $project_id = $this->taskFinderModel->getProjectId($task_id);\n\n if ($project_id !== $this->request->getIntegerParam('project_id')) {\n throw new AccessForbiddenException();\n }\n }\n\n $file = $this->$model->getById($file_id);\n\n if (empty($file)) {\n throw new PageNotFoundException();\n }\n\n $file['model'] = $model;\n return $file;\n }", "label_name": "CWE-200", "label": "200"} -{"code": " $name = ucfirst($module->name);\n if (in_array($name, $skipModules)) {\n continue;\n }\n if($name != 'Document'){\n $controllerName = $name.'Controller';\n if(file_exists('protected/modules/'.$module->name.'/controllers/'.$controllerName.'.php')){\n Yii::import(\"application.modules.$module->name.controllers.$controllerName\");\n $controller = new $controllerName($controllerName);\n $model = $controller->modelClass;\n if(class_exists($model)){\n $moduleList[$model] = Yii::t('app', $module->title);\n }\n }\n }\n }\n return $moduleList;\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\tprivate function initData() {\n\n\t\t$this->Set('customer', 0, true, true);\n\t\t$this->Set('admin', 1, true, true);\n\t\t$this->Set('subject', '', true, true);\n\t\t$this->Set('category', '0', true, true);\n\t\t$this->Set('priority', '2', true, true);\n\t\t$this->Set('message', '', true, true);\n\t\t$this->Set('dt', 0, true, true);\n\t\t$this->Set('lastchange', 0, true, true);\n\t\t$this->Set('ip', '', true, true);\n\t\t$this->Set('status', '0', true, true);\n\t\t$this->Set('lastreplier', '0', true, true);\n\t\t$this->Set('by', '0', true, true);\n\t\t$this->Set('answerto', '0', true, true);\n\t\t$this->Set('archived', '0', true, true);\n\t}", "label_name": "CWE-732", "label": "732"} -{"code": " function showByModel() {\n global $order, $template, $db;\n\n expHistory::set('viewable', $this->params);\n $product = new product();\n $model = $product->find(\"first\", 'model=\"' . $this->params['model'] . '\"');\n //eDebug($model);\n $product_type = new $model->product_type($model->id);\n //eDebug($product_type);\n $tpl = $product_type->getForm('show');\n if (!empty($tpl)) $template = new controllertemplate($this, $tpl);\n //eDebug($template);\n $this->grabConfig(); // grab the global config\n assign_to_template(array(\n 'config' => $this->config,\n 'product' => $product_type,\n 'last_category' => $order->lastcat\n ));\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function toolbar() {\n// global $user;\n\n $menu = array();\n\t\t$dirs = array(\n\t\t\tBASE.'framework/modules/administration/menus',\n\t\t\tBASE.'themes/'.DISPLAY_THEME.'/modules/administration/menus'\n\t\t);\n\n\t\tforeach ($dirs as $dir) {\n\t\t if (is_readable($dir)) {\n\t\t\t $dh = opendir($dir);\n\t\t\t while (($file = readdir($dh)) !== false) {\n\t\t\t\t if (substr($file,-4,4) == '.php' && is_readable($dir.'/'.$file) && is_file($dir.'/'.$file)) {\n\t\t\t\t\t $menu[substr($file,0,-4)] = include($dir.'/'.$file);\n if (empty($menu[substr($file,0,-4)])) unset($menu[substr($file,0,-4)]);\n\t\t\t\t }\n\t\t\t }\n\t\t }\n\t\t}\n\n // sort the top level menus alphabetically by filename\n\t\tksort($menu);\t\t\n\t\t$sorted = array();\n\t\tforeach($menu as $m) $sorted[] = $m;\n \n // slingbar position\n if (isset($_COOKIE['slingbar-top'])){\n $top = $_COOKIE['slingbar-top'];\n } else {\n $top = SLINGBAR_TOP;\n }\n \n\t\tassign_to_template(array(\n 'menu'=>(bs3()) ? $sorted : json_encode($sorted),\n \"top\"=>$top\n ));\n }", "label_name": "CWE-74", "label": "74"} -{"code": " function remove() {\r\n global $db;\r\n\r\n $section = $db->selectObject('section', 'id=' . $this->params['id']);\r\n if ($section) {\r\n section::removeLevel($section->id);\r\n $db->decrement('section', 'rank', 1, 'rank > ' . $section->rank . ' AND parent=' . $section->parent);\r\n $section->parent = -1;\r\n $db->updateObject($section, 'section');\r\n expSession::clearAllUsersSessionCache('navigation');\r\n expHistory::back();\r\n } else {\r\n notfoundController::handle_not_authorized();\r\n }\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public function activate_address()\n {\n global $db, $user;\n\n $object = new stdClass();\n $object->id = $this->params['id'];\n $db->setUniqueFlag($object, 'addresses', $this->params['is_what'], \"user_id=\" . $user->id);\n flash(\"message\", gt(\"Successfully updated address.\"));\n expHistory::back(); \n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function confirm()\n {\n $task = $this->getTask();\n $link = $this->getTaskLink();\n\n $this->response->html($this->template->render('task_internal_link/remove', array(\n 'link' => $link,\n 'task' => $task,\n )));\n }", "label_name": "CWE-200", "label": "200"} -{"code": "\tpublic function initializeObject() {\n\t\t$this->initializeFormStateFromRequest();\n\t\t$this->initializeCurrentPageFromRequest();\n\n\t\tif (!$this->isFirstRequest()) {\n\t\t\t$this->processSubmittedFormValues();\n\t\t}\n\t}", "label_name": "CWE-20", "label": "20"} -{"code": " function updateObject($object, $table, $where=null, $identifier='id', $is_revisioned=false) {\n\n if ($is_revisioned) {\n $object->revision_id++;\n //if ($table==\"text\") eDebug($object);\n $res = $this->insertObject($object, $table);\n //if ($table==\"text\") eDebug($object,true); \n $this->trim_revisions($table, $object->$identifier, WORKFLOW_REVISION_LIMIT);\n return $res;\n }\n $sql = \"UPDATE \" . $this->prefix . \"$table SET \";\n foreach (get_object_vars($object) as $var => $val) {\n //We do not want to save any fields that start with an '_'\n //if($is_revisioned && $var=='revision_id') $val++;\n if ($var{0} != '_') {\n if (is_array($val) || is_object($val)) {\n $val = serialize($val); \n $sql .= \"`$var`='\".$val.\"',\";\n } else {\n $sql .= \"`$var`='\" . $this->escapeString($val) . \"',\";\n }\n }\n }\n $sql = substr($sql, 0, -1) . \" WHERE \";\n if ($where != null)\n $sql .= $this->injectProof($where);\n else\n $sql .= \"`\" . $identifier . \"`=\" . $object->$identifier;\n //if ($table == 'text') eDebug($sql,true); \n $res = (@mysqli_query($this->connection, $sql) != false);\n return $res;\n }", "label_name": "CWE-74", "label": "74"} -{"code": "\tpublic function showall() {\n\t expHistory::set('viewable', $this->params);\n\t $hv = new help_version();\n\t //$current_version = $hv->find('first', 'is_current=1');\n\t $ref_version = $hv->find('first', 'version=\\''.$this->help_version.'\\'');\n\n // pagination parameter..hard coded for now.\t \n\t\t$where = $this->aggregateWhereClause();\n\t $where .= 'AND help_version_id='.(empty($ref_version->id)?'0':$ref_version->id);", "label_name": "CWE-74", "label": "74"} -{"code": "\tprivate function _minoredits( $option ) {\n\t\tif ( isset( $option ) && $option == 'exclude' ) {\n\t\t\t$this->addTable( 'revision', 'revision' );\n\t\t\t$this->addWhere( 'revision.rev_minor_edit = 0' );\n\t\t}\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " public function manage_messages() {\n expHistory::set('manageable', $this->params);\n \n $page = new expPaginator(array(\n\t\t\t'model'=>'order_status_messages',\n\t\t\t'where'=>1,\n 'limit'=>10,\n\t\t\t'order'=>'body',\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->params['controller'],\n 'action'=>$this->params['action'],\n\t\t\t//'columns'=>array('Name'=>'title')\n ));\n\n //eDebug($page);\n\t\tassign_to_template(array(\n 'page'=>$page\n ));\n }", "label_name": "CWE-74", "label": "74"} -{"code": " $this->markTestSkipped('Function openssl_random_pseudo_bytes need LibreSSL version >=2.1.5 or Windows system on server');\n }\n }\n\n static::$functions = $functions;\n\n // test various string lengths\n for ($length = 1; $length < 64; $length++) {\n $key1 = $this->security->generateRandomKey($length);\n $this->assertInternalType('string', $key1);\n $this->assertEquals($length, strlen($key1));\n $key2 = $this->security->generateRandomKey($length);\n $this->assertInternalType('string', $key2);\n $this->assertEquals($length, strlen($key2));\n if ($length >= 7) { // avoid random test failure, short strings are likely to collide\n $this->assertNotEquals($key1, $key2);\n }\n }\n\n // test for /dev/urandom, reading larger data to see if loop works properly\n $length = 1024 * 1024;\n $key1 = $this->security->generateRandomKey($length);\n $this->assertInternalType('string', $key1);\n $this->assertEquals($length, strlen($key1));\n $key2 = $this->security->generateRandomKey($length);\n $this->assertInternalType('string', $key2);\n $this->assertEquals($length, strlen($key2));\n $this->assertNotEquals($key1, $key2);\n\n // force /dev/urandom reading loop to deal with chunked data\n // the above test may have read everything in one run.\n // not sure if this can happen in real life but if it does\n // we should be prepared\n static::$fopen = fopen('php://memory', 'rwb');\n $length = 1024 * 1024;\n $key1 = $this->security->generateRandomKey($length);\n $this->assertInternalType('string', $key1);\n $this->assertEquals($length, strlen($key1));\n }", "label_name": "CWE-330", "label": "330"} -{"code": "\tpublic function __construct( \\DPL\\Parameters $parameters, \\Parser $parser ) {\n\t\tparent::__construct( $parameters, $parser );\n\t\t$this->textSeparator = $parameters->getParameter( 'inlinetext' );\n\t\t$listSeparators = $parameters->getParameter( 'listseparators' );\n\t\tif ( isset( $listSeparators[0] ) ) {\n\t\t\t$this->listStart = $listSeparators[0];\n\t\t}\n\t\tif ( isset( $listSeparators[1] ) ) {\n\t\t\t$this->itemStart = $listSeparators[1];\n\t\t}\n\t\tif ( isset( $listSeparators[2] ) ) {\n\t\t\t$this->itemEnd = $listSeparators[2];\n\t\t}\n\t\tif ( isset( $listSeparators[3] ) ) {\n\t\t\t$this->listEnd = $listSeparators[3];\n\t\t}\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": "\tpublic function myaddressbook() {\n\t\tglobal $user;\n\n\t\t// check if the user is logged in.\n\t\texpQueue::flashIfNotLoggedIn('message',gt('You must be logged in to manage your address book.'));\n if (!$user->isAdmin() && $this->params['user_id'] != $user->id) {\n unset($this->params['user_id']);\n }\n\t\texpHistory::set('viewable', $this->params);\n\t\t$userid = (empty($this->params['user_id'])) ? $user->id : $this->params['user_id'];\n\t\tassign_to_template(array(\n 'addresses'=>$this->address->find('all', 'user_id='.$userid)\n ));\n\t}", "label_name": "CWE-200", "label": "200"} -{"code": " public function execute(&$params){\n $options = &$this->config['options'];\n $notif = new Notification;\n $notif->user = $this->parseOption('user', $params);\n $notif->createdBy = 'API';\n $notif->createDate = time();\n // file_put_contents('triggerLog.txt',\"\\n\".$notif->user,FILE_APPEND);\n // if($this->parseOption('type',$params) == 'auto') {\n // if(!isset($params['model']))\n // return false;\n // $notif->modelType = get_class($params['model']);\n // $notif->modelId = $params['model']->id;\n // $notif->type = $this->getNotifType();\n // } else {\n $notif->type = 'custom';\n $notif->text = $this->parseOption('text', $params);\n // }\n\n if ($notif->save()) {\n return array (true, \"\");\n } else {\n return array(false, array_shift($notif->getErrors()));\n }\n\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function save($check_notify = false)\n {\n if (isset($_POST['email_recipients']) && is_array($_POST['email_recipients'])) {\n $this->email_recipients = base64_encode(serialize($_POST['email_recipients']));\n }\n\n return parent::save($check_notify);\n }", "label_name": "CWE-863", "label": "863"} -{"code": " public static function restoreX2WebUser () {\n if (isset (self::$_oldUserComponent)) {\n Yii::app()->setComponent ('user', self::$_oldUserComponent);\n } else {\n throw new CException ('X2WebUser component could not be restored'); \n }\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\t\t\treturn \\DPL\\Variables::setVarDefault( $args );\n\t\t}\n\t\treturn \\DPL\\Variables::getVar( $cmd );\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " public function update()\n {\n $project = $this->getProject();\n\n $values = $this->request->getValues();\n list($valid, $errors) = $this->swimlaneValidator->validateModification($values);\n\n if ($valid) {\n if ($this->swimlaneModel->update($values['id'], $values)) {\n $this->flash->success(t('Swimlane updated successfully.'));\n return $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));\n } else {\n $errors = array('name' => array(t('Another swimlane with the same name exists in the project')));\n }\n }\n\n return $this->edit($values, $errors);\n }", "label_name": "CWE-200", "label": "200"} -{"code": " static function description() { return gt(\"Places navigation links/menus on the page.\"); }\r", "label_name": "CWE-74", "label": "74"} -{"code": "\tpublic function init() {\r\n\t\tglobal $geo_mashup_options, $pagenow;\r\n\r\n\t\t// Enable this interface when the option is set and we're on a destination page\r\n\t\t$enabled = is_admin() &&\r\n\t\t\t$geo_mashup_options->get( 'overall', 'located_object_name', 'user' ) == 'true' &&\r\n\t\t\tpreg_match( '/(user-edit|profile).php/', $pagenow );\r\n\t\t$enabled = apply_filters( 'geo_mashup_load_user_editor', $enabled );\r\n\r\n\t\t// If enabled, register all the interface elements\r\n\t\tif ( $enabled ) { \r\n\r\n\t\t\t// Form generation\r\n\t\t\tadd_action( 'show_user_profile', array( &$this, 'print_form' ) );\r\n\t\t\tadd_action( 'edit_user_profile', array( &$this, 'print_form' ) );\r\n\t\t\t// MAYBEDO: add location to registration page?\r\n\r\n\t\t\t// Form processing\r\n\t\t\tadd_action( 'personal_options_update', array( &$this, 'save_user'));\r\n\t\t\tadd_action( 'edit_user_profile_update', array( &$this, 'save_user'));\r\n\r\n\t\t\t$this->enqueue_form_client_items();\r\n\t\t}\r\n\t}\r", "label_name": "CWE-20", "label": "20"} -{"code": " $evs = $this->event->find('all', \"id=\" . $edate->event_id . $featuresql);\r\n foreach ($evs as $key=>$event) {\r\n if ($condense) {\r\n $eventid = $event->id;\r\n $multiday_event = array_filter($events, create_function('$event', 'global $eventid; return $event->id === $eventid;'));\r\n if (!empty($multiday_event)) {\r\n unset($evs[$key]);\r\n continue;\r\n }\r\n }\r\n $evs[$key]->eventstart += $edate->date;\r\n $evs[$key]->eventend += $edate->date;\r\n $evs[$key]->date_id = $edate->id;\r\n if (!empty($event->expCat)) {\r\n $catcolor = empty($event->expCat[0]->color) ? null : trim($event->expCat[0]->color);\r\n// if (substr($catcolor,0,1)=='#') $catcolor = '\" style=\"color:'.$catcolor.';';\r\n $evs[$key]->color = $catcolor;\r\n }\r\n }\r\n if (count($events) < 500) { // magic number to not crash loop?\r\n $events = array_merge($events, $evs);\r\n } else {\r\n// $evs[$key]->title = gt('Too many events to list').', '.(count($edates)-count($events)).' '.gt('not displayed!');\r\n// $events = array_merge($events, $evs);\r\n flash('notice',gt('Too many events to list').', '.(count($edates)-count($events)).' '.gt('not displayed!'));\r\n break; // keep from breaking system by too much data\r\n }\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public function checkRedirect(RequestInterface $request, array $options, ResponseInterface $response)\n {\n if (\\strpos((string) $response->getStatusCode(), '3') !== 0\n || !$response->hasHeader('Location')\n ) {\n return $response;\n }\n\n $this->guardMax($request, $response, $options);\n $nextRequest = $this->modifyRequest($request, $options, $response);\n\n // If authorization is handled by curl, unset it if host is different.\n if ($request->getUri()->getHost() !== $nextRequest->getUri()->getHost()\n && defined('\\CURLOPT_HTTPAUTH')\n ) {\n unset(\n $options['curl'][\\CURLOPT_HTTPAUTH],\n $options['curl'][\\CURLOPT_USERPWD]\n );\n }\n\n if (isset($options['allow_redirects']['on_redirect'])) {\n ($options['allow_redirects']['on_redirect'])(\n $request,\n $response,\n $nextRequest->getUri()\n );\n }\n\n $promise = $this($nextRequest, $options);\n\n // Add headers to be able to track history of redirects.\n if (!empty($options['allow_redirects']['track_redirects'])) {\n return $this->withTracking(\n $promise,\n (string) $nextRequest->getUri(),\n $response->getStatusCode()\n );\n }\n\n return $promise;\n }", "label_name": "CWE-200", "label": "200"} -{"code": " private function _verify($public_key_or_secret, $expected_alg = null) {\n $segments = explode('.', $this->raw);\n $signature_base_string = implode('.', array($segments[0], $segments[1]));\n if (!$expected_alg) {\n # NOTE: might better to warn here\n $expected_alg = $this->header['alg'];\n }\n switch ($expected_alg) {\n case 'HS256':\n case 'HS384':\n case 'HS512':\n return $this->signature === hash_hmac($this->digest(), $signature_base_string, $public_key_or_secret, true);\n case 'RS256':\n case 'RS384':\n case 'RS512':\n return $this->rsa($public_key_or_secret, RSA::SIGNATURE_PKCS1)->verify($signature_base_string, $this->signature);\n case 'ES256':\n case 'ES384':\n case 'ES512':\n throw new JOSE_Exception_UnexpectedAlgorithm('Algorithm not supported');\n case 'PS256':\n case 'PS384':\n case 'PS512':\n return $this->rsa($public_key_or_secret, RSA::SIGNATURE_PSS)->verify($signature_base_string, $this->signature);\n default:\n throw new JOSE_Exception_UnexpectedAlgorithm('Unknown algorithm');\n }\n }", "label_name": "CWE-200", "label": "200"} -{"code": " protected function markCompleted($endStatus, ServiceResponse $serviceResponse, $gatewayMessage)\n {\n parent::markCompleted($endStatus, $serviceResponse, $gatewayMessage);\n $this->createMessage(Message\\PurchasedResponse::class, $gatewayMessage);\n ErrorHandling::safeExtend($this->payment, 'onCaptured', $serviceResponse);\n }", "label_name": "CWE-436", "label": "436"} -{"code": " private function _getMetaTags()\n {\n $retval = '';\n $retval .= '';\n $retval .= '';\n $retval .= '';\n return $retval;\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\tpublic function formatItem( Article $article, $pageText = null ) {\n\t\t$item = '';\n\n\t\tif ( $pageText !== null ) {\n\t\t\t//Include parsed/processed wiki markup content after each item before the closing tag.\n\t\t\t$item .= $pageText;\n\t\t}\n\n\t\t$item = $this->getItemStart() . $item . $this->getItemEnd();\n\n\t\t$item = $this->replaceTagParameters( $item, $article );\n\n\t\treturn $item;\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": "\tpublic function enqueue_scripts() {\r\n\t\tglobal $geo_mashup_options, $pagenow, $post;\r\n\r\n\t\t// The location editor works only on posts\r\n\t\tif ( empty( $post ) )\r\n\t\t\treturn null;\r\n\r\n\t\t$load_location_editor = (\r\n\t\t\t\tis_admin() and\r\n\t\t\t\tpreg_match( '/(post|page)(-new|).php/', $pagenow ) and\r\n\t\t\t\tin_array( $post->post_type, $geo_mashup_options->get( 'overall', 'located_post_types' ) )\r\n\t\t\t\t);\r\n\t\t$load_location_editor = apply_filters( 'geo_mashup_load_location_editor', $load_location_editor );\r\n\r\n\t\t// If we're on a post editing page, queue up the form interface elements\r\n\t\tif ( $load_location_editor ) {\r\n\r\n\t\t\t$this->enqueue_form_client_items();\r\n\r\n\t\t} \r\n\t}\r", "label_name": "CWE-20", "label": "20"} -{"code": " foreach ($page as $pageperm) {\r\n if (!empty($pageperm['manage'])) return true;\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": "function mci_account_get_array_by_id( $p_user_id ) {\n\t$t_result = array();\n\t$t_result['id'] = $p_user_id;\n\n\tif( user_exists( $p_user_id ) ) {\n\t\t$t_result['name'] = user_get_field( $p_user_id, 'username' );\n\t\t$t_dummy = user_get_field( $p_user_id, 'realname' );\n\n\t\tif( !empty( $t_dummy ) ) {\n\t\t\t$t_result['real_name'] = $t_dummy;\n\t\t}\n\n\t\t$t_dummy = user_get_field( $p_user_id, 'email' );\n\n\t\tif( !empty( $t_dummy ) ) {\n\t\t\t$t_result['email'] = $t_dummy;\n\t\t}\n\t}\n\treturn $t_result;\n}", "label_name": "CWE-200", "label": "200"} -{"code": "\tprivate function getFullOutput( $totalResults = false, $skipHeaderFooter = true ) {\n\t\tif ( !$skipHeaderFooter ) {\n\t\t\t$header = '';\n\t\t\t$footer = '';\n\t\t\t//Only override header and footers if specified.\n\t\t\t$_headerType = $this->getHeaderFooterType( 'header', $totalResults );\n\t\t\tif ( $_headerType !== false ) {\n\t\t\t\t$header = $this->parameters->getParameter( $_headerType );\n\t\t\t}\n\t\t\t$_footerType = $this->getHeaderFooterType( 'footer', $totalResults );\n\t\t\tif ( $_footerType !== false ) {\n\t\t\t\t$footer = $this->parameters->getParameter( $_footerType );\n\t\t\t}\n\n\t\t\t$this->setHeader( $header );\n\t\t\t$this->setFooter( $footer );\n\t\t}\n\n\t\tif ( !$totalResults && !strlen( $this->getHeader() ) && !strlen( $this->getFooter() ) ) {\n\t\t\t$this->logger->addMessage( \\DynamicPageListHooks::WARN_NORESULTS );\n\t\t}\n\t\t$messages = $this->logger->getMessages( false );\n\n\t\treturn ( count( $messages ) ? implode( \"
\\n\", $messages ) : null ) . $this->getHeader() . $this->getOutput() . $this->getFooter();\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": "\tpublic function Delete() {\n\n\t\t// Delete \"main\" ticket\n\t\t$del_stmt = Database::prepare('\n\t\t\tDELETE FROM `' . TABLE_PANEL_TICKETS . '` WHERE `id` = :tid'\n\t\t);\n\t\tDatabase::pexecute($del_stmt, array('tid' => $this->tid));\n\n\t\t// Delete \"answers\" to ticket\"\n\t\t$del_stmt = Database::prepare('\n\t\t\tDELETE FROM `' . TABLE_PANEL_TICKETS . '` WHERE `answerto` = :tid'\n\t\t);\n\t\tDatabase::pexecute($del_stmt, array('tid' => $this->tid));\n\t\treturn true;\n\t}", "label_name": "CWE-732", "label": "732"} -{"code": " static function displayname() {\n return gt(\"e-Commerce Category Manager\");\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function __construct($exceptions = false) {\n $this->exceptions = ($exceptions == true);\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\tfunction execute( $par ) {\n\t\t$this->setHeaders();\n\t\t$this->outputHeader();\n\n\t\t$pager = new GlobalNewFilesPager();\n\t\t\n\t\t$this->getOutput()->addParserOutputContent( $pager->getFullOutput() );\n\t}", "label_name": "CWE-20", "label": "20"} -{"code": " function searchName() {\r\n return gt(\"Calendar Event\");\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": "\tpublic function getPurchaseOrderByJSON() {\n\n\t\tif(!empty($this->params['vendor'])) {\n\t\t\t$purchase_orders = $this->purchase_order->find('all', 'vendor_id=' . $this->params['vendor']);\n\t\t} else {\n\t\t\t$purchase_orders = $this->purchase_order->find('all');\n\t\t}\n\n\t\techo json_encode($purchase_orders);\n\t}", "label_name": "CWE-20", "label": "20"} -{"code": " function reset_stats() {\n// global $db;\n\n // reset the counters\n// $db->sql ('UPDATE '.$db->prefix.'banner SET impressions=0 WHERE 1');\n banner::resetImpressions();\n// $db->sql ('UPDATE '.$db->prefix.'banner SET clicks=0 WHERE 1');\n banner::resetClicks();\n \n // let the user know we did stuff. \n flash('message', gt(\"Banner statistics reset.\"));\n expHistory::back();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function Connected() {\n if(!empty($this->smtp_conn)) {\n $sock_status = socket_get_status($this->smtp_conn);\n if($sock_status[\"eof\"]) {\n // the socket is valid but we are not connected\n if($this->do_debug >= 1) {\n $this->edebug(\"SMTP -> NOTICE:\" . $this->CRLF . \"EOF caught while checking if connected\");\n }\n $this->Close();\n return false;\n }\n return true; // everything looks good\n }\n return false;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function editAlt() {\n global $user; \n $file = new expFile($this->params['id']);\n if ($user->id==$file->poster || $user->isAdmin()) {\n $file->alt = $this->params['newValue'];\n $file->save();\n $ar = new expAjaxReply(200, gt('Your alt was updated successfully'), $file);\n } else {\n $ar = new expAjaxReply(300, gt(\"You didn't create this file, so you can't edit it.\"));\n }\n $ar->send();\n echo json_encode($file); //FIXME we exit before hitting this\n } ", "label_name": "CWE-74", "label": "74"} -{"code": " $comments->records[$key]->avatar = $db->selectObject('user_avatar',\"user_id='\".$record->poster.\"'\");\n }\n\n if (empty($this->params['config']['disable_nested_comments'])) $comments->records = self::arrangecomments($comments->records);\n // eDebug($sql, true);\n \n // count the unapproved comments\n if ($require_approval == 1 && $user->isAdmin()) {\n $sql = 'SELECT count(com.id) as c FROM '.$db->prefix.'expComments com ';\n $sql .= 'JOIN '.$db->prefix.'content_expComments cnt ON com.id=cnt.expcomments_id ';\n $sql .= 'WHERE cnt.content_id='.$this->params['content_id'].\" AND cnt.content_type='\".$this->params['content_type'].\"' \";\n $sql .= 'AND com.approved=0';\n $unapproved = $db->countObjectsBySql($sql);\n } else {\n $unapproved = 0;\n } \n \n $this->config = $this->params['config'];\n $type = !empty($this->params['type']) ? $this->params['type'] : gt('Comment');\n $ratings = !empty($this->params['ratings']) ? true : false;\n\n assign_to_template(array(\n 'comments'=>$comments,\n 'config'=>$this->params['config'],\n 'unapproved'=>$unapproved,\n\t\t\t'content_id'=>$this->params['content_id'], \n\t\t\t'content_type'=>$this->params['content_type'],\n\t\t\t'user'=>$user,\n\t\t\t'hideform'=>$this->params['hideform'],\n\t\t\t'hidecomments'=>$this->params['hidecomments'],\n\t\t\t'title'=>$this->params['title'],\n\t\t\t'formtitle'=>$this->params['formtitle'],\n 'type'=>$type,\n 'ratings'=>$ratings,\n 'require_login'=>$require_login,\n 'require_approval'=>$require_approval,\n 'require_notification'=>$require_notification,\n 'notification_email'=>$notification_email,\n\t\t));\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": " public function Login ($username = '', $password = '') {\n if ($this->connected == false) {\n $this->error = 'Not connected to POP3 server';\n\n if ($this->do_debug >= 1) {\n $this->displayErrors();\n }\n }\n\n if (empty($username)) {\n $username = $this->username;\n }\n\n if (empty($password)) {\n $password = $this->password;\n }\n\n $pop_username = \"USER $username\" . $this->CRLF;\n $pop_password = \"PASS $password\" . $this->CRLF;\n\n // Send the Username\n $this->sendString($pop_username);\n $pop3_response = $this->getResponse();\n\n if ($this->checkResponse($pop3_response)) {\n // Send the Password\n $this->sendString($pop_password);\n $pop3_response = $this->getResponse();\n\n if ($this->checkResponse($pop3_response)) {\n return true;\n }\n }\n return false;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function checkRedirect(RequestInterface $request, array $options, ResponseInterface $response)\n {\n if (\\strpos((string) $response->getStatusCode(), '3') !== 0\n || !$response->hasHeader('Location')\n ) {\n return $response;\n }\n\n $this->guardMax($request, $response, $options);\n $nextRequest = $this->modifyRequest($request, $options, $response);\n\n // If authorization is handled by curl, unset it if host is different.\n if ($request->getUri()->getHost() !== $nextRequest->getUri()->getHost()\n && defined('\\CURLOPT_HTTPAUTH')\n ) {\n unset(\n $options['curl'][\\CURLOPT_HTTPAUTH],\n $options['curl'][\\CURLOPT_USERPWD]\n );\n }\n\n if (isset($options['allow_redirects']['on_redirect'])) {\n ($options['allow_redirects']['on_redirect'])(\n $request,\n $response,\n $nextRequest->getUri()\n );\n }\n\n $promise = $this($nextRequest, $options);\n\n // Add headers to be able to track history of redirects.\n if (!empty($options['allow_redirects']['track_redirects'])) {\n return $this->withTracking(\n $promise,\n (string) $nextRequest->getUri(),\n $response->getStatusCode()\n );\n }\n\n return $promise;\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public function crossOriginRedirectProvider()\n {\n return [\n ['http://example.com?a=b', 'http://test.com/', false],\n ['https://example.com?a=b', 'https://test.com/', false],\n ['http://example.com?a=b', 'https://test.com/', false],\n ['https://example.com?a=b', 'http://test.com/', false],\n ['http://example.com?a=b', 'http://example.com/', true],\n ['https://example.com?a=b', 'https://example.com/', true],\n ['http://example.com?a=b', 'https://example.com/', true],\n ['https://example.com?a=b', 'http://example.com/', false],\n ];\n }", "label_name": "CWE-200", "label": "200"} -{"code": "\tprivate function _hiddencategories( $option ) {\n\t\t//@TODO: Unfinished functionality! Never implemented by original author.\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " static function displayname() { return gt(\"Navigation\"); }\r", "label_name": "CWE-74", "label": "74"} -{"code": " function build_daterange_sql($timestamp, $endtimestamp=null, $field='date', $multiday=false) {\r\n if (empty($endtimestamp)) {\r\n $date_sql = \"((\".$field.\" >= \" . expDateTime::startOfDayTimestamp($timestamp) . \" AND \".$field.\" <= \" . expDateTime::endOfDayTimestamp($timestamp) . \")\";\r\n } else {\r\n $date_sql = \"((\".$field.\" >= \" . expDateTime::startOfDayTimestamp($timestamp) . \" AND \".$field.\" <= \" . expDateTime::endOfDayTimestamp($endtimestamp) . \")\";\r\n }\r\n if ($multiday)\r\n $date_sql .= \" OR (\" . expDateTime::startOfDayTimestamp($timestamp) . \" BETWEEN \".$field.\" AND dateFinished)\";\r\n $date_sql .= \")\";\r\n return $date_sql;\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": "\tprivate function _namespace( $option ) {\n\t\t$option === 0 ?? $option = '0';\n\t\tif ( is_array( $option ) && count( $option ) ) {\n\t\t\tif ( $this->parameters->getParameter( 'openreferences' ) ) {\n\t\t\t\t$this->addWhere(\n\t\t\t\t\t[\n\t\t\t\t\t\t\"{$this->tableNames['pagelinks']}.pl_namespace\"\t=> $option\n\t\t\t\t\t]\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\t$this->addWhere(\n\t\t\t\t\t[\n\t\t\t\t\t\t\"{$this->tableNames['page']}.page_namespace\"\t=> $option\n\t\t\t\t\t]\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " foreach ($week as $dayNum => $day) {\r\n if ($dayNum == $now['mday']) {\r\n $currentweek = $weekNum;\r\n }\r\n if ($dayNum <= $endofmonth) {\r\n// $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;\r\n $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;\r\n }\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public function create_file() {\n if (!AuthUser::hasPermission('file_manager_mkfile')) {\n Flash::set('error', __('You do not have sufficient permissions to create a file.'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n \n // CSRF checks\n if (isset($_POST['csrf_token'])) {\n $csrf_token = $_POST['csrf_token'];\n if (!SecureToken::validateToken($csrf_token, BASE_URL.'plugin/file_manager/create_file')) {\n Flash::set('error', __('Invalid CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n }\n else {\n Flash::set('error', __('No CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n\n $data = $_POST['file'];\n\n $path = str_replace('..', '', $data['path']);\n $filename = str_replace('..', '', $data['name']);\n $file = FILES_DIR . DS . $path . DS . $filename;\n\n if (file_put_contents($file, '') !== false) {\n $mode = Plugin::getSetting('filemode', 'file_manager');\n chmod($file, octdec($mode));\n } else {\n Flash::set('error', __('File :name has not been created!', array(':name' => $filename)));\n }\n redirect(get_url('plugin/file_manager/browse/' . $path));\n }", "label_name": "CWE-20", "label": "20"} -{"code": " return $fa->nameGlyph($icons, 'icon-');\r\n }\r\n } else {\r\n return array();\r\n }\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " private function sendString ($string) {\n $bytes_sent = fwrite($this->pop_conn, $string, strlen($string));\n\n return $bytes_sent;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function AddReplyTo($address, $name = '') {\n return $this->AddAnAddress('Reply-To', $address, $name);\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\tprivate function getOutput() {\n\t\t//@TODO: 2015-08-28 Consider calling $this->replaceVariables() here. Might cause issues with text returned in the results.\n\t\treturn $this->output;\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": "\tpublic function delete() {\n\t global $db;\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n// $require_login = empty($this->params['require_login']) ? COMMENTS_REQUIRE_LOGIN : $this->params['require_login'];\n// $require_approval = empty($this->params['require_approval']) ? COMMENTS_REQUIRE_APPROVAL : $this->params['require_approval'];\n// $require_notification = empty($this->params['require_notification']) ? COMMENTS_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n// $notification_email = empty($this->params['notification_email']) ? COMMENTS_NOTIFICATION_EMAIL : $this->params['notification_email'];\n\t \n\t if (empty($this->params['id'])) {\n\t flash('error', gt('Missing id for the comment you would like to delete'));\n\t expHistory::back();\n\t }\n\t \n\t // delete the comment\n $comment = new expComment($this->params['id']);\n $comment->delete();\n \n // delete the association too\n $db->delete($comment->attachable_table, 'expcomments_id='.$this->params['id']); \n \n // send the user back where they came from.\n expHistory::back();\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": " public static function hasChildren($i) {\r\n global $sections;\r\n\r\n if (($i + 1) >= count($sections)) return false;\r\n return ($sections[$i]->depth < $sections[$i + 1]->depth) ? true : false;\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " function searchByModelForm() {\n // get the search terms\n $terms = $this->params['search_string'];\n\n $sql = \"model like '%\" . $terms . \"%'\";\n\n $limit = !empty($this->config['limit']) ? $this->config['limit'] : 10;\n $page = new expPaginator(array(\n 'model' => 'product',\n 'where' => $sql,\n 'limit' => !empty($this->config['pagination_default']) ? $this->config['pagination_default'] : $limit,\n 'order' => 'title',\n 'dir' => 'DESC',\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller' => $this->params['controller'],\n 'action' => $this->params['action'],\n 'columns' => array(\n gt('Model #') => 'model',\n gt('Product Name') => 'title',\n gt('Price') => 'base_price'\n ),\n ));\n\n assign_to_template(array(\n 'page' => $page,\n 'terms' => $terms\n ));\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\t function update_upcharge() {\n $this->loc->src = \"@globalstoresettings\";\n $config = new expConfig($this->loc);\n\t\t$this->config = $config->config;\n\t\t\n\t\t//This will make sure that only the country or region that given a rate value will be saved in the db\n\t\t$upcharge = array();\n\t\tforeach($this->params['upcharge'] as $key => $item) {\n\t\t\tif(!empty($item)) {\n\t\t\t\t$upcharge[$key] = $item;\n\t\t\t}\n\t\t}\n\t\t$this->config['upcharge'] = $upcharge;\n\t\t\n $config->update(array('config'=>$this->config));\n flash('message', gt('Configuration updated'));\n expHistory::back();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " private function getStateId(string $state, string $machine)\n {\n return $this->getContainer()->get(Connection::class)\n ->fetchColumn('\n SELECT LOWER(HEX(state_machine_state.id))\n FROM state_machine_state\n INNER JOIN state_machine\n ON state_machine.id = state_machine_state.state_machine_id\n AND state_machine.technical_name = :machine\n WHERE state_machine_state.technical_name = :state\n ', [\n 'state' => $state,\n 'machine' => $machine,\n ]);\n }", "label_name": "CWE-732", "label": "732"} -{"code": " function login($redirectCallback = null)\n {\n $aConf = $GLOBALS['_MAX']['CONF'];\n\n if (!is_callable($redirectCallback)) {\n // Set the default callback\n $redirectCallback = array('OA_Auth', 'checkRedirect');\n }\n\n if (call_user_func($redirectCallback)) {\n header('location: http://'.$aConf['webpath']['admin']);\n exit();\n }\n\n if (defined('OA_SKIP_LOGIN')) {\n return OA_Auth::getFakeSessionData();\n }\n\n if (OA_Auth::suppliedCredentials()) {\n $doUser = OA_Auth::authenticateUser();\n\n if (!$doUser) {\n sleep(3);\n OA_Auth::restart($GLOBALS['strUsernameOrPasswordWrong']);\n }\n\n return OA_Auth::getSessionData($doUser);\n }\n\n OA_Auth::restart();\n }", "label_name": "CWE-287", "label": "287"} -{"code": "function XMLRPCaddResourceGroupPriv($name, $type, $nodeid, $permissions){\n require_once(\".ht-inc/privileges.php\");\n global $user;\n\n if(! checkUserHasPriv(\"resourceGrant\", $user['id'], $nodeid)){\n return array('status' => 'error',\n 'errorcode' => 53,\n 'errormsg' => 'Unable to add resource group to this node');\n }\n\n if($typeid = getResourceTypeID($type)){\n if(!checkForGroupName($name, 'resource', '', $typeid)){\n return array('status' => 'error',\n 'errorcode' => 28,\n 'errormsg' => 'resource group does not exist');\n }\n $perms = explode(':', $permissions);\n updateResourcePrivs(\"$type/$name\", $nodeid, $perms, array());\n return array('status' => 'success');\n } else {\n return array('status' => 'error',\n 'errorcode' => 56,\n 'errormsg' => 'Invalid resource type');\n }\n}", "label_name": "CWE-20", "label": "20"} -{"code": " public static function getHost() {\n\n if (isset($_SERVER['HTTP_HOST'])) {\n $site_address = (erLhcoreClassSystem::$httpsMode == true ? 'https:' : 'http:') . '//' . $_SERVER['HTTP_HOST'] ;\n } else if (class_exists('erLhcoreClassInstance')) {\n $site_address = 'https://' . erLhcoreClassInstance::$instanceChat->address . '.' . erConfigClassLhConfig::getInstance()->getSetting( 'site', 'seller_domain');\n } else if (class_exists('erLhcoreClassExtensionLhcphpresque')) {\n $site_address = erLhcoreClassModule::getExtensionInstance('erLhcoreClassExtensionLhcphpresque')->settings['site_address'];\n } else {\n $site_address = '';\n }\n\n return $site_address;\n }", "label_name": "CWE-116", "label": "116"} -{"code": "\tpublic function delete_version() {\n\t if (empty($this->params['id'])) {\n\t flash('error', gt('The version you are trying to delete could not be found'));\n\t }\n\t \n\t // get the version\n\t $version = new help_version($this->params['id']);\n\t if (empty($version->id)) {\n\t flash('error', gt('The version you are trying to delete could not be found'));\n\t }\n\t \n\t // if we have errors than lets get outta here!\n\t if (!expQueue::isQueueEmpty('error')) expHistory::back();\n\t \n\t // delete the version\n\t $version->delete();\n\t \n\t expSession::un_set('help-version');\n\n\t flash('message', gt('Deleted version').' '.$version->version.' '.gt('and all documents in that version.'));\n\t expHistory::back();\t \n\t}", "label_name": "CWE-74", "label": "74"} -{"code": " function manage() {\r\n global $db, $router, $user;\r\n\r\n expHistory::set('manageable', $router->params);\r\n assign_to_template(array(\r\n 'canManageStandalones' => self::canManageStandalones(),\r\n 'sasections' => $db->selectObjects('section', 'parent=-1'),\r\n 'user' => $user,\r\n// 'canManagePagesets' => $user->isAdmin(),\r\n// 'templates' => $db->selectObjects('section_template', 'parent=0'),\r\n ));\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": "function XMLRPCgetUserGroupPrivs($name, $affiliation, $nodeid){\n require_once(\".ht-inc/privileges.php\");\n global $user;\n\n if(! checkUserHasPriv(\"userGrant\", $user['id'], $nodeid)){\n return array('status' => 'error',\n 'errorcode' => 53,\n 'errormsg' => 'Unable to add resource group to this node');\n }\n\n\t$validate = array('name' => $name,\n\t 'affiliation' => $affiliation);\n\t$rc = validateAPIgroupInput($validate, 1);\n\tif($rc['status'] == 'error')\n\t\treturn $rc;\n\n $privileges = array();\n $nodePrivileges = getNodePrivileges($nodeid, 'usergroups');\n $cascadedNodePrivileges = getNodeCascadePrivileges($nodeid, 'usergroups'); \n $cngp = $cascadedNodePrivileges['usergroups'];\n $ngp = $nodePrivileges['usergroups'];\n if(array_key_exists($name, $cngp)){\n foreach($cngp[$name]['privs'] as $p){\n if(! array_key_exists($name, $ngp) ||\n ! in_array(\"block\", $ngp[$name]['privs'])){\n array_push($privileges, $p);\n }\n }\n }\n if(array_key_exists($name, $ngp)){\n foreach($ngp[$name]['privs'] as $p){\n if($p != \"block\"){\n array_push($privileges, $p);\n }\n }\n }\n\n return array(\n 'status' => 'success',\n 'privileges' => array_unique($privileges));\n}", "label_name": "CWE-20", "label": "20"} -{"code": " $section = new section(intval($page));\r\n if ($section) {\r\n// self::deleteLevel($section->id);\r\n $section->delete();\r\n }\r\n }\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " private function SendHello($hello, $host) {\n fputs($this->smtp_conn, $hello . \" \" . $host . $this->CRLF);\n\n $rply = $this->get_lines();\n $code = substr($rply,0,3);\n\n if($this->do_debug >= 2) {\n $this->edebug(\"SMTP -> FROM SERVER: \" . $rply . $this->CRLF . '
');\n }\n\n if($code != 250) {\n $this->error =\n array(\"error\" => $hello . \" not accepted from server\",\n \"smtp_code\" => $code,\n \"smtp_msg\" => substr($rply,4));\n if($this->do_debug >= 1) {\n $this->edebug(\"SMTP -> ERROR: \" . $this->error[\"error\"] . \": \" . $rply . $this->CRLF . '
');\n }\n return false;\n }\n\n $this->helo_rply = $rply;\n\n return true;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function confirm() {\n global $db;\n \n // make sure we have what we need.\n if (empty($this->params['key'])) expQueue::flashAndFlow('error', gt('The security key for account was not supplied.'));\n if (empty($this->params['id'])) expQueue::flashAndFlow('error', gt('The subscriber id for account was not supplied.'));\n \n // verify the id/key pair \n $id = $db->selectValue('subscribers','id', 'id='.$this->params['id'].' AND hash=\"'.$this->params['key'].'\"');\n if (empty($id)) expQueue::flashAndFlow('error', gt('We could not find any subscriptions matching the ID and Key you provided.'));\n \n // activate this users pending subscriptions\n $sub = new stdClass();\n $sub->enabled = 1;\n $db->updateObject($sub, 'expeAlerts_subscribers', 'subscribers_id='.$id);\n \n // find the users active subscriptions\n $ealerts = expeAlerts::getBySubscriber($id);\n assign_to_template(array(\n 'ealerts'=>$ealerts\n ));\n }", "label_name": "CWE-74", "label": "74"} -{"code": " function remove() {\r\n global $db;\r\n\r\n $section = $db->selectObject('section', 'id=' . $this->params['id']);\r\n if ($section) {\r\n section::removeLevel($section->id);\r\n $db->decrement('section', 'rank', 1, 'rank > ' . $section->rank . ' AND parent=' . $section->parent);\r\n $section->parent = -1;\r\n $db->updateObject($section, 'section');\r\n expSession::clearAllUsersSessionCache('navigation');\r\n expHistory::back();\r\n } else {\r\n notfoundController::handle_not_authorized();\r\n }\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public function save($check_notify = false)\n {\n if (isset($_POST['email_recipients']) && is_array($_POST['email_recipients'])) {\n $this->email_recipients = base64_encode(serialize($_POST['email_recipients']));\n }\n\n return parent::save($check_notify);\n }", "label_name": "CWE-287", "label": "287"} -{"code": " private static function _aesEncrypt($data, $secret)\n {\n if (!is_string($data)) {\n throw new \\InvalidArgumentException('Input parameter \"$data\" must be a string.');\n }\n\n if (!function_exists(\"openssl_encrypt\")) {\n throw new \\SimpleSAML_Error_Exception('The openssl PHP module is not loaded.');\n }\n\n $raw = defined('OPENSSL_RAW_DATA') ? OPENSSL_RAW_DATA : true;\n $key = openssl_digest($secret, 'sha256');\n $method = 'AES-256-CBC';\n $ivSize = 16;\n $iv = substr($key, 0, $ivSize);\n\n return $iv.openssl_encrypt($data, $method, $key, $raw, $iv);\n }", "label_name": "CWE-326", "label": "326"} -{"code": " public function testClientIpIsAlwaysLocalhostForForwardedRequests()\n {\n $this->setNextResponse();\n $this->request('GET', '/', array('REMOTE_ADDR' => '10.0.0.1'));\n\n $this->assertEquals('127.0.0.1', $this->kernel->getBackendRequest()->server->get('REMOTE_ADDR'));\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\tpublic function goingForthAndBackStoresFormValuesOfSecondPageAndTriggersValidationOnlyWhenGoingForward() {\n\t\t$this->browser->request('http://localhost/test/form/simpleform/ThreePageFormWithValidation');\n\n\t\t$this->gotoNextFormPage($this->browser->getForm());\n\n\t\t$form = $this->browser->getForm();\n\t\t$form['--three-page-form-with-validation']['text2-1']->setValue('My Text on the second page');\n\t\t$this->gotoPreviousFormPage($form);\n\t\t$this->gotoNextFormPage($this->browser->getForm());\n\t\t$r = $this->gotoNextFormPage($this->browser->getForm());\n\n\t\t$this->assertSame(' error', $this->browser->getCrawler()->filterXPath('//*[contains(@class,\"error\")]//input[@id=\"three-page-form-with-validation-text2-1\"]')->attr('class'));\n\t\t$form = $this->browser->getForm();\n\t\t$form['--three-page-form-with-validation']['text2-1']->setValue('42');\n\t\t$this->gotoNextFormPage($form);\n\n\t\t$form = $this->browser->getForm();\n\t\t$this->assertSame('', $form['--three-page-form-with-validation']['text3-1']->getValue());\n\t}", "label_name": "CWE-20", "label": "20"} -{"code": "\tpublic function __construct(string $appName,\n\t\t\t\t\t\t\t\tIRequest $request,\n\t\t\t\t\t\t\t\tITimeFactory $timeFactory,\n\t\t\t\t\t\t\t\tIInitialState $initialState,\n\t\t\t\t\t\t\t\tBookingService $bookingService,\n\t\t\t\t\t\t\t\tAppointmentConfigService $appointmentConfigService,\n\t\t\t\t\t\t\t\tURLGenerator $urlGenerator,\n\t\t\t\t\t\t\t\tLoggerInterface $logger) {\n\t\tparent::__construct($appName, $request);\n\n\t\t$this->bookingService = $bookingService;\n\t\t$this->timeFactory = $timeFactory;\n\t\t$this->appointmentConfigService = $appointmentConfigService;\n\t\t$this->initialState = $initialState;\n\t\t$this->urlGenerator = $urlGenerator;\n\t\t$this->logger = $logger;\n\t}", "label_name": "CWE-77", "label": "77"} -{"code": " public function toolbar() {\n// global $user;\n\n $menu = array();\n\t\t$dirs = array(\n\t\t\tBASE.'framework/modules/administration/menus',\n\t\t\tBASE.'themes/'.DISPLAY_THEME.'/modules/administration/menus'\n\t\t);\n\n\t\tforeach ($dirs as $dir) {\n\t\t if (is_readable($dir)) {\n\t\t\t $dh = opendir($dir);\n\t\t\t while (($file = readdir($dh)) !== false) {\n\t\t\t\t if (substr($file,-4,4) == '.php' && is_readable($dir.'/'.$file) && is_file($dir.'/'.$file)) {\n\t\t\t\t\t $menu[substr($file,0,-4)] = include($dir.'/'.$file);\n if (empty($menu[substr($file,0,-4)])) unset($menu[substr($file,0,-4)]);\n\t\t\t\t }\n\t\t\t }\n\t\t }\n\t\t}\n\n // sort the top level menus alphabetically by filename\n\t\tksort($menu);\t\t\n\t\t$sorted = array();\n\t\tforeach($menu as $m) $sorted[] = $m;\n \n // slingbar position\n if (isset($_COOKIE['slingbar-top'])){\n $top = $_COOKIE['slingbar-top'];\n } else {\n $top = SLINGBAR_TOP;\n }\n \n\t\tassign_to_template(array(\n 'menu'=>(bs3()) ? $sorted : json_encode($sorted),\n \"top\"=>$top\n ));\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function actionView($id){\n\n // add media object to user's recent item list\n User::addRecentItem('m', $id, Yii::app()->user->getId()); \n\n $this->render('view', array(\n 'model' => $this->loadModel($id),\n ));\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function actionGetItems(){\n $sql = 'SELECT id, name as value FROM x2_x2leads WHERE name LIKE :qterm ORDER BY name ASC';\n $command = Yii::app()->db->createCommand($sql);\n $qterm = $_GET['term'].'%';\n $command->bindParam(\":qterm\", $qterm, PDO::PARAM_STR);\n $result = $command->queryAll();\n echo CJSON::encode($result);\n Yii::app()->end();\n }", "label_name": "CWE-20", "label": "20"} -{"code": "function format_install_param( $value )\n{\n\t$value = str_replace( array( \"'\", \"\\$\" ), array( \"\\'\", \"\\\\$\" ), $value );\n\treturn preg_replace( \"#([\\\\\\\\]*)(\\\\\\\\\\\\\\')#\", \"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'\", $value );\n}", "label_name": "CWE-20", "label": "20"} -{"code": "\tfunction update_vendor() {\n\t\t$vendor = new vendor();\n\t\t\n\t\t$vendor->update($this->params['vendor']);\n expHistory::back();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $swimlane_id = $this->request->getIntegerParam('swimlane_id');\n\n if ($this->swimlaneModel->remove($project['id'], $swimlane_id)) {\n $this->flash->success(t('Swimlane removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this swimlane.'));\n }\n\n $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public function getDisplayName ($plural=true) {\n return Yii::t('workflow', '{process}', array(\n '{process}' => Modules::displayName($plural, 'Process'),\n ));\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\t\tpublic function addRemote($name, $url, array $params = NULL)\n\t\t{\n\t\t\t$this->run('remote', 'add', $params, $name, $url);\n\t\t\treturn $this;\n\t\t}", "label_name": "CWE-77", "label": "77"} -{"code": "\tpublic function __construct() {\n\t\tglobal $wgRequest;\n\n\t\t$this->DB\t\t\t= wfGetDB( DB_REPLICA, 'dpl' );\n\t\t$this->parameters\t= new Parameters();\n\t\t$this->logger\t\t= new Logger( $this->parameters->getData( 'debug' )['default'] );\n\t\t$this->tableNames\t= Query::getTableNames();\n\t\t$this->wgRequest\t= $wgRequest;\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " public function search(){\n // Warning: Please modify the following code to remove attributes that\n // should not be searched.\n\n $criteria = new CDbCriteria;\n $username = Yii::app()->user->name;\n $criteria->addCondition(\"uploadedBy='$username' OR private=0 OR private=null\");\n $criteria->addCondition(\"associationType != 'theme'\");\n return $this->searchBase($criteria);\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function handle($stanza, $parent = false)\n {\n $message = $stanza->forwarded->message;\n\n $jid = explode('/',(string)$message->attributes()->from);\n $to = current(explode('/',(string)$message->attributes()->to));\n\n if($message->composing)\n $this->event('composing', array($jid[0], $to));\n if($message->paused)\n $this->event('paused', array($jid[0], $to));\n if($message->gone)\n $this->event('gone', array($jid[0], $to));\n\n if($message->body || $message->subject) {\n $m = new \\Modl\\Message;\n $m->set($message, $stanza->forwarded);\n\n if(!preg_match('#^\\?OTR#', $m->body)) {\n $md = new \\Modl\\MessageDAO;\n $md->set($m);\n\n $this->pack($m);\n $this->deliver();\n }\n }\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\tpublic function fixsessions() {\n\t global $db;\n\n//\t\t$test = $db->sql('CHECK TABLE '.$db->prefix.'sessionticket');\n\t\t$fix = $db->sql('REPAIR TABLE '.$db->prefix.'sessionticket');\n\t\tflash('message', gt('Sessions Table was Repaired'));\n\t\texpHistory::back();\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": " private function edebug($str) {\n if ($this->Debugoutput == \"error_log\") {\n error_log($str);\n } else {\n echo $str;\n }\n }", "label_name": "CWE-20", "label": "20"} -{"code": " fwrite(STDERR, sprintf(\"%2d %s ==> %s\\n\", $i + 1, $test, var_export($result, true)));", "label_name": "CWE-330", "label": "330"} -{"code": "\tfunction update_vendor() {\n\t\t$vendor = new vendor();\n\t\t\n\t\t$vendor->update($this->params['vendor']);\n expHistory::back();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function delete(DeleteInvoiceRequest $request)\n {\n $this->authorize('delete multiple invoices');\n\n Invoice::destroy($request->ids);\n\n return response()->json([\n 'success' => true,\n ]);\n }", "label_name": "CWE-862", "label": "862"} -{"code": "\tfunction show_vendor () {\n\t\t$vendor = new vendor();\n\t\t\n\t\tif(isset($this->params['id'])) {\n\t\t\t$vendor = $vendor->find('first', 'id =' .$this->params['id']);\n\t\t\t$vendor_title = $vendor->title;\n\t\t\t$state = new geoRegion($vendor->state);\n\t\t\t$vendor->state = $state->name;\n\t\t\t//Removed unnecessary fields\n\t\t\tunset(\n $vendor->title,\n $vendor->table,\n $vendor->tablename,\n $vendor->classname,\n $vendor->identifier\n );\n\t\t\n\t\t\tassign_to_template(array(\n 'vendor_title' => $vendor_title,\n 'vendor'=>$vendor\n ));\n\t\t}\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": "\tpublic function update_groupdiscounts() {\n\t global $db;\n\t \n\t if (empty($this->params['id'])) {\n\t // look for existing discounts for the same group\n\t $existing_id = $db->selectValue('groupdiscounts', 'id', 'group_id='.$this->params['group_id']);\n\t if (!empty($existing_id)) flashAndFlow('error',gt('There is already a discount for that group.'));\n\t }\n\n $gd = new groupdiscounts();\n\t $gd->update($this->params);\n\t expHistory::back();\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": "\tprivate function setFooter( $footer ) {\n\t\tif ( \\DynamicPageListHooks::getDebugLevel() == 5 ) {\n\t\t\t$footer .= '';\n\t\t}\n\t\t$this->footer = $this->replaceVariables( $footer );\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " function move_standalone() {\r\n expSession::clearAllUsersSessionCache('navigation');\r\n assign_to_template(array(\r\n 'parent' => $this->params['parent'],\r\n ));\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public function getBackendRequest()\n {\n return $this->backendRequest;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " private function checkAuthenticationTag() {\n if ($this->authentication_tag === $this->calculateAuthenticationTag()) {\n return true;\n } else {\n throw new JOSE_Exception_UnexpectedAlgorithm('Invalid authentication tag');\n }\n }", "label_name": "CWE-200", "label": "200"} -{"code": " private function generateFakeFileData()\n {\n return [\n 'name' => md5(mt_rand()),\n 'tmp_name' => md5(mt_rand()),\n 'type' => 'image/jpeg',\n 'size' => mt_rand(1000, 10000),\n 'error' => '0',\n ];\n }", "label_name": "CWE-330", "label": "330"} -{"code": " public function generateMessageFileName()\n {\n $time = microtime(true);\n\n return date('Ymd-His-', $time) . sprintf('%04d', (int) (($time - (int) $time) * 10000)) . '-' . sprintf('%04d', mt_rand(0, 10000)) . '.eml';\n }", "label_name": "CWE-330", "label": "330"} -{"code": "\tpublic function delete() {\n\t global $db;\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n// $require_login = empty($this->params['require_login']) ? COMMENTS_REQUIRE_LOGIN : $this->params['require_login'];\n// $require_approval = empty($this->params['require_approval']) ? COMMENTS_REQUIRE_APPROVAL : $this->params['require_approval'];\n// $require_notification = empty($this->params['require_notification']) ? COMMENTS_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n// $notification_email = empty($this->params['notification_email']) ? COMMENTS_NOTIFICATION_EMAIL : $this->params['notification_email'];\n\t \n\t if (empty($this->params['id'])) {\n\t flash('error', gt('Missing id for the comment you would like to delete'));\n\t expHistory::back();\n\t }\n\t \n\t // delete the comment\n $comment = new expComment($this->params['id']);\n $comment->delete();\n \n // delete the association too\n $db->delete($comment->attachable_table, 'expcomments_id='.$this->params['id']); \n \n // send the user back where they came from.\n expHistory::back();\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": " private function decryptContentEncryptionKey($private_key_or_secret) {\n switch ($this->header['alg']) {\n case 'RSA1_5':\n $rsa = $this->rsa($private_key_or_secret, RSA::ENCRYPTION_PKCS1);\n $this->content_encryption_key = $rsa->decrypt($this->jwe_encrypted_key);\n break;\n case 'RSA-OAEP':\n $rsa = $this->rsa($private_key_or_secret, RSA::ENCRYPTION_OAEP);\n $this->content_encryption_key = $rsa->decrypt($this->jwe_encrypted_key);\n break;\n case 'dir':\n $this->content_encryption_key = $private_key_or_secret;\n break;\n case 'A128KW':\n case 'A256KW':\n case 'ECDH-ES':\n case 'ECDH-ES+A128KW':\n case 'ECDH-ES+A256KW':\n throw new JOSE_Exception_UnexpectedAlgorithm('Algorithm not supported');\n default:\n throw new JOSE_Exception_UnexpectedAlgorithm('Unknown algorithm');\n }\n if (!$this->content_encryption_key) {\n # NOTE:\n # Not to disclose timing difference between CEK decryption error and others.\n # Mitigating Bleichenbacher Attack on PKCS#1 v1.5\n # ref.) http://inaz2.hatenablog.com/entry/2016/01/26/222303\n $this->generateContentEncryptionKey(null);\n }\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public function manage()\n {\n expHistory::set('manageable',$this->params);\n $gc = new geoCountry();\n $countries = $gc->find('all');\n \n $gr = new geoRegion(); \n $regions = $gr->find('all',null,'rank asc,name asc');\n \n assign_to_template(array(\n 'countries'=>$countries,\n 'regions'=>$regions\n ));\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function IsQmail() {\n if (stristr(ini_get('sendmail_path'), 'qmail')) {\n $this->Sendmail = '/var/qmail/bin/sendmail';\n }\n $this->Mailer = 'sendmail';\n }", "label_name": "CWE-20", "label": "20"} -{"code": " $rst[$key] = self::parseAndTrim($st, $unescape);\n }\n return $rst;\n }\n\n $str = str_replace(\"
\",\" \",$str);\n $str = str_replace(\"
\",\" \",$str);\n $str = str_replace(\"
\",\" \",$str);\n $str = str_replace(\"
\",\" \",$str);\n $str = str_replace(\"\\r\\n\",\" \",$str);\n $str = str_replace('\"',\""\",$str);\n $str = str_replace(\"'\",\"'\",$str);\n $str = str_replace(\"\u2019\",\"’\",$str);\n $str = str_replace(\"\u2018\",\"‘\",$str);\n $str = str_replace(\"\u00ae\",\"®\",$str);\n $str = str_replace(\"\u2013\",\"-\", $str);\n $str = str_replace(\"\u2014\",\"—\", $str);\n $str = str_replace(\"\u201d\",\"”\", $str);\n $str = str_replace(\"\u201c\",\"“\", $str);\n $str = str_replace(\"\u00bc\",\"¼\",$str);\n $str = str_replace(\"\u00bd\",\"½\",$str);\n $str = str_replace(\"\u00be\",\"¾\",$str);\n\t\t$str = str_replace(\"\u2122\",\"™\", $str);\n\t\t$str = trim($str);\n\t\t\n if ($unescape) {\n\t\t\t$str = stripcslashes($str); \n\t\t} else {\n\t $str = addslashes($str);\n }\n\n return $str;\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public static function hasChildren($i) {\r\n global $sections;\r\n\r\n if (($i + 1) >= count($sections)) return false;\r\n return ($sections[$i]->depth < $sections[$i + 1]->depth) ? true : false;\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public function update()\n {\n $project = $this->getProject();\n $tag_id = $this->request->getIntegerParam('tag_id');\n $tag = $this->tagModel->getById($tag_id);\n $values = $this->request->getValues();\n list($valid, $errors) = $this->tagValidator->validateModification($values);\n\n if ($tag['project_id'] != $project['id']) {\n throw new AccessForbiddenException();\n }\n\n if ($valid) {\n if ($this->tagModel->update($values['id'], $values['name'])) {\n $this->flash->success(t('Tag updated successfully.'));\n } else {\n $this->flash->failure(t('Unable to update this tag.'));\n }\n\n $this->response->redirect($this->helper->url->to('ProjectTagController', 'index', array('project_id' => $project['id'])));\n } else {\n $this->edit($values, $errors);\n }\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public static function returnChildrenAsJSON() {\r\n global $db;\r\n\r\n //$nav = section::levelTemplate(intval($_REQUEST['id'], 0));\r\n $id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;\r\n $nav = $db->selectObjects('section', 'parent=' . $id, 'rank');\r\n //FIXME $manage_all is moot w/ cascading perms now?\r\n $manage_all = false;\r\n if (expPermissions::check('manage', expCore::makeLocation('navigation', '', $id))) {\r\n $manage_all = true;\r\n }\r\n //FIXME recode to use foreach $key=>$value\r\n $navcount = count($nav);\r\n for ($i = 0; $i < $navcount; $i++) {\r\n if ($manage_all || expPermissions::check('manage', expCore::makeLocation('navigation', '', $nav[$i]->id))) {\r\n $nav[$i]->manage = 1;\r\n $view = true;\r\n } else {\r\n $nav[$i]->manage = 0;\r\n $view = $nav[$i]->public ? true : expPermissions::check('view', expCore::makeLocation('navigation', '', $nav[$i]->id));\r\n }\r\n $nav[$i]->link = expCore::makeLink(array('section' => $nav[$i]->id), '', $nav[$i]->sef_name);\r\n if (!$view) unset($nav[$i]);\r\n }\r\n $nav= array_values($nav);\r\n// $nav[$navcount - 1]->last = true;\r\n if (count($nav)) $nav[count($nav) - 1]->last = true;\r\n// echo expJavascript::ajaxReply(201, '', $nav);\r\n $ar = new expAjaxReply(201, '', $nav);\r\n $ar->send();\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": "\tpublic static function wpSetUpBeforeClass( $factory ) {\n\t\tself::make_user_by_role( 'administrator' );\n\t\tself::$post = $factory->post->create_and_get();\n\t}", "label_name": "CWE-862", "label": "862"} -{"code": "\tpublic function update_groupdiscounts() {\n\t global $db;\n\t \n\t if (empty($this->params['id'])) {\n\t // look for existing discounts for the same group\n\t $existing_id = $db->selectValue('groupdiscounts', 'id', 'group_id='.$this->params['group_id']);\n\t if (!empty($existing_id)) flashAndFlow('error',gt('There is already a discount for that group.'));\n\t }\n\n $gd = new groupdiscounts();\n\t $gd->update($this->params);\n\t expHistory::back();\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": " public function Close() {\n $this->error = null; // so there is no confusion\n $this->helo_rply = null;\n if(!empty($this->smtp_conn)) {\n // close the connection and cleanup\n fclose($this->smtp_conn);\n $this->smtp_conn = 0;\n }\n }", "label_name": "CWE-20", "label": "20"} -{"code": " function delete_option_master() {\n global $db;\n\n $masteroption = new option_master($this->params['id']);\n \n // delete any implementations of this option master\n $db->delete('option', 'option_master_id='.$masteroption->id);\n $masteroption->delete('optiongroup_master_id=' . $masteroption->optiongroup_master_id);\n //eDebug($masteroption);\n expHistory::back();\n }", "label_name": "CWE-74", "label": "74"} -{"code": "\tpublic function __construct( Parameters $parameters ) {\n\t\t$this->parameters = $parameters;\n\n\t\t$this->tableNames = self::getTableNames();\n\n\t\t$this->DB = wfGetDB( DB_REPLICA, 'dpl' );\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " public function autocomplete() {\n return;\n global $db;\n\n $model = $this->params['model'];\n $mod = new $model();\n $srchcol = explode(\",\",$this->params['searchoncol']);\n /*for ($i=0; $i=1) $sql .= \" OR \";\n $sql .= $srchcol[$i].' LIKE \\'%'.$this->params['query'].'%\\'';\n }*/\n // $sql .= ' AND parent_id=0';\n //eDebug($sql);\n \n //$res = $mod->find('all',$sql,'id',25);\n $sql = \"select DISTINCT(p.id), p.title, model, sef_url, f.id as fileid from \".$db->prefix.\"product as p INNER JOIN \".$db->prefix.\"content_expfiles as cef ON p.id=cef.content_id INNER JOIN \".$db->prefix.\"expfiles as f ON cef.expfiles_id = f.id where match (p.title,p.model,p.body) against ('\" . $this->params['query'] . \"') AND p.parent_id=0 order by match (p.title,p.model,p.body) against ('\" . $this->params['query'] . \"') desc LIMIT 25\";\n //$res = $db->selectObjectsBySql($sql);\n //$res = $db->selectObjectBySql('SELECT * FROM `exponent_product`');\n \n $ar = new expAjaxReply(200, gt('Here\\'s the items you wanted'), $res);\n $ar->send();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public static function checkPermissions($permission,$location) {\r\n global $exponent_permissions_r, $router;\r\n\r\n // only applies to the 'manage' method\r\n if (empty($location->src) && empty($location->int) && (!empty($router->params['action']) && $router->params['action'] == 'manage') || strpos($router->current_url, 'action=manage') !== false) {\r\n if (!empty($exponent_permissions_r['navigation'])) foreach ($exponent_permissions_r['navigation'] as $page) {\r\n foreach ($page as $pageperm) {\r\n if (!empty($pageperm['manage'])) return true;\r\n }\r\n }\r\n }\r\n return false;\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": "\tpublic function getPurchaseOrderByJSON() {\n\n\t\tif(!empty($this->params['vendor'])) {\n\t\t\t$purchase_orders = $this->purchase_order->find('all', 'vendor_id=' . $this->params['vendor']);\n\t\t} else {\n\t\t\t$purchase_orders = $this->purchase_order->find('all');\n\t\t}\n\n\t\techo json_encode($purchase_orders);\n\t}", "label_name": "CWE-20", "label": "20"} -{"code": " $body = str_replace(array(\"\\n\"), \"
\", $body);\r\n } else {\r\n // It's going elsewhere (doesn't like quoted-printable)\r\n $body = str_replace(array(\"\\n\"), \" -- \", $body);\r\n }\r\n $title = $items[$i]->title;\r\n\r\n $msg .= \"BEGIN:VEVENT\\n\";\r\n $msg .= $dtstart . $dtend;\r\n $msg .= \"UID:\" . $items[$i]->date_id . \"\\n\";\r\n $msg .= \"DTSTAMP:\" . date(\"Ymd\\THis\", time()) . \"Z\\n\";\r\n if ($title) {\r\n $msg .= \"SUMMARY:$title\\n\";\r\n }\r\n if ($body) {\r\n $msg .= \"DESCRIPTION;ENCODING=QUOTED-PRINTABLE:\" . $body . \"\\n\";\r\n }\r\n //\tif($link_url) { $msg .= \"URL: $link_url\\n\";}\r\n if (!empty($this->config['usecategories'])) {\r\n if (!empty($items[$i]->expCat[0]->title)) {\r\n $msg .= \"CATEGORIES:\".$items[$i]->expCat[0]->title.\"\\n\";\r\n } else {\r\n $msg .= \"CATEGORIES:\".$this->config['uncat'].\"\\n\";\r\n }\r\n }\r\n $msg .= \"END:VEVENT\\n\";\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " function searchByModelForm() {\n // get the search terms\n $terms = $this->params['search_string'];\n\n $sql = \"model like '%\" . $terms . \"%'\";\n\n $limit = !empty($this->config['limit']) ? $this->config['limit'] : 10;\n $page = new expPaginator(array(\n 'model' => 'product',\n 'where' => $sql,\n 'limit' => !empty($this->config['pagination_default']) ? $this->config['pagination_default'] : $limit,\n 'order' => 'title',\n 'dir' => 'DESC',\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller' => $this->params['controller'],\n 'action' => $this->params['action'],\n 'columns' => array(\n gt('Model #') => 'model',\n gt('Product Name') => 'title',\n gt('Price') => 'base_price'\n ),\n ));\n\n assign_to_template(array(\n 'page' => $page,\n 'terms' => $terms\n ));\n }", "label_name": "CWE-20", "label": "20"} -{"code": " function delete() {\n global $db;\n\n if (empty($this->params['id'])) return false;\n $product_type = $db->selectValue('product', 'product_type', 'id=' . $this->params['id']);\n $product = new $product_type($this->params['id'], true, false);\n //eDebug($product_type); \n //eDebug($product, true);\n //if (!empty($product->product_type_id)) {\n //$db->delete($product_type, 'id='.$product->product_id);\n //}\n\n $db->delete('option', 'product_id=' . $product->id . \" AND optiongroup_id IN (SELECT id from \" . $db->prefix . \"optiongroup WHERE product_id=\" . $product->id . \")\");\n $db->delete('optiongroup', 'product_id=' . $product->id);\n //die();\n $db->delete('product_storeCategories', 'product_id=' . $product->id . ' AND product_type=\"' . $product_type . '\"');\n\n if ($product->product_type == \"product\") {\n if ($product->hasChildren()) {\n $this->deleteChildren();\n }\n }\n\n $product->delete();\n\n flash('message', gt('Product deleted successfully.'));\n expHistory::back();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function testXForwarderForHeaderForPassRequests()\n {\n $this->setNextResponse();\n $server = array('REMOTE_ADDR' => '10.0.0.1');\n $this->request('POST', '/', $server);\n\n $this->assertEquals('10.0.0.1', $this->kernel->getBackendRequest()->headers->get('X-Forwarded-For'));\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function renderAttribute ($name) {\n switch ($name) {\n case 'name':\n echo $this->relatedModel->getLink (/*array (\n 'class' => 'quick-read-link',\n 'data-id' => $this->relatedModel->id,\n 'data-class' => get_class ($this->relatedModel),\n 'data-name' => CHtml::encode ($this->relatedModel->name),\n )*/);\n break;\n case 'relatedModelName':\n echo $this->getRelatedModelName ();\n break;\n case 'assignedTo':\n echo $this->relatedModel->renderAttribute ('assignedTo');\n break;\n case 'label':\n echo $this->getLabel ();\n break;\n case 'createDate':\n echo X2Html::dynamicDate ($this->relatedModel->createDate);\n break;\n }\n }", "label_name": "CWE-20", "label": "20"} -{"code": " private function getProjectForUser($id)\n {\n $project = $this->project_manager->getProject($id);\n $user = $this->user_manager->getCurrentUser();\n\n ProjectAuthorization::userCanAccessProject($user, $project, new URLVerification());\n\n return $project;\n }", "label_name": "CWE-863", "label": "863"} -{"code": " public function session() {\n // Test if logged in, log in if not, log in.\n try {\n $this->assertElementPresent('css=ul#user-menu');\n } catch (PHPUnit_Framework_AssertionFailedError $e) {\n /* If this isn't the first time we've logged in, we have a problem;\n * the user should have been logged in throughout the life of the\n * test case class. Append t\n */\n if (!$this->firstLogin)\n array_push($this->verificationErrors, $e->toString());\n $this->firstLogin = false;\n $this->login();\n return 0;\n }\n try {\n $this->assertCorrectUser();\n } catch (PHPUnit_Framework_AssertionFailedError $e) {\n /**\n * The browser is logged in but not as the correct user.\n */\n $this->logout();\n $this->login();\n $this->firstLogin = false;\n return 0;\n }\n // Indicator of whether the session was already initialized properly\n return 1;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function testOnKernelResponseListenerRemovesItself()\n {\n $session = $this->createMock(SessionInterface::class);\n $session->expects($this->any())->method('getName')->willReturn('SESSIONNAME');\n $tokenStorage = $this->createMock(TokenStorageInterface::class);\n $dispatcher = $this->createMock(EventDispatcherInterface::class);\n\n $listener = new ContextListener($tokenStorage, [], 'key123', null, $dispatcher);\n\n $request = new Request();\n $request->attributes->set('_security_firewall_run', true);\n $request->setSession($session);\n\n $event = new ResponseEvent($this->createMock(HttpKernelInterface::class), $request, HttpKernelInterface::MAIN_REQUEST, new Response());\n\n $dispatcher->expects($this->once())\n ->method('removeListener')\n ->with(KernelEvents::RESPONSE, [$listener, 'onKernelResponse']);\n\n $listener->onKernelResponse($event);\n }", "label_name": "CWE-287", "label": "287"} -{"code": "\t\t\t$return[$index] = strip_tags($value);\n\t\t\tif($return[$index] == 'zero')\n\t\t\t\t$return[$index] = '0';\n\t\t}\n\t}\n\telseif($type == ARG_MULTISTRING) {\n\t\tforeach($return as $index => $value) {\n\t\t\t$return[$index] = strip_tags($value);\n\t\t}\n\t}\n\telse\n\t\t$return = strip_tags($return);\n\n\tif(! empty($return) && $type == ARG_NUMERIC) {\n\t\tif(! is_numeric($return)) {\n\t\t\treturn preg_replace('([^\\d])', '', $return);\n\t\t}\n\t}\n\telseif(! empty($return) && $type == ARG_STRING) {\n\t\tif(! is_string($return))\n\t\t\t$return = $defaultvalue;\n\t}\n\telseif(! empty($return) && $type == ARG_MULTINUMERIC) {\n\t\tforeach($return as $index => $value) {\n\t\t\tif(! is_numeric($value)) {\n\t\t\t\t$return[$index] = preg_replace('([^\\d])', '', $value);\n\t\t\t}\n\t\t}\n\t\treturn $return;\n\t}\n\telseif(! empty($return) && $type == ARG_MULTISTRING) {\n\t\tforeach($return as $index => $value) {\n\t\t\tif(! is_string($value))\n\t\t\t\t$return[$index] = $defaultvalue;\n\t\t\telseif($addslashes)\n\t\t\t\t$return[$index] = addslashes($value);\n\t\t}\n\t\treturn $return;\n\t}\n\n\tif(is_string($return)) {\n\t\tif(strlen($return) == 0)\n\t\t\t$return = $defaultvalue;\n\t\telseif($addslashes)\n\t\t\t$return = addslashes($return);\n\t}\n\n\treturn $return;\n}", "label_name": "CWE-20", "label": "20"} -{"code": " function build_daterange_sql($timestamp, $endtimestamp=null, $field='date', $multiday=false) {\r\n if (empty($endtimestamp)) {\r\n $date_sql = \"((\".$field.\" >= \" . expDateTime::startOfDayTimestamp($timestamp) . \" AND \".$field.\" <= \" . expDateTime::endOfDayTimestamp($timestamp) . \")\";\r\n } else {\r\n $date_sql = \"((\".$field.\" >= \" . expDateTime::startOfDayTimestamp($timestamp) . \" AND \".$field.\" <= \" . expDateTime::endOfDayTimestamp($endtimestamp) . \")\";\r\n }\r\n if ($multiday)\r\n $date_sql .= \" OR (\" . expDateTime::startOfDayTimestamp($timestamp) . \" BETWEEN \".$field.\" AND dateFinished)\";\r\n $date_sql .= \")\";\r\n return $date_sql;\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": "\t\t\t$tokens = preg_split( '/ - */', $title );\n\t\t\t$newKey = '';\n\t\t\tforeach ( $tokens as $token ) {\n\t\t\t\t$initial = substr( $token, 0, 1 );\n\t\t\t\tif ( $initial >= '1' && $initial <= '7' ) {\n\t\t\t\t\t$newKey .= $initial;\n\t\t\t\t\t$suit = substr( $token, 1 );\n\t\t\t\t\tif ( $suit == '\u2663' ) {\n\t\t\t\t\t\t$newKey .= '1';\n\t\t\t\t\t} elseif ( $suit == '\u2666' ) {\n\t\t\t\t\t\t$newKey .= '2';\n\t\t\t\t\t} elseif ( $suit == '\u2665' ) {\n\t\t\t\t\t\t$newKey .= '3';\n\t\t\t\t\t} elseif ( $suit == '\u2660' ) {\n\t\t\t\t\t\t$newKey .= '4';\n\t\t\t\t\t} elseif ( strtolower( $suit ) == 'sa' || strtolower( $suit ) == 'nt' ) {\n\t\t\t\t\t\t$newKey .= '5 ';\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$newKey .= $suit;\n\t\t\t\t\t}\n\t\t\t\t} elseif ( strtolower( $initial ) == 'p' ) {\n\t\t\t\t\t$newKey .= '0 ';\n\t\t\t\t} elseif ( strtolower( $initial ) == 'x' ) {\n\t\t\t\t\t$newKey .= '8 ';\n\t\t\t\t} else {\n\t\t\t\t\t$newKey .= $token;\n\t\t\t\t}\n\t\t\t}\n\t\t\t$sortKeys[$key] = $newKey;\n\t\t}\n\t\tasort( $sortKeys );\n\t\tforeach ( $sortKeys as $oldKey => $newKey ) {\n\t\t\t$sortedArticles[] = $articles[$oldKey];\n\t\t}\n\t\treturn $sortedArticles;\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " public function index($id)\n {\n $this->paginate['conditions'] = array('GalaxyElement.galaxy_cluster_id' => $id);\n $clusters = $this->paginate();\n $this->set('list', $clusters);\n if ($this->request->is('ajax')) {\n $this->layout = 'ajax';\n $this->render('ajax/index');\n }\n }", "label_name": "CWE-862", "label": "862"} -{"code": " function edit_internalalias() {\r\n $section = isset($this->params['id']) ? $this->section->find($this->params['id']) : new section($this->params);\r\n if ($section->parent == -1) {\r\n notfoundController::handle_not_found();\r\n exit;\r\n } // doesn't work for standalone pages\r\n if (empty($section->id)) {\r\n $section->public = 1;\r\n if (!isset($section->parent)) {\r\n // This is another precaution. The parent attribute\r\n // should ALWAYS be set by the caller.\r\n //FJD - if that's the case, then we should die.\r\n notfoundController::handle_not_authorized();\r\n exit;\r\n //$section->parent = 0;\r\n }\r\n }\r\n assign_to_template(array(\r\n 'section' => $section,\r\n 'glyphs' => self::get_glyphs(),\r\n ));\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": "\t\t\tforeach($paths as $path)\n\t\t\t{\n\t\t\t\t// Convert wild-cards to RegEx\n\t\t\t\t$path = str_replace(array(':any', '*'), '.*', str_replace(':num', '[0-9]+', $path));\n\n\t\t\t\t// Does the RegEx match?\n\t\t\t\tif (!empty($_SERVER['HTTP_HOST']) AND preg_match('#^'.$path.'$#', $_SERVER['HTTP_HOST']))\n\t\t\t\t{\n\t\t\t\t\tdefine('ENVIRONMENT', $env);\n\t\t\t\t\tbreak 2;\n\t\t\t\t}\n\t\t\t}", "label_name": "CWE-74", "label": "74"} -{"code": "\tprotected function sort(&$rowsKey, $sortColumn) {\n\t\t$sortMethod = $this->getTableSortMethod();\n\t\n\t\tif ($sortColumn < 0) {\n\t\t\tswitch ($sortMethod) {\n\t\t\t\tcase 'natural':\n\t\t\t\t\t// Reverse natsort()\n uasort($rowsKey, function($first, $second) {\n \treturn strnatcmp($second, $first);\n\t\t\t\t\t});\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'standard':\n\t\t\t\tdefault:\n\t\t\t\t\tarsort($rowsKey);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t} else {\n\t\t\tswitch ($sortMethod) {\n\t\t\t\tcase 'natural':\n\t\t\t\tnatsort($rowsKey);\n\t\t\t\tbreak;\n\t\t\tcase 'standard':\n\t\t\tdefault:\n\t\t\t\tasort($rowsKey);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " $tags = array_merge($matches[1], $tags);\n }\n $tags = array_unique($tags);\n return $tags;\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\tpublic function newModel() {\n\t\treturn new APIModel('testuser','5f4dcc3b5aa765d61d8327deb882cf99',rtrim(TEST_BASE_URL,'/'));\n\t}", "label_name": "CWE-20", "label": "20"} -{"code": " private function getCategory()\n {\n $category = $this->categoryModel->getById($this->request->getIntegerParam('category_id'));\n\n if (empty($category)) {\n throw new PageNotFoundException();\n }\n\n return $category;\n }", "label_name": "CWE-200", "label": "200"} -{"code": " foreach ($allgroups as $gid) {\r\n $g = group::getGroupById($gid);\r\n expPermissions::grantGroup($g, 'manage', $sloc);\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " private function generateTempFileData()\n {\n return [\n 'name' => md5(mt_rand()),\n 'tmp_name' => tempnam(sys_get_temp_dir(), ''),\n 'type' => 'image/jpeg',\n 'size' => mt_rand(1000, 10000),\n 'error' => '0',\n ];\n }", "label_name": "CWE-330", "label": "330"} -{"code": "\t\t\t\t$this->run('mv', $from, $to);\n\t\t\t}\n\n\t\t\treturn $this;\n\t\t}", "label_name": "CWE-77", "label": "77"} -{"code": "\tprivate function __construct($userinfo, $tid = - 1) {\n\t\t$this->userinfo = $userinfo;\n\t\t$this->tid = $tid;\n\n\t\t// initialize data array\n\t\t$this->initData();\n\n\t\t// read data from database\n\t\t$this->readData();\n\t}", "label_name": "CWE-732", "label": "732"} -{"code": "\t\t\t\t$curVal[$key] = $tp->post_toForm($val);\n\t\t\t}\n\t\t}\n\n\t\t$target = e107::getUrl()->create('user/myprofile/edit',array('id'=>USERID));\n\n\t\t$text = '
';\n\n\t\t//$text = (is_numeric($_uid) ? $rs->form_open(\"post\", e_SELF.\"?\".e_QUERY, \"dataform\", \"\", \" class='form-horizontal' role='form' enctype='multipart/form-data'\") : $rs->form_open(\"post\", e_SELF, \"dataform\", \"\", \" class='form-horizontal' role='form' enctype='multipart/form-data'\"));\n\n\t\tif (e_QUERY == \"update\")\n\t\t{\n\t\t\t$text .= \"

\".str_replace(\"*\", \"*\", LAN_USET_9).\"
\".LAN_USET_10.\"

\";\n\t\t}\n\n\t\t// e107::scStyle($sc_style);\n\t\te107::getScBatch('usersettings')->setVars($curVal)->reset();\n\n\t\t$USERSETTINGS_EDIT = $this->getTemplate('edit');\n\t\t$USERSETTINGS_EDIT_CAPTION = $this->getTemplate('edit_caption');\n\n\t\t$text .= $tp->parseTemplate($USERSETTINGS_EDIT, true, $this->sc); //ParseSC must be set to true so that custom plugin -shortcodes can be utilized.\n\n\n\t\t$text .= \"
\n\t\t
\n\t\t\";\n\n\t\t$caption = (isset($USERSETTINGS_EDIT_CAPTION)) ? $USERSETTINGS_EDIT_CAPTION : LAN_USET_39; // 'Update User Settings'\n\n\t\t$ns->tablerender($caption, $text);\n\n\n\n\n\n\t}", "label_name": "CWE-326", "label": "326"} -{"code": "\tpublic function addGroupBy( $groupBy ) {\n\t\tif ( empty( $groupBy ) ) {\n\t\t\tthrow new \\MWException( __METHOD__ . ': An empty group by clause was passed.' );\n\t\t}\n\t\t$this->groupBy[] = $groupBy;\n\t\treturn true;\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": "\tpublic function Archive() {\n\n\t\t// Update \"main\" ticket\n\t\t$upd_stmt = Database::prepare('\n\t\t\tUPDATE `' . TABLE_PANEL_TICKETS . '` SET `archived` = \"1\" WHERE `id` = :tid'\n\t\t);\n\t\tDatabase::pexecute($upd_stmt, array('tid' => $this->tid));\n\n\t\t// Update \"answers\" to ticket\n\t\t$upd_stmt = Database::prepare('\n\t\t\tUPDATE `' . TABLE_PANEL_TICKETS . '` SET `archived` = \"1\" WHERE `answerto` = :tid'\n\t\t);\n\t\tDatabase::pexecute($upd_stmt, array('tid' => $this->tid));\n\t\treturn true;\n\t}", "label_name": "CWE-732", "label": "732"} -{"code": " public function saveConfig() { \n if (!empty($this->params['aggregate']) || !empty($this->params['pull_rss'])) {\n if ($this->params['order'] == 'rank ASC') {\n expValidator::failAndReturnToForm(gt('User defined ranking is not allowed when aggregating or pull RSS data feeds.'), $this->params);\n }\n }\n \n parent::saveConfig();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function upload() {\n \n // upload the file, but don't save the record yet...\n if ($this->params['resize'] != 'false') {\n $maxwidth = $this->params['max_width'];\n } else {\n $maxwidth = null;\n }\n $file = expFile::fileUpload('Filedata',false,false,null,null,$maxwidth);\n // since most likely this function will only get hit via flash in YUI Uploader\n // and since Flash can't pass cookies, we lose the knowledge of our $user\n // so we're passing the user's ID in as $_POST data. We then instantiate a new $user,\n // and then assign $user->id to $file->poster so we have an audit trail for the upload\n\n if (is_object($file)) {\n $resized = !empty($file->resized) ? true : false;\n $user = new user($this->params['usrid']);\n $file->poster = $user->id;\n $file->posted = $file->last_accessed = time();\n $file->save();\n if (!empty($this->params['cat'])) {\n $expcat = new expCat($this->params['cat']);\n $params['expCat'][0] = $expcat->id;\n $file->update($params);\n }\n\n // a echo so YUI Uploader is notified of the function's completion\n if ($resized) {\n echo gt('File resized and then saved');\n } else {\n echo gt('File saved');\n }\n } else {\n echo gt('File was NOT uploaded!');\n// flash('error',gt('File was not uploaded!'));\n }\n } ", "label_name": "CWE-74", "label": "74"} -{"code": " public function delete() {\n global $db, $history;\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n $require_login = empty($this->params['require_login']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];\n $require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];\n $require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n $notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];\n \n if (empty($this->params['id'])) {\n flash('error', gt('Missing id for the comment you would like to delete'));\n $lastUrl = expHistory::getLast('editable');\n }\n \n // delete the note\n $simplenote = new expSimpleNote($this->params['id']);\n $rows = $simplenote->delete();\n \n // delete the assocication too\n $db->delete($simplenote->attachable_table, 'expsimplenote_id='.$this->params['id']); \n \n // send the user back where they came from.\n $lastUrl = expHistory::getLast('editable');\n if (!empty($this->params['tab']))\n {\n $lastUrl .= \"#\".$this->params['tab'];\n }\n redirect_to($lastUrl);\n }", "label_name": "CWE-74", "label": "74"} -{"code": " foreach ($allusers as $uid) {\r\n $u = user::getUserById($uid);\r\n expPermissions::grant($u, 'manage', $sloc);\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " foreach ($evs as $key=>$event) {\r\n if ($condense) {\r\n $eventid = $event->id;\r\n $multiday_event = array_filter($events, create_function('$event', 'global $eventid; return $event->id === $eventid;'));\r\n if (!empty($multiday_event)) {\r\n unset($evs[$key]);\r\n continue;\r\n }\r\n }\r\n $evs[$key]->eventstart += $edate->date;\r\n $evs[$key]->eventend += $edate->date;\r\n $evs[$key]->date_id = $edate->id;\r\n if (!empty($event->expCat)) {\r\n $catcolor = empty($event->expCat[0]->color) ? null : trim($event->expCat[0]->color);\r\n// if (substr($catcolor,0,1)=='#') $catcolor = '\" style=\"color:'.$catcolor.';';\r\n $evs[$key]->color = $catcolor;\r\n }\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " ->first(function (User $user) {\n return $user->getPreference('blocksPd', false);\n }) !== null;", "label_name": "CWE-269", "label": "269"} -{"code": " private function getSwimlane()\n {\n $swimlane = $this->swimlaneModel->getById($this->request->getIntegerParam('swimlane_id'));\n\n if (empty($swimlane)) {\n throw new PageNotFoundException();\n }\n\n return $swimlane;\n }", "label_name": "CWE-200", "label": "200"} -{"code": " function categoryBreadcrumb() {\n// global $db, $router;\n\n //eDebug($this->category);\n\n /*if(isset($router->params['action']))\n {\n $ancestors = $this->category->pathToNode(); \n }else if(isset($router->params['section']))\n {\n $current = $db->selectObject('section',' id= '.$router->params['section']);\n $ancestors[] = $current;\n if( $current->parent != -1 || $current->parent != 0 )\n { \n while ($db->selectObject('section',' id= '.$router->params['section']);)\n if ($section->id == $id) {\n $current = $section;\n break;\n }\n }\n }\n eDebug($sections);\n $ancestors = $this->category->pathToNode(); \n }*/\n\n $ancestors = $this->category->pathToNode();\n // eDebug($ancestors);\n assign_to_template(array(\n 'ancestors' => $ancestors\n ));\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function actionGetLists() {\n if (!Yii::app()->user->checkAccess('ContactsAdminAccess')) {\n $condition = ' AND (visibility=\"1\" OR assignedTo=\"Anyone\" OR assignedTo=\"' . Yii::app()->user->getName() . '\"';\n /* x2temp */\n $groupLinks = Yii::app()->db->createCommand()->select('groupId')->from('x2_group_to_user')->where('userId=' . Yii::app()->user->getId())->queryColumn();\n if (!empty($groupLinks))\n $condition .= ' OR assignedTo IN (' . implode(',', $groupLinks) . ')';\n\n $condition .= ' OR (visibility=2 AND assignedTo IN\n (SELECT username FROM x2_group_to_user WHERE groupId IN\n (SELECT groupId FROM x2_group_to_user WHERE userId=' . Yii::app()->user->getId() . '))))';\n } else {\n $condition = '';\n }\n // Optional search parameter for autocomplete\n $qterm = isset($_GET['term']) ? $_GET['term'] . '%' : '';\n $result = Yii::app()->db->createCommand()\n ->select('id,name as value')\n ->from('x2_lists')\n ->where('modelName=\"Contacts\" AND type!=\"campaign\" AND name LIKE :qterm' . $condition, array(':qterm' => $qterm))\n ->order('name ASC')\n ->queryAll();\n echo CJSON::encode($result);\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\tpublic function print_form() {\r\n\t\tglobal $user_id;\r\n\r\n\t\tinclude_once( GEO_MASHUP_DIR_PATH . '/edit-form.php');\r\n\t\tif ( isset( $_GET['user_id'] ) ) {\r\n\t\t\t$object_id = $_GET['user_id'];\r\n\t\t} else {\r\n\t\t\t$object_id = $user_id;\r\n\t\t}\r\n\t\techo '

' . __( 'Location', 'GeoMashup' ) . '

';\r\n\t\tgeo_mashup_edit_form( 'user', $object_id, get_class( $this ) );\r\n\t}\r", "label_name": "CWE-20", "label": "20"} -{"code": " public function subscriptions() {\n global $db;\n \n expHistory::set('manageable', $this->params);\n // make sure we have what we need.\n if (empty($this->params['key'])) expQueue::flashAndFlow('error', gt('The security key for account was not supplied.'));\n if (empty($this->params['id'])) expQueue::flashAndFlow('error', gt('The subscriber id for account was not supplied.'));\n \n // verify the id/key pair \n $sub = new subscribers($this->params['id']);\n if (empty($sub->id)) expQueue::flashAndFlow('error', gt('We could not find any subscriptions matching the ID and Key you provided.'));\n \n // get this users subscriptions\n $subscriptions = $db->selectColumn('expeAlerts_subscribers', 'expeAlerts_id', 'subscribers_id='.$sub->id);\n \n // get a list of all available E-Alerts\n $ealerts = new expeAlerts();\n assign_to_template(array(\n 'subscriber'=>$sub,\n 'subscriptions'=>$subscriptions,\n 'ealerts'=>$ealerts->find('all')\n ));\n }", "label_name": "CWE-74", "label": "74"} -{"code": " private function getSwimlane()\n {\n $swimlane = $this->swimlaneModel->getById($this->request->getIntegerParam('swimlane_id'));\n\n if (empty($swimlane)) {\n throw new PageNotFoundException();\n }\n\n return $swimlane;\n }", "label_name": "CWE-200", "label": "200"} -{"code": " $text = preg_replace($exp, '', $text);\n }\n\n // Primary expression to filter out tags\n $exp = '/(?:^|\\s|\\.)(#\\w+[-\\w]+\\w+|#\\w+)(?:$|[^\\'\"])/u';\n\n $matches = array();\n preg_match_all($exp, $text, $matches);\n\n return $matches;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function delete($id)\n {\n $this->CRUD->delete($id);\n $responsePayload = $this->CRUD->getResponsePayload();\n if (!empty($responsePayload)) {\n return $responsePayload;\n }\n $this->set('metaGroup', 'Trust Circles');\n }", "label_name": "CWE-668", "label": "668"} -{"code": " public function getClone($modelId = null)\n {\n $this->authorize('view', AssetModel::class);\n // Check if the model exists\n if (is_null($model_to_clone = AssetModel::find($modelId))) {\n return redirect()->route('models.index')->with('error', trans('admin/models/message.does_not_exist'));\n }\n\n $model = clone $model_to_clone;\n $model->id = null;\n\n // Show the page\n return view('models/edit')\n ->with('depreciation_list', Helper::depreciationList())\n ->with('item', $model)\n ->with('clone_model', $model_to_clone);\n }", "label_name": "CWE-862", "label": "862"} -{"code": " public function generateMessageFileName()\n {\n $time = microtime(true);\n\n return date('Ymd-His-', $time) . sprintf('%04d', (int) (($time - (int) $time) * 10000)) . '-' . sprintf('%04d', mt_rand(0, 10000)) . '.eml';\n }", "label_name": "CWE-330", "label": "330"} -{"code": "\tpublic function showall() {\n\t expHistory::set('viewable', $this->params);\n\t $hv = new help_version();\n\t //$current_version = $hv->find('first', 'is_current=1');\n\t $ref_version = $hv->find('first', 'version=\\''.$this->help_version.'\\'');\n\n // pagination parameter..hard coded for now.\t \n\t\t$where = $this->aggregateWhereClause();\n\t $where .= 'AND help_version_id='.(empty($ref_version->id)?'0':$ref_version->id);", "label_name": "CWE-74", "label": "74"} -{"code": " $layout[$position] = array($elem => $initLayout[$position][$elem]) + $layout[$position]; // unshift key-value pair\n $changed = true;\n }\n\n // remove obsolete widgets\n $arrayDiff =\n array_diff(array_keys($layoutWidgets), array_keys($initLayoutWidgets));\n foreach($arrayDiff as $elem){\n if(in_array ($elem, array_keys ($layout[$position]))) {\n unset($layout[$position][$elem]);\n $changed = true;\n } else if($position === 'center' && in_array ($elem, array_keys ($layout['hidden']))) {\n unset($layout['hidden'][$elem]);\n $changed = true;\n }\n }\n\n\n // ensure that widget properties are the same as those in the default layout\n foreach($layout[$position] as $name=>$arr){\n if (in_array ($name, array_keys ($initLayout[$position])) &&\n $initLayout[$position][$name]['title'] !== $arr['title']) {\n\n $layout[$position][$name]['title'] = $initLayout[$position][$name]['title'];\n $changed = true;\n }\n }\n if ($position === 'center') {\n foreach($layout['hidden'] as $name=>$arr){\n if (in_array ($name, array_keys ($initLayout[$position])) &&\n $initLayout[$position][$name]['title'] !== $arr['title']) {\n\n $layout['hidden'][$name]['title'] = $initLayout[$position][$name]['title'];\n $changed = true;\n }\n }\n }\n\n if($changed){\n $this->layout = json_encode($layout);\n $this->update(array('layout'));\n }\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public static function canImportData() {\r\n return true;\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": "function getTypes($subtype=\"both\") {\n\t$types = array(\"users\" => array(),\n\t \"resources\" => array());\n\tif($subtype == \"users\" || $subtype == \"both\") {\n\t\t$query = \"SELECT id, name FROM userprivtype\";\n\t\t$qh = doQuery($query, 365);\n\t\twhile($row = mysql_fetch_assoc($qh)) {\n\t\t\tif($row[\"name\"] == \"block\" || $row[\"name\"] == \"cascade\")\n\t\t\t\tcontinue;\n\t\t\t$types[\"users\"][$row[\"id\"]] = $row[\"name\"];\n\t\t}\n\t}\n\tif($subtype == \"resources\" || $subtype == \"both\") {\n\t\t$query = \"SELECT id, name FROM resourcetype\";\n\t\t$qh = doQuery($query, 366);\n\t\twhile($row = mysql_fetch_assoc($qh)) {\n\t\t\tif($row[\"name\"] == \"block\" || $row[\"name\"] == \"cascade\")\n\t\t\t\tcontinue;\n\t\t\t$types[\"resources\"][$row[\"id\"]] = $row[\"name\"];\n\t\t}\n\t}\n\treturn $types;\n}", "label_name": "CWE-20", "label": "20"} -{"code": " public static function getHelpVersion($version_id) {\n global $db;\n\n return $db->selectValue('help_version', 'version', 'id=\"'.$version_id.'\"');\n }", "label_name": "CWE-74", "label": "74"} -{"code": " protected function assertCsvUploaded($csv) {\n $uploadedPath = implode(DIRECTORY_SEPARATOR, array(\n Yii::app()->basePath,\n 'data',\n 'data.csv'\n ));\n $this->assertFileExists ($uploadedPath);\n $this->assertFileEquals ($csv, $uploadedPath);\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function __construct() {\n $this->pop_conn = 0;\n $this->connected = false;\n $this->error = null;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " $fileName = ltrim(dirname($fileName) . '/' . basename($fileName, '.js'), '/.');\n\n if (empty($fileName)) {\n continue;\n }\n\n $templateNames[] = $inflector->filter(array(\n 'module' => $moduleName,\n 'controller' => $controllerName,\n 'file' => $fileName)\n );\n }", "label_name": "CWE-20", "label": "20"} -{"code": " $connecttext = preg_replace(\"/#connectport#/\", $connectport, $connecttext); \n $connectMethods[$key][\"connecttext\"] = $connecttext;\n }\n\t\treturn array('status' => 'ready',\n\t\t 'serverIP' => $serverIP,\n\t\t 'user' => $thisuser,\n 'password' => $passwd,\n 'connectport' => $connectport,\n 'connectMethods' => $connectMethods);\n\t}\n\treturn array('status' => 'notready');\n}", "label_name": "CWE-20", "label": "20"} -{"code": " function fread($handle, $length)\n {\n if (\\yiiunit\\framework\\base\\SecurityTest::$fread !== null) {\n return \\yiiunit\\framework\\base\\SecurityTest::$fread;\n }\n if (\\yiiunit\\framework\\base\\SecurityTest::$fopen !== null) {\n return $length < 8 ? \\str_repeat('s', $length) : 'test1234';\n }\n\n return \\fread($handle, $length);\n }", "label_name": "CWE-330", "label": "330"} -{"code": "\t\timagepng( $im_crop, $output );\n\t}\n\n\t$new_avatar = false;\n\n\tif ( file_exists( $output ) ) {\n\n\t\t$old_avatar = get_user_meta( $user_id, '_lp_profile_picture', true );\n\n\t\tif ( file_exists( $upload_dir['basedir'] . '/' . $old_avatar ) ) {\n\t\t\t@unlink( $upload_dir['basedir'] . '/' . $old_avatar );\n\t\t}\n\n\t\t$new_avatar = preg_replace( '!^/!', '', $upload_dir['subdir'] ) . '/' . $newname;\n\t\tupdate_user_meta( $user_id, '_lp_profile_picture', $new_avatar );\n\t\tupdate_user_meta( $user_id, '_lp_profile_picture_changed', 'yes' );\n\n\t\t$new_avatar = $upload_dir['baseurl'] . '/' . $new_avatar;\n\t}\n\n\t@unlink( $path );\n\n\treturn $new_avatar;\n}", "label_name": "CWE-610", "label": "610"} -{"code": " public function __construct() {\n $this->smtp_conn = 0;\n $this->error = null;\n $this->helo_rply = null;\n\n $this->do_debug = 0;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " foreach($image->expTag as $tag) {\n if (isset($used_tags[$tag->id])) {\n $used_tags[$tag->id]->count++;\n } else {\n $exptag = new expTag($tag->id);\n $used_tags[$tag->id] = $exptag;\n $used_tags[$tag->id]->count = 1;\n }\n \n }", "label_name": "CWE-74", "label": "74"} -{"code": " public static function getTemplateHierarchyFlat($parent, $depth = 1) {\r\n global $db;\r\n\r\n $arr = array();\r\n $kids = $db->selectObjects('section_template', 'parent=' . $parent, 'rank');\r\n//\t\t$kids = expSorter::sort(array('array'=>$kids,'sortby'=>'rank', 'order'=>'ASC'));\r\n for ($i = 0, $iMax = count($kids); $i < $iMax; $i++) {\r\n $page = $kids[$i];\r\n $page->depth = $depth;\r\n $page->first = ($i == 0 ? 1 : 0);\r\n $page->last = ($i == count($kids) - 1 ? 1 : 0);\r\n $arr[] = $page;\r\n $arr = array_merge($arr, self::getTemplateHierarchyFlat($page->id, $depth + 1));\r\n }\r\n return $arr;\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": "\t\t\tarray_push($newgroupprivs, $type);\n\t}\n\tif(empty($newgroupprivs) || (count($newgroupprivs) == 1 && \n in_array(\"cascade\", $newgroupprivs))) {\n\t\treturn array('status' => 'error',\n 'errorcode' => 53,\n 'errormsg' => 'Invalid or missing permissions list supplied');\n\t}\n updateUserOrGroupPrivs($groupid, $nodeid, $newgroupprivs, array(), \"group\");\n\treturn array('status' => 'success');\n}", "label_name": "CWE-20", "label": "20"} -{"code": " function edit() {\n global $user;\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n $require_login = empty($this->params['require_login']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];\n $require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];\n $require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n $notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];\n \n if (empty($this->params['formtitle'])) \n {\n if (empty($this->params['id']))\n {\n $formtitle = gt(\"Add New Note\");\n }\n else\n {\n $formtitle = gt(\"Edit Note\");\n }\n }\n else\n {\n $formtitle = $this->params['formtitle'];\n }\n \n $id = empty($this->params['id']) ? null : $this->params['id'];\n $simpleNote = new expSimpleNote($id);\n //FIXME here is where we might sanitize the note before displaying/editing it\n\n assign_to_template(array(\n 'simplenote'=>$simpleNote,\n 'user'=>$user,\n 'require_login'=>$require_login,\n 'require_approval'=>$require_approval,\n 'require_notification'=>$require_notification,\n 'notification_email'=>$notification_email,\n 'formtitle'=>$formtitle,\n 'content_type'=>$this->params['content_type'],\n 'content_id'=>$this->params['content_id'],\n 'tab'=>empty($this->params['tab'])?0:$this->params['tab']\n ));\n } ", "label_name": "CWE-74", "label": "74"} -{"code": " public function save()\n {\n $project = $this->getProject();\n\n $values = $this->request->getValues();\n list($valid, $errors) = $this->categoryValidator->validateCreation($values);\n\n if ($valid) {\n if ($this->categoryModel->create($values) !== false) {\n $this->flash->success(t('Your category have been created successfully.'));\n $this->response->redirect($this->helper->url->to('CategoryController', 'index', array('project_id' => $project['id'])), true);\n return;\n } else {\n $errors = array('name' => array(t('Another category with the same name exists in this project')));\n }\n }\n\n $this->create($values, $errors);\n }", "label_name": "CWE-200", "label": "200"} -{"code": "\tpublic static function dplReplaceParserFunction( &$parser, $text, $pat = '', $repl = '' ) {\n\t\t$parser->addTrackingCategory( 'dplreplace-parserfunc-tracking-category' );\n\t\tif ( $text == '' || $pat == '' ) {\n\t\t\treturn '';\n\t\t}\n\t\t# convert \\n to a real newline character\n\t\t$repl = str_replace( '\\n', \"\\n\", $repl );\n\n\t\t# replace\n\t\tif ( !self::isRegexp( $pat ) ) {\n\t\t\t$pat = '`' . str_replace( '`', '\\`', $pat ) . '`';\n\t\t}\n\n\t\treturn @preg_replace( $pat, $repl, $text );\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " function showByModel() {\n global $order, $template, $db;\n\n expHistory::set('viewable', $this->params);\n $product = new product();\n $model = $product->find(\"first\", 'model=\"' . $this->params['model'] . '\"');\n //eDebug($model);\n $product_type = new $model->product_type($model->id);\n //eDebug($product_type);\n $tpl = $product_type->getForm('show');\n if (!empty($tpl)) $template = new controllertemplate($this, $tpl);\n //eDebug($template);\n $this->grabConfig(); // grab the global config\n assign_to_template(array(\n 'config' => $this->config,\n 'product' => $product_type,\n 'last_category' => $order->lastcat\n ));\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\t\t\t$iloc = expUnserialize($container->internal);\n\t\t\tif ($db->selectObject('sectionref',\"module='\".$iloc->mod.\"' AND source='\".$iloc->src.\"'\") == null) {\n\t\t\t// There is no sectionref for this container. Populate sectionref\n if ($container->external != \"N;\") {\n $newSecRef = new stdClass();\n $newSecRef->module = $iloc->mod;\n $newSecRef->source = $iloc->src;\n $newSecRef->internal = '';\n $newSecRef->refcount = 1;\n// $newSecRef->is_original = 1;\n\t\t\t\t\t$eloc = expUnserialize($container->external);\n//\t\t\t\t\t$section = $db->selectObject('sectionref',\"module='containermodule' AND source='\".$eloc->src.\"'\");\n $section = $db->selectObject('sectionref',\"module='container' AND source='\".$eloc->src.\"'\");\n\t\t\t\t\tif (!empty($section)) {\n\t\t\t\t\t\t$newSecRef->section = $section->id;\n\t\t\t\t\t\t$db->insertObject($newSecRef,\"sectionref\");\n\t\t\t\t\t\t$missing_sectionrefs[] = gt(\"Missing sectionref for container replaced\").\": \".$iloc->mod.\" - \".$iloc->src.\" - PageID #\".$section->id;\n\t\t\t\t\t} else {\n $db->delete('container','id=\"'.$container->id.'\"');\n $missing_sectionrefs[] = gt(\"Cant' find the container page for container\").\": \".$iloc->mod.\" - \".$iloc->src.' - '.gt('deleted');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n assign_to_template(array(\n 'missing_sectionrefs'=>$missing_sectionrefs,\n ));\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": "\tprivate function _stablepages( $option ) {\n\t\tif ( function_exists( 'efLoadFlaggedRevs' ) ) {\n\t\t\t//Do not add this again if 'qualitypages' has already added it.\n\t\t\tif ( !$this->parametersProcessed['qualitypages'] ) {\n\t\t\t\t$this->addJoin(\n\t\t\t\t\t'flaggedpages',\n\t\t\t\t\t[\n\t\t\t\t\t\t\"LEFT JOIN\",\n\t\t\t\t\t\t\"page_id = fp_page_id\"\n\t\t\t\t\t]\n\t\t\t\t);\n\t\t\t}\n\t\t\tswitch ( $option ) {\n\t\t\t\tcase 'only':\n\t\t\t\t\t$this->addWhere(\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t'fp_stable IS NOT NULL'\n\t\t\t\t\t\t]\n\t\t\t\t\t);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'exclude':\n\t\t\t\t\t$this->addWhere(\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t'fp_stable'\t=> null\n\t\t\t\t\t\t]\n\t\t\t\t\t);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " public function get_view_config() {\n global $template;\n \n // set paths we will search in for the view\n $paths = array(\n BASE.'themes/'.DISPLAY_THEME.'/modules/common/views/file/configure',\n BASE.'framework/modules/common/views/file/configure',\n );\n\n foreach ($paths as $path) {\n $view = $path.'/'.$this->params['view'].'.tpl';\n if (is_readable($view)) {\n if (bs(true)) {\n $bstrapview = $path.'/'.$this->params['view'].'.bootstrap.tpl';\n if (file_exists($bstrapview)) {\n $view = $bstrapview;\n }\n }\n if (bs3(true)) {\n $bstrapview = $path.'/'.$this->params['view'].'.bootstrap3.tpl';\n if (file_exists($bstrapview)) {\n $view = $bstrapview;\n }\n }\n $template = new controllertemplate($this, $view);\n $ar = new expAjaxReply(200, 'ok');\n\t\t $ar->send();\n }\n }\n }", "label_name": "CWE-74", "label": "74"} -{"code": "\tfunction selectBillingOptions() {\n\t\t\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": " private function edebug($str) {\n if ($this->Debugoutput == \"error_log\") {\n error_log($str);\n } else {\n echo $str;\n }\n }", "label_name": "CWE-20", "label": "20"} -{"code": " return $fa->nameGlyph($icons, 'icon-');\r\n }\r\n } else {\r\n return array();\r\n }\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public function testUserCredentials($email, $password, $server, $port, $security) {\n require_once(realpath(Yii::app()->basePath.'/components/phpMailer/class.phpmailer.php'));\n require_once(realpath(Yii::app()->basePath.'/components/phpMailer/class.smtp.php'));\n $phpMail = new PHPMailer(true);\n\n $phpMail->isSMTP();\n $phpMail->SMTPAuth = true;\n $phpMail->Username = $email;\n $phpMail->Password = $password;\n $phpMail->Host = $server;\n $phpMail->Port = $port;\n $phpMail->SMTPSecure = $security;\n\n try {\n $validCredentials = $phpMail->SmtpConnect();\n } catch(phpmailerException $error) {\n $validCredentials = false;\n }\n return $validCredentials;\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\tpublic function wp_footer() {\r\n\t\tglobal $geo_mashup_options;\r\n\t\tif ( $this->add_form_script ) {\r\n\t\t\tGeoMashup::register_script( \r\n\t\t\t\t\t'geo-mashup-comment-form', \r\n\t\t\t\t\t'js/comment-form.js', \r\n\t\t\t\t\tarray( 'jquery' ), \r\n\t\t\t\t\tGEO_MASHUP_VERSION, \r\n\t\t\t\t\ttrue );\r\n\t\t\t\t\t\r\n\t\t\twp_localize_script( 'geo-mashup-comment-form', 'geo_mashup_comment_form_settings', array( 'geonames_username' => $geo_mashup_options->get( 'overall', 'geonames_username' ) ) );\r\n\t\t\twp_print_scripts( 'geo-mashup-comment-form' );\r\n\t\t}\r\n\t}\r", "label_name": "CWE-20", "label": "20"} -{"code": " static function authenticate() {\n if (isset($_REQUEST['backend_login'])) {\n $user = DB_DataObject::factory('users');\n $user->active = true;\n $user->name = $_REQUEST['username'];\n $user->find(true);\n\n // Don't look whether that user exists, so we give less timing information\n // Instead, rely only on having a matching password\n $proffered_password = $_REQUEST['password'];\n if (in_array(\n $user->password,\n self::password_hashes($proffered_password, $user->password_salt)\n )) {\n // Regenerate the session ID, unless it's an IE we're talking to which would use the old session ID to load the frame contents\n // Remove this guard once we no longer use frames\n if(!preg_match('/(?i)msie /', $_SERVER['HTTP_USER_AGENT'])) {\n session_regenerate_id();\n }\n $user->login();\n \n return $user;\n } else {\n Log::warn(\"Failed login for user name '\".$_REQUEST['username'].\"' from \" . $_SERVER['REMOTE_ADDR'].' user-agent '.$_SERVER['HTTP_USER_AGENT']);\n return -1;\n }\n }\n return false;\n }", "label_name": "CWE-522", "label": "522"} -{"code": "\tpublic function __construct( \\DPL\\Parameters $parameters, \\Parser $parser ) {\n\t\t$this->setHeadListAttributes( $parameters->getParameter( 'hlistattr' ) );\n\t\t$this->setHeadItemAttributes( $parameters->getParameter( 'hitemattr' ) );\n\t\t$this->setListAttributes( $parameters->getParameter( 'listattr' ) );\n\t\t$this->setItemAttributes( $parameters->getParameter( 'itemattr' ) );\n\t\t$this->setDominantSectionCount( $parameters->getParameter( 'dominantsection' ) );\n\t\t$this->setTemplateSuffix( $parameters->getParameter( 'defaulttemplatesuffix' ) );\n\t\t$this->setTrimIncluded( $parameters->getParameter( 'includetrim' ) );\n\t\t$this->setTableSortColumn( $parameters->getParameter( 'tablesortcol' ) );\n\t\t$this->setTableSortMethod($parameters->getParameter('tablesortmethod'));\n\t\t$this->setTitleMaxLength( $parameters->getParameter( 'titlemaxlen' ) );\n\t\t$this->setEscapeLinks( $parameters->getParameter( 'escapelinks' ) );\n\t\t$this->setSectionSeparators( $parameters->getParameter( 'secseparators' ) );\n\t\t$this->setMultiSectionSeparators( $parameters->getParameter( 'multisecseparators' ) );\n\t\t$this->setIncludePageText( $parameters->getParameter( 'incpage' ) );\n\t\t$this->setIncludePageMaxLength( $parameters->getParameter( 'includemaxlen' ) );\n\t\t$this->setPageTextMatch( (array)$parameters->getParameter( 'seclabels' ) );\n\t\t$this->setPageTextMatchRegex( (array)$parameters->getParameter( 'seclabelsmatch' ) );\n\t\t$this->setPageTextMatchNotRegex( (array)$parameters->getParameter( 'seclabelsnotmatch' ) );\n\t\t$this->setIncludePageParsed( $parameters->getParameter( 'incparsed' ) );\n\t\t$this->parameters = $parameters;\n\t\t$this->parser = clone $parser;\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": "\tpublic function setHeadItemAttributes( $attributes ) {\n\t\t$this->headItemAttributes = \\Sanitizer::fixTagAttributes( $attributes, 'li' );\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " public static function fixName($name) {\n $name = preg_replace('/[^A-Za-z0-9\\.]/','_',$name);\n if ($name[0] == '.')\n $name[0] = '_';\n return $name;\n// return preg_replace('/[^A-Za-z0-9\\.]/', '-', $name);\n }", "label_name": "CWE-74", "label": "74"} -{"code": " $emails[$u->email] = trim(user::getUserAttribution($u->id));\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " $this->markTestSkipped('Function openssl_random_pseudo_bytes need LibreSSL version >=2.1.5 or Windows system on server');\n }\n }\n\n static::$functions = $functions;\n\n // test various string lengths\n for ($length = 1; $length < 64; $length++) {\n $key1 = $this->security->generateRandomKey($length);\n $this->assertInternalType('string', $key1);\n $this->assertEquals($length, strlen($key1));\n $key2 = $this->security->generateRandomKey($length);\n $this->assertInternalType('string', $key2);\n $this->assertEquals($length, strlen($key2));\n if ($length >= 7) { // avoid random test failure, short strings are likely to collide\n $this->assertNotEquals($key1, $key2);\n }\n }\n\n // test for /dev/urandom, reading larger data to see if loop works properly\n $length = 1024 * 1024;\n $key1 = $this->security->generateRandomKey($length);\n $this->assertInternalType('string', $key1);\n $this->assertEquals($length, strlen($key1));\n $key2 = $this->security->generateRandomKey($length);\n $this->assertInternalType('string', $key2);\n $this->assertEquals($length, strlen($key2));\n $this->assertNotEquals($key1, $key2);\n\n // force /dev/urandom reading loop to deal with chunked data\n // the above test may have read everything in one run.\n // not sure if this can happen in real life but if it does\n // we should be prepared\n static::$fopen = fopen('php://memory', 'rwb');\n $length = 1024 * 1024;\n $key1 = $this->security->generateRandomKey($length);\n $this->assertInternalType('string', $key1);\n $this->assertEquals($length, strlen($key1));\n }", "label_name": "CWE-330", "label": "330"} -{"code": "\t\tpublic function push($remote = NULL, array $params = NULL)\n\t\t{\n\t\t\t$this->run('push', $remote, $params);\n\t\t\treturn $this;\n\t\t}", "label_name": "CWE-77", "label": "77"} -{"code": "\t\t\t\t\t$text = wfMessage( 'intersection_noincludecats', $args )->text();\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ( empty( $text ) ) {\n\t\t\t\t$text = wfMessage( 'dpl_log_' . $errorMessageId, $args )->text();\n\t\t\t}\n\t\t\t$this->buffer[] = '

Extension:DynamicPageList (DPL), version ' . DPL_VERSION . ': ' . $text . '

';\n\t\t}\n\t\treturn false;\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": "\tpublic function setPageTextMatchRegex( array $pageTextMatchRegex = [] ) {\n\t\t$this->pageTextMatchRegex = (array)$pageTextMatchRegex;\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " $section = new section($this->params);\r\n } else {\r\n notfoundController::handle_not_found();\r\n exit;\r\n }\r\n if (!empty($section->id)) {\r\n $check_id = $section->id;\r\n } else {\r\n $check_id = $section->parent;\r\n }\r\n if (expPermissions::check('manage', expCore::makeLocation('navigation', '', $check_id))) {\r\n if (empty($section->id)) {\r\n $section->active = 1;\r\n $section->public = 1;\r\n if (!isset($section->parent)) {\r\n // This is another precaution. The parent attribute\r\n // should ALWAYS be set by the caller.\r\n //FJD - if that's the case, then we should die.\r\n notfoundController::handle_not_authorized();\r\n exit;\r\n //$section->parent = 0;\r\n }\r\n }\r\n assign_to_template(array(\r\n 'section' => $section,\r\n 'glyphs' => self::get_glyphs(),\r\n ));\r\n } else { // User does not have permission to manage sections. Throw a 403\r\n notfoundController::handle_not_authorized();\r\n }\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public static function validateByRegex($path, $values, $regex)\n {\n $result = preg_match($regex, $values[$path]);\n return array($path => ($result ? '' : __('Incorrect value!')));\n }", "label_name": "CWE-200", "label": "200"} -{"code": " private function generateFakeFileData()\n {\n return [\n 'name' => md5(mt_rand()),\n 'tmp_name' => md5(mt_rand()),\n 'type' => 'image/jpeg',\n 'size' => mt_rand(1000, 10000),\n 'error' => '0',\n ];\n }", "label_name": "CWE-330", "label": "330"} -{"code": " protected function getFile()\n {\n $task_id = $this->request->getIntegerParam('task_id');\n $file_id = $this->request->getIntegerParam('file_id');\n $model = 'projectFileModel';\n\n if ($task_id > 0) {\n $model = 'taskFileModel';\n $project_id = $this->taskFinderModel->getProjectId($task_id);\n\n if ($project_id !== $this->request->getIntegerParam('project_id')) {\n throw new AccessForbiddenException();\n }\n }\n\n $file = $this->$model->getById($file_id);\n\n if (empty($file)) {\n throw new PageNotFoundException();\n }\n\n $file['model'] = $model;\n return $file;\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public function IsHTML($ishtml = true) {\n if ($ishtml) {\n $this->ContentType = 'text/html';\n } else {\n $this->ContentType = 'text/plain';\n }\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function setModelAttributes(&$model,&$attributeList,&$params) {\n $data = array ();\n foreach($attributeList as &$attr) {\n if(!isset($attr['name'],$attr['value']))\n continue;\n\n if(null !== $field = $model->getField($attr['name'])) {\n // first do variable/expression evaluation, // then process with X2Fields::parseValue()\n $type = $field->type;\n $value = $attr['value'];\n if(is_string($value)){\n if(strpos($value, '=') === 0){\n $evald = X2FlowFormatter::parseFormula($value, $params);\n if(!$evald[0])\n return false;\n $value = $evald[1];\n } elseif($params !== null){\n\n if(is_string($value) && isset($params['model'])){\n $value = X2FlowFormatter::replaceVariables(\n $value, $params['model'], $type);\n }\n }\n }\n\n $data[$attr['name']] = $value;\n }\n }\n if (!isset ($model->scenario)) \n $model->setScenario ('X2Flow');\n $model->setX2Fields ($data);\n\n if ($model instanceof Actions && isset($data['complete'])) {\n switch($data['complete']) {\n case 'Yes':\n $model->complete();\n break;\n case 'No':\n $model->uncomplete();\n break;\n }\n }\n\n return true;\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\tfunction manage() {\n\t global $db;\n\t \n\t expHistory::set('manageable', $this->params);\n//\t $classes = array();\n $dir = BASE.\"framework/modules/ecommerce/billingcalculators\";\n if (is_readable($dir)) {\n $dh = opendir($dir);\n while (($file = readdir($dh)) !== false) {\n if (is_file(\"$dir/$file\") && substr(\"$dir/$file\", -4) == \".php\") {\n include_once(\"$dir/$file\");\n $classname = substr($file, 0, -4);\n $id = $db->selectValue('billingcalculator', 'id', 'calculator_name=\"'.$classname.'\"');\n if (empty($id)) {\n// $calobj = null;\n $calcobj = new $classname();\n if ($calcobj->isSelectable() == true) {\n $obj = new billingcalculator(array(\n 'title'=>$calcobj->name(),\n// 'user_title'=>$calcobj->title,\n 'body'=>$calcobj->description(), \n 'calculator_name'=>$classname,\n 'enabled'=>false));\n $obj->save();\n }\n }\n }\n }\n }\n \n $bcalc = new billingcalculator();\n $calculators = $bcalc->find('all');\n assign_to_template(array(\n 'calculators'=>$calculators\n ));\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": "\tpublic function delete_version() {\n\t if (empty($this->params['id'])) {\n\t flash('error', gt('The version you are trying to delete could not be found'));\n\t }\n\t \n\t // get the version\n\t $version = new help_version($this->params['id']);\n\t if (empty($version->id)) {\n\t flash('error', gt('The version you are trying to delete could not be found'));\n\t }\n\t \n\t // if we have errors than lets get outta here!\n\t if (!expQueue::isQueueEmpty('error')) expHistory::back();\n\t \n\t // delete the version\n\t $version->delete();\n\t \n\t expSession::un_set('help-version');\n\n\t flash('message', gt('Deleted version').' '.$version->version.' '.gt('and all documents in that version.'));\n\t expHistory::back();\t \n\t}", "label_name": "CWE-74", "label": "74"} -{"code": " public function confirm()\n {\n $task = $this->getTask();\n $subtask = $this->getSubtask();\n\n $this->response->html($this->template->render('subtask/remove', array(\n 'subtask' => $subtask,\n 'task' => $task,\n )));\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public function upload() {\n if (!AuthUser::hasPermission('file_manager_upload')) {\n Flash::set('error', __('You do not have sufficient permissions to upload a file.'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n \n // CSRF checks\n if (isset($_POST['csrf_token'])) {\n $csrf_token = $_POST['csrf_token'];\n if (!SecureToken::validateToken($csrf_token, BASE_URL.'plugin/file_manager/upload')) {\n Flash::set('error', __('Invalid CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n }\n else {\n Flash::set('error', __('No CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n \n $mask = Plugin::getSetting('umask', 'file_manager');\n umask(octdec($mask));\n\n $data = $_POST['upload'];\n $path = str_replace('..', '', $data['path']);\n $overwrite = isset($data['overwrite']) ? true : false;\n\n // Clean filenames\n $filename = preg_replace('/ /', '_', $_FILES['upload_file']['name']);\n $filename = preg_replace('/[^a-z0-9_\\-\\.]/i', '', $filename);\n\n if (isset($_FILES)) {\n $file = $this->_upload_file($filename, FILES_DIR . '/' . $path . '/', $_FILES['upload_file']['tmp_name'], $overwrite);\n\n if ($file === false)\n Flash::set('error', __('File has not been uploaded!'));\n }\n redirect(get_url('plugin/file_manager/browse/' . $path));\n }", "label_name": "CWE-20", "label": "20"} -{"code": " foreach ($grpusers as $u) {\r\n $emails[$u->email] = trim(user::getUserAttribution($u->id));\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " foreach ($grpusers as $u) {\r\n $emails[$u->email] = trim(user::getUserAttribution($u->id));\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public function __construct(\n GlyphFinder $glyph_finder,\n ProjectXMLMerger $project_xml_merger,\n ConsistencyChecker $consistency_checker,\n TemplateDao $template_dao,\n ProjectManager $project_manager,\n EventDispatcherInterface $event_dispatcher,\n ) {\n $this->template_dao = $template_dao;\n $this->templates = [\n AgileALMTemplate::NAME => new AgileALMTemplate($glyph_finder, $project_xml_merger, $consistency_checker),\n ScrumTemplate::NAME => new ScrumTemplate($glyph_finder, $project_xml_merger, $consistency_checker),\n KanbanTemplate::NAME => new KanbanTemplate($glyph_finder, $project_xml_merger, $consistency_checker),\n IssuesTemplate::NAME => new IssuesTemplate($glyph_finder, $consistency_checker, $event_dispatcher),\n EmptyTemplate::NAME => new EmptyTemplate($glyph_finder),\n ];\n $this->project_manager = $project_manager;\n $this->glyph_finder = $glyph_finder;\n\n $this->external_templates = self::getExternalTemplatesByName($event_dispatcher);\n }", "label_name": "CWE-863", "label": "863"} -{"code": "\tstatic public function getInstanceOf($_usernfo, $_tid) {\n\t\tif (!isset(self::$tickets[$_tid])) {\n\t\t\tself::$tickets[$_tid] = new ticket($_usernfo, $_tid);\n\t\t}\n\t\treturn self::$tickets[$_tid];\n\t}", "label_name": "CWE-732", "label": "732"} -{"code": "function PMA_linkURL($url)\n{\n if (!preg_match('#^https?://#', $url) || defined('PMA_SETUP')) {\n return $url;\n }\n\n if (!function_exists('PMA_URL_getCommon')) {\n include_once './libraries/url_generating.lib.php';\n }\n $params = array();\n $params['url'] = $url;\n\n $url = PMA_URL_getCommon($params);\n //strip off token and such sensitive information. Just keep url.\n $arr = parse_url($url);\n parse_str($arr[\"query\"], $vars);\n $query = http_build_query(array(\"url\" => $vars[\"url\"]));\n $url = './url.php?' . $query;\n\n return $url;\n}", "label_name": "CWE-200", "label": "200"} -{"code": " public function getError() {\n return $this->error;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " $backup = ['sys' => $GLOBALS['TYPO3_CONF_VARS']['SYS'], 'server' => $_SERVER];", "label_name": "CWE-20", "label": "20"} -{"code": " function connect() {\n\n return $this->connectToServer($this->fields['host'], $this->fields['port'],\n $this->fields['rootdn'],\n Toolbox::decrypt($this->fields['rootdn_passwd'], GLPIKEY),\n $this->fields['use_tls'],\n $this->fields['deref_option']);\n }", "label_name": "CWE-327", "label": "327"} -{"code": "function XMLRPCremoveUserGroupPriv($name, $affiliation, $nodeid, $permissions){\n require_once(\".ht-inc/privileges.php\");\n\tglobal $user;\n\n if(! checkUserHasPriv(\"userGrant\", $user['id'], $nodeid)){\n\t\treturn array('status' => 'error',\n 'errorcode' => 53,\n 'errormsg' => 'Unable to remove group privileges on this node');\n }\n\n\t$validate = array('name' => $name,\n\t 'affiliation' => $affiliation);\n\t$rc = validateAPIgroupInput($validate, 1);\n\tif($rc['status'] == 'error')\n\t\treturn $rc;\n\n $groupid = $rc['id'];\n $groupname = \"$name@$affiliation\";\n $perms = explode(':', $permissions);\n $usertypes = getTypes('users');\n array_push($usertypes[\"users\"], \"block\");\n\tarray_push($usertypes[\"users\"], \"cascade\");\n $cascadePrivs = getNodeCascadePriviliges($nodeid, \"usergroups\");\n $removegroupprivs = array();\n if(array_key_exists($groupname, $cascadePrivs['usergroups'])){\n foreach($perms as $permission){\n if(in_array($permission, $cascadePrivs['usergroups'][$groupname]['privs'])){\n array_push($removegroupprivs, $permission);\n }\n }\n $diff = array_diff($cascadePrivs['usergroups'][$groupname], $removegroupprivs);\n if(count($diff) == 1 && in_array(\"cascade\", $diff)){\n array_push($removegroupprivs, \"cascade\");\n\t}\n\t}\n if(empty($removegroupprivs)){\n\t\treturn array('status' => 'error',\n 'errorcode' => 53,\n 'errormsg' => 'Invalid or missing permissions list supplied');\n\t}\n\n updateUserOrGroupPrivs($groupid, $nodeid, array(), $removegroupprivs, \"group\");\n return array('status' => 'success');\n}", "label_name": "CWE-20", "label": "20"} -{"code": " public function AddBCC($address, $name = '') {\n return $this->AddAnAddress('bcc', $address, $name);\n }", "label_name": "CWE-20", "label": "20"} -{"code": " function showallSubcategories() {\n// global $db;\n\n expHistory::set('viewable', $this->params);\n// $parent = isset($this->params['cat']) ? $this->params['cat'] : expSession::get('catid');\n $catid = expSession::get('catid');\n $parent = !empty($catid) ? $catid : (!empty($this->params['cat']) ? $this->params['cat'] : 0);\n $category = new storeCategory($parent);\n $categories = $category->getEcomSubcategories();\n $ancestors = $category->pathToNode();\n assign_to_template(array(\n 'categories' => $categories,\n 'ancestors' => $ancestors,\n 'category' => $category\n ));\n }", "label_name": "CWE-20", "label": "20"} -{"code": " $object->size = convert_size($cur->getSize());\n $object->mtime = date('D, j M, Y', $cur->getMTime());\n list($object->perms, $object->chmod) = $this->_getPermissions($cur->getPerms());\n \n // Find the file type\n $object->type = $this->_getFileType($cur);\n\n // make the link depending on if it's a file or a dir\n if ($cur->isDir()) {\n $object->link = 'path . $object->name) . '\">' . $object->name . '';\n } else {\n $object->link = 'path . $object->name . (endsWith($object->name, URL_SUFFIX) ? '?has_url_suffix=1' : '')) . '\">' . $object->name . '';\n }\n\n $files[$object->name] = $object;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " protected function generateCookieHash($class, $username, $expires, $password)\n {\n return hash_hmac('sha256', $class.$username.$expires.$password, $this->getSecret());\n }", "label_name": "CWE-287", "label": "287"} -{"code": " private function catchWarning ($errno, $errstr, $errfile, $errline) {\n $this->error[] = array(\n 'error' => \"Connecting to the POP3 server raised a PHP warning: \",\n 'errno' => $errno,\n 'errstr' => $errstr\n );\n }", "label_name": "CWE-20", "label": "20"} -{"code": " function productFeed() {\n// global $db;\n //check query password to avoid DDOS\n /*\n * condition = new\n * description \n * id - SKU \n * link \n * price \n * title \n * brand - manufacturer \n * image link - fullsized image, up to 10, comma seperated \n * product type - category - \"Electronics > Audio > Audio Accessories MP3 Player Accessories\",\"Health & Beauty > Healthcare > Biometric Monitors > Pedometers\" \n */\n $out = '\"id\",\"condition\",\"description\",\"like\",\"price\",\"title\",\"brand\",\"image link\",\"product type\"' . chr(13) . chr(10);\n\n $p = new product();\n $prods = $p->find('all', 'parent_id=0 AND ');\n //$prods = $db->selectObjects('product','parent_id=0 AND');\n }", "label_name": "CWE-74", "label": "74"} -{"code": " protected function tearDown()\n {\n static::$functions = [];\n static::$fopen = null;\n static::$fread = null;\n parent::tearDown();\n }", "label_name": "CWE-330", "label": "330"} -{"code": "function getResourceGroupID($groupdname) {\n\tlist($type, $name) = explode('/', $groupdname);\n\t$query = \"SELECT g.id \"\n\t . \"FROM resourcegroup g, \"\n\t . \"resourcetype t \"\n\t . \"WHERE g.name = '$name' AND \"\n\t . \"t.name = '$type' AND \"\n\t . \"g.resourcetypeid = t.id\";\n\t$qh = doQuery($query, 371);\n\tif($row = mysql_fetch_row($qh))\n\t\treturn $row[0];\n\telse\n\t\treturn NULL;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "function BadAuthDigestTestController($serverPort) {\n $args = array('Authorization' => 'Digest \"username=\"admin\", ' .\n 'realm=\"Restricted area\", nonce=\"564a12f5c065e\", ' .\n 'uri=\"/test_auth_digest.php\", cnonce=\"MjIyMTg2\", nc=00000001, ' .\n 'qop=\"auth\", response=\"6dfbea52fbf13016476c1879e6436004\", ' .\n 'opaque=\"cdce8a5c95a1427d74df7acbf41c9ce0\"');\n var_dump(request(php_uname('n'), $serverPort, \"test_auth_digest.php\",\n [], [], $args));\n}", "label_name": "CWE-668", "label": "668"} -{"code": "\tpublic function setPageTextMatchNotRegex( array $pageTextMatchNotRegex = [] ) {\n\t\t$this->pageTextMatchNotRegex = (array)$pageTextMatchNotRegex;\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " function update() {\r\n parent::update();\r\n expSession::clearAllUsersSessionCache('navigation');\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public function destroy(PaymentMethod $paymentMethod)\n {\n $this->authorize('delete', $paymentMethod);\n\n $payments = $paymentMethod->payments;\n\n if ($payments->count() > 0) {\n return respondJson('payments_attached', 'Payments Attached.');\n }\n\n $paymentMethod->delete();\n\n return response()->json([\n 'success' => 'Payment method deleted successfully',\n ]);\n }", "label_name": "CWE-862", "label": "862"} -{"code": " function edit() {\n global $user;\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n $require_login = empty($this->params['require_login']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];\n $require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];\n $require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n $notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];\n \n if (empty($this->params['formtitle'])) \n {\n if (empty($this->params['id']))\n {\n $formtitle = gt(\"Add New Note\");\n }\n else\n {\n $formtitle = gt(\"Edit Note\");\n }\n }\n else\n {\n $formtitle = $this->params['formtitle'];\n }\n \n $id = empty($this->params['id']) ? null : $this->params['id'];\n $simpleNote = new expSimpleNote($id);\n //FIXME here is where we might sanitize the note before displaying/editing it\n\n assign_to_template(array(\n 'simplenote'=>$simpleNote,\n 'user'=>$user,\n 'require_login'=>$require_login,\n 'require_approval'=>$require_approval,\n 'require_notification'=>$require_notification,\n 'notification_email'=>$notification_email,\n 'formtitle'=>$formtitle,\n 'content_type'=>$this->params['content_type'],\n 'content_id'=>$this->params['content_id'],\n 'tab'=>empty($this->params['tab'])?0:$this->params['tab']\n ));\n } ", "label_name": "CWE-74", "label": "74"} -{"code": "\t\t\tVariables::setVar( [ '', '', $variable, $value ] );\n\t\t\tif ( defined( 'ExtVariables::VERSION' ) ) {\n\t\t\t\t\\ExtVariables::get( $this->parser )->setVarValue( $variable, $value );\n\t\t\t}\n\t\t}\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": "function barcode_encode_genbarcode($code,$encoding)\n{\n global $genbarcode_loc;\n\n // Clean parameters\n if (preg_match(\"/^ean$/i\", $encoding) && strlen($code)==13) $code=substr($code,0,12);\n if (!$encoding) $encoding=\"ANY\";\n $encoding=preg_replace(\"/[\\\\\\|]/\", \"_\", $encoding);\n $code=preg_replace(\"/[\\\\\\|]/\", \"_\", $code);\n\n $command=escapeshellarg($genbarcode_loc);\n $paramclear=\" \\\"\".str_replace(\"\\\"\", \"\\\\\\\"\",$code).\"\\\" \\\"\".str_replace(\"\\\"\", \"\\\\\\\"\",strtoupper($encoding)).\"\\\"\";\n\n $fullcommandclear=$command.\" \".$paramclear.\" 2>&1\";\n //print $fullcommandclear.\"
\\n\";\n\n dol_syslog(\"Run command \".$fullcommandclear);\n $fp=popen($fullcommandclear, \"r\");\n if ($fp)\n {\n $bars=fgets($fp, 1024);\n $text=fgets($fp, 1024);\n $encoding=fgets($fp, 1024);\n pclose($fp);\n }\n else\n {\n dol_syslog(\"barcode.lib.php::barcode_encode_genbarcode failed to run popen \".$fullcommandclear, LOG_ERR);\n return false;\n }\n //var_dump($bars);\n $ret=array(\n\t\t\"encoding\" => trim($encoding),\n\t\t\"bars\" => trim($bars),\n\t\t\"text\" => trim($text)\n );\n //var_dump($ret);\n if (!$ret['encoding']) return false;\n if (!$ret['bars']) return false;\n if (!$ret['text']) return false;\n return $ret;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "function headerTestController($serverPort) {\n $args = array('Authorization' => 'foo');\n var_dump(request(php_uname('n'), $serverPort, \"test_headers.php\",\n [], ['PROXY' => 'foobar'], $args));\n}", "label_name": "CWE-668", "label": "668"} -{"code": " public function browse() {\n $params = func_get_args();\n\n $this->path = join('/', $params);\n // make sure there's a / at the end\n if (substr($this->path, -1, 1) != '/')\n $this->path .= '/';\n\n //security\n // we dont allow back link\n if (strpos($this->path, '..') !== false) {\n /*\n if (Plugin::isEnabled('statistics_api')) {\n $user = null;\n if (AuthUser::isLoggedIn())\n $user = AuthUser::getUserName();\n $ip = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : ($_SERVER['REMOTE_ADDR']);\n $event = array('event_type' => 'hack_attempt', // simple event type identifier\n 'description' => __('A possible hack attempt was detected.'), // translatable description\n 'ipaddress' => $ip,\n 'username' => $user);\n Observer::notify('stats_file_manager_hack_attempt', $event);\n }\n */\n }\n $this->path = str_replace('..', '', $this->path);\n\n // clean up nicely\n $this->path = str_replace('//', '', $this->path);\n\n // we dont allow leading slashes\n $this->path = preg_replace('/^\\//', '', $this->path);\n\n $this->fullpath = FILES_DIR . '/' . $this->path;\n\n // clean up nicely\n $this->fullpath = preg_replace('/\\/\\//', '/', $this->fullpath);\n\n $this->display('file_manager/views/index', array(\n 'dir' => $this->path,\n //'files' => $this->_getListFiles()\n 'files' => $this->_listFiles()\n ));\n }", "label_name": "CWE-20", "label": "20"} -{"code": " static function dropdownConnect($itemtype, $fromtype, $myname, $entity_restrict = -1,\n $onlyglobal = 0, $used = []) {\n global $CFG_GLPI;\n\n $rand = mt_rand();\n\n $field_id = Html::cleanId(\"dropdown_\".$myname.$rand);\n $param = [\n 'entity_restrict' => $entity_restrict,\n 'fromtype' => $fromtype,\n 'itemtype' => $itemtype,\n 'onlyglobal' => $onlyglobal,\n 'used' => $used,\n '_idor_token' => Session::getNewIDORToken($itemtype),\n ];\n\n echo Html::jsAjaxDropdown($myname, $field_id,\n $CFG_GLPI['root_doc'].\"/ajax/getDropdownConnect.php\",\n $param);\n\n return $rand;\n }", "label_name": "CWE-862", "label": "862"} -{"code": " public function afterSave($event) {\n // look up current tags\n $oldTags = $this->getTags();\n $newTags = array();\n\n foreach ($this->scanForTags() as $tag) {\n if (!in_array($tag, $oldTags)) { // don't add duplicates if there are already tags\n $tagModel = new Tags;\n $tagModel->tag = $tag; // includes the #\n $tagModel->type = get_class($this->getOwner());\n $tagModel->itemId = $this->getOwner()->id;\n $tagModel->itemName = $this->getOwner()->name;\n $tagModel->taggedBy = Yii::app()->getSuName();\n $tagModel->timestamp = time();\n if ($tagModel->save())\n $newTags[] = $tag;\n }\n }\n $this->_tags = $newTags + $oldTags; // update tag cache\n\n if (!empty($newTags) && $this->flowTriggersEnabled) {\n X2Flow::trigger('RecordTagAddTrigger', array(\n 'model' => $this->getOwner(),\n 'tags' => $newTags,\n ));\n }\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function getXForwardedForData()\n {\n return array(\n array(false, '10.0.0.1'),\n array('10.0.0.2', '10.0.0.2, 10.0.0.1'),\n array('10.0.0.2, 10.0.0.3', '10.0.0.2, 10.0.0.3, 10.0.0.1'),\n );\n }", "label_name": "CWE-20", "label": "20"} -{"code": " $sloc = expCore::makeLocation('navigation', null, $section->id);\r\n // remove any manage permissions for this page and it's children\r\n // $db->delete('userpermission', \"module='navigationController' AND internal=\".$section->id);\r\n // $db->delete('grouppermission', \"module='navigationController' AND internal=\".$section->id);\r\n foreach ($allusers as $uid) {\r\n $u = user::getUserById($uid);\r\n expPermissions::grant($u, 'manage', $sloc);\r\n }\r\n foreach ($allgroups as $gid) {\r\n $g = group::getGroupById($gid);\r\n expPermissions::grantGroup($g, 'manage', $sloc);\r\n }\r\n }\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " $cLoc = serialize(expCore::makeLocation('container','@section' . $page->id));\r\n $ret .= scan_container($cLoc, $page->id);\r\n $ret .= scan_page($page->id);\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public function __construct(AuthManager $auth, Repository $config)\n {\n $this->lockoutTime = $config->get('auth.lockout.time');\n $this->maxLoginAttempts = $config->get('auth.lockout.attempts');\n\n $this->auth = $auth;\n $this->config = $config;\n }", "label_name": "CWE-287", "label": "287"} -{"code": " static::$functions = ['random_bytes' => false, 'openssl_random_pseudo_bytes' => false, 'mcrypt_create_iv' => false];", "label_name": "CWE-330", "label": "330"} -{"code": "\tpublic function test_valid_comment_allow_empty_content() {\n\t\tadd_filter( 'allow_empty_comment', '__return_true' );\n\t\t$result = $this->myxmlrpcserver->wp_newComment(\n\t\t\tarray(\n\t\t\t\t1,\n\t\t\t\t'administrator',\n\t\t\t\t'administrator',\n\t\t\t\tself::$post->ID,\n\t\t\t\tarray(\n\t\t\t\t\t'content' => ' ',\n\t\t\t\t),\n\t\t\t)\n\t\t);\n\n\t\t$this->assertNotIXRError( $result );\n\t}", "label_name": "CWE-862", "label": "862"} -{"code": " public function validate() {\n global $db;\n // check for an sef url field. If it exists make sure it's valid and not a duplicate\n //this needs to check for SEF URLS being turned on also: TODO\n\n if (property_exists($this, 'sef_url') && !(in_array('sef_url', $this->do_not_validate))) {\n if (empty($this->sef_url)) $this->makeSefUrl();\n if (!isset($this->validates['is_valid_sef_name']['sef_url'])) $this->validates['is_valid_sef_name']['sef_url'] = array();\n if (!isset($this->validates['uniqueness_of']['sef_url'])) $this->validates['uniqueness_of']['sef_url'] = array();\n }\n\n // safeguard again loc data not being pass via forms...sometimes this happens when you're in a router\n // mapped view and src hasn't been passed in via link to the form \n if (isset($this->id) && empty($this->location_data)) {\n $loc = $db->selectValue($this->tablename, 'location_data', 'id=' . $this->id);\n if (!empty($loc)) $this->location_data = $loc;\n }\n\n // run the validation as defined in the models\n if (!isset($this->validates)) return true;\n $messages = array();\n $post = empty($_POST) ? array() : expString::sanitize($_POST);\n foreach ($this->validates as $validation=> $field) {\n foreach ($field as $key=> $value) {\n $fieldname = is_numeric($key) ? $value : $key;\n $opts = is_numeric($key) ? array() : $value;\n $ret = expValidator::$validation($fieldname, $this, $opts);\n if (!is_bool($ret)) {\n $messages[] = $ret;\n expValidator::setErrorField($fieldname);\n unset($post[$fieldname]);\n }\n }\n }\n\n if (count($messages) >= 1) expValidator::failAndReturnToForm($messages, $post);\n }", "label_name": "CWE-74", "label": "74"} -{"code": " $this->subtaskTimeTrackingModel->logEndTime($subtaskId, $this->userSession->getId());\n $this->subtaskTimeTrackingModel->updateTaskTimeTracking($task['id']);\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = false)\n {\n $this->catch = $catch;\n $this->backendRequest = $request;\n\n return parent::handle($request, $type, $catch);\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\tprivate function _addeditdate( $option ) {\n\t\t$this->addTable( 'revision_actor_temp', 'rev' );\n\t\t$this->addSelect( [ 'rev.revactor_timestamp' ] );\n\t\t$this->addWhere(\n\t\t\t[\n\t\t\t\t$this->tableNames['page'] . '.page_id = rev.revactor_page',\n\t\t\t]\n\t\t);\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " public function subscriptions() {\n global $db;\n \n expHistory::set('manageable', $this->params);\n // make sure we have what we need.\n if (empty($this->params['key'])) expQueue::flashAndFlow('error', gt('The security key for account was not supplied.'));\n if (empty($this->params['id'])) expQueue::flashAndFlow('error', gt('The subscriber id for account was not supplied.'));\n \n // verify the id/key pair \n $sub = new subscribers($this->params['id']);\n if (empty($sub->id)) expQueue::flashAndFlow('error', gt('We could not find any subscriptions matching the ID and Key you provided.'));\n \n // get this users subscriptions\n $subscriptions = $db->selectColumn('expeAlerts_subscribers', 'expeAlerts_id', 'subscribers_id='.$sub->id);\n \n // get a list of all available E-Alerts\n $ealerts = new expeAlerts();\n assign_to_template(array(\n 'subscriber'=>$sub,\n 'subscriptions'=>$subscriptions,\n 'ealerts'=>$ealerts->find('all')\n ));\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function params()\n {\n $project = $this->getProject();\n $values = $this->request->getValues();\n\n if (empty($values['action_name']) || empty($values['project_id']) || empty($values['event_name'])) {\n $this->create();\n return;\n }\n\n $action = $this->actionManager->getAction($values['action_name']);\n $action_params = $action->getActionRequiredParameters();\n\n if (empty($action_params)) {\n $this->doCreation($project, $values + array('params' => array()));\n }\n\n $projects_list = $this->projectUserRoleModel->getActiveProjectsByUser($this->userSession->getId());\n unset($projects_list[$project['id']]);\n\n $this->response->html($this->template->render('action_creation/params', array(\n 'values' => $values,\n 'action_params' => $action_params,\n 'columns_list' => $this->columnModel->getList($project['id']),\n 'users_list' => $this->projectUserRoleModel->getAssignableUsersList($project['id']),\n 'projects_list' => $projects_list,\n 'colors_list' => $this->colorModel->getList(),\n 'categories_list' => $this->categoryModel->getList($project['id']),\n 'links_list' => $this->linkModel->getList(0, false),\n 'priorities_list' => $this->projectTaskPriorityModel->getPriorities($project),\n 'project' => $project,\n 'available_actions' => $this->actionManager->getAvailableActions(),\n 'swimlane_list' => $this->swimlaneModel->getList($project['id']),\n 'events' => $this->actionManager->getCompatibleEvents($values['action_name']),\n )));\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public function show()\n {\n $task = $this->getTask();\n $subtask = $this->getSubtask();\n\n $this->response->html($this->template->render('subtask_restriction/show', array(\n 'status_list' => array(\n SubtaskModel::STATUS_TODO => t('Todo'),\n SubtaskModel::STATUS_DONE => t('Done'),\n ),\n 'subtask_inprogress' => $this->subtaskStatusModel->getSubtaskInProgress($this->userSession->getId()),\n 'subtask' => $subtask,\n 'task' => $task,\n )));\n }", "label_name": "CWE-200", "label": "200"} -{"code": "\tpublic function getListStart() {\n\t\t// increase start value of ordered lists at multi-column output\n\t\t//The offset that comes from the URL parameter is zero based, but has to be +1'ed for display.\n\t\t$offset = $this->getParameters()->getParameter( 'offset' ) + 1;\n\n\t\tif ( $offset != 0 ) {\n\t\t\t//@TODO: So this adds the total count of articles to the offset. I have not found a case where this does not mess up the displayed count. I am commenting this out for now.\n\t\t\t//$offset += $this->offsetCount;\n\t\t}\n\n\t\treturn sprintf( $this->listStart, $this->listAttributes . ' start=\"' . $offset . '\"' );\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $tag_id = $this->request->getIntegerParam('tag_id');\n $tag = $this->tagModel->getById($tag_id);\n\n if ($tag['project_id'] != $project['id']) {\n throw new AccessForbiddenException();\n }\n\n if ($this->tagModel->remove($tag_id)) {\n $this->flash->success(t('Tag removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this tag.'));\n }\n\n $this->response->redirect($this->helper->url->to('ProjectTagController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-200", "label": "200"} -{"code": "\tprivate function _allrevisionssince( $option ) {\n\t\t$this->addTable( 'revision_actor_temp', 'rev' );\n\t\t$this->addSelect(\n\t\t\t[\n\t\t\t\t'rev.revactor_rev',\n\t\t\t\t'rev.revactor_timestamp'\n\t\t\t]\n\t\t);\n\t\t$this->addOrderBy( 'rev.revactor_rev' );\n\t\t$this->setOrderDir( 'DESC' );\n\t\t$this->addWhere(\n\t\t\t[\n\t\t\t\t$this->tableNames['page'] . '.page_id = rev.revactor_page',\n\t\t\t\t'rev.revactor_timestamp >= ' . $this->convertTimestamp( $option )\n\t\t\t]\n\t\t);\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " static function displayname() {\r\n return \"Events\";\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " $rndString = function ($len = 10) {\n $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n $randomString = '';\n for ($i = 0; $i < $len; $i++) {\n $randomString .= $characters[rand(0, strlen($characters) - 1)];\n }\n\n return $randomString;\n };", "label_name": "CWE-330", "label": "330"} -{"code": " $section = new section($this->params);\r\n } else {\r\n notfoundController::handle_not_found();\r\n exit;\r\n }\r\n if (!empty($section->id)) {\r\n $check_id = $section->id;\r\n } else {\r\n $check_id = $section->parent;\r\n }\r\n if (expPermissions::check('manage', expCore::makeLocation('navigation', '', $check_id))) {\r\n if (empty($section->id)) {\r\n $section->active = 1;\r\n $section->public = 1;\r\n if (!isset($section->parent)) {\r\n // This is another precaution. The parent attribute\r\n // should ALWAYS be set by the caller.\r\n //FJD - if that's the case, then we should die.\r\n notfoundController::handle_not_authorized();\r\n exit;\r\n //$section->parent = 0;\r\n }\r\n }\r\n assign_to_template(array(\r\n 'section' => $section,\r\n 'glyphs' => self::get_glyphs(),\r\n ));\r\n } else { // User does not have permission to manage sections. Throw a 403\r\n notfoundController::handle_not_authorized();\r\n }\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public function update()\n {\n $project = $this->getProject();\n\n $values = $this->request->getValues();\n list($valid, $errors) = $this->swimlaneValidator->validateModification($values);\n\n if ($valid) {\n if ($this->swimlaneModel->update($values['id'], $values)) {\n $this->flash->success(t('Swimlane updated successfully.'));\n return $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));\n } else {\n $errors = array('name' => array(t('Another swimlane with the same name exists in the project')));\n }\n }\n\n return $this->edit($values, $errors);\n }", "label_name": "CWE-200", "label": "200"} -{"code": "\t\t\t\tforeach ($aco_value_array as $aco_value) {\n\t\t\t\t\t$this->debug_text(\"shift_acl(): ACO Section Value: $aco_section_value ACO VALUE: $aco_value\");\n\t\t\t\t\t$aco_key = array_search($aco_value, $acl_array['aco'][$aco_section_value]);\n\n\t\t\t\t\tif ($aco_key !== FALSE) {\n\t\t\t\t\t\t$this->debug_text(\"shift_acl(): Removing ACO. ($aco_key)\");\n\t\t\t\t\t\tunset($acl_array['aco'][$aco_section_value][$aco_key]);\n\t\t\t\t\t\t$update = 1;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$this->debug_text(\"shift_acl(): ACO doesn't exist, can't remove it.\");\n\t\t\t\t\t}\n\t\t\t\t}", "label_name": "CWE-863", "label": "863"} -{"code": "\tpublic function approve_submit() {\n\t if (empty($this->params['id'])) {\n\t flash('error', gt('No ID supplied for comment to approve'));\n\t expHistory::back();\n\t }\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n// $require_login = empty($this->params['require_login']) ? COMMENTS_REQUIRE_LOGIN : $this->params['require_login'];\n// $require_approval = empty($this->params['require_approval']) ? COMMENTS_REQUIRE_APPROVAL : $this->params['require_approval'];\n// $require_notification = empty($this->params['require_notification']) ? COMMENTS_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n// $notification_email = empty($this->params['notification_email']) ? COMMENTS_NOTIFICATION_EMAIL : $this->params['notification_email'];\n\t \n\t $comment = new expComment($this->params['id']);\n\t $comment->body = $this->params['body'];\n\t $comment->approved = $this->params['approved'];\n\t $comment->save();\n\t expHistory::back();\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": " public static function getIconName($module)\n {\n return isset(static::$iconNames[$module])\n ? static::$iconNames[$module]\n : strtolower(str_replace('_', '-', $module));\n }", "label_name": "CWE-287", "label": "287"} -{"code": "\t\t\t\t} elseif ( $sSecLabel[0] != '{' ) {\n\t\t\t\t\t$limpos = strpos( $sSecLabel, '[' );\n\t\t\t\t\t$cutLink = 'default';\n\t\t\t\t\t$skipPattern = [];\n\t\t\t\t\tif ( $limpos > 0 && $sSecLabel[strlen( $sSecLabel ) - 1] == ']' ) {\n\t\t\t\t\t\t// regular expressions which define a skip pattern may precede the text\n\t\t\t\t\t\t$fmtSec = explode( '~', substr( $sSecLabel, $limpos + 1, strlen( $sSecLabel ) - $limpos - 2 ) );\n\t\t\t\t\t\t$sSecLabel = substr( $sSecLabel, 0, $limpos );\n\t\t\t\t\t\t$cutInfo = explode( \" \", $fmtSec[count( $fmtSec ) - 1], 2 );\n\t\t\t\t\t\t$maxLength = intval( $cutInfo[0] );\n\t\t\t\t\t\tif ( array_key_exists( '1', $cutInfo ) ) {\n\t\t\t\t\t\t\t$cutLink = $cutInfo[1];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tforeach ( $fmtSec as $skipKey => $skipPat ) {\n\t\t\t\t\t\t\tif ( $skipKey == count( $fmtSec ) - 1 ) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t$skipPattern[] = $skipPat;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif ( $maxLength < 0 ) {\n\t\t\t\t\t\t$maxLength = -1; // without valid limit include whole section\n\t\t\t\t\t}\n\t\t\t\t}", "label_name": "CWE-400", "label": "400"} -{"code": " public function confirm()\n {\n $project = $this->getProject();\n $swimlane = $this->getSwimlane();\n\n $this->response->html($this->helper->layout->project('swimlane/remove', array(\n 'project' => $project,\n 'swimlane' => $swimlane,\n )));\n }", "label_name": "CWE-200", "label": "200"} -{"code": "\t\tpublic function checkout($name)\n\t\t{\n\t\t\t$this->run('checkout', $name);\n\t\t\treturn $this;\n\t\t}", "label_name": "CWE-77", "label": "77"} -{"code": " foreach ($week as $dayNum => $day) {\r\n if ($dayNum == $now['mday']) {\r\n $currentweek = $weekNum;\r\n }\r\n if ($dayNum <= $endofmonth) {\r\n// $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;\r\n $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;\r\n }\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " function edit_internalalias() {\r\n $section = isset($this->params['id']) ? $this->section->find($this->params['id']) : new section($this->params);\r\n if ($section->parent == -1) {\r\n notfoundController::handle_not_found();\r\n exit;\r\n } // doesn't work for standalone pages\r\n if (empty($section->id)) {\r\n $section->public = 1;\r\n if (!isset($section->parent)) {\r\n // This is another precaution. The parent attribute\r\n // should ALWAYS be set by the caller.\r\n //FJD - if that's the case, then we should die.\r\n notfoundController::handle_not_authorized();\r\n exit;\r\n //$section->parent = 0;\r\n }\r\n }\r\n assign_to_template(array(\r\n 'section' => $section,\r\n 'glyphs' => self::get_glyphs(),\r\n ));\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": "function twig_array_filter(Environment $env, $array, $arrow)\n{\n if (!twig_test_iterable($array)) {\n throw new RuntimeError(sprintf('The \"filter\" filter expects an array or \"Traversable\", got \"%s\".', \\is_object($array) ? \\get_class($array) : \\gettype($array)));\n }\n\n if (!$arrow instanceof Closure && $env->hasExtension('\\Twig\\Extension\\SandboxExtension') && $env->getExtension('\\Twig\\Extension\\SandboxExtension')->isSandboxed()) {\n throw new RuntimeError('The callable passed to \"filter\" filter must be a Closure in sandbox mode.');\n }\n\n if (\\is_array($array)) {\n return array_filter($array, $arrow, \\ARRAY_FILTER_USE_BOTH);\n }\n\n // the IteratorIterator wrapping is needed as some internal PHP classes are \\Traversable but do not implement \\Iterator\n return new \\CallbackFilterIterator(new \\IteratorIterator($array), $arrow);\n}", "label_name": "CWE-74", "label": "74"} -{"code": " public function testPopBeforeSmtpBad()\n {\n //Start a fake POP server on a different port\n //so we don't inadvertently connect to the previous instance\n $pid = shell_exec('nohup ./runfakepopserver.sh 1101 >/dev/null 2>/dev/null & printf \"%u\" $!');\n $this->pids[] = $pid;\n\n sleep(2);\n //Test a known-bad login\n $this->assertFalse(\n POP3::popBeforeSmtp('localhost', 1101, 10, 'user', 'xxx', $this->Mail->SMTPDebug),\n 'POP before SMTP should have failed'\n );\n shell_exec('kill -TERM '.escapeshellarg($pid));\n sleep(2);\n }", "label_name": "CWE-20", "label": "20"} -{"code": " private function get_lines() {\n $data = \"\";\n $endtime = 0;\n /* If for some reason the fp is bad, don't inf loop */\n if (!is_resource($this->smtp_conn)) {\n return $data;\n }\n stream_set_timeout($this->smtp_conn, $this->Timeout);\n if ($this->Timelimit > 0) {\n $endtime = time() + $this->Timelimit;\n }\n while(is_resource($this->smtp_conn) && !feof($this->smtp_conn)) {\n $str = @fgets($this->smtp_conn,515);\n if($this->do_debug >= 4) {\n $this->edebug(\"SMTP -> get_lines(): \\$data was \\\"$data\\\"\" . $this->CRLF . '
');\n $this->edebug(\"SMTP -> get_lines(): \\$str is \\\"$str\\\"\" . $this->CRLF . '
');\n }\n $data .= $str;\n if($this->do_debug >= 4) {\n $this->edebug(\"SMTP -> get_lines(): \\$data is \\\"$data\\\"\" . $this->CRLF . '
');\n }\n // if 4th character is a space, we are done reading, break the loop\n if(substr($str,3,1) == \" \") { break; }\n // Timed-out? Log and break\n $info = stream_get_meta_data($this->smtp_conn);\n if ($info['timed_out']) {\n if($this->do_debug >= 4) {\n $this->edebug(\"SMTP -> get_lines(): timed-out (\" . $this->Timeout . \" seconds)
\");\n }\n break;\n }\n // Now check if reads took too long\n if ($endtime) {\n if (time() > $endtime) {\n if($this->do_debug >= 4) {\n $this->edebug(\"SMTP -> get_lines(): timelimit reached (\" . $this->Timelimit . \" seconds)
\");\n }\n break;\n }\n }\n }\n return $data;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " $loc = expCore::makeLocation('navigation', '', $standalone->id);\r\n if (expPermissions::check('manage', $loc)) return true;\r\n }\r\n return false;\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " private function __checkIfPulledEventExistsAndAddOrUpdate($event, $eventId, &$successes, &$fails, $eventModel, $server, $user, $jobId)\n {\n // check if the event already exist (using the uuid)\n $existingEvent = $eventModel->find('first', array('conditions' => array('Event.uuid' => $event['Event']['uuid'])));\n $passAlong = $server['Server']['id'];\n if (!$existingEvent) {\n // add data for newly imported events\n $result = $eventModel->_add($event, true, $user, $server['Server']['org_id'], $passAlong, true, $jobId);\n if ($result === true) {\n $successes[] = $eventId;\n } else {\n $fails[$eventId] = __('Failed (partially?) because of errors: ') . $result;\n }\n } else {\n if (!$existingEvent['Event']['locked'] && !$server['Server']['internal']) {\n $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.');\n } else {\n $result = $eventModel->_edit($event, $user, $existingEvent['Event']['id'], $jobId, $passAlong);\n if ($result === true) {\n $successes[] = $eventId;\n } elseif (isset($result['error'])) {\n $fails[$eventId] = $result['error'];\n } else {\n $fails[$eventId] = json_encode($result);\n }\n }\n }\n }", "label_name": "CWE-269", "label": "269"} -{"code": " public function Authorise ($host, $port = false, $tval = false, $username, $password, $debug_level = 0) {\n $this->host = $host;\n\n // If no port value is passed, retrieve it\n if ($port == false) {\n $this->port = $this->POP3_PORT;\n } else {\n $this->port = $port;\n }\n\n // If no port value is passed, retrieve it\n if ($tval == false) {\n $this->tval = $this->POP3_TIMEOUT;\n } else {\n $this->tval = $tval;\n }\n\n $this->do_debug = $debug_level;\n $this->username = $username;\n $this->password = $password;\n\n // Refresh the error log\n $this->error = null;\n\n // Connect\n $result = $this->Connect($this->host, $this->port, $this->tval);\n\n if ($result) {\n $login_result = $this->Login($this->username, $this->password);\n\n if ($login_result) {\n $this->Disconnect();\n\n return true;\n }\n\n }\n\n // We need to disconnect regardless if the login succeeded\n $this->Disconnect();\n\n return false;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public static function initializeNavigation() {\r\n $sections = section::levelTemplate(0, 0);\r\n return $sections;\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public function testGetDropdownValue($params, $expected, $session_params = []) {\n $this->login();\n\n $bkp_params = [];\n //set session params if any\n if (count($session_params)) {\n foreach ($session_params as $param => $value) {\n if (isset($_SESSION[$param])) {\n $bkp_params[$param] = $_SESSION[$param];\n }\n $_SESSION[$param] = $value;\n }\n }\n\n $params['_idor_token'] = \\Session::getNewIDORToken($params['itemtype'] ?? '');\n\n $result = \\Dropdown::getDropdownValue($params, false);\n\n //reset session params before executing test\n if (count($session_params)) {\n foreach ($session_params as $param => $value) {\n if (isset($bkp_params[$param])) {\n $_SESSION[$param] = $bkp_params[$param];\n } else {\n unset($_SESSION[$param]);\n }\n }\n }\n\n $this->array($result)->isIdenticalTo($expected);\n }", "label_name": "CWE-862", "label": "862"} -{"code": " function function_exists($name)\n {\n if (isset(\\yiiunit\\framework\\base\\SecurityTest::$functions[$name])) {\n return \\yiiunit\\framework\\base\\SecurityTest::$functions[$name];\n }\n\n return \\function_exists($name);\n }", "label_name": "CWE-330", "label": "330"} -{"code": " public static function getHost() {\n\n if (isset($_SERVER['HTTP_HOST'])) {\n $site_address = (erLhcoreClassSystem::$httpsMode == true ? 'https:' : 'http:') . '//' . $_SERVER['HTTP_HOST'] ;\n } else if (class_exists('erLhcoreClassInstance')) {\n $site_address = 'https://' . erLhcoreClassInstance::$instanceChat->address . '.' . erConfigClassLhConfig::getInstance()->getSetting( 'site', 'seller_domain');\n } else if (class_exists('erLhcoreClassExtensionLhcphpresque')) {\n $site_address = erLhcoreClassModule::getExtensionInstance('erLhcoreClassExtensionLhcphpresque')->settings['site_address'];\n } else {\n $site_address = '';\n }\n\n return $site_address;\n }", "label_name": "CWE-116", "label": "116"} -{"code": "function XMLRPCaddImageToGroup($name, $imageid){\n $groups = getUserResources(array(\"imageAdmin\"), array(\"manageGroup\"), 1);\n \n if($groupid = getResourceGroupID(\"image/$name\")){\n if(!array_key_exists($groupid, $groups['image'])){\n return array('status' => 'error',\n 'errorcode' => 46,\n 'errormsg' => 'Unable to access image group');\n }\n $resources = getUserResources(array(\"imageAdmin\"), array(\"manageGroup\"));\n if(!array_key_exists($imageid, $resources['image'])){\n return array('status' => 'error',\n 'errorcode' => 47,\n 'errormsg' => 'Unable to access image');\n }\n\n $allimages = getImages();\n $query = \"INSERT IGNORE INTO resourcegroupmembers \"\n . \"(resourceid, resourcegroupid) VALUES \"\n . \"({$allimages[$imageid]['resourceid']}, $groupid)\";\n doQuery($query, 287);\n return array('status' => 'success');\n } else {\n return array('status' => 'error',\n 'errorcode' => 83,\n 'errormsg' => 'invalid resource group name');\n }\n}", "label_name": "CWE-20", "label": "20"} -{"code": "\tstatic public function getStatusText($_lng, $_status = 0)\n\t{\n\t\tswitch($_status)\n\t\t{\n\t\t\tcase 0:\n\t\t\t\treturn $_lng['ticket']['open'];\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\treturn $_lng['ticket']['wait_reply'];\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\treturn $_lng['ticket']['replied'];\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn $_lng['ticket']['closed'];\n\t\t\t\tbreak;\n\t\t}\n\t}", "label_name": "CWE-732", "label": "732"} -{"code": " static function description() {\n return gt(\"This module is for managing categories in your store.\");\n }", "label_name": "CWE-74", "label": "74"} -{"code": "\tpublic static function newFromRow( $row, Parameters $parameters, \\Title $title, $pageNamespace, $pageTitle ) {\n\t\tglobal $wgLang;\n\n\t\t$article = new Article( $title, $pageNamespace );\n\n\t\t$revActorName = null;\n\t\tif ( isset( $row['revactor_actor'] ) ) {\n\t\t\t$revActorName = User::newFromActorId( $row['revactor_actor'] )->getName();\n\t\t}\n\n\t\t$titleText = $title->getText();\n\t\tif ( $parameters->getParameter( 'shownamespace' ) === true ) {\n\t\t\t$titleText = $title->getPrefixedText();\n\t\t}\n\t\t$replaceInTitle = $parameters->getParameter( 'replaceintitle' );\n\t\tif ( is_array( $replaceInTitle ) && count( $replaceInTitle ) === 2 ) {\n\t\t\t$titleText = preg_replace( $replaceInTitle[0], $replaceInTitle[1], $titleText );\n\t\t}\n\n\t\t//Chop off title if longer than the 'titlemaxlen' parameter.\n\t\tif ( $parameters->getParameter( 'titlemaxlen' ) !== null && strlen( $titleText ) > $parameters->getParameter( 'titlemaxlen' ) ) {\n\t\t\t$titleText = substr( $titleText, 0, $parameters->getParameter( 'titlemaxlen' ) ) . '...';\n\t\t}\n\t\tif ( $parameters->getParameter( 'showcurid' ) === true && isset( $row['page_id'] ) ) {\n\t\t\t$articleLink = '[' . $title->getLinkURL( [ 'curid' => $row['page_id'] ] ) . ' ' . htmlspecialchars( $titleText ) . ']';\n\t\t} else {\n\t\t\t$articleLink = '[[' . ( $parameters->getParameter( 'escapelinks' ) && ( $pageNamespace == NS_CATEGORY || $pageNamespace == NS_FILE ) ? ':' : '' ) . $title->getFullText() . '|' . htmlspecialchars( $titleText ) . ']]';\n\t\t}", "label_name": "CWE-400", "label": "400"} -{"code": " protected function AddAnAddress($kind, $address, $name = '') {\n if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) {\n $this->SetError($this->Lang('Invalid recipient array').': '.$kind);\n if ($this->exceptions) {\n throw new phpmailerException('Invalid recipient array: ' . $kind);\n }\n if ($this->SMTPDebug) {\n $this->edebug($this->Lang('Invalid recipient array').': '.$kind);\n }\n return false;\n }\n $address = trim($address);\n $name = trim(preg_replace('/[\\r\\n]+/', '', $name)); //Strip breaks and trim\n if (!$this->ValidateAddress($address)) {\n $this->SetError($this->Lang('invalid_address').': '. $address);\n if ($this->exceptions) {\n throw new phpmailerException($this->Lang('invalid_address').': '.$address);\n }\n if ($this->SMTPDebug) {\n $this->edebug($this->Lang('invalid_address').': '.$address);\n }\n return false;\n }\n if ($kind != 'Reply-To') {\n if (!isset($this->all_recipients[strtolower($address)])) {\n array_push($this->$kind, array($address, $name));\n $this->all_recipients[strtolower($address)] = true;\n return true;\n }\n } else {\n if (!array_key_exists(strtolower($address), $this->ReplyTo)) {\n $this->ReplyTo[strtolower($address)] = array($address, $name);\n return true;\n }\n }\n return false;\n}", "label_name": "CWE-20", "label": "20"} -{"code": " $product = X2Model::model('Products')->findByAttributes(array('name'=>$lineItem->name));\n if (isset($product))\n $lineItem->productId = $product->id;\n if(empty($lineItem->currency))\n\t\t\t\t$lineItem->currency = $defaultCurrency;\n\t\t\tif($lineItem->isPercentAdjustment) {\n\t\t\t\t$lineItem->adjustment = Fields::strToNumeric(\n $lineItem->adjustment,'percentage');\n\t\t\t} else {\n\t\t\t\t$lineItem->adjustment = Fields::strToNumeric(\n $lineItem->adjustment,'currency',$curSym);\n\t\t\t}\n\t\t\t$lineItem->price = Fields::strToNumeric($lineItem->price,'currency',$curSym);\n\t\t\t$lineItem->total = Fields::strToNumeric($lineItem->total,'currency',$curSym);\n\t\t}", "label_name": "CWE-20", "label": "20"} -{"code": "\tprotected function doDBUpdates() {\n\t\t$title = Title::newFromText( 'Template:Extension DPL' );\n\n\t\t// Make sure template does not already exist\n\t\tif ( !$title->exists() ) {\n\t\t\t$wikipage = WikiPage::factory( $title );\n\t\t\t$updater = $wikipage->newPageUpdater( User::newSystemUser( 'DynamicPageList3 extension' ) );\n\t\t\t$content = $wikipage->getContentHandler()->makeContent( 'This page was automatically created. It serves as an anchor page for all \\'\\'\\'[[Special:WhatLinksHere/Template:Extension_DPL|invocations]]\\'\\'\\' of [https://www.mediawiki.org/wiki/Special:MyLanguage/Extension:DynamicPageList3 Extension:DynamicPageList3].', $title );\n\t\t\t$updater->setContent( SlotRecord::MAIN, $content );\n\t\t\t$comment = CommentStoreComment::newUnsavedComment( 'Autogenerated DPL\\'s necessary template for content inclusion' );\n\t\t\t$updater->saveRevision(\n\t\t\t\t$comment,\n\t\t\t\tEDIT_NEW | EDIT_FORCE_BOT\n\t\t\t);\n\t\t}\n\n\t\treturn true;\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " function searchByModelForm() {\n // get the search terms\n $terms = $this->params['search_string'];\n\n $sql = \"model like '%\" . $terms . \"%'\";\n\n $limit = !empty($this->config['limit']) ? $this->config['limit'] : 10;\n $page = new expPaginator(array(\n 'model' => 'product',\n 'where' => $sql,\n 'limit' => !empty($this->config['pagination_default']) ? $this->config['pagination_default'] : $limit,\n 'order' => 'title',\n 'dir' => 'DESC',\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller' => $this->params['controller'],\n 'action' => $this->params['action'],\n 'columns' => array(\n gt('Model #') => 'model',\n gt('Product Name') => 'title',\n gt('Price') => 'base_price'\n ),\n ));\n\n assign_to_template(array(\n 'page' => $page,\n 'terms' => $terms\n ));\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function testCookiePathWithEmptySetCookiePath($uriPath, $cookiePath)\n {\n $response = (new Response(200))\n ->withAddedHeader(\n 'Set-Cookie',\n \"foo=bar; expires={$this->futureExpirationDate()}; domain=www.example.com; path=;\"\n )\n ->withAddedHeader(\n 'Set-Cookie',\n \"bar=foo; expires={$this->futureExpirationDate()}; domain=www.example.com; path=foobar;\"\n )\n ;\n $request = (new Request('GET', $uriPath))->withHeader('Host', 'www.example.com');\n $this->jar->extractCookies($request, $response);\n\n self::assertSame($cookiePath, $this->jar->toArray()[0]['Path']);\n self::assertSame($cookiePath, $this->jar->toArray()[1]['Path']);\n }", "label_name": "CWE-200", "label": "200"} -{"code": "\tpublic function update() {\n global $user;\n\n if (expSession::get('customer-signup')) expSession::set('customer-signup', false);\n if (isset($this->params['address_country_id'])) {\n $this->params['country'] = $this->params['address_country_id'];\n unset($this->params['address_country_id']);\n }\n if (isset($this->params['address_region_id'])) {\n $this->params['state'] = $this->params['address_region_id'];\n unset($this->params['address_region_id']);\n }\n\t\tif ($user->isLoggedIn()) {\n\t\t\t// check to see how many other addresses this user has already.\n\t\t\t$count = $this->address->find('count', 'user_id='.$user->id);\n\t\t\t// if this is first address save for this user we'll make this the default\n\t\t\tif ($count == 0) \n {\n $this->params['is_default'] = 1;\n $this->params['is_billing'] = 1;\n $this->params['is_shipping'] = 1;\n }\n\t\t\t// associate this address with the current user.\n\t\t\t$this->params['user_id'] = $user->id;\n\t\t\t// save the object\n\t\t\t$this->address->update($this->params);\n\t\t}\n else { //if (ecomconfig::getConfig('allow_anonymous_checkout')){\n //user is not logged in, but allow anonymous checkout is enabled so we'll check \n //a few things that we don't check in the parent 'stuff and create a user account.\n $this->params['is_default'] = 1;\n $this->params['is_billing'] = 1;\n $this->params['is_shipping'] = 1; \n $this->address->update($this->params);\n }\n\t\texpHistory::back(); \n\t}", "label_name": "CWE-74", "label": "74"} -{"code": " public function show()\n {\n $task = $this->getTask();\n $subtask = $this->getSubtask();\n\n $this->response->html($this->template->render('subtask_converter/show', array(\n 'subtask' => $subtask,\n 'task' => $task,\n )));\n }", "label_name": "CWE-200", "label": "200"} -{"code": " function update_option_master() { \n global $db;\n\n $id = empty($this->params['id']) ? null : $this->params['id'];\n $opt = new option_master($id);\n $oldtitle = $opt->title;\n \n $opt->update($this->params);\n \n // if the title of the master changed we should update the option groups that are already using it.\n if ($oldtitle != $opt->title) {\n \n }$db->sql('UPDATE '.$db->prefix.'option SET title=\"'.$opt->title.'\" WHERE option_master_id='.$opt->id);\n \n expHistory::back();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " function move_standalone() {\r\n expSession::clearAllUsersSessionCache('navigation');\r\n assign_to_template(array(\r\n 'parent' => $this->params['parent'],\r\n ));\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": "\tprivate function _notmodifiedby( $option ) {\n\t\t$user = new \\User;\n\t\t$this->addWhere( 'NOT EXISTS (SELECT 1 FROM ' . $this->tableNames['revision_actor_temp'] . ' WHERE ' . $this->tableNames['revision_actor_temp'] . '.revactor_page=page_id AND ' . $this->tableNames['revision_actor_temp'] . '.revactor_actor = ' . $this->DB->addQuotes( $user->newFromName( $option )->getActorId() ) . ' LIMIT 1)' );\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " public function execute(&$params){\n $model = new Actions;\n $model->type = 'note';\n $model->complete = 'Yes';\n $model->associationId = $params['model']->id;\n $model->associationType = $params['model']->module;\n $model->actionDescription = $this->parseOption('comment', $params);\n $model->assignedTo = $this->parseOption('assignedTo', $params);\n $model->completedBy = $this->parseOption('assignedTo', $params);\n\n if(empty($model->assignedTo) && $params['model']->hasAttribute('assignedTo')){\n $model->assignedTo = $params['model']->assignedTo;\n $model->completedBy = $params['model']->assignedTo;\n }\n\n if($params['model']->hasAttribute('visibility'))\n $model->visibility = $params['model']->visibility;\n $model->createDate = time();\n $model->completeDate = time();\n\n if($model->save()){\n return array(\n true,\n Yii::t('studio', 'View created action: ').$model->getLink());\n }else{\n return array(false, array_shift($model->getErrors()));\n }\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\t\tpublic static function upload_user_avatar() {\n\t\t\t$file = $_FILES['lp-upload-avatar'];\n\t\t\t$upload_dir = learn_press_user_profile_picture_upload_dir();\n\n\t\t\tadd_filter( 'upload_dir', array( __CLASS__, '_user_avatar_upload_dir' ), 10000 );\n\n\t\t\t$result = wp_handle_upload(\n\t\t\t\t$file,\n\t\t\t\tarray(\n\t\t\t\t\t'test_form' => false,\n\t\t\t\t)\n\t\t\t);\n\n\t\t\tremove_filter( 'upload_dir', array( __CLASS__, '_user_avatar_upload_dir' ), 10000 );\n\n\t\t\tif ( is_array( $result ) ) {\n\t\t\t\t$result['name'] = $upload_dir['subdir'] . '/' . basename( $result['file'] );\n\t\t\t\tunset( $result['file'] );\n\t\t\t} else {\n\t\t\t\t$result = array(\n\t\t\t\t\t'error' => __( 'Profile picture upload failed', 'learnpress' ),\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlearn_press_send_json( $result );\n\t\t}", "label_name": "CWE-610", "label": "610"} -{"code": " public function upload() {\n if (!AuthUser::hasPermission('file_manager_upload')) {\n Flash::set('error', __('You do not have sufficient permissions to upload a file.'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n \n // CSRF checks\n if (isset($_POST['csrf_token'])) {\n $csrf_token = $_POST['csrf_token'];\n if (!SecureToken::validateToken($csrf_token, BASE_URL.'plugin/file_manager/upload')) {\n Flash::set('error', __('Invalid CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n }\n else {\n Flash::set('error', __('No CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n \n $mask = Plugin::getSetting('umask', 'file_manager');\n umask(octdec($mask));\n\n $data = $_POST['upload'];\n $path = str_replace('..', '', $data['path']);\n $overwrite = isset($data['overwrite']) ? true : false;\n\n // Clean filenames\n $filename = preg_replace('/ /', '_', $_FILES['upload_file']['name']);\n $filename = preg_replace('/[^a-z0-9_\\-\\.]/i', '', $filename);\n\n if (isset($_FILES)) {\n $file = $this->_upload_file($filename, FILES_DIR . '/' . $path . '/', $_FILES['upload_file']['tmp_name'], $overwrite);\n\n if ($file === false)\n Flash::set('error', __('File has not been uploaded!'));\n }\n redirect(get_url('plugin/file_manager/browse/' . $path));\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\tprivate function _addcontribution( $option ) {\n\t\t$this->addTable( 'recentchanges', 'rc' );\n\n\t\t$field = 'rc.rc_actor';\n\n\t\t$this->addSelect(\n\t\t\t[\n\t\t\t\t'contribution'\t=> 'SUM(ABS(rc.rc_new_len - rc.rc_old_len))',\n\t\t\t\t'contributor'\t=> $field\n\t\t\t]\n\t\t);\n\t\t$this->addWhere(\n\t\t\t[\n\t\t\t\t$this->tableNames['page'] . '.page_id = rc.rc_cur_id'\n\t\t\t]\n\t\t);\n\t\t$this->addGroupBy( 'rc.rc_cur_id' );\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " function addDiscountToCart() {\n// global $user, $order;\n global $order;\n //lookup discount to see if it's real and valid, and not already in our cart\n //this will change once we allow more than one coupon code\n\n $discount = new discounts();\n $discount = $discount->getCouponByName($this->params['coupon_code']);\n\n if (empty($discount)) {\n flash('error', gt(\"This discount code you entered does not exist.\"));\n //redirect_to(array('controller'=>'cart', 'action'=>'checkout')); \n expHistory::back();\n }\n\n //check to see if it's in our cart already\n if ($this->isDiscountInCart($discount->id)) {\n flash('error', gt(\"This discount code is already in your cart.\"));\n //redirect_to(array('controller'=>'cart', 'action'=>'checkout'));\n expHistory::back();\n }\n\n //this should really be reworked, as it shoudn't redirect directly and not return\n $validateDiscountMessage = $discount->validateDiscount();\n if ($validateDiscountMessage == \"\") {\n //if all good, add to cart, otherwise it will have redirected\n $od = new order_discounts();\n $od->orders_id = $order->id;\n $od->discounts_id = $discount->id;\n $od->coupon_code = $discount->coupon_code;\n $od->title = $discount->title;\n $od->body = $discount->body;\n $od->save();\n // set this to just the discount applied via this coupon?? if so, when though? $od->discount_total = ??;\n flash('message', gt(\"The discount code has been applied to your cart.\"));\n } else {\n flash('error', $validateDiscountMessage);\n }\n //redirect_to(array('controller'=>'cart', 'action'=>'checkout')); \n expHistory::back();\n }", "label_name": "CWE-20", "label": "20"} -{"code": " function productFeed() {\n// global $db;\n //check query password to avoid DDOS\n /*\n * condition = new\n * description \n * id - SKU \n * link \n * price \n * title \n * brand - manufacturer \n * image link - fullsized image, up to 10, comma seperated \n * product type - category - \"Electronics > Audio > Audio Accessories MP3 Player Accessories\",\"Health & Beauty > Healthcare > Biometric Monitors > Pedometers\" \n */\n $out = '\"id\",\"condition\",\"description\",\"like\",\"price\",\"title\",\"brand\",\"image link\",\"product type\"' . chr(13) . chr(10);\n\n $p = new product();\n $prods = $p->find('all', 'parent_id=0 AND ');\n //$prods = $db->selectObjects('product','parent_id=0 AND');\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function showUnpublished() {\n expHistory::set('viewable', $this->params);\n \n // setup the where clause for looking up records.\n $where = parent::aggregateWhereClause();\n $where = \"((unpublish != 0 AND unpublish < \".time().\") OR (publish > \".time().\")) AND \".$where;\n if (isset($this->config['only_featured'])) $where .= ' AND is_featured=1';\n\n $page = new expPaginator(array(\n 'model'=>'news',\n 'where'=>$where,\n 'limit'=>25,\n 'order'=>'unpublish',\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->baseclassname,\n 'action'=>$this->params['action'],\n 'src'=>$this->loc->src,\n 'columns'=>array(\n gt('Title')=>'title',\n gt('Published On')=>'publish',\n gt('Status')=>'unpublish'\n ),\n ));\n \n assign_to_template(array(\n 'page'=>$page\n ));\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function getChart($renderer, $id, $store_in_session = true)\n {\n $c = null;\n $chart_data = null;\n if ($renderer != null && $store_in_session) {\n $session = new Tracker_Report_Session($renderer->report->id);\n $session->changeSessionNamespace(\"renderers.{$renderer->id}\");\n\n // look for the chart in the session\n $chart_data = $session->get(\"charts.$id\");\n }\n\n if (! $chart_data) {\n // not found. look in the db\n $dao = new GraphOnTrackersV5_ChartDao(CodendiDataAccess::instance());\n $chart_data = $dao->searchById($id)->getRow();\n }\n\n if ($chart_data) {\n if (! $renderer) {\n $report = null; //We don't know the report\n $renderer = Tracker_Report_RendererFactory::instance()->getReportRendererById($chart_data['report_graphic_id'], $report, $store_in_session);\n }\n if ($renderer) {\n $c = $this->instanciateChart($chart_data, $renderer, $store_in_session);\n }\n }\n return $c;\n }", "label_name": "CWE-862", "label": "862"} -{"code": " public function __construct(private \\Git_Exec $git_exec, private BranchCreationExecutor $branch_creation_executor)\n {\n }", "label_name": "CWE-862", "label": "862"} -{"code": " public function __get($var) {\n\n switch ($var) {\n case 'configuration_array':\n $this->configuration_array = array();\n if ($this->configuration != ''){\n $jsonData = json_decode($this->configuration,true);\n if ($jsonData !== null) {\n $this->configuration_array = $jsonData;\n } else {\n $this->configuration_array = array();\n }\n }\n return $this->configuration_array;\n break;\n\n case 'name_support':\n return $this->name_support = $this->nick;\n break;\n\n case 'has_photo':\n return $this->filename != '';\n break;\n\n case 'photo_path':\n $this->photo_path = ($this->filepath != '' ? '//' . $_SERVER['HTTP_HOST'] . erLhcoreClassSystem::instance()->wwwDir() : erLhcoreClassSystem::instance()->wwwImagesDir() ) .'/'. $this->filepath . $this->filename;\n return $this->photo_path;\n break;\n\n case 'file_path_server':\n return $this->filepath . $this->filename;\n break;\n\n default:\n break;\n }\n }", "label_name": "CWE-116", "label": "116"} -{"code": " public function edit()\n {\n if((isset($this->params['id']))) $record = new address(intval($this->params['id']));\n else $record = null;\n $config = ecomconfig::getConfig('address_allow_admins_all');\n assign_to_template(array(\n 'record'=>$record,\n 'admin_config'=>$config\n ));\n if (expSession::get('customer-signup')) {\n assign_to_template(array(\n 'checkout'=>true\n ));\n }\n }", "label_name": "CWE-200", "label": "200"} -{"code": " function scan_page($parent_id) {\r\n global $db;\r\n\r\n $sections = $db->selectObjects('section','parent=' . $parent_id);\r\n $ret = '';\r\n foreach ($sections as $page) {\r\n $cLoc = serialize(expCore::makeLocation('container','@section' . $page->id));\r\n $ret .= scan_container($cLoc, $page->id);\r\n $ret .= scan_page($page->id);\r\n }\r\n return $ret;\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " $loc = expCore::makeLocation('navigation', '', $standalone->id);\r\n if (expPermissions::check('manage', $loc)) return true;\r\n }\r\n return false;\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public function resetauthkey($id = null)\n {\n if (!$this->_isAdmin() && Configure::read('MISP.disableUserSelfManagement')) {\n throw new MethodNotAllowedException('User self-management has been disabled on this instance.');\n }\n if ($id == 'me') {\n $id = $this->Auth->user('id');\n }\n if (!$this->userRole['perm_auth']) {\n throw new MethodNotAllowedException('Invalid action.');\n }\n $this->User->id = $id;\n if (!$id || !$this->User->exists($id)) {\n throw new MethodNotAllowedException('Invalid user.');\n }\n $user = $this->User->read();\n $oldKey = $this->User->data['User']['authkey'];\n if (!$this->_isSiteAdmin() && !($this->_isAdmin() && $this->Auth->user('org_id') == $this->User->data['User']['org_id']) && ($this->Auth->user('id') != $id)) {\n throw new MethodNotAllowedException('Invalid user.');\n }\n $newkey = $this->User->generateAuthKey();\n $this->User->saveField('authkey', $newkey);\n $this->__extralog(\n 'reset_auth_key',\n 'Authentication key for user ' . $user['User']['id'] . ' (' . $user['User']['email'] . ')',\n $fieldsResult = 'authkey(' . $oldKey . ') => (' . $newkey . ')'\n );\n if (!$this->_isRest()) {\n $this->Flash->success(__('New authkey generated.', true));\n $this->_refreshAuth();\n $this->redirect($this->referer());\n } else {\n return $this->RestResponse->saveSuccessResponse('User', 'resetauthkey', $id, $this->response->type(), 'Authkey updated: ' . $newkey);\n }\n }", "label_name": "CWE-269", "label": "269"} -{"code": " $escapedArgument .= '^%\"'.substr($part, 1, -1).'\"^%';\n } else {\n // escape trailing backslash\n if ('\\\\' === substr($part, -1)) {\n $part .= '\\\\';\n }\n $quote = true;\n $escapedArgument .= $part;\n }\n }\n if ($quote) {\n $escapedArgument = '\"'.$escapedArgument.'\"';\n }\n\n return $escapedArgument;\n }", "label_name": "CWE-77", "label": "77"} -{"code": "function XMLRPCtest($string) {\n\t$string = processInputData($string, ARG_STRING);\n\treturn array('status' => 'success',\n\t 'message' => 'RPC call worked successfully',\n\t 'string' => $string);\n}", "label_name": "CWE-20", "label": "20"} -{"code": " function delete_selected() {\r\n $item = $this->event->find('first', 'id=' . $this->params['id']);\r\n if ($item && $item->is_recurring == 1) {\r\n $event_remaining = false;\r\n $eventdates = $item->eventdate[0]->find('all', 'event_id=' . $item->id);\r\n foreach ($eventdates as $ed) {\r\n if (array_key_exists($ed->id, $this->params['dates'])) {\r\n $ed->delete();\r\n } else {\r\n $event_remaining = true;\r\n }\r\n }\r\n if (!$event_remaining) {\r\n $item->delete(); // model will also ensure we delete all event dates\r\n }\r\n expHistory::back();\r\n } else {\r\n notfoundController::handle_not_found();\r\n }\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public function delete() {\n if (!AuthUser::hasPermission('file_manager_delete')) {\n Flash::set('error', __('You do not have sufficient permissions to delete a file or directory.'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n\n $paths = func_get_args();\n\n $file = urldecode(join('/', $paths));\n \n // CSRF checks\n if (isset($_GET['csrf_token'])) {\n $csrf_token = $_GET['csrf_token'];\n if (!SecureToken::validateToken($csrf_token, BASE_URL.'plugin/file_manager/delete/'.$file)) {\n Flash::set('error', __('Invalid CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n }\n else {\n Flash::set('error', __('No CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n\n $file = FILES_DIR . '/' . str_replace('..', '', $file);\n $filename = array_pop($paths);\n $paths = join('/', $paths);\n\n if (is_file($file)) {\n if (!unlink($file))\n Flash::set('error', __('Permission denied!'));\n }\n else {\n if (!$this->_rrmdir($file))\n Flash::set('error', __('Permission denied!'));\n }\n\n redirect(get_url('plugin/file_manager/browse/' . $paths));\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function Quit($close_on_error = true) {\n $this->error = null; // so there is no confusion\n\n if(!$this->connected()) {\n $this->error = array(\n \"error\" => \"Called Quit() without being connected\");\n return false;\n }\n\n // send the quit command to the server\n fputs($this->smtp_conn,\"quit\" . $this->CRLF);\n\n // get any good-bye messages\n $byemsg = $this->get_lines();\n\n if($this->do_debug >= 2) {\n $this->edebug(\"SMTP -> FROM SERVER:\" . $byemsg . $this->CRLF . '
');\n }\n\n $rval = true;\n $e = null;\n\n $code = substr($byemsg,0,3);\n if($code != 221) {\n // use e as a tmp var cause Close will overwrite $this->error\n $e = array(\"error\" => \"SMTP server rejected quit command\",\n \"smtp_code\" => $code,\n \"smtp_rply\" => substr($byemsg,4));\n $rval = false;\n if($this->do_debug >= 1) {\n $this->edebug(\"SMTP -> ERROR: \" . $e[\"error\"] . \": \" . $byemsg . $this->CRLF . '
');\n }\n }\n\n if(empty($e) || $close_on_error) {\n $this->Close();\n }\n\n return $rval;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function getLayout(){\n $layout = $this->getAttribute('layout');\n\n $initLayout = $this->initLayout();\n\n if(!$layout){ // layout hasn't been initialized?\n $layout = $initLayout;\n $this->layout = json_encode($layout);\n $this->update(array('layout'));\n }else{\n $layout = json_decode($layout, true); // json to associative array\n $this->addRemoveLayoutElements('center', $layout, $initLayout);\n $this->addRemoveLayoutElements('left', $layout, $initLayout);\n $this->addRemoveLayoutElements('right', $layout, $initLayout);\n }\n\n return $layout;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function testRedirectLinkGeneration () {\n Yii::app()->controller = new MarketingController (\n 'campaign', new MarketingModule ('campaign', null));\n $_SERVER['SERVER_NAME'] = 'localhost';\n $cmb = $this->instantiate();\n $contact = $this->contacts('testUser_unsent');\n $campaign = $this->campaign('redirectLinkGeneration');\n $url = preg_replace ('/^[^\"]*\"([^\"]*)\".*$/', '$1', $campaign->content);\n list($subject,$message,$uniqueId) = $cmb->prepareEmail(\n $this->campaign('redirectLinkGeneration'),\n $contact,$this->listItem('testUser_unsent')->emailAddress);\n $this->assertRegExp ('/'.preg_quote (urlencode ($url)).'/', $message);\n\n }", "label_name": "CWE-20", "label": "20"} -{"code": " function showallSubcategories() {\n// global $db;\n\n expHistory::set('viewable', $this->params);\n// $parent = isset($this->params['cat']) ? $this->params['cat'] : expSession::get('catid');\n $catid = expSession::get('catid');\n $parent = !empty($catid) ? $catid : (!empty($this->params['cat']) ? $this->params['cat'] : 0);\n $category = new storeCategory($parent);\n $categories = $category->getEcomSubcategories();\n $ancestors = $category->pathToNode();\n assign_to_template(array(\n 'categories' => $categories,\n 'ancestors' => $ancestors,\n 'category' => $category\n ));\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function shouldRun(DateTime $date)\n {\n global $timedate;\n\n $runDate = clone $date;\n $this->handleTimeZone($runDate);\n\n $cron = Cron\\CronExpression::factory($this->schedule);\n if (empty($this->last_run) && $cron->isDue($runDate)) {\n return true;\n }\n\n $lastRun = $this->last_run ? $timedate->fromDb($this->last_run) : $timedate->fromDb($this->date_entered);\n \n $this->handleTimeZone($lastRun);\n $next = $cron->getNextRunDate($lastRun);\n\n return $next <= $runDate;\n }", "label_name": "CWE-863", "label": "863"} -{"code": " function edit_option_master() {\n expHistory::set('editable', $this->params);\n \n $params = isset($this->params['id']) ? $this->params['id'] : $this->params;\n $record = new option_master($params); \n assign_to_template(array(\n 'record'=>$record\n ));\n }", "label_name": "CWE-74", "label": "74"} -{"code": "\tstatic function validUTF($string) {\n\t\tif(!mb_check_encoding($string, 'UTF-8') OR !($string === mb_convert_encoding(mb_convert_encoding($string, 'UTF-32', 'UTF-8' ), 'UTF-8', 'UTF-32'))) {\n\t\t\treturn false;\n\t\t}\t\t\n\t\treturn true;\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": " public function save()\n {\n $project = $this->getProject();\n\n $values = $this->request->getValues();\n list($valid, $errors) = $this->categoryValidator->validateCreation($values);\n\n if ($valid) {\n if ($this->categoryModel->create($values) !== false) {\n $this->flash->success(t('Your category have been created successfully.'));\n $this->response->redirect($this->helper->url->to('CategoryController', 'index', array('project_id' => $project['id'])), true);\n return;\n } else {\n $errors = array('name' => array(t('Another category with the same name exists in this project')));\n }\n }\n\n $this->create($values, $errors);\n }", "label_name": "CWE-200", "label": "200"} -{"code": " protected function markCompleted($endStatus, ServiceResponse $serviceResponse, $gatewayMessage)\n {\n parent::markCompleted($endStatus, $serviceResponse, $gatewayMessage);\n $this->createMessage(Message\\VoidedResponse::class, $gatewayMessage);\n\n ErrorHandling::safeExtend($this->payment, 'onVoid', $serviceResponse);\n }", "label_name": "CWE-436", "label": "436"} -{"code": " private function isWindows()\n {\n return DIRECTORY_SEPARATOR !== '/';\n }", "label_name": "CWE-330", "label": "330"} -{"code": "\t\tpublic function pull($remote = NULL, array $params = NULL)\n\t\t{\n\t\t\t$this->run('pull', $remote, $params);\n\t\t\treturn $this;\n\t\t}", "label_name": "CWE-77", "label": "77"} -{"code": "\t\t\t$result = $search->getSearchResults($item->query, false, true);\n\t\t\tif(empty($result) && !in_array($item->query, $badSearchArr)) {\n\t\t\t\t$badSearchArr[] = $item->query;\n\t\t\t\t$badSearch[$ctr2]['query'] = $item->query;\n\t\t\t\t$badSearch[$ctr2]['count'] = $db->countObjects(\"search_queries\", \"query='{$item->query}'\");\n\t\t\t\t$ctr2++;\n\t\t\t}\n\t\t\t\n\t\t}\n\t\n\t\t//Check if the user choose from the dropdown\n\t\tif(!empty($user_default)) {\n\t\t\tif($user_default == $anonymous) {\n\t\t\t\t$u_id = 0;\n\t\t\t} else {\n\t\t\t\t$u_id = $user_default;\n\t\t\t}\n\t\t\t$where .= \"user_id = {$u_id}\";\n\t\t}\n\t\n\t\t//Get all the search query records\n\t\t$records = $db->selectObjects('search_queries', $where);\n for ($i = 0, $iMax = count($records); $i < $iMax; $i++) {\n\t\t\tif(!empty($records[$i]->user_id)) {\n\t\t\t\t$u = user::getUserById($records[$i]->user_id);\n\t\t\t\t$records[$i]->user = $u->firstname . ' ' . $u->lastname;\n\t\t\t}\n\t\t}\n\t\t\n $page = new expPaginator(array(\n 'records' => $records,\n 'where'=>1,\n 'model'=>'search_queries',\n 'limit'=>(isset($this->config['limit']) && $this->config['limit'] != '') ? 10 : $this->config['limit'],\n 'order'=>empty($this->config['order']) ? 'timestamp' : $this->config['order'],\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->baseclassname,\n 'action'=>$this->params['action'],\n 'columns'=>array(\n 'ID'=>'id',\n gt('Query')=>'query',\n gt('Timestamp')=>'timestamp',\n gt('User')=>'user_id',\n ),\n ));\n\n $uname['id'] = implode($uname['id'],',');\n $uname['name'] = implode($uname['name'],',');\n assign_to_template(array(\n 'page'=>$page,\n 'users'=>$uname,\n 'user_default' => $user_default,\n 'badSearch' => $badSearch\n ));\n\t\t\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": " } elseif (!empty($this->params['src'])) {\r\n if ($this->params['src'] == $loc->src) {\r\n $this->config = $config->config;\r\n break;\r\n }\r\n }\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " $banner->increaseImpressions();\n }\n }\n \n // assign banner to the template and show it!\n assign_to_template(array(\n 'banners'=>$banners\n ));\n }", "label_name": "CWE-74", "label": "74"} -{"code": "\tpublic function approve_submit() {\n\t if (empty($this->params['id'])) {\n\t flash('error', gt('No ID supplied for comment to approve'));\n\t expHistory::back();\n\t }\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n// $require_login = empty($this->params['require_login']) ? COMMENTS_REQUIRE_LOGIN : $this->params['require_login'];\n// $require_approval = empty($this->params['require_approval']) ? COMMENTS_REQUIRE_APPROVAL : $this->params['require_approval'];\n// $require_notification = empty($this->params['require_notification']) ? COMMENTS_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n// $notification_email = empty($this->params['notification_email']) ? COMMENTS_NOTIFICATION_EMAIL : $this->params['notification_email'];\n\t \n\t $comment = new expComment($this->params['id']);\n\t $comment->body = $this->params['body'];\n\t $comment->approved = $this->params['approved'];\n\t $comment->save();\n\t expHistory::back();\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": "\tprivate function _firstrevisionsince( $option ) {\n\t\t$this->addTable( 'revision_actor_temp', 'rev' );\n\t\t$this->addSelect(\n\t\t\t[\n\t\t\t\t'rev.revactor_rev',\n\t\t\t\t'rev.revactor_timestamp'\n\t\t\t]\n\t\t);\n\t\t// tell the query optimizer not to look at rows that the following subquery will filter out anyway\n\t\t$this->addWhere(\n\t\t\t[\n\t\t\t\t$this->tableNames['page'] . '.page_id = rev.revactor_page',\n\t\t\t\t'rev.revactor_timestamp >= ' . $this->DB->addQuotes( $option )\n\t\t\t]\n\t\t);\n\t\t$this->addWhere(\n\t\t\t[\n\t\t\t\t$this->tableNames['page'] . '.page_id = rev.revactor_page',\n\t\t\t\t'rev.revactor_timestamp = (SELECT MIN(rev_aux_snc.revactor_timestamp) FROM ' . $this->tableNames['revision_actor_temp'] . ' AS rev_aux_snc WHERE rev_aux_snc.revactor_page=rev.revactor_page AND rev_aux_snc.revactor_timestamp >= ' . $this->convertTimestamp( $option ) . ')'\n\t\t\t]\n\t\t);\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " public function testGetEvents(){\n TestingAuxLib::loadX2NonWebUser ();\n TestingAuxLib::suLogin ('admin');\n\n Yii::app()->settings->historyPrivacy = null;\n $lastEventId = 0;\n $lastTimestamp = 0;\n $events = Events::getEvents ($lastEventId, $lastTimestamp, 4);\n $this->assertEquals (\n Yii::app()->db->createCommand (\n \"select id from x2_events order by timestamp desc, id desc limit 4\")\n ->queryColumn (),\n array_map(function ($event) { return $event->id; }, $events['events'])\n ); \n TestingAuxLib::restoreX2WebUser ();\n }", "label_name": "CWE-20", "label": "20"} -{"code": " static::$functions = ['random_bytes' => false, 'openssl_random_pseudo_bytes' => false, 'mcrypt_create_iv' => false];", "label_name": "CWE-330", "label": "330"} -{"code": " public function testIsExpiredReturnsTrueWhenModificationTimesWarrant()\n {\n $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__);\n $files->shouldReceive('exists')->once()->with(__DIR__.'/'.sha1('foo').'.php')->andReturn(true);\n $files->shouldReceive('lastModified')->once()->with('foo')->andReturn(100);\n $files->shouldReceive('lastModified')->once()->with(__DIR__.'/'.sha1('foo').'.php')->andReturn(0);\n $this->assertTrue($compiler->isExpired('foo'));\n }", "label_name": "CWE-327", "label": "327"} -{"code": " function searchCategory() {\r\n return gt('Event');\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " } elseif (!empty($this->params['src'])) {\r\n if ($this->params['src'] == $loc->src) {\r\n $this->config = $config->config;\r\n break;\r\n }\r\n }\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " function _setupMcrypt()\n {\n $this->_clearBuffers();\n $this->enchanged = $this->dechanged = true;\n\n if (!isset($this->enmcrypt)) {\n static $mcrypt_modes = array(\n self::MODE_CTR => 'ctr',\n self::MODE_ECB => MCRYPT_MODE_ECB,\n self::MODE_CBC => MCRYPT_MODE_CBC,\n self::MODE_CFB => 'ncfb',\n self::MODE_OFB => MCRYPT_MODE_NOFB,\n self::MODE_STREAM => MCRYPT_MODE_STREAM,\n );\n\n $this->demcrypt = mcrypt_module_open($this->cipher_name_mcrypt, '', $mcrypt_modes[$this->mode], '');\n $this->enmcrypt = mcrypt_module_open($this->cipher_name_mcrypt, '', $mcrypt_modes[$this->mode], '');\n\n // we need the $ecb mcrypt resource (only) in MODE_CFB with enableContinuousBuffer()\n // to workaround mcrypt's broken ncfb implementation in buffered mode\n // see: {@link http://phpseclib.sourceforge.net/cfb-demo.phps}\n if ($this->mode == self::MODE_CFB) {\n $this->ecb = mcrypt_module_open($this->cipher_name_mcrypt, '', MCRYPT_MODE_ECB, '');\n }\n\n } // else should mcrypt_generic_deinit be called?\n\n if ($this->mode == self::MODE_CFB) {\n mcrypt_generic_init($this->ecb, $this->key, str_repeat(\"\\0\", $this->block_size));\n }\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public function bind($dn = null, $password = null)\n {\n /* Fetch current bind credentials. */\n if (empty($dn)) {\n $dn = $this->_config['binddn'];\n }\n if (empty($password)) {\n $password = $this->_config['bindpw'];\n }\n\n /* Connect first, if we haven't so far. This will also bind\n * us to the server. */\n if (!$this->_link) {\n /* Store old credentials so we can revert them later, then\n * overwrite config with new bind credentials. */\n $olddn = $this->_config['binddn'];\n $oldpw = $this->_config['bindpw'];\n\n /* Overwrite bind credentials in config so\n * _connect() knows about them. */\n $this->_config['binddn'] = $dn;\n $this->_config['bindpw'] = $password;\n\n /* Try to connect with provided credentials. */\n $msg = $this->_connect();\n\n /* Reset to previous config. */\n $this->_config['binddn'] = $olddn;\n $this->_config['bindpw'] = $oldpw;\n return;\n }\n\n /* Do the requested bind as we are asked to bind manually. */\n if (empty($dn)) {\n /* Anonymous bind. */\n $msg = @ldap_bind($this->_link);\n } else {\n /* Privileged bind. */\n $msg = @ldap_bind($this->_link, $dn, $password);\n }\n if (!$msg) {\n throw new Horde_Ldap_Exception('Bind failed: ' . @ldap_error($this->_link),\n @ldap_errno($this->_link));\n }\n }", "label_name": "CWE-287", "label": "287"} -{"code": " function function_exists($name)\n {\n if (isset(\\yiiunit\\framework\\base\\SecurityTest::$functions[$name])) {\n return \\yiiunit\\framework\\base\\SecurityTest::$functions[$name];\n }\n\n return \\function_exists($name);\n }", "label_name": "CWE-330", "label": "330"} -{"code": " function update() {\r\n parent::update();\r\n expSession::clearAllUsersSessionCache('navigation');\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public function settings() {\n AuthUser::load();\n if (!AuthUser::isLoggedIn()) {\n redirect(get_url('login'));\n } else if (!AuthUser::hasPermission('admin_edit')) {\n Flash::set('error', __('You do not have permission to access the requested page!'));\n redirect(get_url());\n }\n \n $settings = Plugin::getAllSettings('file_manager');\n\n if (!$settings) {\n Flash::set('error', 'Files - ' . __('unable to retrieve plugin settings.'));\n return;\n }\n\n $this->display('file_manager/views/settings', array('settings' => $settings));\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public function approve_toggle() {\n global $history;\n \n if (empty($this->params['id'])) return;\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n $require_login = empty($this->params['require_login']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];\n $require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];\n $require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n $notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];\n \n \n $simplenote = new expSimpleNote($this->params['id']);\n $simplenote->approved = $simplenote->approved == 1 ? 0 : 1;\n $simplenote->save();\n \n $lastUrl = makelink($history->history[$history->history['lasts']['type']][count($history->history[$history->history['lasts']['type']])-1]['params']);\n if (!empty($this->params['tab']))\n {\n $lastUrl .= \"#\".$this->params['tab'];\n }\n redirect_to($lastUrl);\n }", "label_name": "CWE-74", "label": "74"} -{"code": " self::assertSame($shouldBePresent, $request->hasHeader('Authorization'));\n self::assertSame($shouldBePresent, $request->hasHeader('Cookie'));\n\n return new Response(200);\n }\n ]);", "label_name": "CWE-200", "label": "200"} -{"code": " public function confirm()\n {\n $task = $this->getTask();\n $link_id = $this->request->getIntegerParam('link_id');\n $link = $this->taskExternalLinkModel->getById($link_id);\n\n if (empty($link)) {\n throw new PageNotFoundException();\n }\n\n $this->response->html($this->template->render('task_external_link/remove', array(\n 'link' => $link,\n 'task' => $task,\n )));\n }", "label_name": "CWE-200", "label": "200"} -{"code": " foreach ($allgroups as $gid) {\r\n $g = group::getGroupById($gid);\r\n expPermissions::grantGroup($g, 'manage', $sloc);\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public function testNotRemoveAuthorizationHeaderOnRedirect()\n {\n $mock = new MockHandler([\n new Response(302, ['Location' => 'http://example.com/2']),\n static function (RequestInterface $request) {\n self::assertTrue($request->hasHeader('Authorization'));\n return new Response(200);\n }\n ]);\n $handler = HandlerStack::create($mock);\n $client = new Client(['handler' => $handler]);\n $client->get('http://example.com?a=b', ['auth' => ['testuser', 'testpass']]);\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public function update() {\n\n //populate the alt tag field if the user didn't\n if (empty($this->params['alt'])) $this->params['alt'] = $this->params['title'];\n \n // call expController update to save the image\n parent::update();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function beforeSave() {\n if(strpos($this->tag,self::DELIM) !== false) {\n $this->tag = strtr($this->tag,array(self::DELIM => ''));\n }\n return true;\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\tpublic function Update() {\n\n\t\t// Update \"main\" ticket\n\t\t$upd_stmt = Database::prepare('\n\t\t\tUPDATE `' . TABLE_PANEL_TICKETS . '` SET\n `priority` = :priority,\n `lastchange` = :lastchange,\n `status` = :status,\n `lastreplier` = :lastreplier\n WHERE `id` = :tid'\n\t\t);\n\t\t$upd_data = array(\n\t\t\t'priority' => $this->Get('priority'),\n\t\t\t'lastchange' => $this->Get('lastchange'),\n\t\t\t'status' => $this->Get('status'),\n\t\t\t'lastreplier' => $this->Get('lastreplier'),\n\t\t\t'tid' => $this->tid\n\t\t);\n\t\tDatabase::pexecute($upd_stmt, $upd_data);\n\t\treturn true;\n\t}", "label_name": "CWE-732", "label": "732"} -{"code": "\t\t\t$result = $search->getSearchResults($item->query, false, true);\n\t\t\tif(empty($result) && !in_array($item->query, $badSearchArr)) {\n\t\t\t\t$badSearchArr[] = $item->query;\n\t\t\t\t$badSearch[$ctr2]['query'] = $item->query;\n\t\t\t\t$badSearch[$ctr2]['count'] = $db->countObjects(\"search_queries\", \"query='{$item->query}'\");\n\t\t\t\t$ctr2++;\n\t\t\t}\n\t\t\t\n\t\t}\n\t\n\t\t//Check if the user choose from the dropdown\n\t\tif(!empty($user_default)) {\n\t\t\tif($user_default == $anonymous) {\n\t\t\t\t$u_id = 0;\n\t\t\t} else {\n\t\t\t\t$u_id = $user_default;\n\t\t\t}\n\t\t\t$where .= \"user_id = {$u_id}\";\n\t\t}\n\t\n\t\t//Get all the search query records\n\t\t$records = $db->selectObjects('search_queries', $where);\n for ($i = 0, $iMax = count($records); $i < $iMax; $i++) {\n\t\t\tif(!empty($records[$i]->user_id)) {\n\t\t\t\t$u = user::getUserById($records[$i]->user_id);\n\t\t\t\t$records[$i]->user = $u->firstname . ' ' . $u->lastname;\n\t\t\t}\n\t\t}\n\t\t\n $page = new expPaginator(array(\n 'records' => $records,\n 'where'=>1,\n 'model'=>'search_queries',\n 'limit'=>(isset($this->config['limit']) && $this->config['limit'] != '') ? 10 : $this->config['limit'],\n 'order'=>empty($this->config['order']) ? 'timestamp' : $this->config['order'],\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->baseclassname,\n 'action'=>$this->params['action'],\n 'columns'=>array(\n 'ID'=>'id',\n gt('Query')=>'query',\n gt('Timestamp')=>'timestamp',\n gt('User')=>'user_id',\n ),\n ));\n\n $uname['id'] = implode($uname['id'],',');\n $uname['name'] = implode($uname['name'],',');\n assign_to_template(array(\n 'page'=>$page,\n 'users'=>$uname,\n 'user_default' => $user_default,\n 'badSearch' => $badSearch\n ));\n\t\t\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": "\tpublic function approve() {\n\t expHistory::set('editable', $this->params);\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n// $require_login = empty($this->params['require_login']) ? COMMENTS_REQUIRE_LOGIN : $this->params['require_login'];\n// $require_approval = empty($this->params['require_approval']) ? COMMENTS_REQUIRE_APPROVAL : $this->params['require_approval'];\n// $require_notification = empty($this->params['require_notification']) ? COMMENTS_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n// $notification_email = empty($this->params['notification_email']) ? COMMENTS_NOTIFICATION_EMAIL : $this->params['notification_email'];\n\t \n\t if (empty($this->params['id'])) {\n\t flash('error', gt('No ID supplied for comment to approve'));\n\t expHistory::back();\n\t }\n\t \n\t $comment = new expComment($this->params['id']);\n\t assign_to_template(array(\n 'comment'=>$comment\n ));\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": "\t\t\t$text = preg_replace( $skipPat, '', $text );\n\t\t}\n\n\t\tif ( self::open( $parser, $part1 ) ) {\n\n\t\t\t//Handle recursion here, so we can break cycles.\n\t\t\tif ( $recursionCheck == false ) {\n\t\t\t\t$text = $parser->preprocess( $text, $parser->mTitle, $parser->mOptions );\n\t\t\t\tself::close( $parser, $part1 );\n\t\t\t}\n\n\t\t\tif ( $maxLength > 0 ) {\n\t\t\t\t$text = self::limitTranscludedText( $text, $maxLength, $link );\n\t\t\t}\n\t\t\tif ( $trim ) {\n\t\t\t\treturn trim( $text );\n\t\t\t} else {\n\t\t\t\treturn $text;\n\t\t\t}\n\t\t} else {\n\t\t\treturn \"[[\" . $title->getPrefixedText() . \"]]\" . \"\";\n\t\t}\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " public function showall() {\n expHistory::set('viewable', $this->params);\n // figure out if should limit the results\n if (isset($this->params['limit'])) {\n $limit = $this->params['limit'] == 'none' ? null : $this->params['limit'];\n } else {\n $limit = (isset($this->config['limit']) && $this->config['limit'] != '') ? $this->config['limit'] : 10;\n } \n $order = isset($this->config['order']) ? $this->config['order'] : 'publish DESC';\n\n // pull the news posts from the database\n $items = $this->news->find('all', $this->aggregateWhereClause(), $order);\n\n // merge in any RSS news and perform the sort and limit the number of posts we return to the configured amount.\n if (!empty($this->config['pull_rss'])) $items = $this->mergeRssData($items);\n \n // setup the pagination object to paginate the news stories.\n $page = new expPaginator(array(\n 'records'=>$items,\n 'limit'=>$limit,\n 'order'=>$order,\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->params['controller'],\n 'action'=>$this->params['action'],\n 'src'=>$this->loc->src,\n 'view'=>empty($this->params['view']) ? null : $this->params['view']\n ));\n \n assign_to_template(array(\n 'page'=>$page,\n 'items'=>$page->records,\n 'rank'=>($order==='rank')?1:0,\n 'params'=>$this->params,\n ));\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function fromFile($filePath)\n {\n if ($filePath === null) {\n return;\n }\n\n $file = new FileObj($filePath);\n $this->file_name = $file->getFilename();\n $this->file_size = $file->getSize();\n $this->content_type = $file->getMimeType();\n $this->disk_name = $this->getDiskName();\n\n $this->putFile($file->getRealPath(), $this->disk_name);\n\n return $this;\n }", "label_name": "CWE-362", "label": "362"} -{"code": " $masteroption->delete();\n }\n \n // delete the mastergroup\n $db->delete('optiongroup', 'optiongroup_master_id='.$mastergroup->id);\n $mastergroup->delete();\n \n expHistory::back();\n }", "label_name": "CWE-74", "label": "74"} -{"code": "function XMLRPCremoveImageFromGroup($name, $imageid){\n $groups = getUserResources(array(\"imageAdmin\"), array(\"manageGroup\"), 1);\n \n if($groupid = getResourceGroupID(\"image/$name\")){\n if(!array_key_exists($groupid, $groups['image'])){\n return array('status' => 'error',\n 'errorcode' => 46,\n 'errormsg' => 'Unable to access image group');\n }\n $resources = getUserResources(array(\"imageAdmin\"), array(\"manageGroup\"));\n if(!array_key_exists($imageid, $resources['image'])){\n return array('status' => 'error',\n 'errorcode' => 47,\n 'errormsg' => 'Unable to access image');\n }\n\n $allimages = getImages();\n $query = \"DELETE FROM resourcegroupmembers \"\n . \"WHERE resourceid={$allimages[$imageid]['resourceid']} \"\n . \"AND resourcegroupid=$groupid\";\n doQuery($query, 287);\n return array('status' => 'success');\n } else {\n return array('status' => 'error',\n 'errorcode' => 83,\n 'errormsg' => 'invalid resource group name');\n }\n}", "label_name": "CWE-20", "label": "20"} -{"code": " static function getRSSFeed($url, $cache_duration = DAY_TIMESTAMP) {\n global $CFG_GLPI;\n\n $feed = new SimplePie();\n $feed->set_cache_location(GLPI_RSS_DIR);\n $feed->set_cache_duration($cache_duration);\n\n // proxy support\n if (!empty($CFG_GLPI[\"proxy_name\"])) {\n $prx_opt = [];\n $prx_opt[CURLOPT_PROXY] = $CFG_GLPI[\"proxy_name\"];\n $prx_opt[CURLOPT_PROXYPORT] = $CFG_GLPI[\"proxy_port\"];\n if (!empty($CFG_GLPI[\"proxy_user\"])) {\n $prx_opt[CURLOPT_HTTPAUTH] = CURLAUTH_ANYSAFE;\n $prx_opt[CURLOPT_PROXYUSERPWD] = $CFG_GLPI[\"proxy_user\"].\":\".\n Toolbox::decrypt($CFG_GLPI[\"proxy_passwd\"],\n GLPIKEY);\n }\n $feed->set_curl_options($prx_opt);\n }\n\n $feed->enable_cache(true);\n $feed->set_feed_url($url);\n $feed->force_feed(true);\n // Initialize the whole SimplePie object. Read the feed, process it, parse it, cache it, and\n // all that other good stuff. The feed's information will not be available to SimplePie before\n // this is called.\n $feed->init();\n\n // We'll make sure that the right content type and character encoding gets set automatically.\n // This function will grab the proper character encoding, as well as set the content type to text/html.\n $feed->handle_content_type();\n if ($feed->error()) {\n return false;\n }\n return $feed;\n }", "label_name": "CWE-327", "label": "327"} -{"code": " public function testPopBeforeSmtpGood()\n {\n //Start a fake POP server\n $pid = shell_exec('nohup ./runfakepopserver.sh >/dev/null 2>/dev/null & printf \"%u\" $!');\n $this->pids[] = $pid;\n\n sleep(2);\n //Test a known-good login\n $this->assertTrue(\n POP3::popBeforeSmtp('localhost', 1100, 10, 'user', 'test', $this->Mail->SMTPDebug),\n 'POP before SMTP failed'\n );\n //Kill the fake server\n shell_exec('kill -TERM '.escapeshellarg($pid));\n sleep(2);\n }", "label_name": "CWE-20", "label": "20"} -{"code": " foreach ($page as $pageperm) {\r\n if (!empty($pageperm['manage'])) return true;\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " static function isSearchable() { return true; }\r", "label_name": "CWE-74", "label": "74"} -{"code": "\tfunction getTextColumns($table) {\n\t\t$sql = \"SHOW COLUMNS FROM \" . $this->prefix.$table . \" WHERE type = 'text' OR type like 'varchar%'\";\n\t\t$res = @mysqli_query($this->connection, $sql);\n\t\tif ($res == null)\n return array();\n\t\t$records = array();\n\t\twhile($row = mysqli_fetch_object($res)) {\n\t\t\t$records[] = $row->Field;\n\t\t}\n\t\t\n\t\treturn $records;\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $filter = $this->customFilterModel->getById($this->request->getIntegerParam('filter_id'));\n\n $this->checkPermission($project, $filter);\n\n if ($this->customFilterModel->remove($filter['id'])) {\n $this->flash->success(t('Custom filter removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this custom filter.'));\n }\n\n $this->response->redirect($this->helper->url->to('CustomFilterController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public function save_change_password() {\n global $user;\n\n $isuser = ($this->params['uid'] == $user->id) ? 1 : 0;\n\n if (!$user->isAdmin() && !$isuser) {\n flash('error', gt('You do not have permissions to change this users password.'));\n expHistory::back();\n }\n\n if (($isuser && empty($this->params['password'])) || (!empty($this->params['password']) && $user->password != user::encryptPassword($this->params['password']))) {\n flash('error', gt('The current password you entered is not correct.'));\n expHistory::returnTo('editable');\n }\n //eDebug($user);\n $u = new user($this->params['uid']);\n\n $ret = $u->setPassword($this->params['new_password1'], $this->params['new_password2']);\n //eDebug($u, true);\n if (is_string($ret)) {\n flash('error', $ret);\n expHistory::returnTo('editable');\n } else {\n $params = array();\n $params['is_admin'] = !empty($u->is_admin);\n $params['is_acting_admin'] = !empty($u->is_acting_admin);\n $u->update($params);\n }\n\n if (!$isuser) {\n flash('message', gt('The password for') . ' ' . $u->username . ' ' . gt('has been changed.'));\n } else {\n $user->password = $u->password;\n flash('message', gt('Your password has been changed.'));\n }\n expHistory::back();\n }", "label_name": "CWE-74", "label": "74"} -{"code": "\tprivate function _modifiedby( $option ) {\n\t\t$this->addTable( 'revision_actor_temp', 'change_rev' );\n\t\t$user = new \\User;\n\n\t\t$this->addWhere( $this->DB->addQuotes( $user->newFromName( $option )->getActorId() ) . ' = change_rev.revactor_actor AND change_rev.revactor_page = page_id' );\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": "\tpublic function execute(&$params) {\n\t\t$options = $this->config['options'];\n\n\t\t$action = new Actions;\n\n\t\t$action->subject = $this->parseOption('subject',$params);\n $action->dueDate = $this->parseOption('dueDate',$params);\n\t\t$action->actionDescription = $this->parseOption('description',$params);\n\t\t$action->priority = $this->parseOption('priority',$params);\n\t\t$action->visibility = $this->parseOption('visibility',$params);\n\n\t\tif(isset($params['model']))\n\t\t\t$action->assignedTo = $this->parseOption('assignedTo',$params);\n\n\t\t// if(isset($this->config['attributes']))\n\t\t\t// $this->setModelAttributes($action,$this->config['attributes'],$params);\n\n if ($action->save()) {\n return array (\n true,\n Yii::t('studio', \"View created action: \").$action->getLink ());\n } else {\n return array(false, array_shift($action->getErrors()));\n }\n\n\n\n\t\t// if($this->parseOption('reminder',$params)) {\n\t\t\t// $notif=new Notification;\n\t\t\t// $notif->modelType='Actions';\n\t\t\t// $notif->createdBy=Yii::app()->user->getName();\n\t\t\t// $notif->modelId=$model->id;\n\t\t\t// if($_POST['notificationUsers']=='me'){\n\t\t\t\t// $notif->user=Yii::app()->user->getName();\n\t\t\t// }else{\n\t\t\t\t// $notif->user=$model->assignedTo;\n\t\t\t// }\n\t\t\t// $notif->createDate=$model->dueDate-($_POST['notificationTime']*60);\n\t\t\t// $notif->type='action_reminder';\n\t\t\t// $notif->save();\n\t\t\t// if($_POST['notificationUsers']=='both' && Yii::app()->user->getName()!=$model->assignedTo){\n\t\t\t\t// $notif2=new Notification;\n\t\t\t\t// $notif2->modelType='Actions';\n\t\t\t\t// $notif2->createdBy=Yii::app()->user->getName();\n\t\t\t\t// $notif2->modelId=$model->id;\n\t\t\t\t// $notif2->user=Yii::app()->user->getName();\n\t\t\t\t// $notif2->createDate=$model->dueDate-($_POST['notificationTime']*60);\n\t\t\t\t// $notif2->type='action_reminder';\n\t\t\t\t// $notif2->save();\n\t\t\t// }\n\t\t// }\n\t}", "label_name": "CWE-20", "label": "20"} -{"code": " public function beforeAction($action)\n {\n // Bypass when not installed for installer\n if (empty(Yii::$app->params['installed']) &&\n Yii::$app->controller->module != null &&\n Yii::$app->controller->module->id == 'installer') {\n return true;\n }\n\n $this->handleDeprecatedSettings();\n $this->controllerAccess = $this->getControllerAccess($this->rules);\n\n if (!$this->controllerAccess->run()) {\n if (isset($this->controllerAccess->codeCallback) &&\n method_exists($this, $this->controllerAccess->codeCallback)) {\n // Call a specific function for current action filter,\n // may be used to filter a logged in user for some restriction e.g. \"must change password\"\n return call_user_func([$this, $this->controllerAccess->codeCallback]);\n } else if ($this->controllerAccess->code == 401) {\n return $this->loginRequired();\n } else {\n $this->forbidden();\n }\n }\n\n return parent::beforeAction($action);\n }", "label_name": "CWE-863", "label": "863"} -{"code": "\tprivate function _notcreatedby( $option ) {\n\t\t$this->addTable( 'revision', 'no_creation_rev' );\n\t\t$this->addTable( 'revision_actor_temp', 'no_creation_rev_actor' );\n\t\t$user = new \\User;\n\n\t\t$this->addWhere( $this->DB->addQuotes( $user->newFromName( $option )->getActorId() ) . ' != no_creation_rev_actor.revactor_actor AND no_creation_rev_actor.revactor_page = page_id AND no_creation_rev.rev_parent_id = 0' );\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": "\tpublic function setItemAttributes( $attributes ) {\n\t\t$this->itemAttributes = \\Sanitizer::fixTagAttributes( $attributes, 'li' );\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " private function checkResponse ($string) {\n if (substr($string, 0, 3) !== '+OK') {\n $this->error = array(\n 'error' => \"Server reported an error: $string\",\n 'errno' => 0,\n 'errstr' => ''\n );\n\n if ($this->do_debug >= 1) {\n $this->displayErrors();\n }\n\n return false;\n } else {\n return true;\n }\n\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\tprivate function _minrevisions( $option ) {\n\t\t$this->addWhere( \"((SELECT count(rev_aux2.revactor_page) FROM {$this->tableNames['revision_actor_temp']} AS rev_aux2 WHERE rev_aux2.revactor_page = {$this->tableNames['page']}.page_id) >= {$option})\" );\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " Contacts::model()->deleteAll($criteria);\n }\n }\n echo $model->id;\n }\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\tstatic public function getLastArchived($_num = 10, $_admin = 1) {\n\n\t\tif ($_num > 0) {\n\n\t\t\t$archived = array();\n\t\t\t$counter = 0;\n\t\t\t$result_stmt = Database::prepare(\"\n\t\t\t\tSELECT *, (\n\t\t\t\t\tSELECT COUNT(`sub`.`id`)\n\t\t\t\t\tFROM `\" . TABLE_PANEL_TICKETS . \"` `sub`\n\t\t\t\t\tWHERE `sub`.`answerto` = `main`.`id`\n\t\t\t\t) as `ticket_answers`\n\t\t\t\tFROM `\" . TABLE_PANEL_TICKETS . \"` `main`\n\t\t\t\tWHERE `main`.`answerto` = '0' AND `main`.`archived` = '1'\n\t\t\t\tAND `main`.`adminid` = :adminid\n\t\t\t\tORDER BY `main`.`lastchange` DESC LIMIT 0, \".(int)$_num\n\t\t\t);\n\t\t\tDatabase::pexecute($result_stmt, array('adminid' => $_admin));\n\n\t\t\twhile ($row = $result_stmt->fetch(PDO::FETCH_ASSOC)) {\n\n\t\t\t\t$archived[$counter]['id'] = $row['id'];\n\t\t\t\t$archived[$counter]['customerid'] = $row['customerid'];\n\t\t\t\t$archived[$counter]['adminid'] = $row['adminid'];\n\t\t\t\t$archived[$counter]['lastreplier'] = $row['lastreplier'];\n\t\t\t\t$archived[$counter]['ticket_answers'] = $row['ticket_answers'];\n\t\t\t\t$archived[$counter]['category'] = $row['category'];\n\t\t\t\t$archived[$counter]['priority'] = $row['priority'];\n\t\t\t\t$archived[$counter]['subject'] = $row['subject'];\n\t\t\t\t$archived[$counter]['message'] = $row['message'];\n\t\t\t\t$archived[$counter]['dt'] = $row['dt'];\n\t\t\t\t$archived[$counter]['lastchange'] = $row['lastchange'];\n\t\t\t\t$archived[$counter]['status'] = $row['status'];\n\t\t\t\t$archived[$counter]['by'] = $row['by'];\n\t\t\t\t$counter++;\n\t\t\t}\n\n\t\t\tif (isset($archived[0]['id'])) {\n\t\t\t\treturn $archived;\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}", "label_name": "CWE-732", "label": "732"} -{"code": "\t\t\t$eml->prepareBody();\n\t\t}\n\n list ($success, $message) = $this->checkDoNotEmailFields ($eml);\n if (!$success) {\n return array ($success, $message);\n }\n\n\t\t$result = $eml->send($historyFlag);\n\t\tif (isset($result['code']) && $result['code'] == 200) {\n if (YII_UNIT_TESTING) {\n return array(true, $eml->message);\n } else {\n return array(true, \"\");\n }\n } else {\n return array (false, Yii::t('app', \"Email could not be sent\"));\n }\n\t}", "label_name": "CWE-20", "label": "20"} -{"code": " $links[] = CHtml::link(CHtml::encode($tag->tag),array('/search/search','term'=>CHtml::encode($tag->tag)));", "label_name": "CWE-20", "label": "20"} -{"code": " protected function getSubtask()\n {\n $subtask = $this->subtaskModel->getById($this->request->getIntegerParam('subtask_id'));\n\n if (empty($subtask)) {\n throw new PageNotFoundException();\n }\n\n return $subtask;\n }", "label_name": "CWE-200", "label": "200"} -{"code": "\tprivate function _titlegt( $option ) {\n\t\t$where = '(';\n\t\tif ( substr( $option, 0, 2 ) == '=_' ) {\n\t\t\tif ( $this->parameters->getParameter( 'openreferences' ) ) {\n\t\t\t\t$where .= 'pl_title >= ' . $this->DB->addQuotes( substr( $sTitleGE, 2 ) );\n\t\t\t} else {\n\t\t\t\t$where .= $this->tableNames['page'] . '.page_title >= ' . $this->DB->addQuotes( substr( $option, 2 ) );\n\t\t\t}\n\t\t} else {\n\t\t\tif ( $this->parameters->getParameter( 'openreferences' ) ) {\n\t\t\t\t$where .= 'pl_title > ' . $this->DB->addQuotes( $option );\n\t\t\t} else {\n\t\t\t\t$where .= $this->tableNames['page'] . '.page_title > ' . $this->DB->addQuotes( $option );\n\t\t\t}\n\t\t}\n\t\t$where .= ')';\n\t\t$this->addWhere( $where );\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " public function Mail($from) {\n $this->error = null; // so no confusion is caused\n\n if(!$this->connected()) {\n $this->error = array(\n \"error\" => \"Called Mail() without being connected\");\n return false;\n }\n\n $useVerp = ($this->do_verp ? \" XVERP\" : \"\");\n fputs($this->smtp_conn,\"MAIL FROM:<\" . $from . \">\" . $useVerp . $this->CRLF);\n\n $rply = $this->get_lines();\n $code = substr($rply,0,3);\n\n if($this->do_debug >= 2) {\n $this->edebug(\"SMTP -> FROM SERVER:\" . $rply . $this->CRLF . '
');\n }\n\n if($code != 250) {\n $this->error =\n array(\"error\" => \"MAIL not accepted from server\",\n \"smtp_code\" => $code,\n \"smtp_msg\" => substr($rply,4));\n if($this->do_debug >= 1) {\n $this->edebug(\"SMTP -> ERROR: \" . $this->error[\"error\"] . \": \" . $rply . $this->CRLF . '
');\n }\n return false;\n }\n return true;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " private static function sign($input, $key, $algo = 'HS256')\n {\n switch ($algo) {\n\n case 'HS256':\n return hash_hmac('sha256', $input, $key, true);\n\n case 'HS384':\n return hash_hmac('sha384', $input, $key, true);\n\n case 'HS512':\n return hash_hmac('sha512', $input, $key, true);\n\n case 'RS256':\n return JWT::generateRSASignature($input, $key, OPENSSL_ALGO_SHA256);\n\n case 'RS384':\n return JWT::generateRSASignature($input, $key, OPENSSL_ALGO_SHA384);\n\n case 'RS512':\n return JWT::generateRSASignature($input, $key, OPENSSL_ALGO_SHA512);\n\n default:\n throw new Exception(\"Unsupported or invalid signing algorithm.\");\n }\n }", "label_name": "CWE-20", "label": "20"} -{"code": "function test1Controller($hphpdOutput, $hphpdProcessId, $serverPort) {\n // Request a page so that the client can debug it.\n waitForClientToOutput($hphpdOutput, \"Waiting for server response\");\n $url = \"http://\".php_uname('n').':'.$serverPort.'/test1.php';\n echo \"Requesting test1.php\\n\";\n request(php_uname('n'), $serverPort, 'test1.php', 10); // ignore response\n\n // Let client run until script quits\n waitForClientToOutput($hphpdOutput, \"quit\");\n}", "label_name": "CWE-668", "label": "668"} -{"code": "\tpublic static function login() {\n\t\tuser::login(expString::sanitize($_POST['username']),expString::sanitize($_POST['password']));\n\t\tif (!isset($_SESSION[SYS_SESSION_KEY]['user'])) { // didn't successfully log in\n\t\t\tflash('error', gt('Invalid Username / Password'));\n\t\t\tif (expSession::is_set('redirecturl_error')) {\n\t\t\t\t$url = expSession::get('redirecturl_error');\n\t\t\t\texpSession::un_set('redirecturl_error');\n\t\t\t\theader(\"Location: \".$url);\n\t\t\t} else {\n\t\t\t\texpHistory::back();\n\t\t\t}\n\t\t} else { // we're logged in\n\t\t\tglobal $user;\n\n if (expSession::get('customer-login')) expSession::un_set('customer-login');\n\t\t\tif (!empty($_POST['username'])) flash('message', gt('Welcome back').' '.expString::sanitize($_POST['username']));\n if ($user->isAdmin()) {\n expHistory::back();\n } else {\n foreach ($user->groups as $g) {\n if (!empty($g->redirect)) {\n $url = URL_FULL.$g->redirect;\n break;\n }\n }\n if (isset($url)) {\n header(\"Location: \".$url);\n } else {\n expHistory::back();\n }\n }\n\t\t}\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": "\tstatic public function customerHasTickets($_cid = 0) {\n\n\t\tif ($_cid != 0) {\n\t\t\t$result_stmt = Database::prepare(\"\n\t\t\t\tSELECT `id` FROM `\" . TABLE_PANEL_TICKETS . \"` WHERE `customerid` = :cid\"\n\t\t\t);\n\t\t\tDatabase::pexecute($result_stmt, array('cid' => $_cid));\n\n\t\t\t$tickets = array();\n\t\t\twhile ($row = $result_stmt->fetch(PDO::FETCH_ASSOC)) {\n\t\t\t\t$tickets[] = $row['id'];\n\t\t\t}\n\n\t\t\treturn $tickets;\n\t\t}\n\n\t\treturn false;\n\t}", "label_name": "CWE-732", "label": "732"} -{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $category = $this->getCategory();\n\n if ($this->categoryModel->remove($category['id'])) {\n $this->flash->success(t('Category removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this category.'));\n }\n\n $this->response->redirect($this->helper->url->to('CategoryController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-200", "label": "200"} -{"code": "\tpublic function update($user, $notrigger = 0)\n\t{\n\t\tglobal $langs, $conf;\n\n\t\t$error = 0;\n\n\t\t// Clean parameters\n\t\t$this->address = ($this->address > 0 ? $this->address : $this->address);\n\t\t$this->zip = ($this->zip > 0 ? $this->zip : $this->zip);\n\t\t$this->town = ($this->town > 0 ? $this->town : $this->town);\n\t\t$this->country_id = ($this->country_id > 0 ? $this->country_id : $this->country_id);\n\t\t$this->country = ($this->country ? $this->country : $this->country);\n\n\t\t$this->db->begin();\n\n\t\t$sql = \"UPDATE \".MAIN_DB_PREFIX.\"don SET \";\n\t\t$sql .= \"amount = \".price2num($this->amount);\n\t\t$sql .= \",fk_payment = \".($this->modepaymentid ? $this->modepaymentid : \"null\");", "label_name": "CWE-20", "label": "20"} -{"code": "\tpublic function getPurchaseOrderByJSON() {\n\t\t\n\t\tif(!empty($this->params['vendor'])) {\n\t\t\t$purchase_orders = $this->purchase_order->find('all', 'vendor_id=' . $this->params['vendor']);\n\t\t} else {\n\t\t\t$purchase_orders = $this->purchase_order->find('all');\n\t\t}\n\t\t\n\t\techo json_encode($purchase_orders);\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": " protected function setUp()\n {\n $this->originalTrustedHeaderName = Request::getTrustedHeaderName(Request::HEADER_CLIENT_IP);\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\tprivate function get_submit_action() {\r\n\r\n\t\t$action = null;\r\n\r\n\t\tif ( isset( $_POST['geo_mashup_add_location'] ) or isset( $_POST['geo_mashup_update_location'] ) ) {\r\n\r\n\t\t\t// Clients without javascript may need server side geocoding\r\n\t\t\tif ( ! empty( $_POST['geo_mashup_search'] ) and isset( $_POST['geo_mashup_no_js'] ) and 'true' == $_POST['geo_mashup_no_js'] ) {\r\n\r\n\t\t\t\t$action = 'geocode';\r\n\r\n\t\t\t} else {\r\n\r\n\t\t\t\t$action = 'save';\r\n\r\n\t\t\t}\r\n\r\n\t\t} else if ( isset( $_POST['geo_mashup_changed'] ) and 'true' == $_POST['geo_mashup_changed'] and ! empty( $_POST['geo_mashup_location'] ) ) {\r\n\r\n\t\t\t// The geo mashup submit button wasn't used, but a change was made and the post saved\r\n\t\t\t$action = 'save';\r\n\t\t\t\t \r\n\t\t} else if ( isset( $_POST['geo_mashup_delete_location'] ) ) {\r\n\r\n\t\t\t$action = 'delete';\r\n\r\n\t\t} else if ( ! empty( $_POST['geo_mashup_location_id'] ) and empty( $_POST['geo_mashup_location'] ) ) {\r\n\r\n\t\t\t// There was a location, but it was cleared before this save\r\n\t\t\t$action = 'delete';\r\n\r\n\t\t}\r\n\t\treturn $action;\r\n\t}\r", "label_name": "CWE-20", "label": "20"} -{"code": "\t\taddChangeLogEntry($request[\"logid\"], NULL, unixToDatetime($end),\n\t\t $request['start'], NULL, NULL, 0);\n\t\treturn array('status' => 'error',\n\t\t 'errorcode' => 44,\n\t\t 'errormsg' => 'concurrent license restriction');\n\t}", "label_name": "CWE-20", "label": "20"} -{"code": "\t\t\treturn $wgLang->timeanddate( $article->mDate, true );\n\t\t}\n\t\treturn null;\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " function showByModel() {\n global $order, $template, $db;\n\n expHistory::set('viewable', $this->params);\n $product = new product();\n $model = $product->find(\"first\", 'model=\"' . $this->params['model'] . '\"');\n //eDebug($model);\n $product_type = new $model->product_type($model->id);\n //eDebug($product_type);\n $tpl = $product_type->getForm('show');\n if (!empty($tpl)) $template = new controllertemplate($this, $tpl);\n //eDebug($template);\n $this->grabConfig(); // grab the global config\n assign_to_template(array(\n 'config' => $this->config,\n 'product' => $product_type,\n 'last_category' => $order->lastcat\n ));\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public static function initializeNavigation() {\r\n $sections = section::levelTemplate(0, 0);\r\n return $sections;\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": "\t\t\t$rest = $count - ( floor( $nsize ) * floor( $iGroup ) );\n\t\t\tif ( $rest > 0 ) {\n\t\t\t\t$nsize += 1;\n\t\t\t}\n\t\t\t$output .= \"{|\" . $rowColFormat . \"\\n|\\n\";\n\t\t\tfor ( $g = 0; $g < $iGroup; $g++ ) {\n\t\t\t\t$output .= $lister->formatList( $articles, $nstart, $nsize );\n\t\t\t\tif ( $columns != 1 ) {\n\t\t\t\t\t$output .= \"\\n|valign=top|\\n\";\n\t\t\t\t} else {\n\t\t\t\t\t$output .= \"\\n|-\\n|\\n\";\n\t\t\t\t}\n\t\t\t\t$nstart = $nstart + $nsize;\n\t\t\t\t// if ($rest != 0 && $g+1==$rest) $nsize -= 1;\n\t\t\t\tif ( $nstart + $nsize > $count ) {\n\t\t\t\t\t$nsize = $count - $nstart;\n\t\t\t\t}\n\t\t\t}\n\t\t\t$output .= \"\\n|}\\n\";\n\t\t} elseif ( $rowSize > 0 ) {", "label_name": "CWE-400", "label": "400"} -{"code": " public function crossOriginRedirectProvider()\n {\n return [\n ['http://example.com?a=b', 'http://test.com/', false],\n ['https://example.com?a=b', 'https://test.com/', false],\n ['http://example.com?a=b', 'https://test.com/', false],\n ['https://example.com?a=b', 'http://test.com/', false],\n ['http://example.com?a=b', 'http://example.com/', true],\n ['https://example.com?a=b', 'https://example.com/', true],\n ['http://example.com?a=b', 'https://example.com/', true],\n ['https://example.com?a=b', 'http://example.com/', false],\n ];\n }", "label_name": "CWE-200", "label": "200"} -{"code": "\t function manage_upcharge() {\n\t\t$this->loc->src = \"@globalstoresettings\";\n $config = new expConfig($this->loc);\n\t\t$this->config = $config->config;\n\n\t\t$gc = new geoCountry(); \n $countries = $gc->find('all');\n \n $gr = new geoRegion(); \n $regions = $gr->find('all',null,'rank asc,name asc');\n assign_to_template(array(\n 'countries'=>$countries,\n 'regions'=>$regions,\n 'upcharge'=>!empty($this->config['upcharge'])?$this->config['upcharge']:''\n ));\n\t }", "label_name": "CWE-74", "label": "74"} -{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $swimlane_id = $this->request->getIntegerParam('swimlane_id');\n\n if ($this->swimlaneModel->remove($project['id'], $swimlane_id)) {\n $this->flash->success(t('Swimlane removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this swimlane.'));\n }\n\n $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-200", "label": "200"} -{"code": "\tpublic static function onRegistration() {\n\t\tif ( !defined( 'DPL_VERSION' ) ) {\n\t\t\tdefine( 'DPL_VERSION', '3.3.5' );\n\t\t}\n\t}", "label_name": "CWE-400", "label": "400"} -{"code": " public function testEncrypt($string, $key, $expected) {\n $this->string(\\Toolbox::encrypt($string, $key))->isIdenticalTo($expected);\n }", "label_name": "CWE-327", "label": "327"} -{"code": "\tfunction delete_vendor() {\n\t\tglobal $db;\n\t\t\n if (!empty($this->params['id'])){\n\t\t\t$db->delete('vendor', 'id =' .$this->params['id']);\n\t\t}\n expHistory::back();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " function showallSubcategories() {\n// global $db;\n\n expHistory::set('viewable', $this->params);\n// $parent = isset($this->params['cat']) ? $this->params['cat'] : expSession::get('catid');\n $catid = expSession::get('catid');\n $parent = !empty($catid) ? $catid : (!empty($this->params['cat']) ? $this->params['cat'] : 0);\n $category = new storeCategory($parent);\n $categories = $category->getEcomSubcategories();\n $ancestors = $category->pathToNode();\n assign_to_template(array(\n 'categories' => $categories,\n 'ancestors' => $ancestors,\n 'category' => $category\n ));\n }", "label_name": "CWE-20", "label": "20"} -{"code": " $db->updateObject($value, 'section');\r\n }\r\n $db->updateObject($moveSec, 'section');\r\n //handle re-ranking of previous parent\r\n $oldSiblings = $db->selectObjects(\"section\", \"parent=\" . $oldParent . \" AND rank>\" . $oldRank . \" ORDER BY rank\");\r\n $rerank = 1;\r\n foreach ($oldSiblings as $value) {\r\n if ($value->id != $moveSec->id) {\r\n $value->rank = $rerank;\r\n $db->updateObject($value, 'section');\r\n $rerank++;\r\n }\r\n }\r\n if ($oldParent != $moveSec->parent) {\r\n //we need to re-rank the children of the parent that the moving section has just left\r\n $childOfLastMove = $db->selectObjects(\"section\", \"parent=\" . $oldParent . \" ORDER BY rank\");\r\n for ($i = 0, $iMax = count($childOfLastMove); $i < $iMax; $i++) {\r\n $childOfLastMove[$i]->rank = $i;\r\n $db->updateObject($childOfLastMove[$i], 'section');\r\n }\r\n }\r\n }\r\n }\r\n self::checkForSectionalAdmins($move);\r\n expSession::clearAllUsersSessionCache('navigation');\r\n }\r", "label_name": "CWE-74", "label": "74"} -{"code": " public function showall_tags() {\n $images = $this->image->find('all');\n $used_tags = array();\n foreach ($images as $image) {\n foreach($image->expTag as $tag) {\n if (isset($used_tags[$tag->id])) {\n $used_tags[$tag->id]->count++;\n } else {\n $exptag = new expTag($tag->id);\n $used_tags[$tag->id] = $exptag;\n $used_tags[$tag->id]->count = 1;\n }\n \n }\n }\n \n assign_to_template(array(\n 'tags'=>$used_tags\n ));\n } ", "label_name": "CWE-74", "label": "74"} -{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $filter = $this->customFilterModel->getById($this->request->getIntegerParam('filter_id'));\n\n $this->checkPermission($project, $filter);\n\n if ($this->customFilterModel->remove($filter['id'])) {\n $this->flash->success(t('Custom filter removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this custom filter.'));\n }\n\n $this->response->redirect($this->helper->url->to('CustomFilterController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public function actionEditDropdown() {\n $model = new Dropdowns;\n\n if (isset($_POST['Dropdowns'])) {\n $model = Dropdowns::model()->findByPk(\n $_POST['Dropdowns']['id']);\n if ($model->id == Actions::COLORS_DROPDOWN_ID) {\n if (AuxLib::issetIsArray($_POST['Dropdowns']['values']) &&\n AuxLib::issetIsArray($_POST['Dropdowns']['labels']) &&\n count($_POST['Dropdowns']['values']) ===\n count($_POST['Dropdowns']['labels'])) {\n\n if (AuxLib::issetIsArray($_POST['Admin']) &&\n isset($_POST['Admin']['enableColorDropdownLegend'])) {\n\n Yii::app()->settings->enableColorDropdownLegend = \n $_POST['Admin']['enableColorDropdownLegend'];\n Yii::app()->settings->save();\n }\n\n $options = array_combine(\n $_POST['Dropdowns']['values'], $_POST['Dropdowns']['labels']);\n $temp = array();\n foreach ($options as $value => $label) {\n if ($value != \"\")\n $temp[$value] = $label;\n }\n $model->options = json_encode($temp);\n $model->save();\n }\n } else {\n $model->attributes = $_POST['Dropdowns'];\n $temp = array();\n if (is_array($model->options) && count($model->options) > 0) {\n foreach ($model->options as $option) {\n if ($option != \"\")\n $temp[$option] = $option;\n }\n $model->options = json_encode($temp);\n if ($model->save()) {\n \n }\n }\n }\n }\n $this->redirect(\n 'manageDropDowns'\n );\n }", "label_name": "CWE-20", "label": "20"} -{"code": " function selectArraysBySql($sql) { \n $res = @mysqli_query($this->connection, $this->injectProof($sql));\n if ($res == null)\n return array();\n $arrays = array();\n for ($i = 0, $iMax = mysqli_num_rows($res); $i < $iMax; $i++)\n $arrays[] = mysqli_fetch_assoc($res);\n return $arrays;\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function view() {\n $params = func_get_args();\n $content = '';\n\n $filename = urldecode(join('/', $params));\n\n // Sanitize filename for securtiy\n // We don't allow backlinks\n if (strpos($filename, '..') !== false) {\n /*\n if (Plugin::isEnabled('statistics_api')) {\n $user = null;\n if (AuthUser::isLoggedIn())\n $user = AuthUser::getUserName();\n $ip = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : ($_SERVER['REMOTE_ADDR']);\n $event = array('event_type' => 'hack_attempt', // simple event type identifier\n 'description' => __('A possible hack attempt was detected.'), // translatable description\n 'ipaddress' => $ip,\n 'username' => $user);\n Observer::notify('stats_file_manager_hack_attempt', $event);\n }\n */\n }\n $filename = str_replace('..', '', $filename);\n\n // Clean up nicely\n $filename = str_replace('//', '', $filename);\n\n // We don't allow leading slashes\n $filename = preg_replace('/^\\//', '', $filename);\n \n // Check if file had URL_SUFFIX - if so, append it to filename\n $filename .= (isset($_GET['has_url_suffix']) && $_GET['has_url_suffix']==='1') ? URL_SUFFIX : '';\n \n $file = FILES_DIR . '/' . $filename;\n if (!$this->_isImage($file) && file_exists($file)) {\n $content = file_get_contents($file);\n }\n \n $this->display('file_manager/views/view', array(\n 'csrf_token' => SecureToken::generateToken(BASE_URL.'plugin/file_manager/save/'.$filename),\n 'is_image' => $this->_isImage($file),\n 'filename' => $filename,\n 'content' => $content\n ));\n }", "label_name": "CWE-20", "label": "20"} -{"code": " protected function checkMaintenanceMode()\n {\n if (Yii::$app->settings->get('maintenanceMode')) {\n if (!Yii::$app->user->isGuest) {\n Yii::$app->user->logout();\n Yii::$app->getView()->warn(Yii::t('error', 'Maintenance mode activated: You have been automatically logged out and will no longer have access the platform until the maintenance has been completed.'));\n }\n return Yii::$app->getResponse()->redirect(['/user/auth/login']);\n }\n }", "label_name": "CWE-863", "label": "863"} -{"code": " public function activate_discount(){ \n if (isset($this->params['id'])) {\n $discount = new discounts($this->params['id']);\n $discount->update($this->params);\n //if ($discount->discountulator->hasConfig() && empty($discount->config)) {\n //flash('messages', $discount->discountulator->name().' requires configuration. Please do so now.');\n //redirect_to(array('controller'=>'billing', 'action'=>'configure', 'id'=>$discount->id));\n //}\n }\n \n expHistory::back();\n }", "label_name": "CWE-74", "label": "74"} -{"code": "\tpublic static function login() {\n\t\tuser::login(expString::sanitize($_POST['username']),expString::sanitize($_POST['password']));\n\t\tif (!isset($_SESSION[SYS_SESSION_KEY]['user'])) { // didn't successfully log in\n\t\t\tflash('error', gt('Invalid Username / Password'));\n\t\t\tif (expSession::is_set('redirecturl_error')) {\n\t\t\t\t$url = expSession::get('redirecturl_error');\n\t\t\t\texpSession::un_set('redirecturl_error');\n\t\t\t\theader(\"Location: \".$url);\n\t\t\t} else {\n\t\t\t\texpHistory::back();\n\t\t\t}\n\t\t} else { // we're logged in\n\t\t\tglobal $user;\n\n if (expSession::get('customer-login')) expSession::un_set('customer-login');\n\t\t\tif (!empty($_POST['username'])) flash('message', gt('Welcome back').' '.expString::sanitize($_POST['username']));\n if ($user->isAdmin()) {\n expHistory::back();\n } else {\n foreach ($user->groups as $g) {\n if (!empty($g->redirect)) {\n $url = URL_FULL.$g->redirect;\n break;\n }\n }\n if (isset($url)) {\n header(\"Location: \".$url);\n } else {\n expHistory::back();\n }\n }\n\t\t}\n\t}", "label_name": "CWE-74", "label": "74"} -{"code": " public function actionGetItems(){\n $model = X2Model::model ($this->modelClass);\n if (isset ($model)) {\n $tableName = $model->tableName ();\n $sql = \n 'SELECT id, fileName as value\n FROM '.$tableName.' \n WHERE associationType!=\"theme\" and fileName LIKE :qterm \n ORDER BY fileName ASC';\n $command = Yii::app()->db->createCommand($sql);\n $qterm = $_GET['term'].'%';\n $command->bindParam(\":qterm\", $qterm, PDO::PARAM_STR);\n $result = $command->queryAll();\n echo CJSON::encode($result);\n }\n Yii::app()->end();\n }", "label_name": "CWE-20", "label": "20"} -{"code": " function searchName() { return gt('Webpage'); }\r", "label_name": "CWE-74", "label": "74"} -{"code": " $chats[$index]->link = erLhcoreClassXMP::getBaseHost() . $_SERVER['HTTP_HOST'] . erLhcoreClassDesign::baseurl('user/login').'/(r)/'.rawurlencode(base64_encode('chat/single/'.$chat->id));\n }\n }", "label_name": "CWE-116", "label": "116"} -{"code": " public function event()\n {\n $project = $this->getProject();\n $values = $this->request->getValues();\n\n if (empty($values['action_name']) || empty($values['project_id'])) {\n return $this->create();\n }\n\n return $this->response->html($this->template->render('action_creation/event', array(\n 'values' => $values,\n 'project' => $project,\n 'available_actions' => $this->actionManager->getAvailableActions(),\n 'events' => $this->actionManager->getCompatibleEvents($values['action_name']),\n )));\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public function saveconfig() {\n global $db;\n\n if (empty($this->params['id'])) return false;\n $calcname = $db->selectValue('shippingcalculator', 'calculator_name', 'id='.$this->params['id']);\n $calc = new $calcname($this->params['id']);\n $conf = serialize($calc->parseConfig($this->params)); \n $calc->update(array('config'=>$conf));\n expHistory::back();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public function StartTLS() {\n $this->error = null; # to avoid confusion\n\n if(!$this->connected()) {\n $this->error = array(\"error\" => \"Called StartTLS() without being connected\");\n return false;\n }\n\n fputs($this->smtp_conn,\"STARTTLS\" . $this->CRLF);\n\n $rply = $this->get_lines();\n $code = substr($rply,0,3);\n\n if($this->do_debug >= 2) {\n $this->edebug(\"SMTP -> FROM SERVER:\" . $rply . $this->CRLF . '
');\n }\n\n if($code != 220) {\n $this->error =\n array(\"error\" => \"STARTTLS not accepted from server\",\n \"smtp_code\" => $code,\n \"smtp_msg\" => substr($rply,4));\n if($this->do_debug >= 1) {\n $this->edebug(\"SMTP -> ERROR: \" . $this->error[\"error\"] . \": \" . $rply . $this->CRLF . '
');\n }\n return false;\n }\n\n // Begin encrypted connection\n if(!stream_socket_enable_crypto($this->smtp_conn, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {\n return false;\n }\n\n return true;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " $v = trim($v);\n if ($v !== '') {\n $_POST[$key][] = $v;\n }\n }\n }", "label_name": "CWE-200", "label": "200"} -{"code": " watchFns: function() {\n var result = [];\n var fns = this.state.inputs;\n var self = this;\n forEach(fns, function(name) {\n result.push('var ' + name + '=' + self.generateFunction(name, 's'));\n });\n if (fns.length) {\n result.push('fn.inputs=[' + fns.join(',') + '];');\n }\n return result.join('');\n },", "label_name": "CWE-74", "label": "74"} -{"code": "d.addHours=function(a,c){return d.addMinutes(a,60*c)};d.addMinutes=function(a,c){return d.addSeconds(a,60*c)};d.addSeconds=function(a,c){return d.addMilliseconds(a,1E3*c)};d.addMilliseconds=function(a,c){return new Date(a.getTime()+c)};d.subtract=function(a,c){var b=a.getTime()-c.getTime();return{toMilliseconds:function(){return b},toSeconds:function(){return b/1E3},toMinutes:function(){return b/6E4},toHours:function(){return b/36E5},toDays:function(){return b/864E5}}};d.isLeapYear=function(a){return!(a%", "label_name": "CWE-400", "label": "400"} -{"code": "this.spacing=0}function Ca(){mxArrowConnector.call(this);this.spacing=0}function Ra(){mxActor.call(this)}function ab(){mxRectangleShape.call(this)}function Ka(){mxActor.call(this)}function bb(){mxActor.call(this)}function Pa(){mxActor.call(this)}function Za(){mxActor.call(this)}function z(){mxActor.call(this)}function L(){mxActor.call(this)}function M(){mxActor.call(this)}function T(){mxActor.call(this)}function ca(){mxActor.call(this)}function ia(){mxActor.call(this)}function ma(){mxEllipse.call(this)}", "label_name": "CWE-20", "label": "20"} -{"code": "\"-\",\"lockUnlock\",\"enterGroup\"],null,ea),O.addSeparator(),this.addSubmenu(\"layout\",O)):ka.isSelectionEmpty()&&ka.isEnabled()?(O.addSeparator(),this.addMenuItems(O,[\"editData\"],null,ea),O.addSeparator(),this.addSubmenu(\"layout\",O),this.addSubmenu(\"insert\",O),this.addMenuItems(O,[\"-\",\"exitGroup\"],null,ea)):ka.isEnabled()&&this.addMenuItems(O,[\"-\",\"lockUnlock\"],null,ea)};var H=Menus.prototype.addPopupMenuEditItems;Menus.prototype.addPopupMenuEditItems=function(O,X,ea){H.apply(this,arguments);this.editorUi.editor.graph.isSelectionEmpty()&&\nthis.addMenuItems(O,[\"copyAsImage\"],null,ea)};EditorUi.prototype.toggleFormatPanel=function(O){null!=this.formatWindow?this.formatWindow.window.setVisible(null!=O?O:!this.formatWindow.window.isVisible()):b(this)};DiagramFormatPanel.prototype.isMathOptionVisible=function(){return!0};var G=EditorUi.prototype.destroy;EditorUi.prototype.destroy=function(){null!=this.sidebarWindow&&(this.sidebarWindow.window.setVisible(!1),this.sidebarWindow.window.destroy(),this.sidebarWindow=null);null!=this.formatWindow&&", "label_name": "CWE-20", "label": "20"} -{"code": " _handleMeta: function(message, local, callback, context) {\n var method = Channel.parse(message.channel)[1],\n response;\n\n if (array.indexOf(this.META_METHODS, method) < 0) {\n response = this._makeResponse(message);\n response.error = Error.channelForbidden(message.channel);\n response.successful = false;\n return callback.call(context, [response]);\n }\n\n this[method](message, local, function(responses) {\n responses = [].concat(responses);\n for (var i = 0, n = responses.length; i < n; i++) this._advize(responses[i], message.connectionType);\n callback.call(context, responses);\n }, this);\n },", "label_name": "CWE-287", "label": "287"} -{"code": "for(var J=0;J\");K.setAttribute(\"disabled\",\"disabled\");G.appendChild(K)}K=document.createElement(\"option\");mxUtils.write(K,mxResources.get(\"addAccount\"));K.value=L.length;G.appendChild(K)}var L=this.drive.getUsersList(),C=document.createElement(\"div\"),D=document.createElement(\"span\");D.style.marginTop=\"6px\";mxUtils.write(D,mxResources.get(\"changeUser\")+\": \");C.appendChild(D);var G=document.createElement(\"select\");G.style.width=\"200px\";z();mxEvent.addListener(G,\"change\",mxUtils.bind(this,", "label_name": "CWE-20", "label": "20"} -{"code": " left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };\n }\n return left;\n },", "label_name": "CWE-74", "label": "74"} -{"code": " function publish_callback(err, response) {\n should.exist(response);\n should(err.message).match(/BadNoSubscription/);\n }", "label_name": "CWE-400", "label": "400"} -{"code": "0c.indexOf(\"DocumentClosedError\")){EditorUi.lastErrorMessage=c;var x=null!=window.DRAWIO_LOG_URL?window.DRAWIO_LOG_URL:\"\";m=null!=m?m:Error(c);(new Image).src=x+\"/log?severity=\"+q+\"&v=\"+encodeURIComponent(EditorUi.VERSION)+\"&msg=clientError:\"+encodeURIComponent(c)+\":url:\"+encodeURIComponent(window.location.href)+\":lnum:\"+encodeURIComponent(g)+(null!=k?\":colno:\"+\nencodeURIComponent(k):\"\")+(null!=m&&null!=m.stack?\"&stack=\"+encodeURIComponent(m.stack):\"\")}}catch(A){}try{v||null==window.console||console.error(q,c,e,g,k,m)}catch(A){}};EditorUi.logEvent=function(c){if(\"1\"==urlParams.dev)EditorUi.debug(\"logEvent\",c);else if(EditorUi.enableLogging)try{var e=null!=window.DRAWIO_LOG_URL?window.DRAWIO_LOG_URL:\"\";(new Image).src=e+\"/images/1x1.png?v=\"+encodeURIComponent(EditorUi.VERSION)+(null!=c?\"&data=\"+encodeURIComponent(JSON.stringify(c)):\"\")}catch(g){}};EditorUi.sendReport=", "label_name": "CWE-20", "label": "20"} -{"code": "\"geTempDlgCreateBtn geTempDlgBtnDisabled\")}function z(ha,da){if(null!=J){var ca=function(pa){qa.isExternal?g(qa,function(na){la(na,pa)},ia):qa.url?mxUtils.get(TEMPLATE_PATH+\"/\"+qa.url,mxUtils.bind(this,function(na){200<=na.getStatus()&&299>=na.getStatus()?la(na.getText(),pa):ia()})):la(b.emptyDiagramXml,pa)},la=function(pa,na){y||b.hideDialog(!0);e(pa,na,qa,da)},ia=function(){A(mxResources.get(\"cannotLoad\"));ma()},ma=function(){J=qa;za.className=\"geTempDlgCreateBtn\";da&&(Ga.className=\"geTempDlgOpenBtn\")},", "label_name": "CWE-20", "label": "20"} -{"code": "ba,ja,ia){function ma(La,Ta){null==Ja?(Ga=La,Ga=/^https?:\\/\\//.test(Ga)&&!b.editor.isCorsEnabledForUrl(Ga)?PROXY_URL+\"?url=\"+encodeURIComponent(Ga):TEMPLATE_PATH+\"/\"+Ga,mxUtils.get(Ga,mxUtils.bind(this,function(Ua){200<=Ua.getStatus()&&299>=Ua.getStatus()&&(Ja=Ua.getText());Ta(Ja,Ga)}))):Ta(Ja,Ga)}function qa(La,Ta,Ua){if(null!=La&&mxUtils.isAncestorNode(document.body,na)){La=mxUtils.parseXml(La);La=Editor.parseDiagramNode(La.documentElement);var Za=new mxCodec(La.ownerDocument),Wa=new mxGraphModel;\nZa.decode(La,Wa);La=Wa.root.getChildAt(0).children;b.sidebar.createTooltip(na,La,Math.min((window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth)-80,1E3),Math.min((window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight)-80,800),null!=ya?mxResources.get(ya,null,ya):null,!0,new mxPoint(Ta,Ua),!0,function(){Ya=null!=b.sidebar.tooltip&&\"none\"!=b.sidebar.tooltip.style.display;y(na,null,null,pa,fa,ia)},!0,!1)}}function oa(La,Ta){null==pa||Ra||", "label_name": "CWE-20", "label": "20"} -{"code": "DriveFile&&c.isEditable()||c.constructor==DropboxFile)};EditorUi.prototype.getServiceName=function(){return\"draw.io\"};EditorUi.prototype.addRemoteServiceSecurityCheck=function(c){c.setRequestHeader(\"Content-Language\",\"da, mi, en, de-DE\")};EditorUi.prototype.loadUrl=function(c,e,g,k,m,q,v,x){EditorUi.logEvent(\"SHOULD NOT BE CALLED: loadUrl\");return this.editor.loadUrl(c,e,g,k,m,q,v,x)};EditorUi.prototype.loadFonts=function(c){EditorUi.logEvent(\"SHOULD NOT BE CALLED: loadFonts\");return this.editor.loadFonts(c)};", "label_name": "CWE-20", "label": "20"} -{"code": "Sa.dy?Sa.dy:0);Ga.insert(Ha)}ta.push(Ga);mxUtils.remove(qa.invert?ia:Ja,za)}}}});pa(xa,xa,ka);if(null!=v[xa.id])for(Ka=0;KamxUtils.indexOf(q,ia)};this.executeLayout(function(){ra.execute(A.getDefaultParent());", "label_name": "CWE-20", "label": "20"} -{"code": "R,Y,da),this.lastX=Y,this.lastY=da)};p.prototype.curveTo=function(O,R,Y,da,ha,Z){this.passThrough?this.originalCurveTo.apply(this.canvas,arguments):(this.addOp(this.curveOp,O,R,Y,da,ha,Z),this.lastX=ha,this.lastY=Z)};p.prototype.arcTo=function(O,R,Y,da,ha,Z,ea){if(this.passThrough)this.originalArcTo.apply(this.canvas,arguments);else{var aa=mxUtils.arcToCurves(this.lastX,this.lastY,O,R,Y,da,ha,Z,ea);if(null!=aa)for(var ua=0;uamxUtils.indexOf(d,m)&&null!=urlParams[m]&&(f+=g+m+\"=\"+urlParams[m],g=\"&\")}else f=window.location.search;return f};EditorUi.prototype.getUrl=function(d){d=null!=d?d:window.location.pathname;var f=0mxUtils.indexOf(g,m)&&(d=0==f?d+\"?\":d+\"&\",null!=urlParams[m]&&(d+=m+\"=\"+urlParams[m],f++))}return d};EditorUi.prototype.showLinkDialog=function(d,f,g,m,q){d=new LinkDialog(this,d,f,g,!0,m,q);this.showDialog(d.container,560,130,!0,!0);d.init()};EditorUi.prototype.getServiceCount=function(d){var f=1;null==this.drive&&\"function\"!==typeof window.DriveClient||f++;null==this.dropbox&&\"function\"!==typeof window.DropboxClient||f++;null==this.oneDrive&&\"function\"!==typeof window.OneDriveClient||", "label_name": "CWE-20", "label": "20"} -{"code": "k.scrollHeight-k.offsetHeight&&D()},mxEvent.addListener(k,\"scroll\",B))}}),y)});p.okButton.setAttribute(\"disabled\",\"disabled\");this.ui.spinner.spin(k,mxResources.get(\"loading\"));var t=mxUtils.bind(this,function(z){var L=this.ui.spinner,C=0;this.ui.spinner.stop();var D=function(){L.spin(k,mxResources.get(\"loading\"));C+=1},G=function(){--C;0===C&&L.stop()};null==z&&(k.innerHTML=\"\",z=1);null!=B&&(mxEvent.removeListener(k,\"scroll\",B),B=null);null!=A&&null!=A.parentNode&&A.parentNode.removeChild(A);A=document.createElement(\"a\");", "label_name": "CWE-20", "label": "20"} -{"code": "n)for(v=0;v'+Graph.compress('')+\"\",qa(Ta,mxEvent.getClientX(Ma),mxEvent.getClientY(Ma))):(b.sidebar.currentElt=\nna,Ra=!0,ma(oa,function(Ua){Ra&&b.sidebar.currentElt==na&&qa(Ua,mxEvent.getClientX(Ma),mxEvent.getClientY(Ma));Ra=!1})))}var na=document.createElement(\"div\");na.className=\"geTemplate\";na.style.position=\"relative\";na.style.height=Ha+\"px\";na.style.width=ra+\"px\";var Ka=null,Ia=oa;Editor.isDarkMode()&&(na.style.filter=\"invert(100%)\");null!=ya?na.setAttribute(\"title\",mxResources.get(ya,null,ya)):null!=wa&&0 0 && !this.peek('}', ')', ';', ']'))\n body.push(this.expressionStatement());\n if (!this.expect(';')) {\n return { type: AST.Program, body: body};\n }\n }\n },", "label_name": "CWE-74", "label": "74"} -{"code": " text: src.slice(2, cap[0].length - 2)\n };\n }\n }\n }\n };", "label_name": "CWE-400", "label": "400"} -{"code": "function(J){k=J};this.setAutoScroll=function(J){m=J};this.setOpenFill=function(J){q=J};this.setStopClickEnabled=function(J){A=J};this.setSelectInserted=function(J){z=J};this.setSmoothing=function(J){l=J};this.setPerfectFreehandMode=function(J){M=J};this.setBrushSize=function(J){L.size=J};this.getBrushSize=function(){return L.size};var n=function(J){x=J;b.getRubberband().setEnabled(!J);b.graphHandler.setSelectEnabled(!J);b.graphHandler.setMoveEnabled(!J);b.container.style.cursor=J?\"crosshair\":\"\";b.fireEvent(new mxEventObject(\"freehandStateChanged\"))};", "label_name": "CWE-20", "label": "20"} -{"code": "setTimeout(function(){Ia.style.display=\"none\"},4E3)}function z(){null!=X&&(X.style.fontWeight=\"normal\",X.style.textDecoration=\"none\",p=X,X=null)}function L(fa,ca,ba,ja,ia,ma,qa){if(-1
');null==m&&(m=function(){var N=null;try{N=JSON.parse(localStorage.getItem(\"mxODPickerRecentList\"))}catch(Q){}return N});null==n&&(n=function(N){if(null!=N){var Q=m()||{};delete N[\"@microsoft.graph.downloadUrl\"];\nQ[N.id]=N;localStorage.setItem(\"mxODPickerRecentList\",JSON.stringify(Q))}});D='
OneDrive
'+mxUtils.htmlEntities(mxResources.get(\"files\"))+'
'+mxUtils.htmlEntities(mxResources.get(\"recent\"))+'
'+mxUtils.htmlEntities(mxResources.get(\"shared\"))+'
'+", "label_name": "CWE-20", "label": "20"} -{"code": "function moveModuleOnly (from, to, log, done) {\n var fromModules = path.join(from, 'node_modules')\n var tempFromModules = from + '.node_modules'\n var toModules = path.join(to, 'node_modules')\n var tempToModules = to + '.node_modules'\n\n log.silly('move', 'move existing destination node_modules away', toModules)\n\n move(toModules, tempToModules).then(removeDestination(done), removeDestination(done))\n\n function removeDestination (next) {\n return function (er) {\n log.silly('move', 'remove existing destination', to)\n if (er) {\n rimraf(to, iferr(next, makeDestination(next)))\n } else {\n rimraf(to, iferr(next, makeDestination(iferr(next, moveToModulesBack(next)))))\n }\n }\n }\n\n function moveToModulesBack (next) {\n return function () {\n log.silly('move', 'move existing destination node_modules back', toModules)\n move(tempToModules, toModules).then(next, done)\n }\n }\n\n function makeDestination (next) {\n return function () {\n log.silly('move', 'make sure destination parent exists', path.resolve(to, '..'))\n correctMkdir(path.resolve(to, '..'), iferr(done, moveNodeModules(next)))\n }\n }\n\n function moveNodeModules (next) {\n return function () {\n log.silly('move', 'move source node_modules away', fromModules)\n move(fromModules, tempFromModules).then(doMove(moveNodeModulesBack(next)), doMove(next))\n }\n }\n\n function doMove (next) {\n return function () {\n log.silly('move', 'move module dir to final dest', from, to)\n move(from, to).then(next, done)\n }\n }\n\n function moveNodeModulesBack (next) {\n return function () {\n correctMkdir(from, iferr(done, function () {\n log.silly('move', 'put source node_modules back', fromModules)\n move(tempFromModules, fromModules).then(next, done)\n }))\n }\n }\n}", "label_name": "CWE-732", "label": "732"} -{"code": "null);mxEvent.consume(ca)})))}if(null!=L)for(M=0;M'),Xa.writeln(Editor.mathJaxWebkitCss),Xa.writeln(\"\");mxClient.IS_GC&&(Xa.writeln('\"));null!=p.editor.fontCss&&(Xa.writeln('\"));for(var db=Ha.getCustomFonts(),cb=0;cb'):(Xa.writeln('\"))}};if(\"undefined\"!==typeof MathJax){var jb=Na.renderPage;Na.renderPage=function(Xa,db,cb,fb,eb,lb){var kb=mxClient.NO_FO;mxClient.NO_FO=this.graph.mathEnabled&&!p.editor.useForeignObjectForMath?!0:p.editor.originalNoForeignObject;var gb=jb.apply(this,arguments);mxClient.NO_FO=kb;this.graph.mathEnabled?this.mathEnabled=this.mathEnabled||!0:gb.className=\"geDisableMathJax\";return gb}}Wa=null;bb=P.shapeForegroundColor;$a=P.shapeBackgroundColor;Va=P.enableFlowAnimation;", "label_name": "CWE-20", "label": "20"} -{"code": "null!=this.linkHint&&(this.linkHint.style.visibility=\"\")};var Za=mxEdgeHandler.prototype.destroy;mxEdgeHandler.prototype.destroy=function(){Za.apply(this,arguments);null!=this.linkHint&&(this.linkHint.parentNode.removeChild(this.linkHint),this.linkHint=null);null!=this.changeHandler&&(this.graph.getModel().removeListener(this.changeHandler),this.graph.getSelectionModel().removeListener(this.changeHandler),this.changeHandler=null)}}();(function(){function b(c,l,x){mxShape.call(this);this.line=c;this.stroke=l;this.strokewidth=null!=x?x:1;this.updateBoundsFromLine()}function e(){mxSwimlane.call(this)}function k(){mxSwimlane.call(this)}function n(){mxCylinder.call(this)}function D(){mxCylinder.call(this)}function t(){mxActor.call(this)}function F(){mxCylinder.call(this)}function d(){mxCylinder.call(this)}function f(){mxCylinder.call(this)}function g(){mxCylinder.call(this)}function m(){mxShape.call(this)}function q(){mxShape.call(this)}", "label_name": "CWE-20", "label": "20"} -{"code": "function(y){this.spinner.stop();this.handleError(y)})})))}}),mxUtils.bind(this,function(){this.hideDialog()}),mxResources.get(\"saveAs\"),mxResources.get(\"download\"),!1,!1,v,null,1=k.scrollHeight-k.offsetHeight&&C()},mxEvent.addListener(k,\"scroll\",B))}),y)});t()};GitHubClient.prototype.logout=function(){this.clearPersistentToken();this.setUser(null);b=null}})();TrelloFile=function(b,e,f){DrawioFile.call(this,b,e);this.meta=f;this.saveNeededCounter=0};mxUtils.extend(TrelloFile,DrawioFile);TrelloFile.prototype.getHash=function(){return\"T\"+encodeURIComponent(this.meta.compoundId)};TrelloFile.prototype.getMode=function(){return App.MODE_TRELLO};TrelloFile.prototype.isAutosave=function(){return!0};TrelloFile.prototype.getTitle=function(){return this.meta.name};TrelloFile.prototype.isRenamable=function(){return!1};TrelloFile.prototype.getSize=function(){return this.meta.bytes};", "label_name": "CWE-20", "label": "20"} -{"code": "E.appendChild(R);Q.appendChild(E);this.container=Q};var W=ChangePageSetup.prototype.execute;ChangePageSetup.prototype.execute=function(){null==this.page&&(this.page=this.ui.currentPage);if(this.page!=this.ui.currentPage){if(null!=this.page.viewState){this.ignoreColor||(this.page.viewState.background=this.color);if(!this.ignoreImage){var u=this.image;null!=u&&null!=u.src&&Graph.isPageLink(u.src)&&(u={originalSrc:u.src});this.page.viewState.backgroundImage=u}null!=this.format&&(this.page.viewState.pageFormat=\nthis.format);null!=this.mathEnabled&&(this.page.viewState.mathEnabled=this.mathEnabled);null!=this.shadowVisible&&(this.page.viewState.shadowVisible=this.shadowVisible)}}else W.apply(this,arguments),null!=this.mathEnabled&&this.mathEnabled!=this.ui.isMathEnabled()&&(this.ui.setMathEnabled(this.mathEnabled),this.mathEnabled=!this.mathEnabled),null!=this.shadowVisible&&this.shadowVisible!=this.ui.editor.graph.shadowVisible&&(this.ui.editor.graph.setShadowVisible(this.shadowVisible),this.shadowVisible=\n!this.shadowVisible)};Editor.prototype.useCanvasForExport=!1;try{var U=document.createElement(\"canvas\"),X=new Image;X.onload=function(){try{U.getContext(\"2d\").drawImage(X,0,0);var u=U.toDataURL(\"image/png\");Editor.prototype.useCanvasForExport=null!=u&&6
')))}catch(u){}})();", "label_name": "CWE-20", "label": "20"} -{"code": "mxResources.get(\"diagramIsNotPublic\"),mxResources.get(\"share\"),mxUtils.bind(this,function(){b.drive.showPermissions(m.getId())}),null,mxResources.get(\"ok\"),mxUtils.bind(this,function(){})):b.handleError({message:mxResources.get(\"diagramIsNotPublic\")})})}),p.className=\"geBtn\",c.appendChild(p));p=mxUtils.button(mxResources.get(\"export\"),function(){var D=b.createLibraryDataFromImages(l),G=q.value;/(\\.xml)$/i.test(G)||(G+=\".xml\");b.isLocalFileSave()?b.saveLocalFile(D,G,\"text/xml\",null,null,!0,null,\"xml\"):", "label_name": "CWE-20", "label": "20"} -{"code": "(q.parentNode.removeChild(q),q=null)});null!=X&&null!=W&&(/(\\.v(dx|sdx?))($|\\?)/i.test(W)||/(\\.vs(x|sx?))($|\\?)/i.test(W))?this.importVisio(X,function(J){E(J,\"text/xml\")},null,W):(new XMLHttpRequest).upload&&this.isRemoteFileFormat(K,W)&&null!=X?this.isExternalDataComms()?this.parseFile(X,mxUtils.bind(this,function(J){4==J.readyState&&(this.spinner.stop(),200<=J.status&&299>=J.status?E(J.responseText,\"text/xml\"):this.handleError({message:mxResources.get(413==J.status?\"drawingTooLarge\":\"invalidOrMissingFile\")},\nmxResources.get(\"errorLoadingFile\")))})):(this.spinner.stop(),this.showError(mxResources.get(\"error\"),mxResources.get(\"notInOffline\"))):E(K,F)}}));P.stopPropagation();P.preventDefault()})),mxEvent.addListener(y,\"dragleave\",function(P){y.style.cursor=\"\";y.style.backgroundColor=\"\";P.stopPropagation();P.preventDefault()}));I=I.cloneNode(!1);I.setAttribute(\"src\",Editor.editImage);I.setAttribute(\"title\",mxResources.get(\"edit\"));B.insertBefore(I,B.firstChild);mxEvent.addListener(I,\"click\",L);mxEvent.addListener(y,", "label_name": "CWE-20", "label": "20"} -{"code": " function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {\n var unwatch, lastValue;\n unwatch = scope.$watch(function oneTimeWatch(scope) {\n return parsedExpression(scope);\n }, function oneTimeListener(value, old, scope) {\n lastValue = value;\n if (isFunction(listener)) {\n listener(value, old, scope);\n }\n if (isAllDefined(value)) {\n scope.$$postDigest(function() {\n if (isAllDefined(lastValue)) unwatch();\n });\n }\n }, objectEquality);\n\n return unwatch;\n\n function isAllDefined(value) {\n var allDefined = true;\n forEach(value, function(val) {\n if (!isDefined(val)) allDefined = false;\n });\n return allDefined;\n }\n }", "label_name": "CWE-74", "label": "74"} -{"code": "return this.editor.exportToCanvas(c,e,g,k,m,q,v,x,A,z,L,M,n,y,K,B)};EditorUi.prototype.createImageUrlConverter=function(){EditorUi.logEvent(\"SHOULD NOT BE CALLED: createImageUrlConverter\");return this.editor.createImageUrlConverter()};EditorUi.prototype.convertImages=function(c,e,g,k){EditorUi.logEvent(\"SHOULD NOT BE CALLED: convertImages\");return this.editor.convertImages(c,e,g,k)};EditorUi.prototype.convertImageToDataUri=function(c,e){EditorUi.logEvent(\"SHOULD NOT BE CALLED: convertImageToDataUri\");", "label_name": "CWE-20", "label": "20"} -{"code": "k.isRemoteFileFormat(z,c.name)?k.isOffline()?k.showError(mxResources.get(\"error\"),mxResources.get(\"notInOffline\"),null,g):k.parseFileData(z,mxUtils.bind(this,function(L){4==L.readyState&&(200<=L.status&&299>=L.status?e(L.responseText):g())}),c.name):g()}):A||g()}},function(q){g(q)}):g()});\"undefined\"!==typeof JSZip||this.loadingExtensions||this.isOffline(!0)?m():(this.loadingExtensions=!0,mxscript(\"js/extensions.min.js\",m))};EditorUi.prototype.importFile=function(c,e,g,k,m,q,v,x,A,z,L,M){z=null!=\nz?z:!0;var n=!1,y=null,K=mxUtils.bind(this,function(B){var F=null;null!=B&&\"
')))}catch(u){}})();", "label_name": "CWE-20", "label": "20"} -{"code": "mxDualRuler.prototype.setUnit=function(b){this.vRuler.setUnit(b);this.hRuler.setUnit(b)};mxDualRuler.prototype.setStyle=function(b){this.vRuler.setStyle(b);this.hRuler.setStyle(b)};mxDualRuler.prototype.destroy=function(){this.vRuler.destroy();this.hRuler.destroy();this.ui.refresh=this.editorUiRefresh;mxGuide.prototype.move=this.origGuideMove;mxGuide.prototype.destroy=this.origGuideDestroy;this.ui.getDiagramContainerOffset=this.editorUiGetDiagContOffset};function mxFreehand(b){var f=null!=b.view&&null!=b.view.canvas?b.view.canvas.ownerSVGElement:null;if(null!=b.container&&null!=f){b.addListener(mxEvent.ESCAPE,mxUtils.bind(this,function(){this.stopDrawing()}));var l=mxFreehand.prototype.NORMAL_SMOOTHING,d=null,u=[],t,D=[],c,e=!1,g=!0,k=!0,m=!0,q=!0,v=[],x=!1,A=!0,z=!1,L={size:12,thinning:.5,smoothing:.5,streamline:.5,start:{taper:0,cap:!0},end:{taper:0,cap:!0}},M=!1;this.setClosedPath=function(J){e=J};this.setAutoClose=function(J){g=J};this.setAutoInsert=", "label_name": "CWE-20", "label": "20"} -{"code": " this.setIdentifierFns = function(identifierStart, identifierContinue) {\n identStart = identifierStart;\n identContinue = identifierContinue;\n return this;\n };", "label_name": "CWE-74", "label": "74"} -{"code": "null!=this.linkHint&&(this.linkHint.style.visibility=\"\")};var Za=mxEdgeHandler.prototype.destroy;mxEdgeHandler.prototype.destroy=function(){Za.apply(this,arguments);null!=this.linkHint&&(this.linkHint.parentNode.removeChild(this.linkHint),this.linkHint=null);null!=this.changeHandler&&(this.graph.getModel().removeListener(this.changeHandler),this.graph.getSelectionModel().removeListener(this.changeHandler),this.changeHandler=null)}}();(function(){function b(c,l,x){mxShape.call(this);this.line=c;this.stroke=l;this.strokewidth=null!=x?x:1;this.updateBoundsFromLine()}function e(){mxSwimlane.call(this)}function k(){mxSwimlane.call(this)}function n(){mxCylinder.call(this)}function D(){mxCylinder.call(this)}function t(){mxActor.call(this)}function F(){mxCylinder.call(this)}function d(){mxCylinder.call(this)}function f(){mxCylinder.call(this)}function g(){mxCylinder.call(this)}function m(){mxShape.call(this)}function q(){mxShape.call(this)}", "label_name": "CWE-20", "label": "20"} -{"code": "Wa,Xa,K,Ga,Ja,Ia,Ha);c.stroke()};Ea.prototype.moveNW=function(c,l,x,p,v,A,B,ha,K){\"square\"==B||\"default\"==B&&\"square\"==A||!K?c.moveTo(0,0):c.moveTo(0,ha)};Ea.prototype.moveNE=function(c,l,x,p,v,A,B,ha,K){\"square\"==B||\"default\"==B&&\"square\"==A||!K?c.moveTo(p,0):c.moveTo(p-ha,0)};Ea.prototype.moveSE=function(c,l,x,p,v,A,B,ha,K){\"square\"==B||\"default\"==B&&\"square\"==A||!K?c.moveTo(p,v):c.moveTo(p,v-ha)};Ea.prototype.moveSW=function(c,l,x,p,v,A,B,ha,K){\"square\"==B||\"default\"==B&&\"square\"==A||!K?c.moveTo(0,\nv):c.moveTo(ha,v)};Ea.prototype.paintNW=function(c,l,x,p,v,A,B,ha,K){if(K)if(\"rounded\"==B||\"default\"==B&&\"rounded\"==A||\"invRound\"==B||\"default\"==B&&\"invRound\"==A){l=0;if(\"rounded\"==B||\"default\"==B&&\"rounded\"==A)l=1;c.arcTo(ha,ha,0,0,l,ha,0)}else(\"snip\"==B||\"default\"==B&&\"snip\"==A||\"fold\"==B||\"default\"==B&&\"fold\"==A)&&c.lineTo(ha,0);else c.lineTo(0,0)};Ea.prototype.paintTop=function(c,l,x,p,v,A,B,ha,K){\"square\"==B||\"default\"==B&&\"square\"==A||!K?c.lineTo(p,0):c.lineTo(p-ha,0)};Ea.prototype.paintNE=", "label_name": "CWE-20", "label": "20"} -{"code": " function m(file) {\n const p = path.join(certificateFolder, file);\n if (!fs.existsSync(p)) {\n console.error(\" cannot find \", p);\n }\n return p;\n }", "label_name": "CWE-400", "label": "400"} -{"code": "m=P.name;v=\"\";O(null,!0)})));k.appendChild(F)})(D[G],G)}100==D.length&&(k.appendChild(A),B=function(){k.scrollTop>=k.scrollHeight-k.offsetHeight&&C()},mxEvent.addListener(k,\"scroll\",B))}),y)});t()};GitHubClient.prototype.logout=function(){this.clearPersistentToken();this.setUser(null);b=null}})();TrelloFile=function(b,e,f){DrawioFile.call(this,b,e);this.meta=f;this.saveNeededCounter=0};mxUtils.extend(TrelloFile,DrawioFile);TrelloFile.prototype.getHash=function(){return\"T\"+encodeURIComponent(this.meta.compoundId)};TrelloFile.prototype.getMode=function(){return App.MODE_TRELLO};TrelloFile.prototype.isAutosave=function(){return!0};TrelloFile.prototype.getTitle=function(){return this.meta.name};TrelloFile.prototype.isRenamable=function(){return!1};TrelloFile.prototype.getSize=function(){return this.meta.bytes};", "label_name": "CWE-20", "label": "20"} -{"code": "null!=this.linkHint&&(this.linkHint.style.visibility=\"\")};var Za=mxEdgeHandler.prototype.destroy;mxEdgeHandler.prototype.destroy=function(){Za.apply(this,arguments);null!=this.linkHint&&(this.linkHint.parentNode.removeChild(this.linkHint),this.linkHint=null);null!=this.changeHandler&&(this.graph.getModel().removeListener(this.changeHandler),this.graph.getSelectionModel().removeListener(this.changeHandler),this.changeHandler=null)}}();(function(){function b(c,l,x){mxShape.call(this);this.line=c;this.stroke=l;this.strokewidth=null!=x?x:1;this.updateBoundsFromLine()}function e(){mxSwimlane.call(this)}function k(){mxSwimlane.call(this)}function n(){mxCylinder.call(this)}function D(){mxCylinder.call(this)}function t(){mxActor.call(this)}function F(){mxCylinder.call(this)}function d(){mxCylinder.call(this)}function f(){mxCylinder.call(this)}function g(){mxCylinder.call(this)}function m(){mxShape.call(this)}function q(){mxShape.call(this)}", "label_name": "CWE-20", "label": "20"} -{"code": "urlParams.sketch&&1E3<=n||null!=urlParams.clibs||null!=urlParams.libs||null!=urlParams[\"search-shapes\"])k(this,!0),null!=this.sidebar&&null!=urlParams[\"search-shapes\"]&&null!=this.sidebar.searchShapes&&(this.sidebar.searchShapes(urlParams[\"search-shapes\"]),this.sidebar.showEntries(\"search\"));var U=this;mxWindow.prototype.fit=function(){if(Editor.inlineFullscreen||null==U.embedViewport)mxUtils.fit(this.div);else{var za=parseInt(this.div.offsetLeft),wa=parseInt(this.div.offsetWidth),Ea=U.embedViewport.x+\nU.embedViewport.width,Da=parseInt(this.div.offsetTop),La=parseInt(this.div.offsetHeight),Ya=U.embedViewport.y+U.embedViewport.height;this.div.style.left=Math.max(U.embedViewport.x,Math.min(za,Ea-wa))+\"px\";this.div.style.top=Math.max(U.embedViewport.y,Math.min(Da,Ya-La))+\"px\";this.div.style.height=Math.min(U.embedViewport.height,parseInt(this.div.style.height))+\"px\";this.div.style.width=Math.min(U.embedViewport.width,parseInt(this.div.style.width))+\"px\"}};this.keyHandler.bindAction(75,!0,\"toggleShapes\",", "label_name": "CWE-20", "label": "20"} -{"code": " compile: function(expression) {\n var self = this;\n var ast = this.astBuilder.ast(expression);\n this.state = {\n nextId: 0,\n filters: {},\n fn: {vars: [], body: [], own: {}},\n assign: {vars: [], body: [], own: {}},\n inputs: []\n };\n findConstantAndWatchExpressions(ast, self.$filter);\n var extra = '';\n var assignable;\n this.stage = 'assign';\n if ((assignable = assignableAST(ast))) {\n this.state.computing = 'assign';\n var result = this.nextId();\n this.recurse(assignable, result);\n this.return_(result);\n extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');\n }\n var toWatch = getInputs(ast.body);\n self.stage = 'inputs';\n forEach(toWatch, function(watch, key) {\n var fnKey = 'fn' + key;\n self.state[fnKey] = {vars: [], body: [], own: {}};\n self.state.computing = fnKey;\n var intoId = self.nextId();\n self.recurse(watch, intoId);\n self.return_(intoId);\n self.state.inputs.push(fnKey);\n watch.watchId = key;\n });\n this.state.computing = 'fn';\n this.stage = 'main';\n this.recurse(ast);\n var fnString =\n // The build and minification steps remove the string \"use strict\" from the code, but this is done using a regex.\n // This is a workaround for this until we do a better job at only removing the prefix only when we should.\n '\"' + this.USE + ' ' + this.STRICT + '\";\\n' +\n this.filterPrefix() +\n 'var fn=' + this.generateFunction('fn', 's,l,a,i') +\n extra +\n this.watchFns() +\n 'return fn;';\n\n // eslint-disable-next-line no-new-func\n var fn = (new Function('$filter',\n 'getStringValue',\n 'ifDefined',\n 'plus',\n fnString))(\n this.$filter,\n getStringValue,\n ifDefined,\n plusFn);\n this.state = this.stage = undefined;\n fn.ast = ast;\nfn.literal = isLiteral(ast);\n fn.constant = isConstant(ast);\n return fn;\n },", "label_name": "CWE-74", "label": "74"} -{"code": " text: src.slice(1, cap[0].length - 1)\n };\n }\n }\n }\n };", "label_name": "CWE-400", "label": "400"} -{"code": "EditorUi.prototype.createSvgDataUri=function(c){EditorUi.logEvent(\"SHOULD NOT BE CALLED: createSvgDataUri\");return Editor.createSvgDataUri(c)};EditorUi.prototype.embedCssFonts=function(c,e){EditorUi.logEvent(\"SHOULD NOT BE CALLED: embedCssFonts\");return this.editor.embedCssFonts(c,e)};EditorUi.prototype.embedExtFonts=function(c){EditorUi.logEvent(\"SHOULD NOT BE CALLED: embedExtFonts\");return this.editor.embedExtFonts(c)};EditorUi.prototype.exportToCanvas=function(c,e,g,k,m,q,v,x,A,z,L,M,n,y,K,B){EditorUi.logEvent(\"SHOULD NOT BE CALLED: exportToCanvas\");\nreturn this.editor.exportToCanvas(c,e,g,k,m,q,v,x,A,z,L,M,n,y,K,B)};EditorUi.prototype.createImageUrlConverter=function(){EditorUi.logEvent(\"SHOULD NOT BE CALLED: createImageUrlConverter\");return this.editor.createImageUrlConverter()};EditorUi.prototype.convertImages=function(c,e,g,k){EditorUi.logEvent(\"SHOULD NOT BE CALLED: convertImages\");return this.editor.convertImages(c,e,g,k)};EditorUi.prototype.convertImageToDataUri=function(c,e){EditorUi.logEvent(\"SHOULD NOT BE CALLED: convertImageToDataUri\");", "label_name": "CWE-20", "label": "20"} -{"code": "q):mxscript(\"js/extensions.min.js\",q))};EditorUi.prototype.generatePlantUmlImage=function(c,e,g,k){function m(x,A,z){c1=x>>2;c2=(x&3)<<4|A>>4;c3=(A&15)<<2|z>>6;c4=z&63;r=\"\";r+=q(c1&63);r+=q(c2&63);r+=q(c3&63);return r+=q(c4&63)}function q(x){if(10>x)return String.fromCharCode(48+x);x-=10;if(26>x)return String.fromCharCode(65+x);x-=26;if(26>x)return String.fromCharCode(97+x);x-=26;return 0==x?\"-\":1==x?\"_\":\"?\"}var v=new XMLHttpRequest;v.open(\"GET\",(\"txt\"==e?PLANT_URL+\"/txt/\":\"png\"==e?PLANT_URL+\"/png/\":", "label_name": "CWE-20", "label": "20"} -{"code": "C=new mxAsyncCanvas(this.thumbImageCache);L.images=this.thumbImageCache.images;var D=new mxImageExport;D.drawShape=function(G,P){G.shape instanceof mxShape&&G.shape.checkBounds()&&(P.save(),P.translate(.5,.5),G.shape.paint(P),P.translate(-.5,-.5),P.restore())};D.drawText=function(G,P){};D.drawState(v.getView().getState(v.model.root),C);C.finish(mxUtils.bind(this,function(){try{D.drawState(v.getView().getState(v.model.root),L),v!=this.editor.graph&&null!=v.container.parentNode&&v.container.parentNode.removeChild(v.container)}catch(G){p=", "label_name": "CWE-20", "label": "20"} -{"code": "function(){g.apply(this,arguments);mxSettings.setRecentColors(ColorDialog.recentColors);mxSettings.save()}}window.EditDataDialog&&(EditDataDialog.getDisplayIdForCell=function(u,E){var J=null;null!=u.editor.graph.getModel().getParent(E)?J=E.getId():null!=u.currentPage&&(J=u.currentPage.getId());return J});if(null!=window.StyleFormatPanel){var k=Format.prototype.init;Format.prototype.init=function(){k.apply(this,arguments);this.editorUi.editor.addListener(\"fileLoaded\",this.update)};var l=Format.prototype.refresh;", "label_name": "CWE-20", "label": "20"} -{"code": "function(c){var e=c.msgMarkers,g=this.remoteInvokeCallbacks[e.callbackId];if(null==g)throw Error(\"No callback for \"+(null!=e?e.callbackId:\"null\"));c.error?g.error&&g.error(c.error.errResp):g.callback&&g.callback.apply(this,c.resp);this.remoteInvokeCallbacks[e.callbackId]=null};EditorUi.prototype.remoteInvoke=function(c,e,g,k,m){var q=!0,v=window.setTimeout(mxUtils.bind(this,function(){q=!1;m({code:App.ERROR_TIMEOUT,message:mxResources.get(\"timeout\")})}),this.timeout),x=mxUtils.bind(this,function(){window.clearTimeout(v);", "label_name": "CWE-20", "label": "20"} -{"code": "this.put(\"editCell\",new Menu(mxUtils.bind(this,function(R,fa){var la=this.editorUi.editor.graph,ra=la.getSelectionCell();ka.call(this,R,ra,null,fa);this.addMenuItems(R,[\"editTooltip\"],fa);la.model.isVertex(ra)&&this.addMenuItems(R,[\"editGeometry\"],fa);this.addMenuItems(R,[\"-\",\"edit\"],fa)})));this.addPopupMenuCellEditItems=function(R,fa,la,ra){R.addSeparator();this.addSubmenu(\"editCell\",R,ra,mxResources.get(\"edit\"))};this.put(\"file\",new Menu(mxUtils.bind(this,function(R,fa){var la=O.getCurrentFile();", "label_name": "CWE-20", "label": "20"} -{"code": "document.createElement(\"div\");oa.className=\"geTempDlgNewDiagramCatItemLbl\";oa.innerHTML=qa;ma.appendChild(oa);Da.appendChild(ma);mxEvent.addListener(ma,\"click\",function(){function Ja(){var Ra=Ga.querySelector(\".geTemplateDrawioCatLink\");null!=Ra?Ra.click():setTimeout(Ja,200)}Z=!0;var Ga=Q.querySelector(\".geTemplatesList\");Ga.style.display=\"block\";Aa.style.width=\"\";Oa.style.display=\"\";Oa.value=\"\";da=null;Ja()});ea.style.display=fa.length<=ba?\"none\":\"\"}function G(fa,ca,ba){function ja(Qa,Ya){var La=\nmxResources.get(Qa);null==La&&(La=Qa.substring(0,1).toUpperCase()+Qa.substring(1));Qa=La+\" (\"+Ya.length+\")\";var Ta=La=mxUtils.htmlEntities(La);15';L.setAttribute(\"title\",mxResources.get(\"showResolved\"));", "label_name": "CWE-20", "label": "20"} -{"code": " isExpOperator: function(ch) {\n return (ch === '-' || ch === '+' || this.isNumber(ch));\n },", "label_name": "CWE-74", "label": "74"} -{"code": "m?this.getFileData(!0,null,null,null,g,x):null,A,null==this.pages||0==this.pages.length,L)}catch(B){this.handleError(B)}}),null,this.thumbImageCache,null,mxUtils.bind(this,function(K){this.spinner.stop();this.handleError(K)}),null,g,c||1,e,k,null,null,q,v,z,M,n)}catch(K){this.spinner.stop(),this.handleError(K)}}};EditorUi.prototype.isCorsEnabledForUrl=function(c){return this.editor.isCorsEnabledForUrl(c)};EditorUi.prototype.importXml=function(c,e,g,k,m,q,v){e=null!=e?e:0;g=null!=g?g:0;var x=[];try{var A=", "label_name": "CWE-20", "label": "20"} -{"code": " function: () => {},", "label_name": "CWE-20", "label": "20"} -{"code": " function bootstrapApply(scope, element, compile, injector) {\n scope.$apply(function() {\n element.data('$injector', injector);\n compile(element)(scope);\n });\n }]", "label_name": "CWE-74", "label": "74"} -{"code": "function convertTimezoneToLocal(date, timezone, reverse) {\n reverse = reverse ? -1 : 1;\n var dateTimezoneOffset = date.getTimezoneOffset();\n var timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);\n return addDateMinutes(date, reverse * (timezoneOffset - dateTimezoneOffset));\n}", "label_name": "CWE-74", "label": "74"} -{"code": "for(ja=ma=0;ja
< '+mxResources.get(\"back\")+'
'+", "label_name": "CWE-20", "label": "20"} -{"code": "function editGroup() {\n var elem = $(this).attr(\"id\");\n var tr = $(this).closest(\"tr\");\n var id = tr.attr(\"data-id\");\n var name = tr.find(\"#name_\" + id).val();\n var status = tr.find(\"#status_\" + id).is(\":checked\") ? 1 : 0;\n var desc = tr.find(\"#desc_\" + id).val();\n\n var done = \"edited\";\n var notDone = \"editing\";\n switch (elem) {\n case \"status_\" + id:\n if (status === 0) {\n done = \"disabled\";\n notDone = \"disabling\";\n } else if (status === 1) {\n done = \"enabled\";\n notDone = \"enabling\";\n }\n\n break;\n case \"name_\" + id:\n done = \"edited name of\";\n notDone = \"editing name of\";\n break;\n case \"desc_\" + id:\n done = \"edited description of\";\n notDone = \"editing description of\";\n break;\n default:\n alert(\"bad element or invalid data-id!\");\n return;\n }\n\n utils.disableAll();\n utils.showAlert(\"info\", \"\", \"Editing group...\", name);\n $.ajax({\n url: \"scripts/pi-hole/php/groups.php\",\n method: \"post\",\n dataType: \"json\",\n data: {\n action: \"edit_group\",\n id: id,\n name: name,\n desc: desc,\n status: status,\n token: token\n },\n success: function (response) {\n utils.enableAll();\n if (response.success) {\n utils.showAlert(\"success\", \"fas fa-pencil-alt\", \"Successfully \" + done + \" group\", name);\n } else {\n utils.showAlert(\n \"error\",\n \"\",\n \"Error while \" + notDone + \" group with ID \" + id,\n response.message\n );\n }\n },\n error: function (jqXHR, exception) {\n utils.enableAll();\n utils.showAlert(\n \"error\",\n \"\",\n \"Error while \" + notDone + \" group with ID \" + id,\n jqXHR.responseText\n );\n console.log(exception); // eslint-disable-line no-console\n }\n });\n}", "label_name": "CWE-862", "label": "862"} -{"code": "this.unitListener=function(n,y){g.setUnit(y.getProperty(\"unit\"))};x.addListener(mxEvent.SIZE,f);x.container.addEventListener(\"scroll\",d);x.view.addListener(\"unitChanged\",this.unitListener);b.addListener(\"pageViewChanged\",this.pageListener);b.addListener(\"pageScaleChanged\",this.pageListener);b.addListener(\"pageFormatChanged\",this.pageListener);this.setStyle=function(n){k=n;m.style.background=k.bkgClr;z()};this.origGuideMove=mxGuide.prototype.move;mxGuide.prototype.move=function(n,y,K,B){if(l&&4'+mxUtils.htmlEntities(u)+\"
\"};mxGraphView.prototype.redrawEnumerationState=function(u){var E=\"1\"==mxUtils.getValue(u.style,\"enumerate\",0);E&&null==u.secondLabel?(u.secondLabel=new mxText(\"\",new mxRectangle,mxConstants.ALIGN_LEFT,", "label_name": "CWE-20", "label": "20"} -{"code": "c,!c&&r[a]&&(d.extend(r[a]),q&&!q.date&&console.warn(\"This method of applying plugins is deprecated. See documentation for details.\")))};d.locale(m,{});\"object\"===typeof module&&\"object\"===typeof module.exports?module.exports=d:\"function\"===typeof define&&define.amd?define([],function(){return d}):q.date=d})(this);", "label_name": "CWE-400", "label": "400"} -{"code": "\"geTempDlgCreateBtn geTempDlgBtnDisabled\")}function y(fa,ca){if(null!=I){var ba=function(oa){qa.isExternal?e(qa,function(na){ja(na,oa)},ia):qa.url?mxUtils.get(TEMPLATE_PATH+\"/\"+qa.url,mxUtils.bind(this,function(na){200<=na.getStatus()&&299>=na.getStatus()?ja(na.getText(),oa):ia()})):ja(b.emptyDiagramXml,oa)},ja=function(oa,na){x||b.hideDialog(!0);f(oa,na,qa,ca)},ia=function(){A(mxResources.get(\"cannotLoad\"));ma()},ma=function(){I=qa;Ba.className=\"geTempDlgCreateBtn\";ca&&(Ka.className=\"geTempDlgOpenBtn\")},", "label_name": "CWE-20", "label": "20"} -{"code": "S&&S(M)}}))}catch(L){null!=S&&S(L)}}),N,sa)}catch(Pa){null!=S&&S(Pa)}};Editor.crcTable=[];for(var D=0;256>D;D++)for(var t=D,F=0;8>F;F++)t=1==(t&1)?3988292384^t>>>1:t>>>1,Editor.crcTable[D]=t;Editor.updateCRC=function(u,J,N,W){for(var S=0;S>>8;return u};Editor.crc32=function(u){for(var J=-1,N=0;N>>8^Editor.crcTable[(J^u.charCodeAt(N))&255];return(J^-1)>>>0};Editor.writeGraphModelToPng=function(u,J,N,W,S){function P(sa,Ba){var ta=", "label_name": "CWE-20", "label": "20"} -{"code": "this.spacing=0}function Ca(){mxArrowConnector.call(this);this.spacing=0}function Ra(){mxActor.call(this)}function ab(){mxRectangleShape.call(this)}function Ka(){mxActor.call(this)}function bb(){mxActor.call(this)}function Pa(){mxActor.call(this)}function Za(){mxActor.call(this)}function z(){mxActor.call(this)}function L(){mxActor.call(this)}function M(){mxActor.call(this)}function T(){mxActor.call(this)}function ca(){mxActor.call(this)}function ia(){mxActor.call(this)}function ma(){mxEllipse.call(this)}", "label_name": "CWE-20", "label": "20"} -{"code": "Graph.fileSupport&&(D.addEventListener(\"dragover\",function(v){v.stopPropagation();v.preventDefault()},!1),D.addEventListener(\"drop\",function(v){v.stopPropagation();v.preventDefault();if(0\")}var B=this.editor.graph.getGraphBounds(),I=this.getSelectedPageIndex();if(this.isExportToCanvas())this.editor.exportToCanvas(mxUtils.bind(this,function(z){var L=l?this.getFileData(!0):null;z=", "label_name": "CWE-20", "label": "20"} -{"code": "function(){function N(){d(K,X,function(){k(X);K.editComment(K.content,function(){p(X)},function(Q){l(X);N();b.handleError(Q,null,null,null,mxUtils.htmlEntities(mxResources.get(\"objectNotFound\")))})})}N()},K.isResolved),M(mxResources.get(\"delete\"),function(){b.confirm(mxResources.get(\"areYouSure\"),function(){k(X);K.deleteComment(function(N){if(!0===N){N=X.querySelector(\".geCommentTxt\");N.innerHTML=\"\";mxUtils.write(N,mxResources.get(\"msgDeleted\"));var Q=X.querySelectorAll(\".geCommentAction\");for(N=", "label_name": "CWE-20", "label": "20"} -{"code": "function(t){k.editorUiRefresh.apply(b,arguments);m()};m();var q=document.createElement(\"canvas\");q.width=p.offsetWidth;q.height=p.offsetHeight;p.style.overflow=\"hidden\";q.style.position=\"relative\";p.appendChild(q);var x=q.getContext(\"2d\");this.ui=b;var y=b.editor.graph;this.graph=y;this.container=p;this.canvas=q;var A=function(t,z,L,C,D){t=Math.round(t);z=Math.round(z);L=Math.round(L);C=Math.round(C);x.beginPath();x.moveTo(t+.5,z+.5);x.lineTo(L+.5,C+.5);x.stroke();D&&(f?(x.save(),x.translate(t,z),", "label_name": "CWE-20", "label": "20"} -{"code": "function(){};var C=k.getSelectionModel().changeSelection;k.getSelectionModel().changeSelection=function(){C.call(this,[v],[v])}};e.onerror=function(){e.onload=null;e.src=Editor.errorImage};e.setAttribute(\"src\",f);e.style.maxWidth=\"300px\";e.style.maxHeight=\"300px\";c.appendChild(e);D.appendChild(c);var g=document.createElement(\"div\");g.style.width=\"300px\";g.style.height=\"300px\";g.style.overflow=\"hidden\";g.style.backgroundColor=\"#fff9\";D.appendChild(g);var k=null,m=new mxGeometry(100,100,100,100),q=", "label_name": "CWE-20", "label": "20"} -{"code": "function setUser (cb) {\n var defaultConf = this.root\n assert(defaultConf !== Object.prototype)\n\n // If global, leave it as-is.\n // If not global, then set the user to the owner of the prefix folder.\n // Just set the default, so it can be overridden.\n if (this.get('global')) return cb()\n if (process.env.SUDO_UID) {\n defaultConf.user = +(process.env.SUDO_UID)\n return cb()\n }\n\n var prefix = path.resolve(this.get('prefix'))\n correctMkdir(prefix, function (er) {\n if (er) return cb(er)\n fs.stat(prefix, function (er, st) {\n defaultConf.user = st && st.uid\n return cb(er)\n })\n })\n}", "label_name": "CWE-732", "label": "732"} -{"code": " scope.findPirate = function (pirate) {\n return Array.prototype.slice.call(arguments);\n };", "label_name": "CWE-74", "label": "74"} -{"code": "this.toolbar.staticElements.push(c);c.style.right=\"atlas\"==uiTheme||\"1\"==urlParams.atlas?\"42px\":\"52px\"}};EditorUi.prototype.showImportCsvDialog=function(){null==this.importCsvDialog&&(this.importCsvDialog=new TextareaDialog(this,mxResources.get(\"csv\")+\":\",Editor.defaultCsvValue,mxUtils.bind(this,function(c){this.importCsv(c)}),null,null,620,430,null,!0,!0,mxResources.get(\"import\"),this.isOffline()?null:\"https://drawio-app.com/import-from-csv-to-drawio/\"));this.showDialog(this.importCsvDialog.container,\n640,520,!0,!0,null,null,null,null,!0);this.importCsvDialog.init()};EditorUi.prototype.executeLayoutList=function(c,e){for(var g=this.editor.graph,k=g.getSelectionCells(),m=0;m=Ga.getStatus()&&(qa=Ga.getText());Ja(qa)}))):Ja(qa)}function ma(na,Ja,Ga){if(null!=na&&mxUtils.isAncestorNode(document.body,ca)&&(na=mxUtils.parseXml(na),na=Editor.extractGraphModel(na.documentElement,!0),null!=na)){\"mxfile\"==\nna.nodeName&&(na=Editor.parseDiagramNode(na.getElementsByTagName(\"diagram\")[0]));var Ra=new mxCodec(na.ownerDocument),Sa=new mxGraphModel;Ra.decode(na,Sa);na=Sa.root.getChildAt(0).children||[];b.sidebar.createTooltip(ca,na,Math.min((window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth)-80,1E3),Math.min((window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight)-80,800),null!=fa.title?mxResources.get(fa.title,null,fa.title):null,!0,new mxPoint(Ja,\nGa),!0,null,!0);var Ha=document.createElement(\"div\");Ha.className=\"geTempDlgDialogMask\";Q.appendChild(Ha);var Na=b.sidebar.hideTooltip;b.sidebar.hideTooltip=function(){Ha&&(Q.removeChild(Ha),Ha=null,Na.apply(this,arguments),b.sidebar.hideTooltip=Na)};mxEvent.addListener(Ha,\"click\",function(){b.sidebar.hideTooltip()})}}var qa=null;if(Ca||b.sidebar.currentElt==ca)b.sidebar.hideTooltip();else{var oa=function(na){Ca&&b.sidebar.currentElt==ca&&ma(na,mxEvent.getClientX(ja),mxEvent.getClientY(ja));Ca=!1;", "label_name": "CWE-20", "label": "20"} -{"code": "2;ua.y+=ua.height/2-ua.width/2;var Ea=ua.width;ua.width=ua.height;ua.height=Ea;M.setGeometry(ia,ua)}var Da=this.view.getState(ia);if(null!=Da){var La=[mxConstants.DIRECTION_EAST,mxConstants.DIRECTION_SOUTH,mxConstants.DIRECTION_WEST,mxConstants.DIRECTION_NORTH],Ya=mxUtils.getValue(Da.style,mxConstants.STYLE_DIRECTION,mxConstants.DIRECTION_EAST);this.setCellStyles(mxConstants.STYLE_DIRECTION,La[mxUtils.mod(mxUtils.indexOf(La,Ya)+(L?-1:1),La.length)],[ia])}T.push(ia)}}}finally{M.endUpdate()}return T};", "label_name": "CWE-20", "label": "20"} -{"code": " plus: function(left, right) {\n return 'plus(' + left + ',' + right + ')';\n },", "label_name": "CWE-74", "label": "74"} -{"code": "this.sidebar&&null!=urlParams[\"search-shapes\"]&&null!=this.sidebar.searchShapes&&(this.sidebar.searchShapes(urlParams[\"search-shapes\"]),this.sidebar.showEntries(\"search\"));var F=this;mxWindow.prototype.fit=function(){if(Editor.inlineFullscreen||null==F.embedViewport)mxUtils.fit(this.div);else{var da=parseInt(this.div.offsetLeft),ca=parseInt(this.div.offsetWidth),la=F.embedViewport.x+F.embedViewport.width,ia=parseInt(this.div.offsetTop),ma=parseInt(this.div.offsetHeight),qa=F.embedViewport.y+F.embedViewport.height;\nthis.div.style.left=Math.max(F.embedViewport.x,Math.min(da,la-ca))+\"px\";this.div.style.top=Math.max(F.embedViewport.y,Math.min(ia,qa-ma))+\"px\";this.div.style.height=Math.min(F.embedViewport.height,parseInt(this.div.style.height))+\"px\";this.div.style.width=Math.min(F.embedViewport.width,parseInt(this.div.style.width))+\"px\"}};this.keyHandler.bindAction(75,!0,\"toggleShapes\",!0);EditorUi.windowed&&(\"1\"==urlParams.sketch||1E3<=c)&&\"1\"!=urlParams.embedInline&&(b(this,!0),\"1\"==urlParams.sketch?(this.initFormatWindow(),", "label_name": "CWE-20", "label": "20"} -{"code": "[H];!u(H)&&!d(H)||D(H)||x.traverse(H,!0,function(U,Q){var W=null!=Q&&x.isTreeEdge(Q);W&&0>mxUtils.indexOf(S,Q)&&S.push(Q);(null==Q||W)&&0>mxUtils.indexOf(S,U)&&S.push(U);return null==Q||W});return S};var G=mxVertexHandler.prototype.init;mxVertexHandler.prototype.init=function(){G.apply(this,arguments);(u(this.state.cell)||d(this.state.cell))&&!D(this.state.cell)&&0this.state.width?10:0)+2+\"px\",this.moveHandle.style.top=this.state.y+this.state.height+(40>this.state.height?10:0)+2+\"px\")};var J=mxVertexHandler.prototype.setHandlesVisible;mxVertexHandler.prototype.setHandlesVisible=function(H){J.apply(this,", "label_name": "CWE-20", "label": "20"} -{"code": "Na+=\"@import url(\"+La+\");\\n\":Fa+='@font-face {\\nfont-family: \"'+Da+'\";\\nsrc: url(\"'+La+'\");\\n}\\n'}Ga.appendChild(za.createTextNode(Na+Fa));ra.getElementsByTagName(\"defs\")[0].appendChild(Ga)}null!=ja&&(this.shapeBackgroundColor=Ha,this.shapeForegroundColor=Ba,this.stylesheet=ja,this.refresh());return ra};var C=Graph.prototype.createSvgImageExport;Graph.prototype.createSvgImageExport=function(){var u=C.apply(this,arguments);if(this.mathEnabled){var E=u.drawText;u.drawText=function(J,T){if(null!=J.text&&\nnull!=J.text.value&&J.text.checkBounds()&&(mxUtils.isNode(J.text.value)||J.text.dialect==mxConstants.DIALECT_STRICTHTML)){var N=J.text.getContentNode();if(null!=N){N=N.cloneNode(!0);if(N.getElementsByTagNameNS)for(var Q=N.getElementsByTagNameNS(\"http://www.w3.org/1998/Math/MathML\",\"math\");0'],{type:\"text/html\"})});navigator.clipboard.write([P]).then(mxUtils.bind(this,function(){b.alert(mxResources.get(\"copiedToClipboard\"))}))[\"catch\"](mxUtils.bind(this,function(K){b.handleError(K)}))}),", "label_name": "CWE-20", "label": "20"} -{"code": "var F=this.editorUi,G=F.editor.graph;if(G.isEnabled()&&\"1\"==urlParams.sketch){var N=this.createOption(mxResources.get(\"sketch\"),function(){return Editor.sketchMode},function(J,E){F.setSketchMode(!Editor.sketchMode);null!=E&&mxEvent.isShiftDown(E)||G.updateCellStyles({sketch:J?\"1\":null},G.getVerticesAndEdges())},{install:function(J){this.listener=function(){J(Editor.sketchMode)};F.addListener(\"sketchModeChanged\",this.listener)},destroy:function(){F.removeListener(this.listener)}});B.appendChild(N)}return B};", "label_name": "CWE-20", "label": "20"} -{"code": "18*B.childNodes.length+\"px\")}),D=mxUtils.bind(this,function(P,K,F,H){P=t.cloneCells(mxUtils.sortCells(t.model.getTopmostCells(P)));for(var S=0;SPlease try refreshing.\",m.getElementsByTagName(\"a\")[0].onclick=function(){mxLanguage=\"en\";l(mxResources.getDefaultBundle(RESOURCE_BASE,mxLanguage)||mxResources.getSpecialBundle(RESOURCE_BASE,mxLanguage))})})}function d(){try{if(null!=mxSettings.settings){document.body.style.backgroundColor=\"dark\"==uiTheme||mxSettings.settings.darkMode?Editor.darkColor:\"#ffffff\";if(null!=mxSettings.settings.autosaveDelay){var k=\nparseInt(mxSettings.settings.autosaveDelay);!isNaN(k)&&0n&&!mxClient.IS_IOS?O.firstChild.nextSibling.setAttribute(\"title\",X.shortcut):m.apply(this,arguments)};var q=App.prototype.updateUserElement;App.prototype.updateUserElement=function(){q.apply(this,arguments);if(null!=this.userElement){var O=this.userElement;O.style.cssText=\"position:relative;margin-right:4px;cursor:pointer;display:\"+O.style.display;O.className=\"geToolbarButton\";O.innerHTML=\"\";O.style.backgroundImage=\"url(\"+Editor.userImage+\")\";O.style.backgroundPosition=\"center center\";\nO.style.backgroundRepeat=\"no-repeat\";O.style.backgroundSize=\"24px 24px\";O.style.height=\"24px\";O.style.width=\"24px\";O.style.cssFloat=\"right\";O.setAttribute(\"title\",mxResources.get(\"changeUser\"));if(\"none\"!=O.style.display){O.style.display=\"inline-block\";var X=this.getCurrentFile();if(null!=X&&X.isRealtimeEnabled()&&X.isRealtimeSupported()){var ea=document.createElement(\"img\");ea.setAttribute(\"border\",\"0\");ea.style.position=\"absolute\";ea.style.left=\"18px\";ea.style.top=\"2px\";ea.style.width=\"12px\";ea.style.height=\n\"12px\";ea.style.cursor=\"default\";var ka=X.getRealtimeError(),ja=X.getRealtimeState();X=mxResources.get(\"realtimeCollaboration\");1==ja?(ea.src=Editor.syncImage,X+=\" (\"+mxResources.get(\"online\")+\")\"):(ea.src=Editor.syncProblemImage,X=null!=ka&&null!=ka.message?X+(\" (\"+ka.message+\")\"):X+(\" (\"+mxResources.get(\"disconnected\")+\")\"));mxEvent.addListener(ea,\"click\",mxUtils.bind(this,function(U){this.showError(mxResources.get(\"realtimeCollaboration\"),mxUtils.htmlEntities(1==ja?mxResources.get(\"online\"):null!=\nka&&null!=ka.message?ka.message:mxResources.get(\"disconnected\")));mxEvent.consume(U)}));ea.setAttribute(\"title\",X);O.style.paddingRight=\"4px\";O.appendChild(ea)}}}};var y=App.prototype.updateButtonContainer;App.prototype.updateButtonContainer=function(){y.apply(this,arguments);if(null!=this.shareButton){var O=this.shareButton;O.style.cssText=\"display:inline-block;position:relative;box-sizing:border-box;margin-right:4px;cursor:pointer;\";O.className=\"geToolbarButton\";O.innerHTML=\"\";O.style.backgroundImage=", "label_name": "CWE-20", "label": "20"} -{"code": "this.spacing=0}function Ca(){mxArrowConnector.call(this);this.spacing=0}function Ra(){mxActor.call(this)}function ab(){mxRectangleShape.call(this)}function Ka(){mxActor.call(this)}function bb(){mxActor.call(this)}function Pa(){mxActor.call(this)}function Za(){mxActor.call(this)}function z(){mxActor.call(this)}function L(){mxActor.call(this)}function M(){mxActor.call(this)}function T(){mxActor.call(this)}function ca(){mxActor.call(this)}function ia(){mxActor.call(this)}function ma(){mxEllipse.call(this)}", "label_name": "CWE-20", "label": "20"} -{"code": "function(c,e,g,k,m,q,v,x,A,z,L){e=null!=e?e:this.editor.graph;m=null!=m?m:!1;A=null!=A?A:!0;var M=null;if(null==g||g.getMode()==App.MODE_DEVICE||g.getMode()==App.MODE_BROWSER)var n=\"_blank\";else M=n=k;if(null==c)return\"\";var y=c;if(\"mxfile\"!=y.nodeName.toLowerCase()){if(L){var K=c.ownerDocument.createElement(\"diagram\");K.setAttribute(\"id\",Editor.guid());K.appendChild(c)}else{K=Graph.zapGremlins(mxUtils.getXml(c));y=Graph.compress(K);if(Graph.decompress(y)!=K)return K;K=c.ownerDocument.createElement(\"diagram\");\nK.setAttribute(\"id\",Editor.guid());mxUtils.setTextContent(K,y)}y=c.ownerDocument.createElement(\"mxfile\");y.appendChild(K)}z?(y=y.cloneNode(!0),y.removeAttribute(\"modified\"),y.removeAttribute(\"host\"),y.removeAttribute(\"agent\"),y.removeAttribute(\"etag\"),y.removeAttribute(\"userAgent\"),y.removeAttribute(\"version\"),y.removeAttribute(\"editor\"),y.removeAttribute(\"type\")):(y.removeAttribute(\"userAgent\"),y.removeAttribute(\"version\"),y.removeAttribute(\"editor\"),y.removeAttribute(\"pages\"),y.removeAttribute(\"type\"),\nmxClient.IS_CHROMEAPP?y.setAttribute(\"host\",\"Chrome\"):EditorUi.isElectronApp?y.setAttribute(\"host\",\"Electron\"):y.setAttribute(\"host\",window.location.hostname),y.setAttribute(\"modified\",(new Date).toISOString()),y.setAttribute(\"agent\",navigator.appVersion),y.setAttribute(\"version\",EditorUi.VERSION),y.setAttribute(\"etag\",Editor.guid()),c=null!=g?g.getMode():this.mode,null!=c&&y.setAttribute(\"type\",c),1f;)x.shift()},P=", "label_name": "CWE-20", "label": "20"} -{"code": "null!=this.linkHint&&(this.linkHint.style.visibility=\"\")};var Za=mxEdgeHandler.prototype.destroy;mxEdgeHandler.prototype.destroy=function(){Za.apply(this,arguments);null!=this.linkHint&&(this.linkHint.parentNode.removeChild(this.linkHint),this.linkHint=null);null!=this.changeHandler&&(this.graph.getModel().removeListener(this.changeHandler),this.graph.getSelectionModel().removeListener(this.changeHandler),this.changeHandler=null)}}();(function(){function b(c,l,x){mxShape.call(this);this.line=c;this.stroke=l;this.strokewidth=null!=x?x:1;this.updateBoundsFromLine()}function e(){mxSwimlane.call(this)}function k(){mxSwimlane.call(this)}function n(){mxCylinder.call(this)}function D(){mxCylinder.call(this)}function t(){mxActor.call(this)}function F(){mxCylinder.call(this)}function d(){mxCylinder.call(this)}function f(){mxCylinder.call(this)}function g(){mxCylinder.call(this)}function m(){mxShape.call(this)}function q(){mxShape.call(this)}", "label_name": "CWE-20", "label": "20"} -{"code": "mxCellRenderer.prototype.destroy=function(u){D.apply(this,arguments);null!=u.secondLabel&&(u.secondLabel.destroy(),u.secondLabel=null)};mxCellRenderer.prototype.getShapesForState=function(u){return[u.shape,u.text,u.secondLabel,u.control]};var G=mxGraphView.prototype.resetValidationState;mxGraphView.prototype.resetValidationState=function(){G.apply(this,arguments);this.enumerationState=0};var P=mxGraphView.prototype.stateValidated;mxGraphView.prototype.stateValidated=function(u){null!=u.shape&&this.redrawEnumerationState(u);", "label_name": "CWE-20", "label": "20"} -{"code": "\"geCommentActionLnk\";mxUtils.write(da,P);Y.appendChild(da);mxEvent.addListener(da,\"click\",function(ha){O(ha,J);ha.preventDefault();mxEvent.consume(ha)});T.appendChild(Y);R&&(Y.style.display=\"none\")}function W(){function P(Y){O.push(R);if(null!=Y.replies)for(var da=0;da= 0 && ((length - 1) in obj || obj instanceof Array) || typeof obj.item === 'function');\n\n}", "label_name": "CWE-74", "label": "74"} -{"code": "u&&J[T].getAttribute(\"data-font-src\")!=E&&J[T].setAttribute(\"data-font-src\",E)}};var t=Graph.prototype.isFastZoomEnabled;Graph.prototype.isFastZoomEnabled=function(){return t.apply(this,arguments)&&(!this.shadowVisible||!mxClient.IS_SF)};Graph.prototype.updateGlobalUrlVariables=function(){this.globalVars=Editor.globalVars;if(null!=urlParams.vars)try{this.globalVars=null!=this.globalVars?mxUtils.clone(this.globalVars):{};var u=JSON.parse(decodeURIComponent(urlParams.vars));if(null!=u)for(var E in u)this.globalVars[E]=\nu[E]}catch(J){null!=window.console&&console.log(\"Error in vars URL parameter: \"+J)}};Graph.prototype.getExportVariables=function(){return null!=this.globalVars?mxUtils.clone(this.globalVars):{}};var z=Graph.prototype.getGlobalVariable;Graph.prototype.getGlobalVariable=function(u){var E=z.apply(this,arguments);null==E&&null!=this.globalVars&&(E=this.globalVars[u]);return E};Graph.prototype.getDefaultStylesheet=function(){if(null==this.defaultStylesheet){var u=this.themes[\"default-style2\"];this.defaultStylesheet=", "label_name": "CWE-20", "label": "20"} -{"code": "function isPromiseLike(obj) {\n return obj && isFunction(obj.then);\n}", "label_name": "CWE-74", "label": "74"} -{"code": "\t\t_removePhoto( e ) {\n\t\t\te.preventDefault();\n\n\t\t\t// eslint-disable-next-line no-alert\n\t\t\tif ( ! confirm( 'Are you sure?' ) ) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis.$().removeAttr( 'data-custom' );\n\t\t\tthis.$( '.profile-picture' ).toggleClass( 'profile-avatar-current' );\n\t\t\tthis.$( '#submit' ).prop( 'disabled', false );\n\n\t\t\t$( '.lp-user-profile-avatar' ).html( this.$( '.profile-avatar-current' ).find( 'img' ).clone() );\n\t\t},", "label_name": "CWE-610", "label": "610"} -{"code": "function(n){g.editorUiRefresh.apply(b,arguments);u()};u();var q=document.createElement(\"canvas\");q.width=m.offsetWidth;q.height=m.offsetHeight;m.style.overflow=\"hidden\";q.style.position=\"relative\";m.appendChild(q);var v=q.getContext(\"2d\");this.ui=b;var x=b.editor.graph;this.graph=x;this.container=m;this.canvas=q;var A=function(n,y,K,B,F){n=Math.round(n);y=Math.round(y);K=Math.round(K);B=Math.round(B);v.beginPath();v.moveTo(n+.5,y+.5);v.lineTo(K+.5,B+.5);v.stroke();F&&(l?(v.save(),v.translate(n,y),", "label_name": "CWE-20", "label": "20"} -{"code": "DotObject.prototype.transform = function (recipe, obj, tgt) {\n obj = obj || {}\n tgt = tgt || {}\n Object.keys(recipe).forEach(function (key) {\n this.set(recipe[key], this.pick(key, obj), tgt)\n }.bind(this))\n return tgt\n}", "label_name": "CWE-74", "label": "74"} -{"code": "ta);Z.editorUi.fireEvent(new mxEventObject(\"styleChanged\",\"keys\",sa,\"values\",ya,\"cells\",fa.getSelectionCells()))}finally{fa.getModel().endUpdate()}}function N(Aa,ta,ka){var oa=mxUtils.getOffset(u,!0),sa=mxUtils.getOffset(Aa,!0);ta.style.position=\"absolute\";ta.style.left=sa.x-oa.x+\"px\";ta.style.top=sa.y-oa.y+\"px\";ta.style.width=Aa.offsetWidth+\"px\";ta.style.height=Aa.offsetHeight-(ka?4:0)+\"px\";ta.style.zIndex=5}function Q(Aa,ta,ka){var oa=document.createElement(\"div\");oa.style.width=\"32px\";oa.style.height=", "label_name": "CWE-20", "label": "20"} -{"code": "function(C){null!=this.formatWindow?this.formatWindow.window.setVisible(null!=C?C:!this.formatWindow.window.isVisible()):b(this)};DiagramFormatPanel.prototype.isMathOptionVisible=function(){return!0};var B=EditorUi.prototype.destroy;EditorUi.prototype.destroy=function(){null!=this.sidebarWindow&&(this.sidebarWindow.window.setVisible(!1),this.sidebarWindow.window.destroy(),this.sidebarWindow=null);null!=this.formatWindow&&(this.formatWindow.window.setVisible(!1),this.formatWindow.window.destroy(),\nthis.formatWindow=null);null!=this.actions.outlineWindow&&(this.actions.outlineWindow.window.setVisible(!1),this.actions.outlineWindow.window.destroy(),this.actions.outlineWindow=null);null!=this.actions.layersWindow&&(this.actions.layersWindow.window.setVisible(!1),this.actions.layersWindow.destroy(),this.actions.layersWindow=null);null!=this.menus.tagsWindow&&(this.menus.tagsWindow.window.setVisible(!1),this.menus.tagsWindow.window.destroy(),this.menus.tagsWindow=null);null!=this.menus.findWindow&&\n(this.menus.findWindow.window.setVisible(!1),this.menus.findWindow.window.destroy(),this.menus.findWindow=null);null!=this.menus.findReplaceWindow&&(this.menus.findReplaceWindow.window.setVisible(!1),this.menus.findReplaceWindow.window.destroy(),this.menus.findReplaceWindow=null);B.apply(this,arguments)};var I=EditorUi.prototype.setGraphEnabled;EditorUi.prototype.setGraphEnabled=function(C){I.apply(this,arguments);if(C){var D=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth;", "label_name": "CWE-20", "label": "20"} -{"code": "\"inline-block\":\"none\"};Ca=function(){ta.innerHTML=\"\";if(null!=F.currentPage){mxUtils.write(ta,F.currentPage.getName());var da=null!=F.pages?F.pages.length:1,ca=F.getPageIndex(F.currentPage);ca=null!=ca?ca+1:1;var la=F.currentPage.getId();ta.setAttribute(\"title\",F.currentPage.getName()+\" (\"+ca+\"/\"+da+\")\"+(null!=la?\" [\"+la+\"]\":\"\"))}};Ea.parentNode.removeChild(Ea);var Da=F.actions.get(\"delete\"),La=D(\"\",Da.funct,null,mxResources.get(\"delete\"),Da,Editor.trashImage);La.style.opacity=\"0.1\";Q.appendChild(La);", "label_name": "CWE-20", "label": "20"} -{"code": "Auth.verifyToken = async function (token, done) {\n\tlet { tokens = [] } = await meta.settings.get('core.api');\n\ttokens = tokens.reduce((memo, cur) => {\n\t\tmemo[cur.token] = cur.uid;\n\t\treturn memo;\n\t}, {});\n\n\tconst uid = tokens[token];\n\n\tif (uid !== undefined) {\n\t\tif (parseInt(uid, 10) > 0) {\n\t\t\tdone(null, {\n\t\t\t\tuid: uid,\n\t\t\t});\n\t\t} else {\n\t\t\tdone(null, {\n\t\t\t\tmaster: true,\n\t\t\t});\n\t\t}\n\t} else {\n\t\tdone(false);\n\t}\n};", "label_name": "CWE-287", "label": "287"} -{"code": "typeof ha.getAttribute&&null!=ha.getAttribute(\"title\")&&sa.push({img:ha.getAttribute(\"img\"),libs:ha.getAttribute(\"libs\"),clibs:ha.getAttribute(\"clibs\"),title:ha.getAttribute(\"title\")}),ha=ha.nextSibling;D(sa)}});var ua=function(ha,da,ca){ja.style.display=\"\";Ea.stop();W=!1;if(U)U=!1;else if(da)aa.innerHTML=da;else{ca=ca||{};da=0;for(var la in ca)da+=ca[la].length;0==ha.length&&0==da?aa.innerHTML=mxUtils.htmlEntities(mxResources.get(\"noDiagrams\")):C(ha,!1,Q,0==da?null:ca)}};K(N);var xa=null;mxEvent.addListener(Na,", "label_name": "CWE-20", "label": "20"} -{"code": "function(){try{var M=L.width,n=L.height;if(0==M&&0==n){var y=A.result,K=y.indexOf(\",\"),B=decodeURIComponent(escape(atob(y.substring(K+1)))),F=mxUtils.parseXml(B).getElementsByTagName(\"svg\");0 hardbreak\n // Lookup in pending chars is bad practice! Don't copy to other rules!\n // Pending string is stored in concat mode, indexed lookups will cause\n // convertion to flat mode.\n if (!silent) {\n if (pmax >= 0 && state.pending.charCodeAt(pmax) === 0x20) {\n if (pmax >= 1 && state.pending.charCodeAt(pmax - 1) === 0x20) {\n state.pending = state.pending.replace(/ +$/, '');\n state.push('hardbreak', 'br', 0);\n } else {\n state.pending = state.pending.slice(0, -1);\n state.push('softbreak', 'br', 0);\n }\n\n } else {\n state.push('softbreak', 'br', 0);\n }\n }\n\n pos++;\n\n // skip heading spaces for next line\n while (pos < max && isSpace(state.src.charCodeAt(pos))) { pos++; }\n\n state.pos = pos;\n return true;\n};", "label_name": "CWE-400", "label": "400"} -{"code": "\"plantUmlData\",JSON.stringify({data:F,format:K.format}))}finally{g.getModel().endUpdate()}},function(H){d.handleError(H)})},null,null,400,220);d.showDialog(G.container,420,300,!0,!0);G.init()};g.cellEditor.editMermaidData=function(D,G,P){var K=JSON.parse(P);G=new TextareaDialog(d,mxResources.get(\"mermaid\")+\":\",K.data,function(F){null!=F&&d.spinner.spin(document.body,mxResources.get(\"inserting\"))&&d.generateMermaidImage(F,K.config,function(H,S,V){d.spinner.stop();g.getModel().beginUpdate();try{g.setCellStyles(\"image\",", "label_name": "CWE-20", "label": "20"} -{"code": "u.appendChild(E));return u}}Graph.fontMapping={\"https://fonts.googleapis.com/css?family=Architects+Daughter\":'@font-face { font-family: \"Architects Daughter\"; src: url('+STYLE_PATH+'/fonts/ArchitectsDaughter-Regular.ttf) format(\"truetype\"); }'};Graph.customFontElements={};Graph.recentCustomFonts={};Graph.isGoogleFontUrl=function(u){return u.substring(0,Editor.GOOGLE_FONTS.length)==Editor.GOOGLE_FONTS};Graph.isCssFontUrl=function(u){return Graph.isGoogleFontUrl(u)};Graph.createFontElement=function(u,", "label_name": "CWE-20", "label": "20"} -{"code": "E=J}return E};Graph.prototype.getCellsById=function(u){var E=[];if(null!=u)for(var J=0;Ju;u++)for(var t=u,D=0;8>D;D++)t=1==(t&1)?3988292384^t>>>1:t>>>1,Editor.crcTable[u]=t;Editor.updateCRC=function(p,C,I,T){for(var P=\n0;P>>8;return p};Editor.crc32=function(p){for(var C=-1,I=0;I>>8^Editor.crcTable[(C^p.charCodeAt(I))&255];return(C^-1)>>>0};Editor.writeGraphModelToPng=function(p,C,I,T,P){function O(Z,ea){var aa=da;da+=ea;return Z.substring(aa,da)}function R(Z){Z=O(Z,4);return Z.charCodeAt(3)+(Z.charCodeAt(2)<<8)+(Z.charCodeAt(1)<<16)+(Z.charCodeAt(0)<<24)}function Y(Z){return String.fromCharCode(Z>>24&255,Z>>16&255,Z>>8&255,Z&255)}p=p.substring(p.indexOf(\",\")+", "label_name": "CWE-20", "label": "20"} -{"code": "null!=this.linkHint&&(this.linkHint.style.visibility=\"\")};var Za=mxEdgeHandler.prototype.destroy;mxEdgeHandler.prototype.destroy=function(){Za.apply(this,arguments);null!=this.linkHint&&(this.linkHint.parentNode.removeChild(this.linkHint),this.linkHint=null);null!=this.changeHandler&&(this.graph.getModel().removeListener(this.changeHandler),this.graph.getSelectionModel().removeListener(this.changeHandler),this.changeHandler=null)}}();(function(){function b(c,l,x){mxShape.call(this);this.line=c;this.stroke=l;this.strokewidth=null!=x?x:1;this.updateBoundsFromLine()}function e(){mxSwimlane.call(this)}function k(){mxSwimlane.call(this)}function n(){mxCylinder.call(this)}function D(){mxCylinder.call(this)}function t(){mxActor.call(this)}function F(){mxCylinder.call(this)}function d(){mxCylinder.call(this)}function f(){mxCylinder.call(this)}function g(){mxCylinder.call(this)}function m(){mxShape.call(this)}function q(){mxShape.call(this)}", "label_name": "CWE-20", "label": "20"} -{"code": "function preprocessRFC2822(s) {\n // Remove comments and folding whitespace and replace multiple-spaces with a single space\n return s\n .replace(/\\([^)]*\\)|[\\n\\t]/g, ' ')\n .replace(/(\\s\\s+)/g, ' ')\n .replace(/^\\s\\s*/, '')\n .replace(/\\s\\s*$/, '');\n}", "label_name": "CWE-400", "label": "400"} -{"code": "this.spacing=0}function Ca(){mxArrowConnector.call(this);this.spacing=0}function Ra(){mxActor.call(this)}function ab(){mxRectangleShape.call(this)}function Ka(){mxActor.call(this)}function bb(){mxActor.call(this)}function Pa(){mxActor.call(this)}function Za(){mxActor.call(this)}function z(){mxActor.call(this)}function L(){mxActor.call(this)}function M(){mxActor.call(this)}function T(){mxActor.call(this)}function ca(){mxActor.call(this)}function ia(){mxActor.call(this)}function ma(){mxEllipse.call(this)}", "label_name": "CWE-20", "label": "20"} -{"code": "(va.appendChild(Z),va.appendChild(fa),ba.appendChild(va));return{div:ba,refresh:aa}};Graph.prototype.getCustomFonts=function(){var u=this.extFonts;u=null!=u?u.slice():[];for(var E in Graph.customFontElements){var J=Graph.customFontElements[E];u.push({name:J.name,url:J.url})}return u};Graph.prototype.setFont=function(u,E){Graph.addFont(u,E);document.execCommand(\"fontname\",!1,u);if(null!=E){var J=this.cellEditor.textarea.getElementsByTagName(\"font\");E=Graph.getFontUrl(u,E);for(var T=0;T').append(element).html();\n try {\n return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :\n elemHtml.\n match(/^(<[^>]+>)/)[1].\n replace(/^<([\\w\\-]+)/, function(match, nodeName) {return '<' + lowercase(nodeName);});\n } catch (e) {\n return lowercase(elemHtml);\n }\n\n}", "label_name": "CWE-74", "label": "74"} -{"code": "p&&I[T].getAttribute(\"data-font-src\")!=C&&I[T].setAttribute(\"data-font-src\",C)}};var n=Graph.prototype.isFastZoomEnabled;Graph.prototype.isFastZoomEnabled=function(){return n.apply(this,arguments)&&(!this.shadowVisible||!mxClient.IS_SF)};Graph.prototype.updateGlobalUrlVariables=function(){this.globalVars=Editor.globalVars;if(null!=urlParams.vars)try{this.globalVars=null!=this.globalVars?mxUtils.clone(this.globalVars):{};var p=JSON.parse(decodeURIComponent(urlParams.vars));if(null!=p)for(var C in p)this.globalVars[C]=\np[C]}catch(I){null!=window.console&&console.log(\"Error in vars URL parameter: \"+I)}};Graph.prototype.getExportVariables=function(){return null!=this.globalVars?mxUtils.clone(this.globalVars):{}};var y=Graph.prototype.getGlobalVariable;Graph.prototype.getGlobalVariable=function(p){var C=y.apply(this,arguments);null==C&&null!=this.globalVars&&(C=this.globalVars[p]);return C};Graph.prototype.getDefaultStylesheet=function(){if(null==this.defaultStylesheet){var p=this.themes[\"default-style2\"];this.defaultStylesheet=", "label_name": "CWE-20", "label": "20"} -{"code": "document.createElement(\"div\");oa.className=\"geTempDlgNewDiagramCatItemLbl\";oa.innerHTML=qa;ma.appendChild(oa);Da.appendChild(ma);mxEvent.addListener(ma,\"click\",function(){function Ja(){var Ra=Ga.querySelector(\".geTemplateDrawioCatLink\");null!=Ra?Ra.click():setTimeout(Ja,200)}Z=!0;var Ga=Q.querySelector(\".geTemplatesList\");Ga.style.display=\"block\";Aa.style.width=\"\";Oa.style.display=\"\";Oa.value=\"\";da=null;Ja()});ea.style.display=fa.length<=ba?\"none\":\"\"}function G(fa,ca,ba){function ja(Qa,Ya){var La=", "label_name": "CWE-20", "label": "20"} -{"code": "ia){ja=fa.getAttribute(\"section\");ba=fa.getAttribute(\"subsection\");if(null==ja&&(ma=ia.indexOf(\"/\"),ja=ia.substring(0,ma),null==ba)){var qa=ia.indexOf(\"/\",ma+1);-1=I.status?C(I.responseText,\"text/xml\"):this.handleError({message:mxResources.get(413==I.status?\"drawingTooLarge\":\"invalidOrMissingFile\")},\nmxResources.get(\"errorLoadingFile\")))})):(this.spinner.stop(),this.showError(mxResources.get(\"error\"),mxResources.get(\"notInOffline\"))):C(J,E)}}));N.stopPropagation();N.preventDefault()})),mxEvent.addListener(x,\"dragleave\",function(N){x.style.cursor=\"\";x.style.backgroundColor=\"\";N.stopPropagation();N.preventDefault()}));L=L.cloneNode(!1);L.setAttribute(\"src\",Editor.editImage);L.setAttribute(\"title\",mxResources.get(\"edit\"));z.insertBefore(L,z.firstChild);mxEvent.addListener(L,\"click\",K);mxEvent.addListener(x,", "label_name": "CWE-20", "label": "20"} -{"code": "function snake_case(name, separator) {\n separator = separator || '_';\n return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {\n return (pos ? separator : '') + letter.toLowerCase();\n });\n}", "label_name": "CWE-74", "label": "74"} -{"code": "ka-aa,ha=ua+(ya.y-ua)/ka-aa,da=new Image;da.onload=function(){try{for(var ca=-Math.round(sa-mxUtils.mod((wa-xa)*Y,sa)),la=-Math.round(sa-mxUtils.mod((ua-ha)*Y,sa));caf&&(mxUtils.br(g),v=1);var O=document.createElement(\"a\");O.style.overflow=\"hidden\";O.style.display=\"inline-block\";O.className=\"geBaseButton\";O.style.boxSizing=\"border-box\";O.style.fontSize=\"11px\";O.style.position=\"relative\";O.style.margin=\"4px\";O.style.marginTop=\"8px\";O.style.marginBottom=\"0px\";O.style.padding=\"8px 10px 8px 10px\";O.style.width=\"88px\";O.style.height=\"100px\";O.style.whiteSpace=\"nowrap\";O.setAttribute(\"title\",", "label_name": "CWE-20", "label": "20"} -{"code": "EditorUi.prototype.createPageMenuTab=function(b,f){b=this.createControlTab(3,'
',b);b.setAttribute(\"title\",mxResources.get(\"pages\"));b.style.position=\"absolute\";b.style.marginLeft=\"0px\";b.style.top=\"0px\";b.style.left=\"1px\";var l=b.getElementsByTagName(\"div\")[0];l.style.display=\"inline-block\";l.style.marginTop=\"5px\";l.style.width=\"21px\";l.style.height=\"21px\";mxEvent.addListener(b,\"click\",mxUtils.bind(this,function(d){this.editor.graph.popupMenuHandler.hideMenu();\nvar u=new mxPopupMenu(mxUtils.bind(this,function(c,e){var g=mxUtils.bind(this,function(){for(var v=0;v=Ua.getStatus()&&(Ka=Ua.getText());Ta(Ka,Ia)}))):Ta(Ka,Ia)}function qa(Ma,Ta,Ua){if(null!=Ma&&mxUtils.isAncestorNode(document.body,na)){Ma=mxUtils.parseXml(Ma);Ma=Editor.parseDiagramNode(Ma.documentElement);var Za=new mxCodec(Ma.ownerDocument),Wa=new mxGraphModel;", "label_name": "CWE-20", "label": "20"} -{"code": "Manager.prototype.generateId = function () {\n return Math.abs(Math.random() * Math.random() * Date.now() | 0).toString()\n + Math.abs(Math.random() * Math.random() * Date.now() | 0).toString();\n};", "label_name": "CWE-330", "label": "330"} -{"code": "ca,la,ia){function ma(Ma,Ta){null==Ka?(Ia=Ma,Ia=/^https?:\\/\\//.test(Ia)&&!b.editor.isCorsEnabledForUrl(Ia)?PROXY_URL+\"?url=\"+encodeURIComponent(Ia):TEMPLATE_PATH+\"/\"+Ia,mxUtils.get(Ia,mxUtils.bind(this,function(Ua){200<=Ua.getStatus()&&299>=Ua.getStatus()&&(Ka=Ua.getText());Ta(Ka,Ia)}))):Ta(Ka,Ia)}function qa(Ma,Ta,Ua){if(null!=Ma&&mxUtils.isAncestorNode(document.body,na)){Ma=mxUtils.parseXml(Ma);Ma=Editor.parseDiagramNode(Ma.documentElement);var Za=new mxCodec(Ma.ownerDocument),Wa=new mxGraphModel;\nZa.decode(Ma,Wa);Ma=Wa.root.getChildAt(0).children;b.sidebar.createTooltip(na,Ma,Math.min((window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth)-80,1E3),Math.min((window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight)-80,800),null!=ya?mxResources.get(ya,null,ya):null,!0,new mxPoint(Ta,Ua),!0,function(){Ya=null!=b.sidebar.tooltip&&\"none\"!=b.sidebar.tooltip.style.display;z(na,null,null,oa,ha,ia)},!0,!1)}}function pa(Ma,Ta){null==oa||Ra||", "label_name": "CWE-20", "label": "20"} -{"code": "d.addHours=function(a,c){return d.addMinutes(a,60*c)};d.addMinutes=function(a,c){return d.addSeconds(a,60*c)};d.addSeconds=function(a,c){return d.addMilliseconds(a,1E3*c)};d.addMilliseconds=function(a,c){return new Date(a.getTime()+c)};d.subtract=function(a,c){var b=a.getTime()-c.getTime();return{toMilliseconds:function(){return b},toSeconds:function(){return b/1E3},toMinutes:function(){return b/6E4},toHours:function(){return b/36E5},toDays:function(){return b/864E5}}};d.isLeapYear=function(a){return!(a%", "label_name": "CWE-400", "label": "400"} -{"code": "H,[D]);var M=g.model.getGeometry(D);null!=M&&(M=M.clone(),M.width=Math.max(M.width,S),M.height=Math.max(M.height,V),g.cellsResized([D],[M],!1));g.setAttributeForCell(D,\"mermaidData\",JSON.stringify({data:F,config:K.config},null,2))}finally{g.getModel().endUpdate()}},function(H){d.handleError(H)})},null,null,400,220);d.showDialog(G.container,420,300,!0,!0);G.init()};var k=g.cellEditor.startEditing;g.cellEditor.startEditing=function(D,G){try{var P=this.graph.getAttributeForCell(D,\"plantUmlData\");if(null!=\nP)this.editPlantUmlData(D,G,P);else if(P=this.graph.getAttributeForCell(D,\"mermaidData\"),null!=P)this.editMermaidData(D,G,P);else{var K=g.getCellStyle(D);\"1\"==mxUtils.getValue(K,\"metaEdit\",\"0\")?d.showDataDialog(D):k.apply(this,arguments)}}catch(F){d.handleError(F)}};g.getLinkTitle=function(D){return d.getLinkTitle(D)};g.customLinkClicked=function(D){var G=!1;try{d.handleCustomLink(D),G=!0}catch(P){d.handleError(P)}return G};var l=g.parseBackgroundImage;g.parseBackgroundImage=function(D){var G=l.apply(this,", "label_name": "CWE-20", "label": "20"} -{"code": " scope.returnThis = function () {\n return this;\n };", "label_name": "CWE-74", "label": "74"} -{"code": " ifDefined: function(id, defaultValue) {\n return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';\n },", "label_name": "CWE-74", "label": "74"} -{"code": "function openExternalLink(link) {\n let u;\n\n try {\n u = url.parse(link);\n } catch (e) {\n return;\n }\n\n if (protocolRegex.test(u.protocol)) {\n shell.openExternal(link);\n }\n}", "label_name": "CWE-345", "label": "345"} -{"code": "null!=this.linkHint&&(this.linkHint.style.visibility=\"\")};var Za=mxEdgeHandler.prototype.destroy;mxEdgeHandler.prototype.destroy=function(){Za.apply(this,arguments);null!=this.linkHint&&(this.linkHint.parentNode.removeChild(this.linkHint),this.linkHint=null);null!=this.changeHandler&&(this.graph.getModel().removeListener(this.changeHandler),this.graph.getSelectionModel().removeListener(this.changeHandler),this.changeHandler=null)}}();(function(){function b(c,l,x){mxShape.call(this);this.line=c;this.stroke=l;this.strokewidth=null!=x?x:1;this.updateBoundsFromLine()}function e(){mxSwimlane.call(this)}function k(){mxSwimlane.call(this)}function n(){mxCylinder.call(this)}function D(){mxCylinder.call(this)}function t(){mxActor.call(this)}function F(){mxCylinder.call(this)}function d(){mxCylinder.call(this)}function f(){mxCylinder.call(this)}function g(){mxCylinder.call(this)}function m(){mxShape.call(this)}function q(){mxShape.call(this)}", "label_name": "CWE-20", "label": "20"} -{"code": "return u};Graph.getFontUrl=function(u,E){u=Graph.customFontElements[u.toLowerCase()];null!=u&&(E=u.url);return E};Graph.processFontAttributes=function(u){u=u.getElementsByTagName(\"*\");for(var E=0;E\\x3c/script>')),ma.closeDocument(),!ma.mathEnabled&&ya&&PrintDialog.printPreview(ma));null!=wa&&(P.shapeForegroundColor=fa,P.shapeBackgroundColor=ca,P.stylesheet=\nwa,P.refresh())}}var P=p.editor.graph,O=document.createElement(\"div\"),R=document.createElement(\"h3\");R.style.width=\"100%\";R.style.textAlign=\"center\";R.style.marginTop=\"0px\";mxUtils.write(R,C||mxResources.get(\"print\"));O.appendChild(R);var Y=1,da=1;R=document.createElement(\"div\");R.style.cssText=\"border-bottom:1px solid lightGray;padding-bottom:12px;margin-bottom:12px;\";var ha=document.createElement(\"input\");ha.style.cssText=\"margin-right:8px;margin-bottom:8px;\";ha.setAttribute(\"value\",\"all\");ha.setAttribute(\"type\",", "label_name": "CWE-20", "label": "20"} -{"code": " peekAhead: function(i, e1, e2, e3, e4) {\n if (this.tokens.length > i) {\n var token = this.tokens[i];\n var t = token.text;\n if (t === e1 || t === e2 || t === e3 || t === e4 ||\n (!e1 && !e2 && !e3 && !e4)) {\n return token;\n }\n }\n return false;\n },", "label_name": "CWE-74", "label": "74"} -{"code": "exports.debug = (msg, tag, traceId) => {\n // @todo: this function should depend on companion's debug option instead\n if (process.env.NODE_ENV !== 'production') {\n // @ts-ignore\n log(msg, tag, 'debug', traceId, chalk.bold.blue)\n }\n}", "label_name": "CWE-863", "label": "863"} -{"code": "C=new mxAsyncCanvas(this.thumbImageCache);L.images=this.thumbImageCache.images;var D=new mxImageExport;D.drawShape=function(G,P){G.shape instanceof mxShape&&G.shape.checkBounds()&&(P.save(),P.translate(.5,.5),G.shape.paint(P),P.translate(-.5,-.5),P.restore())};D.drawText=function(G,P){};D.drawState(v.getView().getState(v.model.root),C);C.finish(mxUtils.bind(this,function(){try{D.drawState(v.getView().getState(v.model.root),L),v!=this.editor.graph&&null!=v.container.parentNode&&v.container.parentNode.removeChild(v.container)}catch(G){p=", "label_name": "CWE-20", "label": "20"} -{"code": "H.x+\" \"+H.y;S=\"\";c=[];for(U=2;Ul;)v.shift()},N=", "label_name": "CWE-20", "label": "20"} -{"code": "function(K){l=K};this.setAutoScroll=function(K){p=K};this.setOpenFill=function(K){q=K};this.setStopClickEnabled=function(K){A=K};this.setSelectInserted=function(K){B=K};this.setSmoothing=function(K){f=K};this.setPerfectFreehandMode=function(K){O=K};this.setBrushSize=function(K){I.size=K};this.getBrushSize=function(){return I.size};var t=function(K){y=K;b.getRubberband().setEnabled(!K);b.graphHandler.setSelectEnabled(!K);b.graphHandler.setMoveEnabled(!K);b.container.style.cursor=K?\"crosshair\":\"\";b.fireEvent(new mxEventObject(\"freehandStateChanged\"))};", "label_name": "CWE-20", "label": "20"} -{"code": " peek: function(e1, e2, e3, e4) {\n return this.peekAhead(0, e1, e2, e3, e4);\n },", "label_name": "CWE-74", "label": "74"} -{"code": "(function(){var b=new mxObjectCodec(new ChangeGridColor,[\"ui\"]);b.beforeDecode=function(f,l,d){d.ui=f.ui;return l};mxCodecRegistry.register(b)})();(function(){EditorUi.VERSION=\"18.0.3\";EditorUi.compactUi=\"atlas\"!=uiTheme;Editor.isDarkMode()&&(mxGraphView.prototype.gridColor=mxGraphView.prototype.defaultDarkGridColor);EditorUi.enableLogging=\"1\"!=urlParams.stealth&&\"1\"!=urlParams.lockdown&&(/.*\\.draw\\.io$/.test(window.location.hostname)||/.*\\.diagrams\\.net$/.test(window.location.hostname))&&\"support.draw.io\"!=window.location.hostname;EditorUi.drawHost=window.DRAWIO_BASE_URL;EditorUi.lightboxHost=window.DRAWIO_LIGHTBOX_URL;EditorUi.lastErrorMessage=", "label_name": "CWE-20", "label": "20"} -{"code": "La,\"geMenuItem\");null!=Ea?(La.style.backgroundImage=\"url(\"+Ea+\")\",La.style.backgroundPosition=\"center center\",La.style.backgroundRepeat=\"no-repeat\",La.style.backgroundSize=\"24px 24px\",La.style.width=\"34px\",La.innerHTML=\"\"):wa||(La.style.backgroundImage=\"url(\"+mxWindow.prototype.normalizeImage+\")\",La.style.backgroundPosition=\"right 6px center\",La.style.backgroundRepeat=\"no-repeat\",La.style.paddingRight=\"22px\");return La}function X(za,wa,Ea,Da,La,Ya){var Ua=document.createElement(\"a\");Ua.className=\n\"1\"==urlParams.sketch?\"geToolbarButton\":\"geMenuItem\";Ua.style.display=\"inline-block\";Ua.style.boxSizing=\"border-box\";Ua.style.height=\"30px\";Ua.style.padding=\"6px\";Ua.style.position=\"relative\";Ua.style.verticalAlign=\"top\";Ua.style.top=\"0px\";\"1\"==urlParams.sketch&&(Ua.style.borderStyle=\"none\",Ua.style.boxShadow=\"none\",Ua.style.padding=\"6px\",Ua.style.margin=\"0px\");null!=U.statusContainer?V.insertBefore(Ua,U.statusContainer):V.appendChild(Ua);null!=Ya?(Ua.style.backgroundImage=\"url(\"+Ya+\")\",Ua.style.backgroundPosition=\n\"center center\",Ua.style.backgroundRepeat=\"no-repeat\",Ua.style.backgroundSize=\"24px 24px\",Ua.style.width=\"34px\"):mxUtils.write(Ua,za);mxEvent.addListener(Ua,mxClient.IS_POINTER?\"pointerdown\":\"mousedown\",mxUtils.bind(this,function(eb){eb.preventDefault()}));mxEvent.addListener(Ua,\"click\",function(eb){\"disabled\"!=Ua.getAttribute(\"disabled\")&&wa(eb);mxEvent.consume(eb)});null==Ea&&(Ua.style.marginRight=\"4px\");null!=Da&&Ua.setAttribute(\"title\",Da);null!=La&&(za=function(){La.isEnabled()?(Ua.removeAttribute(\"disabled\"),\nUa.style.cursor=\"pointer\"):(Ua.setAttribute(\"disabled\",\"disabled\"),Ua.style.cursor=\"default\")},La.addListener(\"stateChanged\",za),I.addListener(\"enabledChanged\",za),za());return Ua}function ea(za,wa,Ea){Ea=document.createElement(\"div\");Ea.className=\"geMenuItem\";Ea.style.display=\"inline-block\";Ea.style.verticalAlign=\"top\";Ea.style.marginRight=\"6px\";Ea.style.padding=\"0 4px 0 4px\";Ea.style.height=\"30px\";Ea.style.position=\"relative\";Ea.style.top=\"0px\";\"1\"==urlParams.sketch&&(Ea.style.boxShadow=\"none\");", "label_name": "CWE-20", "label": "20"} -{"code": "EditorUi.prototype.isRemoteVisioFormat=function(c){return/(\\.v(sd|dx))($|\\?)/i.test(c)||/(\\.vs(s|x))($|\\?)/i.test(c)};EditorUi.prototype.importVisio=function(c,e,g,k,m){k=null!=k?k:c.name;g=null!=g?g:mxUtils.bind(this,function(v){this.handleError(v)});var q=mxUtils.bind(this,function(){this.loadingExtensions=!1;if(this.doImportVisio){var v=this.isRemoteVisioFormat(k);try{var x=\"UNKNOWN-VISIO\",A=k.lastIndexOf(\".\");if(0<=A&&AmxUtils.indexOf(S,Q)&&S.push(Q);(null==Q||W)&&0>mxUtils.indexOf(S,U)&&S.push(U);return null==Q||W});return S};var G=mxVertexHandler.prototype.init;mxVertexHandler.prototype.init=function(){G.apply(this,arguments);(u(this.state.cell)||d(this.state.cell))&&!D(this.state.cell)&&0y.length){H.view.validate();var wa=new mxFastOrganicLayout(H);wa.forceConstant=3*fa;wa.disableEdgeStyle=!1;wa.resetEdges=!1;var Ea=wa.isVertexIgnored;wa.isVertexIgnored=function(Da){return Ea.apply(this,arguments)||0>mxUtils.indexOf(y,Da)};this.executeLayout(function(){wa.execute(H.getDefaultParent());Fa()},!0,u);u=null}}this.hideDialog()}finally{H.model.endUpdate()}null!=u&&u()}}catch(Da){this.handleError(Da)}};EditorUi.prototype.getSearch=", "label_name": "CWE-20", "label": "20"} -{"code": "function(J){k=J};this.setAutoScroll=function(J){m=J};this.setOpenFill=function(J){q=J};this.setStopClickEnabled=function(J){A=J};this.setSelectInserted=function(J){z=J};this.setSmoothing=function(J){l=J};this.setPerfectFreehandMode=function(J){M=J};this.setBrushSize=function(J){L.size=J};this.getBrushSize=function(){return L.size};var n=function(J){x=J;b.getRubberband().setEnabled(!J);b.graphHandler.setSelectEnabled(!J);b.graphHandler.setMoveEnabled(!J);b.container.style.cursor=J?\"crosshair\":\"\";b.fireEvent(new mxEventObject(\"freehandStateChanged\"))};", "label_name": "CWE-20", "label": "20"} -{"code": "(this.menus.findWindow.window.setVisible(!1),this.menus.findWindow.window.destroy(),this.menus.findWindow=null);null!=this.menus.findReplaceWindow&&(this.menus.findReplaceWindow.window.setVisible(!1),this.menus.findReplaceWindow.window.destroy(),this.menus.findReplaceWindow=null);z.apply(this,arguments)};var L=EditorUi.prototype.setGraphEnabled;EditorUi.prototype.setGraphEnabled=function(B){L.apply(this,arguments);if(B){var F=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth;\n1E3<=F&&null!=this.sidebarWindow&&\"1\"!=urlParams.sketch&&this.sidebarWindow.window.setVisible(!0);null!=this.formatWindow&&(1E3<=F||\"1\"==urlParams.sketch)&&this.formatWindow.window.setVisible(!0)}else null!=this.sidebarWindow&&this.sidebarWindow.window.setVisible(!1),null!=this.formatWindow&&this.formatWindow.window.setVisible(!1)};EditorUi.prototype.chromelessWindowResize=function(){};var M=DiagramFormatPanel.prototype.addView;DiagramFormatPanel.prototype.addView=function(B){B=M.apply(this,arguments);", "label_name": "CWE-20", "label": "20"} -{"code": "n.getStatus()&&300>=n.getStatus()?(this.updateDiagram(n.getText()),L()):this.handleError({message:mxResources.get(\"error\")+\" \"+n.getStatus()}))}),mxUtils.bind(this,function(n){this.handleError(n)}))}),L=mxUtils.bind(this,function(){window.clearTimeout(A);A=window.setTimeout(z,x)});this.editor.addListener(\"pageSelected\",mxUtils.bind(this,function(){L();z()}));L();z()}null!=e&&e()});null!=c.url&&0mxUtils.indexOf(q,ia)};this.executeLayout(function(){ra.execute(A.getDefaultParent());", "label_name": "CWE-20", "label": "20"} -{"code": "D=C.createElement(\"output\");C.appendChild(D);C=new mxXmlCanvas2D(D);C.translate(Math.floor((1-z.x)/L),Math.floor((1-z.y)/L));C.scale(1/L);var G=0,P=C.save;C.save=function(){G++;P.apply(this,arguments)};var K=C.restore;C.restore=function(){G--;K.apply(this,arguments)};var F=t.drawShape;t.drawShape=function(H){mxLog.debug(\"entering shape\",H,G);F.apply(this,arguments);mxLog.debug(\"leaving shape\",H,G)};t.drawState(m.getView().getState(m.model.root),C);mxLog.show();mxLog.debug(mxUtils.getXml(D));mxLog.debug(\"stateCounter\",", "label_name": "CWE-20", "label": "20"} -{"code": "function removeDir (pkg, log, next) {\n var modpath = path.join(path.dirname(pkg.path), '.' + path.basename(pkg.path) + '.MODULES')\n\n move(path.join(pkg.path, 'node_modules'), modpath).then(unbuildPackage, unbuildPackage)\n\n function unbuildPackage (moveEr) {\n rimraf(pkg.path, moveEr ? andRemoveEmptyParents(pkg.path) : moveModulesBack)\n }\n\n function andRemoveEmptyParents (path) {\n return function (er) {\n if (er) return next(er)\n removeEmptyParents(pkg.path)\n }\n }\n\n function moveModulesBack () {\n fs.readdir(modpath, makeTarget)\n }\n\n function makeTarget (readdirEr, files) {\n if (readdirEr) return cleanup()\n if (!files.length) return cleanup()\n correctMkdir(path.join(pkg.path, 'node_modules'), function (mkdirEr) { moveModules(mkdirEr, files) })\n }\n\n function moveModules (mkdirEr, files) {\n if (mkdirEr) return next(mkdirEr)\n asyncMap(files, function (file, done) {\n var from = path.join(modpath, file)\n var to = path.join(pkg.path, 'node_modules', file)\n // we ignore errors here, because they can legitimately happen, for instance,\n // bundled modules will be in both node_modules folders\n move(from, to).then(andIgnoreErrors(done), andIgnoreErrors(done))\n }, cleanup)\n }\n\n function cleanup () {\n rimraf(modpath, afterCleanup)\n }\n\n function afterCleanup (rimrafEr) {\n if (rimrafEr) log.warn('remove', rimrafEr)\n removeEmptyParents(path.resolve(pkg.path, '..'))\n }\n\n function removeEmptyParents (pkgdir) {\n fs.rmdir(pkgdir, function (er) {\n // FIXME: Make sure windows does what we want here\n if (er && er.code !== 'ENOENT') return next()\n removeEmptyParents(path.resolve(pkgdir, '..'))\n })\n }\n}", "label_name": "CWE-732", "label": "732"} -{"code": " 'binary&&': function(left, right, context) {\n return function(scope, locals, assign, inputs) {\n var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);\n return context ? {value: arg} : arg;\n };\n },", "label_name": "CWE-74", "label": "74"} -{"code": "function parseKeyValue(/**string*/keyValue) {\n var obj = {};\n forEach((keyValue || '').split('&'), function(keyValue) {\n var splitPoint, key, val;\n if (keyValue) {\n key = keyValue = keyValue.replace(/\\+/g,'%20');\n splitPoint = keyValue.indexOf('=');\n if (splitPoint !== -1) {\n key = keyValue.substring(0, splitPoint);\n val = keyValue.substring(splitPoint + 1);\n }\n key = tryDecodeURIComponent(key);\n if (isDefined(key)) {\n val = isDefined(val) ? tryDecodeURIComponent(val) : true;\n if (!hasOwnProperty.call(obj, key)) {\n obj[key] = val;\n } else if (isArray(obj[key])) {\n obj[key].push(val);\n } else {\n obj[key] = [obj[key],val];\n }\n }\n }\n });\n return obj;\n}", "label_name": "CWE-74", "label": "74"} -{"code": "Array.prototype.push.apply(N.shape.customProperties,Editor.commonEdgeProperties)),T(N.shape.customProperties));u=u.getAttribute(\"customProperties\");if(null!=u)try{T(JSON.parse(u))}catch(Q){}}};var x=StyleFormatPanel.prototype.init;StyleFormatPanel.prototype.init=function(){var u=this.editorUi.getSelectionState();\"image\"!=u.style.shape&&!u.containsLabel&&0>>8;return u};Editor.crc32=function(u){for(var E=-1,J=0;J>>8^Editor.crcTable[(E^u.charCodeAt(J))&255];return(E^-1)>>>0};Editor.writeGraphModelToPng=function(u,E,J,T,N){function Q(Z,fa){var aa=ba;ba+=fa;return Z.substring(aa,ba)}function R(Z){Z=Q(Z,4);return Z.charCodeAt(3)+(Z.charCodeAt(2)<<8)+(Z.charCodeAt(1)<<16)+(Z.charCodeAt(0)<<24)}function Y(Z){return String.fromCharCode(Z>>24&255,Z>>16&255,Z>>8&255,Z&255)}u=u.substring(u.indexOf(\",\")+", "label_name": "CWE-20", "label": "20"} -{"code": "this.editorUi.getCurrentFile();if(mxClient.IS_SVG&&this.isShadowOptionVisible()){var E=this.editorUi,J=E.editor.graph,T=this.createOption(mxResources.get(\"shadow\"),function(){return J.shadowVisible},function(N){var Q=new ChangePageSetup(E);Q.ignoreColor=!0;Q.ignoreImage=!0;Q.shadowVisible=N;J.model.execute(Q)},{install:function(N){this.listener=function(){N(J.shadowVisible)};E.addListener(\"shadowVisibleChanged\",this.listener)},destroy:function(){E.removeListener(this.listener)}});Editor.enableShadowOption||", "label_name": "CWE-20", "label": "20"} -{"code": "folderId:Q,siteId:R});ja=\"/drives/\"+R+(Q?\"/items/\"+Q:\"/root\")+\"/children\";break;case \"search\":N=S;M=[{driveId:N,name:mxResources.get(\"back\",null,\"Back\")}];ba=encodeURIComponent(ba.replace(/'/g,\"\\\\'\"));ja=N?\"/drives/\"+N+\"/root/search(q='\"+ba+\"')\":\"/me/drive/root/search(q='\"+ba+\"')\";break;default:null==Q?M=[{driveId:N}]:M.push({name:Y,driveId:N,folderId:Q}),ja=(N?\"/drives/\"+N:\"/me/drive\")+(Q?\"/items/\"+Q:\"/root\")+\"/children\"}fa||(ja+=(0
');null==m&&(m=function(){var N=null;try{N=JSON.parse(localStorage.getItem(\"mxODPickerRecentList\"))}catch(Q){}return N});null==n&&(n=function(N){if(null!=N){var Q=m()||{};delete N[\"@microsoft.graph.downloadUrl\"];", "label_name": "CWE-20", "label": "20"} -{"code": "e(L)}),null,null,k,null,q.shadowVisible,null,q,m,null,null,null,\"diagram\",null)}catch(L){null!=e&&e(L)}};EditorUi.prototype.getEmbeddedSvg=function(c,e,g,k,m,q,v,x,A,z,L,M,n){x=null!=x?x:!0;L=null!=L?L:0;v=null!=A?A:e.background;v==mxConstants.NONE&&(v=null);q=e.getSvg(v,z,L,null,null,q,null,null,null,e.shadowVisible||M,null,n,\"diagram\");(e.shadowVisible||M)&&e.addSvgShadow(q,null,null,0==L);null!=c&&q.setAttribute(\"content\",c);null!=g&&q.setAttribute(\"resource\",g);var y=mxUtils.bind(this,function(K){K=\n(k?\"\":Graph.xmlDeclaration+\"\\n\"+Graph.svgFileComment+\"\\n\"+Graph.svgDoctype+\"\\n\")+mxUtils.getXml(K);null!=m&&m(K);return K});e.mathEnabled&&this.editor.addMathCss(q);if(null!=m)this.embedFonts(q,mxUtils.bind(this,function(K){x?this.editor.convertImages(K,mxUtils.bind(this,function(B){y(B)})):y(K)}));else return y(q)};EditorUi.prototype.embedFonts=function(c,e){this.editor.loadFonts(mxUtils.bind(this,function(){try{null!=this.editor.resolvedFontCss&&this.editor.addFontCss(c,this.editor.resolvedFontCss),", "label_name": "CWE-20", "label": "20"} -{"code": "\"dblclick\",function(La){n();mxEvent.consume(La)})}else if(!ja&&null!=pa&&0a.Y?22801:1,b||a.Z?new Date(Date.UTC(a.Y,a.M,a.D,a.H,a.m+a.Z,a.s,a.S)):new Date(a.Y,a.M,a.D,a.H,a.m,a.s,a.S)):new Date(NaN)};d.transform=function(a,c,b,e){return d.format(d.parse(a,c),b,e)};d.addYears=function(a,c){return d.addMonths(a,12*c)};d.addMonths=function(a,c){var b=new Date(a.getTime());b.setMonth(b.getMonth()+c);return b};d.addDays=function(a,c){var b=new Date(a.getTime());b.setDate(b.getDate()+c);return b};", "label_name": "CWE-400", "label": "400"} -{"code": "function addCustomDNS() {\n var ip = $(\"#ip\").val();\n var domain = $(\"#domain\").val();\n\n showAlert(\"info\");\n $.ajax({\n url: \"scripts/pi-hole/php/customdns.php\",\n method: \"post\",\n dataType: \"json\",\n data: { action: \"add\", ip: ip, domain: domain, token: token },\n success: function (response) {\n if (response.success) {\n showAlert(\"success\");\n table.ajax.reload();\n } else showAlert(\"error\", response.message);\n },\n error: function () {\n showAlert(\"error\", \"Error while adding this custom DNS entry\");\n }\n });\n}", "label_name": "CWE-862", "label": "862"} -{"code": "q(x)}),mxUtils.bind(this,function(){this.spinner.stop();this.openLocalFile(c,e,k)}));else{if(\"image/png\"==g.type.substring(0,9))c=this.extractGraphModelFromPng(c);else if(\"application/pdf\"==g.type){var v=Editor.extractGraphModelFromPdf(c);null!=v&&(m=null,k=!0,c=v)}this.spinner.stop();this.openLocalFile(c,e,k,m,null!=m?g:null)}}};EditorUi.prototype.openFiles=function(c,e){if(this.spinner.spin(document.body,mxResources.get(\"loading\")))for(var g=0;gm;m++)for(var n=m,v=0;8>v;v++)n=1==(n&1)?3988292384^n>>>1:n>>>1,Editor.crcTable[m]=n;Editor.updateCRC=function(u,E,J,T){for(var N=\n0;N>>8;return u};Editor.crc32=function(u){for(var E=-1,J=0;J>>8^Editor.crcTable[(E^u.charCodeAt(J))&255];return(E^-1)>>>0};Editor.writeGraphModelToPng=function(u,E,J,T,N){function Q(Z,fa){var aa=ba;ba+=fa;return Z.substring(aa,ba)}function R(Z){Z=Q(Z,4);return Z.charCodeAt(3)+(Z.charCodeAt(2)<<8)+(Z.charCodeAt(1)<<16)+(Z.charCodeAt(0)<<24)}function Y(Z){return String.fromCharCode(Z>>24&255,Z>>16&255,Z>>8&255,Z&255)}u=u.substring(u.indexOf(\",\")+", "label_name": "CWE-20", "label": "20"} -{"code": "H&&!V)if(\"sharepoint\"==S)z(\"site\",null,H.id,H.displayName);else if(\"site\"==S)z(\"subsite\",null,H.id,H.name);else{var N=H.folder;H=H.remoteItem?H.remoteItem:H;var Q=(H.parentReference?H.parentReference.driveId:null)||S,R=H.id;N?z(Q,R,null,H.name):B()}}function z(N,Q,R,Y,ba){function ea(ra){P.stop();var Ca=document.createElement(\"table\");Ca.className=\"odFileListGrid\";for(var za=null,Ga=0,Na=0;null!=ra&&NaFa.webUrl.indexOf(\"sharepoint.com/\")){var Ea=Fa.displayName||Fa.name,Da=mxUtils.htmlEntities(Fa.description||Ea);fa&&(Fa.folder=2==fa?{isRoot:!0}:!0);var La=null!=Fa.folder;if(!g||La){var Aa=document.createElement(\"tr\");Aa.className=Ga++%2?\"odOddRow\":\"odEvenRow\";var ta=document.createElement(\"td\");ta.style.width=\"36px\";var ka=document.createElement(\"img\");ka.src=\"/images/\"+(La?\"folder.png\":\"file.png\");ka.className=\"odFileImg\";ta.appendChild(ka);Aa.appendChild(ta);ta=document.createElement(\"td\");\nLa=document.createElement(\"div\");La.className=\"odFileTitle\";La.innerHTML=mxUtils.htmlEntities(Ea);La.setAttribute(\"title\",Da);ta.appendChild(La);Aa.appendChild(ta);Ca.appendChild(Aa);null==za&&(za=Aa,za.className+=\" odRowSelected\",H=Fa,S=N,x||e(H));(function(oa,sa){Aa.addEventListener(\"dblclick\",t);Aa.addEventListener(\"click\",function(){za!=sa&&(za.className=za.className.replace(\"odRowSelected\",\"\"),za=sa,za.className+=\" odRowSelected\",H=oa,S=N,x||e(H))})})(Fa,Aa)}}}0==Ga?(ra=document.createElement(\"div\"),\nra.className=\"odEmptyFolder\",ra.innerHTML=mxUtils.htmlEntities(mxResources.get(\"folderEmpty\",null,\"Folder is empty!\")),va.appendChild(ra)):va.appendChild(Ca);O();V=!1}if(!V){y(\".odCatsList\").style.display=\"block\";y(\".odFilesSec\").style.display=\"block\";null!=E&&(E.innerHTML=\"\",E.style.top=\"50%\");var Z=V=!0,fa=0;W=arguments;var aa=setTimeout(function(){V=Z=!1;P.stop();d(mxResources.get(\"timeout\"))},2E4),va=y(\".odFilesList\");va.innerHTML=\"\";P.spin(va);switch(N){case \"recent\":M=[{name:mxResources.get(\"recent\",", "label_name": "CWE-20", "label": "20"} -{"code": "t.toDataURL();if(z.length 0) {\n History.pushState(null, null, '/messages', false)\n } else {\n var $convoLI = $('#convo-list').find('li[data-conversation-id=\"' + response.conversation._id + '\"]')\n if ($convoLI.length > 0) {\n $convoLI.remove()\n }\n }\n\n $.event.trigger('$trudesk:chat:conversation:deleted', {\n conversation: response.conversation\n })\n\n helpers.UI.showSnackbar('Conversation Deleted.', false)\n }\n },", "label_name": "CWE-662", "label": "662"} -{"code": "function(J){k=J};this.setAutoScroll=function(J){m=J};this.setOpenFill=function(J){q=J};this.setStopClickEnabled=function(J){A=J};this.setSelectInserted=function(J){z=J};this.setSmoothing=function(J){l=J};this.setPerfectFreehandMode=function(J){M=J};this.setBrushSize=function(J){L.size=J};this.getBrushSize=function(){return L.size};var n=function(J){x=J;b.getRubberband().setEnabled(!J);b.graphHandler.setSelectEnabled(!J);b.graphHandler.setMoveEnabled(!J);b.container.style.cursor=J?\"crosshair\":\"\";b.fireEvent(new mxEventObject(\"freehandStateChanged\"))};", "label_name": "CWE-20", "label": "20"} -{"code": "function(y){this.spinner.stop();this.handleError(y)})})))}}),mxUtils.bind(this,function(){this.hideDialog()}),mxResources.get(\"saveAs\"),mxResources.get(\"download\"),!1,!1,v,null,1\\x3c/script>')),ma.closeDocument(),!ma.mathEnabled&&ya&&PrintDialog.printPreview(ma));null!=xa&&(N.shapeForegroundColor=ha,N.shapeBackgroundColor=da,N.stylesheet=\nxa,N.refresh())}}var N=u.editor.graph,Q=document.createElement(\"div\"),R=document.createElement(\"h3\");R.style.width=\"100%\";R.style.textAlign=\"center\";R.style.marginTop=\"0px\";mxUtils.write(R,E||mxResources.get(\"print\"));Q.appendChild(R);var Y=1,ba=1;R=document.createElement(\"div\");R.style.cssText=\"border-bottom:1px solid lightGray;padding-bottom:12px;margin-bottom:12px;\";var ea=document.createElement(\"input\");ea.style.cssText=\"margin-right:8px;margin-bottom:8px;\";ea.setAttribute(\"value\",\"all\");ea.setAttribute(\"type\",", "label_name": "CWE-20", "label": "20"} -{"code": " codePointAt: function(ch) {\n if (ch.length === 1) return ch.charCodeAt(0);\n // eslint-disable-next-line no-bitwise\n return (ch.charCodeAt(0) << 10) + ch.charCodeAt(1) - 0x35FDC00;\n },", "label_name": "CWE-74", "label": "74"} -{"code": "ka.size,ra,sa)):\"readOnly\"==va?(sa=document.createElement(\"input\"),sa.setAttribute(\"readonly\",\"\"),sa.value=ta,sa.style.width=\"96px\",sa.style.borderWidth=\"0px\",wa.appendChild(sa)):(wa.innerHTML=mxUtils.htmlEntities(decodeURIComponent(ta)),mxEvent.addListener(wa,\"click\",mxUtils.bind(Z,function(){function ca(){var ja=ba.value;ja=0==ja.length&&\"string\"!=va?0:ja;ka.allowAuto&&(null!=ja.trim&&\"auto\"==ja.trim().toLowerCase()?(ja=\"auto\",va=\"string\"):(ja=parseFloat(ja),ja=isNaN(ja)?0:ja));null!=ka.min&&ja<\nka.min?ja=ka.min:null!=ka.max&&ja>ka.max&&(ja=ka.max);ja=encodeURIComponent((\"int\"==va?parseInt(ja):ja)+\"\");T(za,ja,ka)}var ba=document.createElement(\"input\");P(wa,ba,!0);ba.value=decodeURIComponent(ta);ba.className=\"gePropEditor\";\"int\"!=va&&\"float\"!=va||ka.allowAuto||(ba.type=\"number\",ba.step=\"int\"==va?\"1\":\"any\",null!=ka.min&&(ba.min=parseFloat(ka.min)),null!=ka.max&&(ba.max=parseFloat(ka.max)));p.appendChild(ba);mxEvent.addListener(ba,\"keypress\",function(ja){13==ja.keyCode&&ca()});ba.focus();mxEvent.addListener(ba,", "label_name": "CWE-20", "label": "20"} -{"code": "d.addHours=function(a,c){return d.addMinutes(a,60*c)};d.addMinutes=function(a,c){return d.addSeconds(a,60*c)};d.addSeconds=function(a,c){return d.addMilliseconds(a,1E3*c)};d.addMilliseconds=function(a,c){return new Date(a.getTime()+c)};d.subtract=function(a,c){var b=a.getTime()-c.getTime();return{toMilliseconds:function(){return b},toSeconds:function(){return b/1E3},toMinutes:function(){return b/6E4},toHours:function(){return b/36E5},toDays:function(){return b/864E5}}};d.isLeapYear=function(a){return!(a%", "label_name": "CWE-400", "label": "400"} -{"code": "function(e){var f=e.split(\"/\");return 1 this.clients.delete(ws));\n }\n\n cb(ws, req);\n }", "label_name": "CWE-400", "label": "400"} -{"code": "ta.style.width=\"40px\";ta.style.height=\"12px\";ta.style.marginBottom=\"-2px\";ta.style.backgroundImage=\"url(\"+mxWindow.prototype.normalizeImage+\")\";ta.style.backgroundPosition=\"top center\";ta.style.backgroundRepeat=\"no-repeat\";ta.setAttribute(\"title\",\"Minimize\");var Na=!1,Ca=mxUtils.bind(this,function(){S.innerHTML=\"\";if(!Na){var za=function(Da,La,Ya){Da=X(\"\",Da.funct,null,La,Da,Ya);Da.style.width=\"40px\";Da.style.opacity=\"0.7\";return wa(Da,null,\"pointer\")},wa=function(Da,La,Ya){null!=La&&Da.setAttribute(\"title\",\nLa);Da.style.cursor=null!=Ya?Ya:\"default\";Da.style.margin=\"2px 0px\";S.appendChild(Da);mxUtils.br(S);return Da};wa(U.sidebar.createVertexTemplate(\"text;strokeColor=none;fillColor=none;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;\",60,30,\"Text\",mxResources.get(\"text\"),!0,!1,null,!0,!0),mxResources.get(\"text\")+\" (\"+Editor.ctrlKey+\"+Shift+X)\");wa(U.sidebar.createVertexTemplate(\"shape=note;whiteSpace=wrap;html=1;backgroundOutline=1;fontColor=#000000;darkOpacity=0.05;fillColor=#FFF9B2;strokeColor=none;fillStyle=solid;direction=west;gradientDirection=north;gradientColor=#FFF2A1;shadow=1;size=20;pointerEvents=1;\",", "label_name": "CWE-20", "label": "20"} -{"code": "function getTestability(rootElement) {\n var injector = angular.element(rootElement).injector();\n if (!injector) {\n throw ngMinErr('test',\n 'no injector found for element argument to getTestability');\n }\n return injector.get('$$testability');\n}", "label_name": "CWE-74", "label": "74"} -{"code": "arguments);null!=G&&null!=G.src&&Graph.isPageLink(G.src)&&(G={originalSrc:G.src});return G};var p=g.setBackgroundImage;g.setBackgroundImage=function(D){null!=D&&null!=D.originalSrc&&(D=d.createImageForPageLink(D.originalSrc,d.currentPage,this));p.apply(this,arguments)};this.editor.addListener(\"pageRenamed\",mxUtils.bind(this,function(){g.refreshBackgroundImage()}));this.editor.addListener(\"pageMoved\",mxUtils.bind(this,function(){g.refreshBackgroundImage()}));this.editor.addListener(\"pagesPatched\",", "label_name": "CWE-20", "label": "20"} -{"code": "RecordViewWidgetManager.prototype._init = function () {\n this._hiddenWidgetsMenuSelector = '#x2-hidden-widgets-menu';\n this._hiddenWidgetsMenuItemSelector = \n '.x2-hidden-widgets-menu-item.' + this.widgetType + '-widget';\n this._setUpRecordViewTypeToggleBehavior ();\n this._widgetsBoxSelector = '#' + this.cssSelectorPrefix + 'widgets-container-2';\n this._widgetsBoxSelector2 = '#' + this.cssSelectorPrefix + 'widgets-container-inner';\n\n SortableWidgetManager.prototype._init.call (this);\n};", "label_name": "CWE-20", "label": "20"} -{"code": "function g(D){D.dataTransfer.dropEffect=null!=B?\"move\":\"copy\";D.stopPropagation();D.preventDefault()}function k(D){D.stopPropagation();D.preventDefault();z=!1;I=v(D);if(null!=B)null!=I&&IB?I-1:I,0,l.splice(B,1)[0]),x.insertBefore(x.children[B],x.children[I])):(l.push(l.splice(B,1)[0]),x.appendChild(x.children[B]));else if(0',start+4);\n\t\t\t//append comment source.substring(4,end)// issue a waring\n Logger.getLogger(this.getClass().getName())\n .log(\n Level.WARNING,\n \"Using \"\n + J2EERootContext\n + jndiName\n + \" instead of \"\n + jndiName\n + \" would avoid an unnecessary JNDI lookup\");\n }\n } catch (NamingException e2) {\n // do nothing, was only a try\n }\n }\n\n if (ds == null) throw new IOException(\"Cannot find JNDI data source: \" + jndiName);\n else return ds;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " private Map> initializeTypeParameters(Argument[] genericTypes) {\n Map> typeParameters;\n if (genericTypes != null && genericTypes.length > 0) {\n typeParameters = new LinkedHashMap<>(genericTypes.length);\n for (Argument genericType : genericTypes) {\n typeParameters.put(genericType.getName(), genericType);\n }\n } else {\n typeParameters = Collections.emptyMap();\n }\n return typeParameters;\n }", "label_name": "CWE-400", "label": "400"} -{"code": " Randoms() {\n random = new Random();\n Date date = new Date();\n random.setSeed(date.getTime());\n }", "label_name": "CWE-327", "label": "327"} -{"code": " public DataSource createNewDataSource(Map params) throws IOException {\n String refName = (String) JNDI_REFNAME.lookUp(params);\n try {\n return (DataSource) GeoTools.getInitialContext().lookup(refName);\n } catch (Exception e) {\n throw new DataSourceException(\"Could not find the specified data source in JNDI\", e);\n }\n }", "label_name": "CWE-20", "label": "20"} -{"code": " protected ObjectStreamClass readClassDescriptor()\n throws IOException, ClassNotFoundException {\n int type = read();\n if (type < 0) {\n throw new EOFException();\n }\n switch (type) {\n case ThrowableObjectOutputStream.TYPE_EXCEPTION:\n return ObjectStreamClass.lookup(Exception.class);\n case ThrowableObjectOutputStream.TYPE_STACKTRACEELEMENT:\n return ObjectStreamClass.lookup(StackTraceElement.class);\n case ThrowableObjectOutputStream.TYPE_FAT_DESCRIPTOR:\n return super.readClassDescriptor();\n case ThrowableObjectOutputStream.TYPE_THIN_DESCRIPTOR:\n String className = readUTF();\n Class clazz = loadClass(className);\n return ObjectStreamClass.lookup(clazz);\n default:\n throw new StreamCorruptedException(\n \"Unexpected class descriptor type: \" + type);\n }\n }", "label_name": "CWE-74", "label": "74"} -{"code": "\tprivate boolean handleJid(Invite invite) {\n\t\tList contacts = xmppConnectionService.findContacts(invite.getJid(), invite.account);\n\t\tif (invite.isAction(XmppUri.ACTION_JOIN)) {\n\t\t\tConversation muc = xmppConnectionService.findFirstMuc(invite.getJid());\n\t\t\tif (muc != null) {\n\t\t\t\tswitchToConversation(muc, invite.getBody());\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\tshowJoinConferenceDialog(invite.getJid().asBareJid().toString());\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} else if (contacts.size() == 0) {\n\t\t\tshowCreateContactDialog(invite.getJid().toString(), invite);\n\t\t\treturn false;\n\t\t} else if (contacts.size() == 1) {\n\t\t\tContact contact = contacts.get(0);\n\t\t\tif (!invite.isSafeSource() && invite.hasFingerprints()) {\n\t\t\t\tdisplayVerificationWarningDialog(contact, invite);\n\t\t\t} else {\n\t\t\t\tif (invite.hasFingerprints()) {\n\t\t\t\t\tif (xmppConnectionService.verifyFingerprints(contact, invite.getFingerprints())) {\n\t\t\t\t\t\tToast.makeText(this, R.string.verified_fingerprints, Toast.LENGTH_SHORT).show();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (invite.account != null) {\n\t\t\t\t\txmppConnectionService.getShortcutService().report(contact);\n\t\t\t\t}\n\t\t\t\tswitchToConversation(contact, invite.getBody());\n\t\t\t}\n\t\t\treturn true;\n\t\t} else {\n\t\t\tif (mMenuSearchView != null) {\n\t\t\t\tmMenuSearchView.expandActionView();\n\t\t\t\tmSearchEditText.setText(\"\");\n\t\t\t\tmSearchEditText.append(invite.getJid().toString());\n\t\t\t\tfilter(invite.getJid().toString());\n\t\t\t} else {\n\t\t\t\tmInitialSearchValue.push(invite.getJid().toString());\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t}", "label_name": "CWE-200", "label": "200"} -{"code": " public void existingDocumentTerminalFromUI() throws Exception\n {\n // current document = xwiki:Main.WebHome\n DocumentReference documentReference = new DocumentReference(\"xwiki\", Arrays.asList(\"Main\"), \"WebHome\");\n XWikiDocument document = mock(XWikiDocument.class);\n when(document.getDocumentReference()).thenReturn(documentReference);\n when(document.isNew()).thenReturn(false);\n when(document.getLocalReferenceMaxLength()).thenReturn(255);\n context.setDoc(document);\n\n // Submit from the UI spaceReference=X&name=Y&tocreate=terminal\n when(mockRequest.getParameter(\"spaceReference\")).thenReturn(\"X\");\n when(mockRequest.getParameter(\"name\")).thenReturn(\"Y\");\n when(mockRequest.getParameter(\"tocreate\")).thenReturn(\"terminal\");\n\n // Run the action\n String result = action.render(context);\n\n // The tests are below this line!\n\n // Verify null is returned (this means the response has been returned)\n assertNull(result);\n\n // Note: We are creating X.Y instead of X.Y.WebHome because the tocreate parameter says \"terminal\".\n verify(mockURLFactory).createURL(\"X\", \"Y\", \"edit\", \"template=&parent=Main.WebHome&title=Y\", null, \"xwiki\",\n context);\n }", "label_name": "CWE-862", "label": "862"} -{"code": " List findRecentModifications(int count) {\n // Currently impossible to check modifications on a remote repository.\n InMemoryStreamConsumer consumer = inMemoryConsumer();\n bombUnless(pull(consumer), \"Failed to run hg pull command: \" + consumer.getAllOutput());\n CommandLine hg = hg(\"log\", \"--limit\", String.valueOf(count), \"-b\", branch, \"--style\", templatePath());\n return new HgModificationSplitter(execute(hg)).modifications();\n }", "label_name": "CWE-77", "label": "77"} -{"code": " public void init(KeyGenerationParameters param)\n {\n this.param = (RSAKeyGenerationParameters)param;\n this.iterations = getNumberOfIterations(this.param.getStrength(), this.param.getCertainty());\n }", "label_name": "CWE-327", "label": "327"} -{"code": " public void subValidateFail(ViolationCollector col) {\n col.addViolation(FAILED+\"subclass\");\n } ", "label_name": "CWE-74", "label": "74"} -{"code": " public void existingDocumentFromUINoName() throws Exception\n {\n // current document = xwiki:Main.WebHome\n DocumentReference documentReference = new DocumentReference(\"xwiki\", Arrays.asList(\"Main\"), \"WebHome\");\n XWikiDocument document = mock(XWikiDocument.class);\n when(document.getDocumentReference()).thenReturn(documentReference);\n when(document.isNew()).thenReturn(false);\n when(document.getLocalReferenceMaxLength()).thenReturn(255);\n context.setDoc(document);\n\n // Just landed on the create page or submitted with no values (no name) specified.\n\n // Run the action\n String result = action.render(context);\n\n // The tests are below this line!\n\n // Verify that the create template is rendered, so the UI is displayed for the user to enter the missing values.\n assertEquals(\"create\", result);\n\n // We should not get this far so no redirect should be done, just the template will be rendered.\n verify(mockURLFactory, never()).createURL(any(), any(), any(), any(), any(),\n any(), any(XWikiContext.class));\n }", "label_name": "CWE-862", "label": "862"} -{"code": " public int getExpirationTime() {\r\n return expirationTime;\r\n }\r", "label_name": "CWE-200", "label": "200"} -{"code": " void newDocumentInvalidName() throws Exception\n {\n when(mockDocument.isNew()).thenReturn(true);\n DocumentReference documentReference = new DocumentReference(\"XWiki\", \"Foo\", \"Bar\");\n when(mockDocument.getDocumentReference()).thenReturn(documentReference);\n when(this.entityNameValidationConfiguration.useValidation()).thenReturn(true);\n EntityNameValidation entityNameValidation = mock(EntityNameValidation.class);\n when(this.entityNameValidationManager.getEntityReferenceNameStrategy()).thenReturn(entityNameValidation);\n when(entityNameValidation.isValid(documentReference)).thenReturn(false);\n\n assertTrue(saveAction.save(this.context));\n assertEquals(\"entitynamevalidation.create.invalidname\", context.get(\"message\"));\n assertArrayEquals(new Object[] { \"Foo.Bar\" }, (Object[]) context.get(\"messageParameters\"));\n }", "label_name": "CWE-862", "label": "862"} -{"code": "\tprotected void runTeardown() {\n\t\tAssert.assertTrue(\"Error during initialization\", messagedInitialization);\n\t\tAssert.assertTrue(\"HTTP connection is not allowed\", messagedAccessDenied);\n\t}", "label_name": "CWE-862", "label": "862"} -{"code": " public void addUser(JpaUser user) throws UnauthorizedException {\n if (!UserDirectoryUtils.isCurrentUserAuthorizedHandleRoles(securityService, user.getRoles()))\n throw new UnauthorizedException(\"The user is not allowed to set the admin role on other users\");\n\n // Create a JPA user with an encoded password.\n String encodedPassword = PasswordEncoder.encode(user.getPassword(), user.getUsername());\n\n // Only save internal roles\n Set roles = UserDirectoryPersistenceUtil.saveRoles(filterRoles(user.getRoles()), emf);\n JpaOrganization organization = UserDirectoryPersistenceUtil.saveOrganization(\n (JpaOrganization) user.getOrganization(), emf);\n\n JpaUser newUser = new JpaUser(user.getUsername(), encodedPassword, organization, user.getName(), user.getEmail(),\n user.getProvider(), user.isManageable(), roles);\n\n // Then save the user\n EntityManager em = null;\n EntityTransaction tx = null;\n try {\n em = emf.createEntityManager();\n tx = em.getTransaction();\n tx.begin();\n em.persist(newUser);\n tx.commit();\n cache.put(user.getUsername() + DELIMITER + user.getOrganization().getId(), newUser);\n } finally {\n if (tx.isActive()) {\n tx.rollback();\n }\n if (em != null)\n em.close();\n }\n\n updateGroupMembership(user);\n\n }", "label_name": "CWE-327", "label": "327"} -{"code": " public void translate(ServerPlaySoundPacket packet, GeyserSession session) {\n String packetSound;\n if (packet.getSound() instanceof BuiltinSound) {\n packetSound = ((BuiltinSound) packet.getSound()).getName();\n } else if (packet.getSound() instanceof CustomSound) {\n packetSound = ((CustomSound) packet.getSound()).getName();\n } else {\n session.getConnector().getLogger().debug(\"Unknown sound packet, we were unable to map this. \" + packet.toString());\n return;\n }\n\n SoundMapping soundMapping = Registries.SOUNDS.get(packetSound.replace(\"minecraft:\", \"\"));\n String playsound;\n if (soundMapping == null || soundMapping.getPlaysound() == null) {\n // no mapping\n session.getConnector().getLogger()\n .debug(\"[PlaySound] Defaulting to sound server gave us for \" + packet.toString());\n playsound = packetSound.replace(\"minecraft:\", \"\");\n } else {\n playsound = soundMapping.getPlaysound();\n }\n\n PlaySoundPacket playSoundPacket = new PlaySoundPacket();\n playSoundPacket.setSound(playsound);\n playSoundPacket.setPosition(Vector3f.from(packet.getX(), packet.getY(), packet.getZ()));\n playSoundPacket.setVolume(packet.getVolume());\n playSoundPacket.setPitch(packet.getPitch());\n\n session.sendUpstreamPacket(playSoundPacket);\n }", "label_name": "CWE-287", "label": "287"} -{"code": " public String getEncryptedValue() {\n try {\n Cipher cipher = KEY.encrypt();\n // add the magic suffix which works like a check sum.\n return new String(Base64.encode(cipher.doFinal((value+MAGIC).getBytes(\"UTF-8\"))));\n } catch (GeneralSecurityException e) {\n throw new Error(e); // impossible\n } catch (UnsupportedEncodingException e) {\n throw new Error(e); // impossible\n }\n }", "label_name": "CWE-326", "label": "326"} -{"code": " public void translate(FilterTextPacket packet, GeyserSession session) {\n if (session.getOpenInventory() instanceof CartographyContainer) {\n // We don't want to be able to rename in the cartography table\n return;\n }\n packet.setFromServer(true);\n session.sendUpstreamPacket(packet);\n\n if (session.getOpenInventory() instanceof AnvilContainer) {\n // Java Edition sends a packet every time an item is renamed even slightly in GUI. Fortunately, this works out for us now\n ClientRenameItemPacket renameItemPacket = new ClientRenameItemPacket(packet.getText());\n session.sendDownstreamPacket(renameItemPacket);\n }\n }", "label_name": "CWE-287", "label": "287"} -{"code": " public void getAllReturnsEmptyListForUnknownName() {\n final HttpHeadersBase headers = newEmptyHeaders();\n assertThat(headers.getAll(\"noname\").size()).isEqualTo(0);\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void translate(ServerScoreboardObjectivePacket packet, GeyserSession session) {\n WorldCache worldCache = session.getWorldCache();\n Scoreboard scoreboard = worldCache.getScoreboard();\n Objective objective = scoreboard.getObjective(packet.getName());\n int pps = worldCache.increaseAndGetScoreboardPacketsPerSecond();\n\n if (objective == null && packet.getAction() != ObjectiveAction.REMOVE) {\n objective = scoreboard.registerNewObjective(packet.getName(), false);\n }\n\n switch (packet.getAction()) {\n case ADD:\n case UPDATE:\n objective.setDisplayName(MessageTranslator.convertMessage(packet.getDisplayName()))\n .setType(packet.getType().ordinal());\n break;\n case REMOVE:\n scoreboard.unregisterObjective(packet.getName());\n break;\n }\n\n if (objective == null || !objective.isActive()) {\n return;\n }\n\n // ScoreboardUpdater will handle it for us if the packets per second\n // (for score and team packets) is higher then the first threshold\n if (pps < ScoreboardUpdater.FIRST_SCORE_PACKETS_PER_SECOND_THRESHOLD) {\n scoreboard.onUpdate();\n }\n }", "label_name": "CWE-287", "label": "287"} -{"code": " public void testGetOperations() {\n final HttpHeadersBase headers = newEmptyHeaders();\n headers.add(\"Foo\", \"1\");\n headers.add(\"Foo\", \"2\");\n\n assertThat(headers.get(\"Foo\")).isEqualTo(\"1\");\n\n final List values = headers.getAll(\"Foo\");\n assertThat(values).containsExactly(\"1\", \"2\");\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public AccessControlList getAccessControlList(String mediaPackageId) throws NotFoundException,\n SearchServiceDatabaseException {\n EntityManager em = null;\n try {\n em = emf.createEntityManager();\n SearchEntity entity = getSearchEntity(mediaPackageId, em);\n if (entity == null) {\n throw new NotFoundException(\"Could not found media package with ID \" + mediaPackageId);\n }\n if (entity.getAccessControl() == null) {\n return null;\n } else {\n return AccessControlParser.parseAcl(entity.getAccessControl());\n }\n } catch (NotFoundException e) {\n throw e;\n } catch (Exception e) {\n logger.error(\"Could not retrieve ACL {}: {}\", mediaPackageId, e.getMessage());\n throw new SearchServiceDatabaseException(e);\n } finally {\n em.close();\n }\n }", "label_name": "CWE-863", "label": "863"} -{"code": " public void translate(RiderJumpPacket packet, GeyserSession session) {\n Entity vehicle = session.getRidingVehicleEntity();\n if (vehicle instanceof AbstractHorseEntity) {\n ClientPlayerStatePacket playerStatePacket = new ClientPlayerStatePacket((int) vehicle.getEntityId(), PlayerState.START_HORSE_JUMP, packet.getJumpStrength());\n session.sendDownstreamPacket(playerStatePacket);\n }\n }", "label_name": "CWE-287", "label": "287"} -{"code": " public void submoduleAdd(String repoUrl, String submoduleNameToPutInGitSubmodules, String folder) {\n String[] addSubmoduleWithSameNameArgs = new String[]{\"submodule\", \"add\", repoUrl, folder};\n String[] changeSubmoduleNameInGitModules = new String[]{\"config\", \"--file\", \".gitmodules\", \"--rename-section\", \"submodule.\" + folder, \"submodule.\" + submoduleNameToPutInGitSubmodules};\n String[] addGitModules = new String[]{\"add\", \".gitmodules\"};\n\n runOrBomb(gitWd().withArgs(addSubmoduleWithSameNameArgs));\n runOrBomb(gitWd().withArgs(changeSubmoduleNameInGitModules));\n runOrBomb(gitWd().withArgs(addGitModules));\n }", "label_name": "CWE-77", "label": "77"} -{"code": " public Group createDefaultReadGroup(Context context, Collection collection, String typeOfGroupString,\n int defaultRead)\n throws SQLException, AuthorizeException {\n Group role = groupService.create(context);\n groupService.setName(role, \"COLLECTION_\" + collection.getID().toString() + \"_\" + typeOfGroupString +\n \"_DEFAULT_READ\");\n\n // Remove existing privileges from the anonymous group.\n authorizeService.removePoliciesActionFilter(context, collection, defaultRead);\n\n // Grant our new role the default privileges.\n authorizeService.addPolicy(context, collection, defaultRead, role);\n groupService.update(context, role);\n return role;\n }", "label_name": "CWE-863", "label": "863"} -{"code": " public IdImpl(String id) {\n this.id = id;\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void translate(LoginPluginRequestPacket packet, GeyserSession session) {\n // A vanilla client doesn't know any PluginMessage in the Login state, so we don't know any either.\n // Note: Fabric Networking API v1 will not let the client log in without sending this\n session.sendDownstreamPacket(\n new LoginPluginResponsePacket(packet.getMessageId(), null)\n );\n }", "label_name": "CWE-287", "label": "287"} -{"code": " public void setExpirationTime(int expirationTime) {\r\n this.expirationTime = expirationTime;\r\n }\r", "label_name": "CWE-200", "label": "200"} -{"code": " public boolean isValid(String value, ConstraintValidatorContext context) {\n if (StringUtils.isEmpty(value)) {\n return true;\n }\n\n try {\n Pattern.compile(value);\n return true;\n } catch (Exception ex) {\n String errorMessage = String.format(\"URL parameter '%s' is not a valid regexp\", value);\n LOG.warn(errorMessage);\n\n context.buildConstraintViolationWithTemplate(errorMessage).addConstraintViolation();\n }\n return false;\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void translate(ServerUpdateViewDistancePacket packet, GeyserSession session) {\n session.setRenderDistance(packet.getViewDistance());\n }", "label_name": "CWE-287", "label": "287"} -{"code": " public void translate(ServerUpdateViewPositionPacket packet, GeyserSession session) {\n if (!session.isSpawned() && session.getLastChunkPosition() == null) {\n ChunkUtils.updateChunkPosition(session, Vector3i.from(packet.getChunkX() << 4, 64, packet.getChunkZ() << 4));\n }\n }", "label_name": "CWE-287", "label": "287"} -{"code": " public static synchronized InitialContext getInitialContext(final Hints hints)\n throws NamingException {\n\n return getInitialContext();\n }", "label_name": "CWE-20", "label": "20"} -{"code": "\tpublic int size() {\n\n\t\treturn ByteUtils.bitLength(n.decode());\n\t}", "label_name": "CWE-345", "label": "345"} -{"code": " public void delete(String databaseType) {\n Path path = Paths.get(driverFilePath(driverBaseDirectory, databaseType));\n try {\n Files.deleteIfExists(path);\n } catch (IOException e) {\n log.error(\"delete driver error \" + databaseType, e);\n }\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public String resolveSqlDriverNameFromJar(String driverFileUrl) {\n String tempFilePath = \"temp/\" + UUID.randomUUID() + \".jar\";\n File driverFile = doDownload(driverFileUrl, tempFilePath);\n String className = doResolveSqlDriverNameFromJar(driverFile);\n try {\n Files.deleteIfExists(driverFile.toPath());\n } catch (IOException e) {\n log.error(\"delete driver error \" + tempFilePath, e);\n }\n return className;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public void subsetOfHeadersShouldNotBeEquivalent() {\n final HttpHeadersBase headers1 = newEmptyHeaders();\n headers1.add(\"name1\", \"value1\");\n headers1.add(\"name2\", \"value2\");\n final HttpHeadersBase headers2 = newEmptyHeaders();\n headers1.add(\"name1\", \"value1\");\n assertThat(headers1).isNotEqualTo(headers2);\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public SecureIntrospector(String[] badClasses, String[] badPackages, Logger log)\n {\n super(badClasses, badPackages, log);\n\n this.secureClassMethods.add(\"getname\");\n this.secureClassMethods.add(\"getName\");\n this.secureClassMethods.add(\"getsimpleName\");\n this.secureClassMethods.add(\"getSimpleName\");\n\n this.secureClassMethods.add(\"isarray\");\n this.secureClassMethods.add(\"isArray\");\n this.secureClassMethods.add(\"isassignablefrom\");\n this.secureClassMethods.add(\"isAssignableFrom\");\n this.secureClassMethods.add(\"isenum\");\n this.secureClassMethods.add(\"isEnum\");\n this.secureClassMethods.add(\"isinstance\");\n this.secureClassMethods.add(\"isInstance\");\n this.secureClassMethods.add(\"isinterface\");\n this.secureClassMethods.add(\"isInterface\");\n this.secureClassMethods.add(\"islocalClass\");\n this.secureClassMethods.add(\"isLocalClass\");\n this.secureClassMethods.add(\"ismemberclass\");\n this.secureClassMethods.add(\"isMemberClass\");\n this.secureClassMethods.add(\"isprimitive\");\n this.secureClassMethods.add(\"isPrimitive\");\n this.secureClassMethods.add(\"issynthetic\");\n this.secureClassMethods.add(\"isSynthetic\");\n this.secureClassMethods.add(\"getEnumConstants\");\n\n // TODO: add more when needed\n }", "label_name": "CWE-668", "label": "668"} -{"code": " public void emptyHeaderNameNotAllowed() {\n newEmptyHeaders().add(\"\", \"foo\");\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void testEntryEquals() {\n final HttpHeadersBase nameValue = newEmptyHeaders();\n nameValue.add(\"name\", \"value\");\n final HttpHeadersBase nameValueCopy = newEmptyHeaders();\n nameValueCopy.add(\"name\", \"value\");\n final Map.Entry same1 = nameValue.iterator().next();\n final Map.Entry same2 = nameValueCopy.iterator().next();\n assertThat(same2).isEqualTo(same1);\n assertThat(same2.hashCode()).isEqualTo(same1.hashCode());\n\n final HttpHeadersBase name1Value = newEmptyHeaders();\n name1Value.add(\"name1\", \"value\");\n final HttpHeadersBase name2Value = newEmptyHeaders();\n name2Value.add(\"name2\", \"value\");\n final Map.Entry nameDifferent1 = name1Value.iterator().next();\n final Map.Entry nameDifferent2 = name2Value.iterator().next();\n assertThat(nameDifferent1).isNotEqualTo(nameDifferent2);\n assertThat(nameDifferent1.hashCode()).isNotEqualTo(nameDifferent2.hashCode());\n\n final HttpHeadersBase nameValue1 = newEmptyHeaders();\n nameValue1.add(\"name\", \"value1\");\n final HttpHeadersBase nameValue2 = newEmptyHeaders();\n nameValue2.add(\"name\", \"value2\");\n final Map.Entry valueDifferent1 = nameValue1.iterator().next();\n final Map.Entry valueDifferent2 = nameValue2.iterator().next();\n assertThat(valueDifferent1).isNotEqualTo(valueDifferent2);\n assertThat(valueDifferent1.hashCode()).isNotEqualTo(valueDifferent2.hashCode());\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void iteratorShouldReturnAllNameValuePairs() {\n final HttpHeadersBase headers1 = newEmptyHeaders();\n headers1.add(\"name1\", \"value1\", \"value2\");\n headers1.add(\"name2\", \"value3\");\n headers1.add(\"name3\", \"value4\", \"value5\", \"value6\");\n headers1.add(\"name1\", \"value7\", \"value8\");\n assertThat(headers1.size()).isEqualTo(8);\n\n final HttpHeadersBase headers2 = newEmptyHeaders();\n for (Map.Entry entry : headers1) {\n headers2.add(entry.getKey(), entry.getValue());\n }\n\n assertThat(headers2).isEqualTo(headers1);\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public static SSLSocketFactory getSslSocketFactory(Properties info) throws PSQLException {\n String classname = PGProperty.SSL_FACTORY.get(info);\n if (classname == null\n || \"org.postgresql.ssl.jdbc4.LibPQFactory\".equals(classname)\n || \"org.postgresql.ssl.LibPQFactory\".equals(classname)) {\n return new LibPQFactory(info);\n }\n try {\n return (SSLSocketFactory) ObjectFactory.instantiate(classname, info, true,\n PGProperty.SSL_FACTORY_ARG.get(info));\n } catch (Exception e) {\n throw new PSQLException(\n GT.tr(\"The SSLSocketFactory class provided {0} could not be instantiated.\", classname),\n PSQLState.CONNECTION_FAILURE, e);\n }\n }", "label_name": "CWE-665", "label": "665"} -{"code": " public void testAddSelf() {\n final HttpHeadersBase headers = newEmptyHeaders();\n headers.add(headers);\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void testUpdateUser() throws Exception {\n Set authorities = new HashSet();\n authorities.add(new JpaRole(\"ROLE_ASTRO_101_SPRING_2011_STUDENT\", org1));\n\n JpaUser user = new JpaUser(\"user1\", \"pass1\", org1, provider.getName(), true, authorities);\n provider.addUser(user);\n\n User loadUser = provider.loadUser(\"user1\");\n\n assertNotNull(loadUser);\n\n authorities.add(new JpaRole(\"ROLE_ASTRO_101_SPRING_2013_STUDENT\", org1));\n String newPassword = \"newPassword\";\n JpaUser updateUser = new JpaUser(user.getUsername(), newPassword, org1, provider.getName(), true, authorities);\n\n User loadUpdatedUser = provider.updateUser(updateUser);\n // User loadUpdatedUser = provider.loadUser(user.getUsername());\n\n assertNotNull(loadUpdatedUser);\n assertEquals(user.getUsername(), loadUpdatedUser.getUsername());\n assertEquals(PasswordEncoder.encode(newPassword, user.getUsername()), loadUpdatedUser.getPassword());\n assertEquals(authorities.size(), loadUpdatedUser.getRoles().size());\n\n updateUser = new JpaUser(\"unknown\", newPassword, org1, provider.getName(), true, authorities);\n\n try {\n provider.updateUser(updateUser);\n fail(\"Should throw a NotFoundException\");\n } catch (NotFoundException e) {\n assertTrue(\"User not found.\", true);\n }\n\n }", "label_name": "CWE-327", "label": "327"} -{"code": " /*package*/ static Secret tryDecrypt(Cipher cipher, byte[] in) throws UnsupportedEncodingException {\n try {\n String plainText = new String(cipher.doFinal(in), \"UTF-8\");\n if(plainText.endsWith(MAGIC))\n return new Secret(plainText.substring(0,plainText.length()-MAGIC.length()));\n return null;\n } catch (GeneralSecurityException e) {\n return null; // if the key doesn't match with the bytes, it can result in BadPaddingException\n }\n }", "label_name": "CWE-326", "label": "326"} -{"code": " public void complexExample() throws Exception {\n assertThat(ConstraintViolations.format(validator.validate(new ComplexExample())))\n .containsExactlyInAnyOrder(\n FAILED_RESULT + \"1\",\n FAILED_RESULT + \"2\",\n FAILED_RESULT + \"3\"\n );\n assertThat(TestLoggerFactory.getAllLoggingEvents())\n .isEmpty();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void validateFail3(ViolationCollector col) {\n col.addViolation(FAILED + \"3\");\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void translate(ServerStatisticsPacket packet, GeyserSession session) {\n session.updateStatistics(packet.getStatistics());\n\n if (session.isWaitingForStatistics()) {\n session.setWaitingForStatistics(false);\n StatisticsUtils.buildAndSendStatisticsMenu(session);\n }\n }", "label_name": "CWE-287", "label": "287"} -{"code": " protected boolean isProbablePrime(BigInteger x)\n {\n /*\n * Primes class for FIPS 186-4 C.3 primality checking\n */\n return !Primes.hasAnySmallFactors(x) && Primes.isMRProbablePrime(x, param.getRandom(), iterations);\n }", "label_name": "CWE-327", "label": "327"} -{"code": " callback: (request: PublishRequest, response: PublishResponse) => void;", "label_name": "CWE-400", "label": "400"} -{"code": "\tpublic static SecretKey decryptCEK(final SecretKey kek,\n\t\t\t\t\t final byte[] iv,\n\t\t\t\t\t final AuthenticatedCipherText authEncrCEK,\n\t\t\t\t\t final int keyLength,\n\t\t\t\t\t final Provider provider)\n\t\tthrows JOSEException {\n\n\t\tbyte[] keyBytes = AESGCM.decrypt(kek, iv, authEncrCEK.getCipherText(), new byte[0], authEncrCEK.getAuthenticationTag(), provider);\n\n\t\tif (ByteUtils.bitLength(keyBytes) != keyLength) {\n\n\t\t\tthrow new KeyLengthException(\"CEK key length mismatch: \" + ByteUtils.bitLength(keyBytes) + \" != \" + keyLength);\n\t\t}\n\n\t\treturn new SecretKeySpec(keyBytes, \"AES\");\n\t}", "label_name": "CWE-345", "label": "345"} -{"code": " public void translate(ServerEntityAttachPacket packet, GeyserSession session) {\n\n Entity holderId;\n if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {\n holderId = session.getPlayerEntity();\n } else {\n holderId = session.getEntityCache().getEntityByJavaId(packet.getEntityId());\n if (holderId == null) {\n return;\n }\n }\n\n Entity attachedToId;\n if (packet.getAttachedToId() == session.getPlayerEntity().getEntityId()) {\n attachedToId = session.getPlayerEntity();\n } else {\n attachedToId = session.getEntityCache().getEntityByJavaId(packet.getAttachedToId());\n if ((attachedToId == null || packet.getAttachedToId() == 0)) {\n // Is not being leashed\n holderId.getMetadata().getFlags().setFlag(EntityFlag.LEASHED, false);\n holderId.getMetadata().put(EntityData.LEASH_HOLDER_EID, -1L);\n holderId.updateBedrockMetadata(session);\n EntityEventPacket eventPacket = new EntityEventPacket();\n eventPacket.setRuntimeEntityId(holderId.getGeyserId());\n eventPacket.setType(EntityEventType.REMOVE_LEASH);\n eventPacket.setData(0);\n session.sendUpstreamPacket(eventPacket);\n return;\n }\n }\n\n holderId.getMetadata().getFlags().setFlag(EntityFlag.LEASHED, true);\n holderId.getMetadata().put(EntityData.LEASH_HOLDER_EID, attachedToId.getGeyserId());\n holderId.updateBedrockMetadata(session);\n }", "label_name": "CWE-287", "label": "287"} -{"code": " public void setShouldOverWritePreviousValue() {\n final HttpHeadersBase headers = newEmptyHeaders();\n headers.set(\"name\", \"value1\");\n headers.set(\"name\", \"value2\");\n assertThat(headers.size()).isEqualTo(1);\n assertThat(headers.getAll(\"name\").size()).isEqualTo(1);\n assertThat(headers.getAll(\"name\").get(0)).isEqualTo(\"value2\");\n assertThat(headers.get(\"name\")).isEqualTo(\"value2\");\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void validateConcreteScmMaterial(ValidationContext validationContext) {\n if (getView() == null || getView().trim().isEmpty()) {\n errors.add(VIEW, \"P4 view cannot be empty.\");\n }\n if (StringUtils.isBlank(getServerAndPort())) {\n errors.add(SERVER_AND_PORT, \"P4 port cannot be empty.\");\n }\n validateEncryptedPassword();\n }", "label_name": "CWE-77", "label": "77"} -{"code": " public String createSession(final String iDatabaseName, final String iUserName, final String iUserPassword) {\r\n acquireExclusiveLock();\r\n try {\r\n final String id = \"OS\" + System.currentTimeMillis() + random.nextLong();\r\n sessions.put(id, new OHttpSession(id, iDatabaseName, iUserName, iUserPassword));\r\n return id;\r\n\r\n } finally {\r\n releaseExclusiveLock();\r\n }\r\n }\r", "label_name": "CWE-200", "label": "200"} -{"code": " void validSave() throws Exception\n {\n when(mockClonedDocument.getRCSVersion()).thenReturn(new Version(\"1.2\"));\n when(mockClonedDocument.getComment()).thenReturn(\"My Changes\");\n when(mockClonedDocument.getLock(this.context)).thenReturn(mock(XWikiLock.class));\n when(mockForm.getTemplate()).thenReturn(\"\");\n assertFalse(saveAction.save(this.context));\n assertEquals(new Version(\"1.2\"), this.context.get(\"SaveAction.savedObjectVersion\"));\n\n verify(mockClonedDocument).readFromTemplate(\"\", this.context);\n verify(mockClonedDocument).setAuthor(\"XWiki.FooBar\");\n verify(mockClonedDocument).setMetaDataDirty(true);\n verify(this.xWiki).checkSavingDocument(USER_REFERENCE, mockClonedDocument, \"My Changes\", false, this.context);\n verify(this.xWiki).saveDocument(mockClonedDocument, \"My Changes\", false, this.context);\n verify(mockClonedDocument).removeLock(this.context);\n }", "label_name": "CWE-862", "label": "862"} -{"code": " public void translate(LoginSuccessPacket packet, GeyserSession session) {\n PlayerEntity playerEntity = session.getPlayerEntity();\n AuthType remoteAuthType = session.getRemoteAuthType();\n\n // Required, or else Floodgate players break with Spigot chunk caching\n GameProfile profile = packet.getProfile();\n playerEntity.setUsername(profile.getName());\n playerEntity.setUuid(profile.getId());\n\n // Check if they are not using a linked account\n if (remoteAuthType == AuthType.OFFLINE || playerEntity.getUuid().getMostSignificantBits() == 0) {\n SkinManager.handleBedrockSkin(playerEntity, session.getClientData());\n }\n\n if (remoteAuthType == AuthType.FLOODGATE) {\n // We'll send the skin upload a bit after the handshake packet (aka this packet),\n // because otherwise the global server returns the data too fast.\n session.getAuthData().upload(session.getConnector());\n }\n }", "label_name": "CWE-287", "label": "287"} -{"code": " public void authorizeRequest(Operation op) {\n op.complete();\n }", "label_name": "CWE-732", "label": "732"} -{"code": " default Optional findInt(CharSequence name) {\n return get(name, Integer.class);\n }", "label_name": "CWE-400", "label": "400"} -{"code": " public void translate(ServerStopSoundPacket packet, GeyserSession session) {\n // Runs if all sounds are stopped\n if (packet.getSound() == null) {\n StopSoundPacket stopPacket = new StopSoundPacket();\n stopPacket.setStoppingAllSound(true);\n stopPacket.setSoundName(\"\");\n session.sendUpstreamPacket(stopPacket);\n return;\n }\n\n String packetSound;\n if (packet.getSound() instanceof BuiltinSound) {\n packetSound = ((BuiltinSound) packet.getSound()).getName();\n } else if (packet.getSound() instanceof CustomSound) {\n packetSound = ((CustomSound) packet.getSound()).getName();\n } else {\n session.getConnector().getLogger().debug(\"Unknown sound packet, we were unable to map this. \" + packet.toString());\n return;\n }\n SoundMapping soundMapping = Registries.SOUNDS.get(packetSound.replace(\"minecraft:\", \"\"));\n session.getConnector().getLogger()\n .debug(\"[StopSound] Sound mapping \" + packetSound + \" -> \"\n + soundMapping + (soundMapping == null ? \"[not found]\" : \"\")\n + \" - \" + packet.toString());\n String playsound;\n if (soundMapping == null || soundMapping.getPlaysound() == null) {\n // no mapping\n session.getConnector().getLogger()\n .debug(\"[StopSound] Defaulting to sound server gave us.\");\n playsound = packetSound;\n } else {\n playsound = soundMapping.getPlaysound();\n }\n\n StopSoundPacket stopSoundPacket = new StopSoundPacket();\n stopSoundPacket.setSoundName(playsound);\n // packet not mapped in the library\n stopSoundPacket.setStoppingAllSound(false);\n\n session.sendUpstreamPacket(stopSoundPacket);\n session.getConnector().getLogger().debug(\"[StopSound] Packet sent - \" + packet.toString() + \" --> \" + stopSoundPacket);\n }", "label_name": "CWE-287", "label": "287"} -{"code": " public List search(final String filter, final Object[] filterArgs, final Mapper mapper, final int maxResultCount) {\n final List searchResults = new ArrayList<>();\n for (String searchBase : ldapConfiguration.getSearchBases()) {\n int resultsToFetch = resultsToFetch(maxResultCount, searchResults.size());\n\n if (resultsToFetch == -1) {\n break;\n }\n\n try {\n final SearchRequest searchRequest = new SearchRequestImpl()\n .setScope(SearchScope.SUBTREE)\n .addAttributes(\"*\")\n .setSizeLimit(resultsToFetch)\n .setFilter(format(filter, filterArgs))\n .setTimeLimit(ldapConfiguration.getSearchTimeout())\n .setBase(new Dn(searchBase));\n\n searchResults.addAll(ldapConnectionTemplate.search(searchRequest, mapper));\n } catch (LdapException e) {\n LOG.error(e.getMessage(), e);\n }\n }\n\n return searchResults;\n }", "label_name": "CWE-74", "label": "74"} -{"code": " final void add(CharSequence name, Iterable values) {\n final AsciiString normalizedName = normalizeName(name);\n requireNonNull(values, \"values\");\n final int h = normalizedName.hashCode();\n final int i = index(h);\n for (String v : values) {\n requireNonNullElement(values, v);\n add0(h, i, normalizedName, v);\n }\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void existingDocumentFromUITemplateProviderSpecifiedRestrictionExists() throws Exception\n {\n // current document = xwiki:Main.WebHome\n DocumentReference documentReference = new DocumentReference(\"xwiki\", Arrays.asList(\"Main\"), \"WebHome\");\n XWikiDocument document = mock(XWikiDocument.class);\n when(document.getDocumentReference()).thenReturn(documentReference);\n when(document.isNew()).thenReturn(false);\n when(document.getLocalReferenceMaxLength()).thenReturn(255);\n context.setDoc(document);\n\n // Submit from the UI spaceReference=X&name=Y&templateProvider=XWiki.MyTemplateProvider\n String templateProviderFullName = \"XWiki.MyTemplateProvider\";\n String spaceReferenceString = \"X\";\n when(mockRequest.getParameter(\"spaceReference\")).thenReturn(spaceReferenceString);\n when(mockRequest.getParameter(\"name\")).thenReturn(\"Y\");\n when(mockRequest.getParameter(\"templateprovider\")).thenReturn(templateProviderFullName);\n\n // Mock 1 existing template provider that allows usage in target space.\n mockExistingTemplateProviders(templateProviderFullName,\n new DocumentReference(\"xwiki\", Arrays.asList(\"XWiki\"), \"MyTemplateProvider\"), Arrays.asList(\"X\"));\n\n // Run the action\n String result = action.render(context);\n\n // The tests are below this line!\n\n // Verify null is returned (this means the response has been returned)\n assertNull(result);\n\n // Note1: We are allowed to create anything under space X, be it a terminal or a non-terminal document.\n // Note2: We are creating X.Y and using the template extracted from the template provider.\n verify(mockURLFactory).createURL(\"X.Y\", \"WebHome\", \"edit\",\n \"template=XWiki.MyTemplate&parent=Main.WebHome&title=Y\", null, \"xwiki\", context);\n }", "label_name": "CWE-862", "label": "862"} -{"code": " public void translate(ServerDisplayScoreboardPacket packet, GeyserSession session) {\n session.getWorldCache().getScoreboard()\n .displayObjective(packet.getName(), packet.getPosition());\n }", "label_name": "CWE-287", "label": "287"} -{"code": " private SecretKey getKey() {\n try {\n if (secret==null) {\n synchronized (this) {\n if (secret==null) {\n byte[] payload = load();\n if (payload==null) {\n payload = ConfidentialStore.get().randomBytes(256);\n store(payload);\n }\n // Due to the stupid US export restriction JDK only ships 128bit version.\n secret = new SecretKeySpec(payload,0,128/8, ALGORITHM);\n }\n }\n }\n return secret;\n } catch (IOException e) {\n throw new Error(\"Failed to load the key: \"+getId(),e);\n }\n }", "label_name": "CWE-326", "label": "326"} -{"code": " public int clone(ConsoleOutputStreamConsumer outputStreamConsumer, UrlArgument repositoryUrl) {\n CommandLine hg = createCommandLine(\"hg\").withArgs(\"clone\").withArg(\"-b\").withArg(branch).withArg(repositoryUrl)\n .withArg(workingDir.getAbsolutePath()).withNonArgSecrets(secrets).withEncoding(\"utf-8\");\n return execute(hg, outputStreamConsumer);\n }", "label_name": "CWE-77", "label": "77"} -{"code": " protected boolean isProbablePrime(BigInteger x, int iterations)\n {\n /*\n * Primes class for FIPS 186-4 C.3 primality checking\n */\n return !Primes.hasAnySmallFactors(x) && Primes.isMRProbablePrime(x, param.getRandom(), iterations);\n }", "label_name": "CWE-327", "label": "327"} -{"code": " public void translate(ServerEntityCollectItemPacket packet, GeyserSession session) {\n // Collected entity is the other entity\n Entity collectedEntity = session.getEntityCache().getEntityByJavaId(packet.getCollectedEntityId());\n if (collectedEntity == null) return;\n // Collector is the entity 'picking up' the item\n Entity collectorEntity;\n if (packet.getCollectorEntityId() == session.getPlayerEntity().getEntityId()) {\n collectorEntity = session.getPlayerEntity();\n } else {\n collectorEntity = session.getEntityCache().getEntityByJavaId(packet.getCollectorEntityId());\n }\n if (collectorEntity == null) return;\n if (collectedEntity instanceof ExpOrbEntity) {\n // Player just picked up an experience orb\n LevelEventPacket xpPacket = new LevelEventPacket();\n xpPacket.setType(LevelEventType.SOUND_EXPERIENCE_ORB_PICKUP);\n xpPacket.setPosition(collectedEntity.getPosition());\n xpPacket.setData(0);\n session.sendUpstreamPacket(xpPacket);\n } else {\n // Item is being picked up (visual only)\n TakeItemEntityPacket takeItemEntityPacket = new TakeItemEntityPacket();\n takeItemEntityPacket.setRuntimeEntityId(collectorEntity.getGeyserId());\n takeItemEntityPacket.setItemRuntimeEntityId(collectedEntity.getGeyserId());\n session.sendUpstreamPacket(takeItemEntityPacket);\n }\n }", "label_name": "CWE-287", "label": "287"} -{"code": " private boolean isAdmin(String accountName) {\n if (this.adminFilter != null) {\n try {\n InitialDirContext context = initContext();\n String searchString = adminFilter.replace(\":login\", accountName);\n SearchControls searchControls = new SearchControls();\n searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);\n NamingEnumeration results = context.search(searchBase, searchString, searchControls);\n if (results.hasMoreElements()) {\n results.nextElement();\n if (results.hasMoreElements()) {\n LOGGER.warn(\"Matched multiple users for the accountName: \" + accountName);\n return false;\n }\n return true;\n }\n } catch (NamingException e) {\n return false;\n }\n }\n return false;\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void translate(ServerSpawnPositionPacket packet, GeyserSession session) {\n SetSpawnPositionPacket spawnPositionPacket = new SetSpawnPositionPacket();\n spawnPositionPacket.setBlockPosition(Vector3i.from(packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ()));\n spawnPositionPacket.setSpawnForced(true);\n spawnPositionPacket.setDimensionId(DimensionUtils.javaToBedrock(session.getDimension()));\n spawnPositionPacket.setSpawnType(SetSpawnPositionPacket.Type.WORLD_SPAWN);\n session.sendUpstreamPacket(spawnPositionPacket);\n }", "label_name": "CWE-287", "label": "287"} -{"code": " public void testSetSelfIsNoOp() {\n final HttpHeadersBase headers = newEmptyHeaders();\n headers.add(\"name\", \"value\");\n headers.set(headers);\n assertThat(headers.size()).isEqualTo(1);\n }", "label_name": "CWE-74", "label": "74"} -{"code": " final void set(CharSequence name, String... values) {\n final AsciiString normalizedName = normalizeName(name);\n requireNonNull(values, \"values\");\n\n final int h = normalizedName.hashCode();\n final int i = index(h);\n\n remove0(h, i, normalizedName);\n for (String v : values) {\n requireNonNullElement(values, v);\n add0(h, i, normalizedName, v);\n }\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void translate(ServerExplosionPacket packet, GeyserSession session) {\n for (ExplodedBlockRecord record : packet.getExploded()) {\n Vector3f pos = Vector3f.from(packet.getX() + record.getX(), packet.getY() + record.getY(), packet.getZ() + record.getZ());\n ChunkUtils.updateBlock(session, BlockStateValues.JAVA_AIR_ID, pos.toInt());\n }\n\n Vector3f pos = Vector3f.from(packet.getX(), packet.getY(), packet.getZ());\n // Since bedrock does not play an explosion sound and particles sound, we have to manually do so\n LevelEventPacket levelEventPacket = new LevelEventPacket();\n levelEventPacket.setType(packet.getRadius() >= 2.0f ? LevelEventType.PARTICLE_HUGE_EXPLODE : LevelEventType.PARTICLE_EXPLOSION);\n levelEventPacket.setData(0);\n levelEventPacket.setPosition(pos.toFloat());\n session.sendUpstreamPacket(levelEventPacket);\n\n LevelSoundEventPacket levelSoundEventPacket = new LevelSoundEventPacket();\n levelSoundEventPacket.setRelativeVolumeDisabled(false);\n levelSoundEventPacket.setBabySound(false);\n levelSoundEventPacket.setExtraData(-1);\n levelSoundEventPacket.setSound(SoundEvent.EXPLODE);\n levelSoundEventPacket.setIdentifier(\":\");\n levelSoundEventPacket.setPosition(Vector3f.from(packet.getX(), packet.getY(), packet.getZ()));\n session.sendUpstreamPacket(levelSoundEventPacket);\n\n if (packet.getPushX() > 0f || packet.getPushY() > 0f || packet.getPushZ() > 0f) {\n SetEntityMotionPacket motionPacket = new SetEntityMotionPacket();\n motionPacket.setRuntimeEntityId(session.getPlayerEntity().getGeyserId());\n motionPacket.setMotion(Vector3f.from(packet.getPushX(), packet.getPushY(), packet.getPushZ()));\n session.sendUpstreamPacket(motionPacket);\n }\n }", "label_name": "CWE-287", "label": "287"} -{"code": " public void afterClearHeadersShouldBeEmpty() {\n final HttpHeadersBase headers = newEmptyHeaders();\n headers.add(\"name1\", \"value1\");\n headers.add(\"name2\", \"value2\");\n assertThat(headers.size()).isEqualTo(2);\n headers.clear();\n assertThat(headers.size()).isEqualTo(0);\n assertThat(headers.isEmpty()).isTrue();\n assertThat(headers.contains(\"name1\")).isFalse();\n assertThat(headers.contains(\"name2\")).isFalse();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " private File doDownload(String driverFileUrl, String filePath) {\n Path path = Path.of(filePath);\n\n // create parent directory\n if (Files.notExists(path)) {\n path.getParent().toFile().mkdirs();\n try {\n Files.createFile(path);\n } catch (IOException e) {\n log.error(\"create file error \" + filePath, e);\n throw DomainErrors.DOWNLOAD_DRIVER_ERROR.exception(e.getMessage());\n }\n }\n\n // download\n try {\n return restTemplate.execute(driverFileUrl, HttpMethod.GET, null, response -> {\n if (response.getStatusCode().is2xxSuccessful()) {\n File file = path.toFile();\n FileOutputStream out = new FileOutputStream(file);\n StreamUtils.copy(response.getBody(), out);\n IOUtils.closeQuietly(out, ex -> log.error(\"close file error\", ex));\n log.info(\"{} download success \", filePath);\n return file;\n } else {\n log.error(\"{} download error from {}: {} \", filePath, driverFileUrl, response);\n throw DomainErrors.DOWNLOAD_DRIVER_ERROR.exception(\"\u9a71\u52a8\u4e0b\u8f7d\u5931\u8d25\uff1a\"\n + response.getStatusCode()\n + \", \"\n + response.getStatusText());\n }\n });\n } catch (IllegalArgumentException e) {\n log.error(filePath + \" download driver error\", e);\n throw DomainErrors.DOWNLOAD_DRIVER_ERROR.exception(e.getMessage());\n }\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public Argument argumentType() {\n return Argument.of(Publisher.class);\n }", "label_name": "CWE-400", "label": "400"} -{"code": " public void existingDocumentFromUITemplateProviderSpecifiedNonTerminal() throws Exception\n {\n // current document = xwiki:Main.WebHome\n DocumentReference documentReference = new DocumentReference(\"xwiki\", Arrays.asList(\"Main\"), \"WebHome\");\n XWikiDocument document = mock(XWikiDocument.class);\n when(document.getDocumentReference()).thenReturn(documentReference);\n when(document.isNew()).thenReturn(false);\n when(document.getLocalReferenceMaxLength()).thenReturn(255);\n context.setDoc(document);\n\n // Submit from the UI spaceReference=X&name=Y&templateProvider=XWiki.MyTemplateProvider\n String templateProviderFullName = \"XWiki.MyTemplateProvider\";\n String spaceReferenceString = \"X\";\n when(mockRequest.getParameter(\"spaceReference\")).thenReturn(spaceReferenceString);\n when(mockRequest.getParameter(\"name\")).thenReturn(\"Y\");\n when(mockRequest.getParameter(\"templateprovider\")).thenReturn(templateProviderFullName);\n\n // Mock 1 existing template provider that creates terminal documents.\n mockExistingTemplateProviders(templateProviderFullName,\n new DocumentReference(\"xwiki\", Arrays.asList(\"XWiki\"), \"MyTemplateProvider\"), Collections.EMPTY_LIST,\n false);\n\n // Run the action\n String result = action.render(context);\n\n // The tests are below this line!\n\n // Verify null is returned (this means the response has been returned)\n assertNull(result);\n\n // Note: We are creating the document X.Y.WebHome as non-terminal and using a template, as specified in the\n // template provider.\n verify(mockURLFactory).createURL(\"X.Y\", \"WebHome\", \"edit\",\n \"template=XWiki.MyTemplate&parent=Main.WebHome&title=Y\", null, \"xwiki\", context);\n }", "label_name": "CWE-862", "label": "862"} -{"code": " public void translate(ServerOpenWindowPacket packet, GeyserSession session) {\n if (packet.getWindowId() == 0) {\n return;\n }\n\n InventoryTranslator newTranslator = InventoryTranslator.INVENTORY_TRANSLATORS.get(packet.getType());\n Inventory openInventory = session.getOpenInventory();\n //No translator exists for this window type. Close all windows and return.\n if (newTranslator == null) {\n if (openInventory != null) {\n InventoryUtils.closeInventory(session, openInventory.getId(), true);\n }\n ClientCloseWindowPacket closeWindowPacket = new ClientCloseWindowPacket(packet.getWindowId());\n session.sendDownstreamPacket(closeWindowPacket);\n return;\n }\n\n String name = MessageTranslator.convertMessageLenient(packet.getName(), session.getLocale());\n name = LocaleUtils.getLocaleString(name, session.getLocale());\n\n Inventory newInventory = newTranslator.createInventory(name, packet.getWindowId(), packet.getType(), session.getPlayerInventory());\n if (openInventory != null) {\n // If the window type is the same, don't close.\n // In rare cases, inventories can do funny things where it keeps the same window type up but change the contents.\n if (openInventory.getWindowType() != packet.getType()) {\n // Sometimes the server can double-open an inventory with the same ID - don't confirm in that instance.\n InventoryUtils.closeInventory(session, openInventory.getId(), openInventory.getId() != packet.getWindowId());\n }\n }\n\n session.setInventoryTranslator(newTranslator);\n InventoryUtils.openInventory(session, newInventory);\n }", "label_name": "CWE-287", "label": "287"} -{"code": " public void testNotThrowWhenConvertFails() {\n final HttpHeadersBase headers = newEmptyHeaders();\n headers.set(\"name1\", \"\");\n assertThat(headers.getInt(\"name1\")).isNull();\n assertThat(headers.getInt(\"name1\", 1)).isEqualTo(1);\n\n assertThat(headers.getDouble(\"name\")).isNull();\n assertThat(headers.getDouble(\"name1\", 1)).isEqualTo(1);\n\n assertThat(headers.getFloat(\"name\")).isNull();\n assertThat(headers.getFloat(\"name1\", Float.MAX_VALUE)).isEqualTo(Float.MAX_VALUE);\n\n assertThat(headers.getLong(\"name\")).isNull();\n assertThat(headers.getLong(\"name1\", Long.MAX_VALUE)).isEqualTo(Long.MAX_VALUE);\n\n assertThat(headers.getTimeMillis(\"name\")).isNull();\n assertThat(headers.getTimeMillis(\"name1\", Long.MAX_VALUE)).isEqualTo(Long.MAX_VALUE);\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void newDocumentFromURL() throws Exception\n {\n // new document = xwiki:X.Y\n DocumentReference documentReference = new DocumentReference(\"xwiki\", Arrays.asList(\"X\"), \"Y\");\n XWikiDocument document = mock(XWikiDocument.class);\n when(document.getDocumentReference()).thenReturn(documentReference);\n when(document.isNew()).thenReturn(true);\n when(document.getLocalReferenceMaxLength()).thenReturn(255);\n context.setDoc(document);\n\n // Run the action\n String result = action.render(context);\n\n // The tests are below this line!\n\n // Verify null is returned (this means the response has been returned)\n assertNull(result);\n\n verify(mockURLFactory).createURL(\"X\", \"Y\", \"edit\", \"template=&parent=Main.WebHome&title=Y\", null, \"xwiki\",\n context);\n }", "label_name": "CWE-862", "label": "862"} -{"code": " public void testOfCharSequence() {\n // Should produce a lower-cased AsciiString.\n assertThat((Object) HttpHeaderNames.of(\"Foo\")).isEqualTo(AsciiString.of(\"foo\"));\n\n // Should reuse known header name instances.\n assertThat((Object) HttpHeaderNames.of(\"date\")).isSameAs(HttpHeaderNames.DATE);\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void newDocumentWebHomeButTerminalFromURL() throws Exception\n {\n // new document = xwiki:X.Y.WebHome\n DocumentReference documentReference = new DocumentReference(\"xwiki\", Arrays.asList(\"X\", \"Y\"), \"WebHome\");\n XWikiDocument document = mock(XWikiDocument.class);\n when(document.getDocumentReference()).thenReturn(documentReference);\n when(document.isNew()).thenReturn(true);\n when(document.getLocalReferenceMaxLength()).thenReturn(255);\n context.setDoc(document);\n\n // Pass the tocreate=terminal request parameter\n when(mockRequest.getParameter(\"tocreate\")).thenReturn(\"terminal\");\n\n // Run the action\n String result = action.render(context);\n\n // The tests are below this line!\n\n // Verify null is returned (this means the response has been returned)\n assertNull(result);\n\n // Note: We are creating X.Y instead of X.Y.WebHome because the tocreate parameter says \"terminal\".\n verify(mockURLFactory).createURL(\"X\", \"Y\", \"edit\", \"template=&parent=Main.WebHome&title=Y\", null, \"xwiki\",\n context);\n }", "label_name": "CWE-862", "label": "862"} -{"code": " default List getPermissions() {\n List permissions = new ArrayList<>();\n permissions.add(\"*:*\");\n permissions.add(this.getName().replace('_', ':'));\n permissions.add(this.getName().substring(0, this.getName().indexOf('_')) + \":*\");\n return permissions;\n };", "label_name": "CWE-400", "label": "400"} -{"code": " public User getUser() {\n return user;\n }", "label_name": "CWE-200", "label": "200"} -{"code": " final void set(CharSequence name, Iterable values) {\n final AsciiString normalizedName = normalizeName(name);\n requireNonNull(values, \"values\");\n\n final int h = normalizedName.hashCode();\n final int i = index(h);\n\n remove0(h, i, normalizedName);\n for (String v : values) {\n requireNonNullElement(values, v);\n add0(h, i, normalizedName, v);\n }\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void setAllShouldOverwriteSomeAndLeaveOthersUntouched() {\n final HttpHeadersBase h1 = newEmptyHeaders();\n\n h1.add(\"name1\", \"value1\");\n h1.add(\"name2\", \"value2\");\n h1.add(\"name2\", \"value3\");\n h1.add(\"name3\", \"value4\");\n\n final HttpHeadersBase h2 = newEmptyHeaders();\n h2.add(\"name1\", \"value5\");\n h2.add(\"name2\", \"value6\");\n h2.add(\"name1\", \"value7\");\n\n final HttpHeadersBase expected = newEmptyHeaders();\n expected.add(\"name1\", \"value5\");\n expected.add(\"name2\", \"value6\");\n expected.add(\"name1\", \"value7\");\n expected.add(\"name3\", \"value4\");\n\n h1.set(h2);\n\n assertThat(h1).isEqualTo(expected);\n }", "label_name": "CWE-74", "label": "74"} -{"code": "\tpublic static byte[] computeLength(final byte[] aad) {\n\n\t\tfinal int bitLength = ByteUtils.bitLength(aad);\n\t\treturn ByteBuffer.allocate(8).putLong(bitLength).array();\n\t}", "label_name": "CWE-345", "label": "345"} -{"code": " public void translate(ServerEntityPositionRotationPacket packet, GeyserSession session) {\n Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());\n if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {\n entity = session.getPlayerEntity();\n }\n if (entity == null) return;\n\n entity.updatePositionAndRotation(session, packet.getMoveX(), packet.getMoveY(), packet.getMoveZ(), packet.getYaw(), packet.getPitch(), packet.isOnGround());\n }", "label_name": "CWE-287", "label": "287"} -{"code": " public void multipleValuesPerNameIterator() {\n final HttpHeadersBase headers = newEmptyHeaders();\n headers.add(\"name1\", \"value1\");\n headers.add(\"name1\", \"value2\");\n assertThat(headers.size()).isEqualTo(2);\n\n final List values = ImmutableList.copyOf(headers.valueIterator(\"name1\"));\n assertThat(values).containsExactly(\"value1\", \"value2\");\n }", "label_name": "CWE-74", "label": "74"} -{"code": " protected OHttpSessionManager() {\r\n expirationTime = OGlobalConfiguration.NETWORK_HTTP_SESSION_EXPIRE_TIMEOUT.getValueAsInteger() * 1000;\r\n\r\n Orient.instance().scheduleTask(new TimerTask() {\r\n @Override\r\n public void run() {\r\n final int expired = checkSessionsValidity();\r\n if (expired > 0)\r\n OLogManager.instance().debug(this, \"Removed %d session because expired\", expired);\r\n }\r\n }, expirationTime, expirationTime);\r\n }\r", "label_name": "CWE-200", "label": "200"} -{"code": " public void shouldCloneFromRemoteRepo() {\n assertThat(clientRepo.listFiles().length > 0, is(true));\n }", "label_name": "CWE-77", "label": "77"} -{"code": " public void handle(final HttpServletRequest request, final HttpServletResponse response)\n throws Exception\n {\n new ContextualHttpServletRequest(request)\n {\n @Override\n public void process() throws Exception\n {\n ServletContexts.instance().setRequest(request);\n \n if (request.getQueryString() == null)\n {\n throw new ServletException(\"Invalid request - no component specified\");\n }\n \n Set components = new HashSet();\n Set types = new HashSet();\n \n response.setContentType(\"text/javascript\");\n\n Enumeration e = request.getParameterNames();\n while (e.hasMoreElements())\n {\n String componentName = ((String) e.nextElement()).trim();\n \n Component component = Component.forName(componentName);\n if (component == null)\n { \n try\n {\n Class c = Reflections.classForName(componentName);\n appendClassSource(response.getOutputStream(), c, types);\n }\n catch (ClassNotFoundException ex)\n {\n log.error(String.format(\"Component not found: [%s]\", componentName));\n throw new ServletException(\"Invalid request - component not found.\");\n }\n }\n else\n {\n components.add(component);\n }\n }\n \n generateComponentInterface(components, response.getOutputStream(), types); \n }\n }.run();\n }", "label_name": "CWE-200", "label": "200"} -{"code": " setImmediate(() => {\n if (!this.pendingPublishRequestCount) {\n return;\n }\n const starving_subscription = this._find_starving_subscription();\n if (starving_subscription) {\n doDebug && debugLog(chalk.bgWhite.red(\"feeding most late subscription subscriptionId = \"), starving_subscription.id);\n starving_subscription.process_subscription();\n }\n });", "label_name": "CWE-400", "label": "400"} -{"code": " public void setHeadersShouldClearAndOverwrite() {\n final HttpHeadersBase headers1 = newEmptyHeaders();\n headers1.add(\"name\", \"value\");\n\n final HttpHeadersBase headers2 = newEmptyHeaders();\n headers2.add(\"name\", \"newvalue\");\n headers2.add(\"name1\", \"value1\");\n\n headers1.set(headers2);\n assertThat(headers2).isEqualTo(headers1);\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void shouldNotIncludeCommitFromAnotherBranchInGetLatestModifications() throws Exception {\n Modification lastCommit = hgCommand.latestOneModificationAsModifications().get(0);\n\n makeACommitToSecondBranch();\n hg(workingDirectory, \"pull\").runOrBomb(null);\n Modification actual = hgCommand.latestOneModificationAsModifications().get(0);\n assertThat(actual, is(lastCommit));\n assertThat(actual.getComment(), is(lastCommit.getComment()));\n }", "label_name": "CWE-77", "label": "77"} -{"code": " public void iteratorSetShouldFail() {\n final HttpHeadersBase headers = newEmptyHeaders();\n headers.add(\"name1\", \"value1\", \"value2\", \"value3\");\n headers.add(\"name2\", \"value4\");\n assertThat(headers.size()).isEqualTo(4);\n\n assertThatThrownBy(() -> headers.iterator().next().setValue(\"\"))\n .isInstanceOf(UnsupportedOperationException.class);\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public static Secret decrypt(String data) {\n if(data==null) return null;\n try {\n byte[] in = Base64.decode(data.toCharArray());\n Secret s = tryDecrypt(KEY.decrypt(), in);\n if (s!=null) return s;\n\n // try our historical key for backward compatibility\n Cipher cipher = getCipher(\"AES\");\n cipher.init(Cipher.DECRYPT_MODE, getLegacyKey());\n return tryDecrypt(cipher, in);\n } catch (GeneralSecurityException e) {\n return null;\n } catch (UnsupportedEncodingException e) {\n throw new Error(e); // impossible\n } catch (IOException e) {\n return null;\n }\n }", "label_name": "CWE-326", "label": "326"} -{"code": " public void existingDocumentFromUITemplateProviderSpecifiedButOldSpaceType() throws Exception\n {\n // current document = xwiki:Main.WebHome\n DocumentReference documentReference = new DocumentReference(\"xwiki\", Arrays.asList(\"Main\"), \"WebHome\");\n XWikiDocument document = mock(XWikiDocument.class);\n when(document.getDocumentReference()).thenReturn(documentReference);\n when(document.isNew()).thenReturn(false);\n when(document.getLocalReferenceMaxLength()).thenReturn(255);\n context.setDoc(document);\n\n // Submit from the UI spaceReference=X&name=Y&templateProvider=XWiki.MyTemplateProvider\n String templateProviderFullName = \"XWiki.MyTemplateProvider\";\n when(mockRequest.getParameter(\"spaceReference\")).thenReturn(\"X\");\n when(mockRequest.getParameter(\"name\")).thenReturn(\"Y\");\n when(mockRequest.getParameter(\"templateprovider\")).thenReturn(templateProviderFullName);\n\n // Mock 1 existing template provider\n mockExistingTemplateProviders(templateProviderFullName,\n new DocumentReference(\"xwiki\", Arrays.asList(\"XWiki\"), \"MyTemplateProvider\"), Collections.EMPTY_LIST, null,\n \"space\");\n\n // Run the action\n String result = action.render(context);\n\n // The tests are below this line!\n\n // Verify null is returned (this means the response has been returned)\n assertNull(result);\n\n // Note: We are creating X.Y.WebHome as non-terminal, since the template provider does not specify a \"terminal\"\n // property and we fallback on the \"type\" property's value. Also using the template extracted from the template\n // provider.\n verify(mockURLFactory).createURL(\"X.Y\", \"WebHome\", \"edit\",\n \"template=XWiki.MyTemplate&parent=Main.WebHome&title=Y\", null, \"xwiki\", context);\n }", "label_name": "CWE-862", "label": "862"} -{"code": " public void whenNameContainsMultipleValuesGetShouldReturnTheFirst() {\n final HttpHeadersBase headers = newEmptyHeaders();\n headers.add(\"name1\", \"value1\", \"value2\");\n assertThat(headers.get(\"name1\")).isEqualTo(\"value1\");\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void testOfAsciiString() {\n // Should produce a lower-cased AsciiString.\n final AsciiString mixedCased = AsciiString.of(\"Foo\");\n assertThat((Object) HttpHeaderNames.of(mixedCased)).isNotSameAs(mixedCased);\n assertThat(HttpHeaderNames.of(mixedCased).toString()).isEqualTo(\"foo\");\n\n // Should not produce a new instance for an AsciiString that's already lower-cased.\n final AsciiString lowerCased = AsciiString.of(\"foo\");\n assertThat((Object) HttpHeaderNames.of(lowerCased)).isSameAs(lowerCased);\n\n // Should reuse known header name instances.\n assertThat((Object) HttpHeaderNames.of(AsciiString.of(\"date\"))).isSameAs(HttpHeaderNames.DATE);\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void newDocumentWebHomeFromURLTemplateProviderSpecifiedTerminal() throws Exception\n {\n // new document = xwiki:X.Y.WebHome\n DocumentReference documentReference = new DocumentReference(\"xwiki\", Arrays.asList(\"X\", \"Y\"), \"WebHome\");\n XWikiDocument document = mock(XWikiDocument.class);\n when(document.getDocumentReference()).thenReturn(documentReference);\n when(document.isNew()).thenReturn(true);\n when(document.getLocalReferenceMaxLength()).thenReturn(255);\n context.setDoc(document);\n\n // Specifying a template provider in the URL: templateprovider=XWiki.MyTemplateProvider\n String templateProviderFullName = \"XWiki.MyTemplateProvider\";\n when(mockRequest.getParameter(\"templateprovider\")).thenReturn(templateProviderFullName);\n\n // Mock 1 existing template provider\n mockExistingTemplateProviders(templateProviderFullName,\n new DocumentReference(\"xwiki\", Arrays.asList(\"XWiki\"), \"MyTemplateProvider\"), Collections.EMPTY_LIST, true);\n\n // Run the action\n String result = action.render(context);\n\n // The tests are below this line!\n\n // Verify null is returned (this means the response has been returned)\n assertNull(result);\n\n // Note: We are creating the document X.Y as terminal and using a template, as specified in the template\n // provider.\n verify(mockURLFactory).createURL(\"X\", \"Y\", \"edit\", \"template=XWiki.MyTemplate&parent=Main.WebHome&title=Y\",\n null, \"xwiki\", context);\n }", "label_name": "CWE-862", "label": "862"} -{"code": " public void correctExample() throws Exception {\n assertThat(ConstraintViolations.format(validator.validate(new CorrectExample())))\n .isEmpty();\n assertThat(TestLoggerFactory.getAllLoggingEvents())\n .isEmpty();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " protected final void populateUrlAttributeMap(final Map urlParameters) {\n urlParameters.put(\"pgtUrl\", encodeUrl(this.proxyCallbackUrl));\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void annotatedSubClassExample() throws Exception {\n assertThat(ConstraintViolations.format(validator.validate(new AnnotatedSubclassExample())))\n .containsExactlyInAnyOrder(\n FAILED_RESULT,\n FAILED_RESULT+\"subclass\"\n );\n assertThat(TestLoggerFactory.getAllLoggingEvents())\n .isEmpty();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " void setup()\n {\n this.saveAction = new SaveAction();\n\n context = oldcore.getXWikiContext();\n\n xWiki = mock(XWiki.class);\n context.setWiki(this.xWiki);\n\n mockRequest = mock(XWikiRequest.class);\n context.setRequest(mockRequest);\n\n mockResponse = mock(XWikiResponse.class);\n context.setResponse(mockResponse);\n\n mockDocument = mock(XWikiDocument.class);\n context.setDoc(mockDocument);\n\n mockClonedDocument = mock(XWikiDocument.class);\n when(mockDocument.clone()).thenReturn(mockClonedDocument);\n\n mockForm = mock(EditForm.class);\n context.setForm(mockForm);\n when(this.entityNameValidationConfiguration.useValidation()).thenReturn(false);\n\n context.setUserReference(USER_REFERENCE);\n }", "label_name": "CWE-862", "label": "862"} -{"code": " protected void afterFeaturesReceived() throws SecurityRequiredException, NotConnectedException {\n StartTls startTlsFeature = getFeature(StartTls.ELEMENT, StartTls.NAMESPACE);\n if (startTlsFeature != null) {\n if (startTlsFeature.required() && config.getSecurityMode() == SecurityMode.disabled) {\n notifyConnectionError(new SecurityRequiredByServerException());\n return;\n }\n\n if (config.getSecurityMode() != ConnectionConfiguration.SecurityMode.disabled) {\n send(new StartTls());\n }\n }\n // If TLS is required but the server doesn't offer it, disconnect\n // from the server and throw an error. First check if we've already negotiated TLS\n // and are secure, however (features get parsed a second time after TLS is established).\n if (!isSecureConnection() && startTlsFeature == null\n && getConfiguration().getSecurityMode() == SecurityMode.required) {\n throw new SecurityRequiredByClientException();\n }\n\n if (getSASLAuthentication().authenticationSuccessful()) {\n // If we have received features after the SASL has been successfully completed, then we\n // have also *maybe* received, as it is an optional feature, the compression feature\n // from the server.\n maybeCompressFeaturesReceived.reportSuccess();\n }\n }", "label_name": "CWE-362", "label": "362"} -{"code": " public void addViolation(String msg) {\n violationOccurred = true;\n context.buildConstraintViolationWithTemplate(msg)\n .addConstraintViolation();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void translate(CommandBlockUpdatePacket packet, GeyserSession session) {\n String command = packet.getCommand();\n boolean outputTracked = packet.isOutputTracked();\n if (packet.isBlock()) {\n CommandBlockMode mode;\n switch (packet.getMode()) {\n case CHAIN: // The green one\n mode = CommandBlockMode.SEQUENCE;\n break;\n case REPEATING: // The purple one\n mode = CommandBlockMode.AUTO;\n break;\n default: // NORMAL, the orange one\n mode = CommandBlockMode.REDSTONE;\n break;\n }\n boolean isConditional = packet.isConditional();\n boolean automatic = !packet.isRedstoneMode(); // Automatic = Always Active option in Java\n ClientUpdateCommandBlockPacket commandBlockPacket = new ClientUpdateCommandBlockPacket(\n new Position(packet.getBlockPosition().getX(), packet.getBlockPosition().getY(), packet.getBlockPosition().getZ()),\n command, mode, outputTracked, isConditional, automatic);\n session.sendDownstreamPacket(commandBlockPacket);\n } else {\n ClientUpdateCommandBlockMinecartPacket commandMinecartPacket = new ClientUpdateCommandBlockMinecartPacket(\n (int) session.getEntityCache().getEntityByGeyserId(packet.getMinecartRuntimeEntityId()).getEntityId(),\n command, outputTracked\n );\n session.sendDownstreamPacket(commandMinecartPacket);\n }\n }", "label_name": "CWE-287", "label": "287"} -{"code": " private DocumentReferenceResolver getCurrentMixedDocumentReferenceResolver()\n {\n return Utils.getComponent(DocumentReferenceResolver.TYPE_STRING, CURRENT_MIXED_RESOLVER_HINT);\n }", "label_name": "CWE-862", "label": "862"} -{"code": " public void translate(ServerOpenHorseWindowPacket packet, GeyserSession session) {\n Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());\n if (entity == null) {\n return;\n }\n\n UpdateEquipPacket updateEquipPacket = new UpdateEquipPacket();\n updateEquipPacket.setWindowId((short) packet.getWindowId());\n updateEquipPacket.setWindowType((short) ContainerType.HORSE.getId());\n updateEquipPacket.setUniqueEntityId(entity.getGeyserId());\n\n NbtMapBuilder builder = NbtMap.builder();\n List slots = new ArrayList<>();\n\n InventoryTranslator inventoryTranslator;\n if (entity instanceof LlamaEntity) {\n inventoryTranslator = new LlamaInventoryTranslator(packet.getNumberOfSlots());\n slots.add(CARPET_SLOT);\n } else if (entity instanceof ChestedHorseEntity) {\n inventoryTranslator = new DonkeyInventoryTranslator(packet.getNumberOfSlots());\n slots.add(SADDLE_SLOT);\n } else {\n inventoryTranslator = new HorseInventoryTranslator(packet.getNumberOfSlots());\n slots.add(SADDLE_SLOT);\n slots.add(ARMOR_SLOT);\n }\n\n // Build the NbtMap that sets the icons for Bedrock (e.g. sets the saddle outline on the saddle slot)\n builder.putList(\"slots\", NbtType.COMPOUND, slots);\n\n updateEquipPacket.setTag(builder.build());\n session.sendUpstreamPacket(updateEquipPacket);\n\n session.setInventoryTranslator(inventoryTranslator);\n InventoryUtils.openInventory(session, new Container(entity.getMetadata().getString(EntityData.NAMETAG), packet.getWindowId(), packet.getNumberOfSlots(), null, session.getPlayerInventory()));\n }", "label_name": "CWE-287", "label": "287"} -{"code": " public void shouldThrowExceptionForBadConnection() throws Exception {\n String url = \"http://not-exists\";\n HgCommand hgCommand = new HgCommand(null, null, null, null, null);\n\n assertThatThrownBy(() -> hgCommand.checkConnection(new UrlArgument(url)))\n .isExactlyInstanceOf(CommandLineException.class);\n }", "label_name": "CWE-77", "label": "77"} -{"code": " public void getPermissions() {\n List permissions = method.getPermissions();\n assertThat(permissions).containsExactlyInAnyOrder(\"net:*\", \"net:listening\", \"*:*\");\n }", "label_name": "CWE-400", "label": "400"} -{"code": " private static AsciiString normalizeName(CharSequence name) {\n checkArgument(requireNonNull(name, \"name\").length() > 0, \"name is empty.\");\n return HttpHeaderNames.of(name);\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void testAddAndGetUser() throws Exception {\n JpaUser user = createUserWithRoles(org1, \"user1\", \"ROLE_ASTRO_101_SPRING_2011_STUDENT\");\n provider.addUser(user);\n\n User loadUser = provider.loadUser(\"user1\");\n assertNotNull(loadUser);\n\n assertEquals(user.getUsername(), loadUser.getUsername());\n assertEquals(PasswordEncoder.encode(user.getPassword(), user.getUsername()), loadUser.getPassword());\n assertEquals(user.getOrganization(), loadUser.getOrganization());\n assertEquals(user.getRoles(), loadUser.getRoles());\n\n assertNull(\"Loading 'does not exist' should return null\", provider.loadUser(\"does not exist\"));\n assertNull(\"Loading 'does not exist' should return null\", provider.loadUser(\"user1\", org2.getId()));\n\n loadUser = provider.loadUser(\"user1\", org1.getId());\n assertNotNull(loadUser);\n\n assertEquals(user.getUsername(), loadUser.getUsername());\n assertEquals(PasswordEncoder.encode(user.getPassword(), user.getUsername()), loadUser.getPassword());\n assertEquals(user.getOrganization(), loadUser.getOrganization());\n assertEquals(user.getRoles(), loadUser.getRoles());\n }", "label_name": "CWE-327", "label": "327"} -{"code": "\tprotected void switchToConversation(Contact contact, String body) {\n\t\tConversation conversation = xmppConnectionService\n\t\t\t\t.findOrCreateConversation(contact.getAccount(),\n\t\t\t\t\t\tcontact.getJid(), false, true);\n\t\tswitchToConversation(conversation, body);\n\t}", "label_name": "CWE-200", "label": "200"} -{"code": " protected BigInteger chooseRandomPrime(int bitlength, BigInteger e, BigInteger sqrdBound)\n {\n for (int i = 0; i != 5 * bitlength; i++)\n {\n BigInteger p = new BigInteger(bitlength, 1, param.getRandom());\n\n if (p.mod(e).equals(ONE))\n {\n continue;\n }\n\n if (p.multiply(p).compareTo(sqrdBound) < 0)\n {\n continue;\n }\n\n if (!isProbablePrime(p))\n {\n continue;\n }\n\n if (!e.gcd(p.subtract(ONE)).equals(ONE))\n {\n continue;\n }\n\n return p;\n }\n\n throw new IllegalStateException(\"unable to generate prime number for RSA key\");\n }", "label_name": "CWE-327", "label": "327"} -{"code": " public void translate(RespawnPacket packet, GeyserSession session) {\n if (packet.getState() == RespawnPacket.State.CLIENT_READY) {\n // Previously we only sent the respawn packet before the server finished loading\n // The message included was 'Otherwise when immediate respawn is on the client never loads'\n // But I assume the new if statement below fixes that problem\n RespawnPacket respawnPacket = new RespawnPacket();\n respawnPacket.setRuntimeEntityId(0);\n respawnPacket.setPosition(Vector3f.ZERO);\n respawnPacket.setState(RespawnPacket.State.SERVER_READY);\n session.sendUpstreamPacket(respawnPacket);\n\n if (session.isSpawned()) {\n // Client might be stuck; resend spawn information\n PlayerEntity entity = session.getPlayerEntity();\n if (entity == null) return;\n SetEntityDataPacket entityDataPacket = new SetEntityDataPacket();\n entityDataPacket.setRuntimeEntityId(entity.getGeyserId());\n entityDataPacket.getMetadata().putAll(entity.getMetadata());\n session.sendUpstreamPacket(entityDataPacket);\n\n MovePlayerPacket movePlayerPacket = new MovePlayerPacket();\n movePlayerPacket.setRuntimeEntityId(entity.getGeyserId());\n movePlayerPacket.setPosition(entity.getPosition());\n movePlayerPacket.setRotation(entity.getBedrockRotation());\n movePlayerPacket.setMode(MovePlayerPacket.Mode.RESPAWN);\n session.sendUpstreamPacket(movePlayerPacket);\n }\n\n ClientRequestPacket javaRespawnPacket = new ClientRequestPacket(ClientRequest.RESPAWN);\n session.sendDownstreamPacket(javaRespawnPacket);\n }\n }", "label_name": "CWE-287", "label": "287"} -{"code": "\tpublic String render(String templateContent, Map context) {\n\t\tVelocityContext velocityContext = new VelocityContext(context);\n\t\ttry (StringWriter sw = new StringWriter()) {\n\t\t\tVelocity.evaluate(velocityContext, sw, \"velocityTemplateEngine\", templateContent);\n\t\t\treturn sw.toString();\n\t\t}\n\t\tcatch (Exception ex) {\n\t\t\tthrow new TemplateRenderException(ex);\n\t\t}\n\t}", "label_name": "CWE-20", "label": "20"} -{"code": " public void failingExample() throws Exception {\n assertThat(ConstraintViolations.format(validator.validate(new FailingExample())))\n .containsExactlyInAnyOrder(FAILED_RESULT);\n assertThat(TestLoggerFactory.getAllLoggingEvents())\n .isEmpty();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " private void initAndSaveDocument(XWikiContext context, XWikiDocument newDocument, String title, String template,\n String parent) throws XWikiException\n {\n XWiki xwiki = context.getWiki();\n\n // Set the locale and default locale, considering that we're creating the original version of the document\n // (not a translation).\n newDocument.setLocale(Locale.ROOT);\n if (newDocument.getDefaultLocale() == Locale.ROOT) {\n newDocument.setDefaultLocale(xwiki.getLocalePreference(context));\n }\n\n // Copy the template.\n readFromTemplate(newDocument, template, context);\n\n // Set the parent field.\n if (!StringUtils.isEmpty(parent)) {\n DocumentReference parentReference = this.currentmixedReferenceResolver.resolve(parent);\n newDocument.setParentReference(parentReference);\n }\n\n // Set the document title\n if (title != null) {\n newDocument.setTitle(title);\n }\n\n // Set the author and creator.\n DocumentReference currentUserReference = context.getUserReference();\n newDocument.setAuthorReference(currentUserReference);\n newDocument.setCreatorReference(currentUserReference);\n\n // Make sure the user is allowed to make this modification\n xwiki.checkSavingDocument(currentUserReference, newDocument, context);\n\n xwiki.saveDocument(newDocument, context);\n }", "label_name": "CWE-862", "label": "862"} -{"code": " public void translate(ServerWindowItemsPacket packet, GeyserSession session) {\n Inventory inventory = InventoryUtils.getInventory(session, packet.getWindowId());\n if (inventory == null)\n return;\n\n inventory.setStateId(packet.getStateId());\n\n for (int i = 0; i < packet.getItems().length; i++) {\n GeyserItemStack newItem = GeyserItemStack.from(packet.getItems()[i]);\n inventory.setItem(i, newItem, session);\n }\n\n InventoryTranslator translator = session.getInventoryTranslator();\n if (translator != null) {\n translator.updateInventory(session, inventory);\n }\n\n session.getPlayerInventory().setCursor(GeyserItemStack.from(packet.getCarriedItem()), session);\n InventoryUtils.updateCursor(session);\n }", "label_name": "CWE-287", "label": "287"} -{"code": " public Argument argumentType() {\n return Argument.of(Session.class);\n }", "label_name": "CWE-400", "label": "400"} -{"code": " public void testGetAndRemove() {\n final HttpHeadersBase headers = newEmptyHeaders();\n headers.add(\"name1\", \"value1\");\n headers.add(\"name2\", \"value2\", \"value3\");\n headers.add(\"name3\", \"value4\", \"value5\", \"value6\");\n\n assertThat(headers.getAndRemove(\"name1\", \"defaultvalue\")).isEqualTo(\"value1\");\n assertThat(headers.getAndRemove(\"name2\")).isEqualTo(\"value2\");\n assertThat(headers.getAndRemove(\"name2\")).isNull();\n assertThat(headers.getAllAndRemove(\"name3\")).containsExactly(\"value4\", \"value5\", \"value6\");\n assertThat(headers.size()).isZero();\n assertThat(headers.getAndRemove(\"noname\")).isNull();\n assertThat(headers.getAndRemove(\"noname\", \"defaultvalue\")).isEqualTo(\"defaultvalue\");\n }", "label_name": "CWE-74", "label": "74"} -{"code": " private SearchResult lookupUser(String accountName) throws NamingException {\n InitialDirContext context = initContext();\n\n String searchString = searchFilter.replace(\":login\", accountName);\n\n SearchControls searchControls = new SearchControls();\n String[] attributeFilter = {idAttribute, nameAttribute, mailAttribute};\n searchControls.setReturningAttributes(attributeFilter);\n searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);\n\n NamingEnumeration results = context.search(searchBase, searchString, searchControls);\n\n SearchResult searchResult = null;\n if (results.hasMoreElements()) {\n searchResult = results.nextElement();\n if (results.hasMoreElements()) {\n LOGGER.warn(\"Matched multiple users for the accountName: \" + accountName);\n return null;\n }\n }\n\n return searchResult;\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void violationMessagesAreEscaped() {\n assertThat(ConstraintViolations.format(validator.validate(new InjectionExample()))).containsExactly(\n \" ${'value'}\",\n \"${'property'} ${'value'}\",\n \"${'property'}[${'key'}] ${'value'}\",\n \"${'property'}[1] ${'value'}\"\n );\n assertThat(TestLoggerFactory.getAllLoggingEvents()).isEmpty();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void setHeadersShouldOnlyOverwriteHeaders() {\n final HttpHeadersBase headers1 = newEmptyHeaders();\n headers1.add(\"name\", \"value\");\n headers1.add(\"name1\", \"value1\");\n\n final HttpHeadersBase headers2 = newEmptyHeaders();\n headers2.add(\"name\", \"newvalue\");\n headers2.add(\"name2\", \"value2\");\n\n final HttpHeadersBase expected = newEmptyHeaders();\n expected.add(\"name\", \"newvalue\");\n expected.add(\"name1\", \"value1\");\n expected.add(\"name2\", \"value2\");\n\n headers1.set(headers2);\n assertThat(expected).isEqualTo(headers1);\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public boolean isValid(Object value, ConstraintValidatorContext context) {\n final ViolationCollector collector = new ViolationCollector(context);\n context.disableDefaultConstraintViolation();\n for (ValidationCaller caller : methodMap.computeIfAbsent(value.getClass(), this::findMethods)) {\n caller.setValidationObject(value);\n caller.call(collector);\n }\n return !collector.hasViolationOccurred();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void testEqualsInsertionOrderDifferentHeaderNames() {\n final HttpHeadersBase h1 = newEmptyHeaders();\n h1.add(\"a\", \"b\");\n h1.add(\"c\", \"d\");\n final HttpHeadersBase h2 = newEmptyHeaders();\n h2.add(\"c\", \"d\");\n h2.add(\"a\", \"b\");\n assertThat(h1).isEqualTo(h2);\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void subValidateFail(ViolationCollector col) {\n col.addViolation(FAILED+\"subclass\");\n } ", "label_name": "CWE-74", "label": "74"} -{"code": " public void addViolation(String propertyName, String message) {\n violationOccurred = true;\n String messageTemplate = escapeEl(message);\n context.buildConstraintViolationWithTemplate(messageTemplate)\n .addPropertyNode(propertyName)\n .addConstraintViolation();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void testContains() {\n final HttpHeadersBase headers = newEmptyHeaders();\n\n headers.addLong(\"long\", Long.MAX_VALUE);\n assertThat(headers.containsLong(\"long\", Long.MAX_VALUE)).isTrue();\n assertThat(headers.containsLong(\"long\", Long.MIN_VALUE)).isFalse();\n\n headers.addInt(\"int\", Integer.MIN_VALUE);\n assertThat(headers.containsInt(\"int\", Integer.MIN_VALUE)).isTrue();\n assertThat(headers.containsInt(\"int\", Integer.MAX_VALUE)).isFalse();\n\n headers.addDouble(\"double\", Double.MAX_VALUE);\n assertThat(headers.containsDouble(\"double\", Double.MAX_VALUE)).isTrue();\n assertThat(headers.containsDouble(\"double\", Double.MIN_VALUE)).isFalse();\n\n headers.addFloat(\"float\", Float.MAX_VALUE);\n assertThat(headers.containsFloat(\"float\", Float.MAX_VALUE)).isTrue();\n assertThat(headers.containsFloat(\"float\", Float.MIN_VALUE)).isFalse();\n\n final long millis = System.currentTimeMillis();\n headers.addTimeMillis(\"millis\", millis);\n assertThat(headers.containsTimeMillis(\"millis\", millis)).isTrue();\n // This test doesn't work on midnight, January 1, 1970 UTC\n assertThat(headers.containsTimeMillis(\"millis\", 0)).isFalse();\n\n headers.addObject(\"object\", \"Hello World\");\n assertThat(headers.containsObject(\"object\", \"Hello World\")).isTrue();\n assertThat(headers.containsObject(\"object\", \"\")).isFalse();\n\n headers.add(\"name\", \"value\");\n assertThat(headers.contains(\"name\", \"value\")).isTrue();\n assertThat(headers.contains(\"name\", \"value1\")).isFalse();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " default OptionalLong contentLength() {\n Optional optional = getFirst(HttpHeaders.CONTENT_LENGTH, Long.class);\n return optional.map(OptionalLong::of).orElseGet(OptionalLong::empty);\n }", "label_name": "CWE-400", "label": "400"} -{"code": " public void testSetNullHeaderValue() {\n final HttpHeadersBase headers = newEmptyHeaders();\n headers.set(\"test\", (String) null);\n }", "label_name": "CWE-74", "label": "74"} -{"code": " private boolean pull(ConsoleOutputStreamConsumer outputStreamConsumer) {\n CommandLine hg = hg(\"pull\", \"-b\", branch, \"--config\", String.format(\"paths.default=%s\", url));\n return execute(hg, outputStreamConsumer) == 0;\n }", "label_name": "CWE-77", "label": "77"} -{"code": " private

void translate0(GeyserSession session, PacketTranslator

translator, P packet) {\n if (session.isClosed()) {\n return;\n }\n\n try {\n translator.translate(packet, session);\n } catch (Throwable ex) {\n GeyserConnector.getInstance().getLogger().error(LanguageUtils.getLocaleStringLog(\"geyser.network.translator.packet.failed\", packet.getClass().getSimpleName()), ex);\n ex.printStackTrace();\n }\n }", "label_name": "CWE-287", "label": "287"} -{"code": " public void handle(HttpServletRequest request, final HttpServletResponse response)\n throws Exception\n {\n // We're sending an XML response, so set the response content type to text/xml\n response.setContentType(\"text/xml\");\n\n // Parse the incoming request as XML\n SAXReader xmlReader = new SAXReader();\n Document doc = xmlReader.read(request.getInputStream());\n Element env = doc.getRootElement();\n\n final List polls = unmarshalRequests(env);\n\n new ContextualHttpServletRequest(request)\n {\n @Override\n public void process() throws Exception\n { \n for (PollRequest req : polls)\n {\n req.poll();\n }\n \n // Package up the response\n marshalResponse(polls, response.getOutputStream()); \n }\n }.run();\n }", "label_name": "CWE-200", "label": "200"} -{"code": " public void shouldNotGetModificationsFromOtherBranches() throws Exception {\n makeACommitToSecondBranch();\n hg(workingDirectory, \"pull\").runOrBomb(null);\n\n List actual = hgCommand.modificationsSince(new StringRevision(REVISION_0));\n assertThat(actual.size(), is(2));\n assertThat(actual.get(0).getRevision(), is(REVISION_2));\n assertThat(actual.get(1).getRevision(), is(REVISION_1));\n }", "label_name": "CWE-77", "label": "77"} -{"code": " public void translate(ServerSpawnPlayerPacket packet, GeyserSession session) {\n Vector3f position = Vector3f.from(packet.getX(), packet.getY(), packet.getZ());\n Vector3f rotation = Vector3f.from(packet.getYaw(), packet.getPitch(), packet.getYaw());\n\n PlayerEntity entity;\n if (packet.getUuid().equals(session.getPlayerEntity().getUuid())) {\n // Server is sending a fake version of the current player\n entity = new PlayerEntity(session.getPlayerEntity().getProfile(), packet.getEntityId(), session.getEntityCache().getNextEntityId().incrementAndGet(), position, Vector3f.ZERO, rotation);\n } else {\n entity = session.getEntityCache().getPlayerEntity(packet.getUuid());\n if (entity == null) {\n GeyserConnector.getInstance().getLogger().error(LanguageUtils.getLocaleStringLog(\"geyser.entity.player.failed_list\", packet.getUuid()));\n return;\n }\n\n entity.setEntityId(packet.getEntityId());\n entity.setPosition(position);\n entity.setRotation(rotation);\n }\n session.getEntityCache().cacheEntity(entity);\n\n entity.sendPlayer(session);\n SkinManager.requestAndHandleSkinAndCape(entity, session, null);\n }", "label_name": "CWE-287", "label": "287"} -{"code": " public void translate(CommandRequestPacket packet, GeyserSession session) {\n String command = packet.getCommand().replace(\"/\", \"\");\n CommandManager commandManager = GeyserConnector.getInstance().getCommandManager();\n if (session.getConnector().getPlatformType() == PlatformType.STANDALONE && command.trim().startsWith(\"geyser \") && commandManager.getCommands().containsKey(command.split(\" \")[1])) {\n commandManager.runCommand(session, command);\n } else {\n String message = packet.getCommand().trim();\n\n if (MessageTranslator.isTooLong(message, session)) {\n return;\n }\n\n ClientChatPacket chatPacket = new ClientChatPacket(message);\n session.sendDownstreamPacket(chatPacket);\n }\n }", "label_name": "CWE-287", "label": "287"} -{"code": " private static CharSequenceMap toLowercaseMap(Iterator valuesIter,\n int arraySizeHint) {\n final CharSequenceMap result = new CharSequenceMap(arraySizeHint);\n\n while (valuesIter.hasNext()) {\n final AsciiString lowerCased = HttpHeaderNames.of(valuesIter.next()).toLowerCase();\n try {\n int index = lowerCased.forEachByte(FIND_COMMA);\n if (index != -1) {\n int start = 0;\n do {\n result.add(lowerCased.subSequence(start, index, false).trim(), EMPTY_STRING);\n start = index + 1;\n } while (start < lowerCased.length() &&\n (index = lowerCased.forEachByte(start,\n lowerCased.length() - start, FIND_COMMA)) != -1);\n result.add(lowerCased.subSequence(start, lowerCased.length(), false).trim(), EMPTY_STRING);\n } else {\n result.add(lowerCased.trim(), EMPTY_STRING);\n }\n } catch (Exception e) {\n // This is not expect to happen because FIND_COMMA never throws but must be caught\n // because of the ByteProcessor interface.\n throw new IllegalStateException(e);\n }\n }\n return result;\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void translate(ServerEntityMetadataPacket packet, GeyserSession session) {\n Entity entity;\n if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {\n entity = session.getPlayerEntity();\n } else {\n entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());\n }\n if (entity == null) return;\n\n for (EntityMetadata metadata : packet.getMetadata()) {\n try {\n entity.updateBedrockMetadata(metadata, session);\n } catch (ClassCastException e) {\n // Class cast exceptions are really the only ones we're going to get in normal gameplay\n // Because some entity rewriters forget about some values\n // Any other errors are actual bugs\n session.getConnector().getLogger().warning(LanguageUtils.getLocaleStringLog(\"geyser.network.translator.metadata.failed\", metadata, entity.getEntityType()));\n session.getConnector().getLogger().debug(\"Entity Java ID: \" + entity.getEntityId() + \", Geyser ID: \" + entity.getGeyserId());\n if (session.getConnector().getConfig().isDebugMode()) {\n e.printStackTrace();\n }\n }\n }\n\n entity.updateBedrockMetadata(session);\n\n // Update the interactive tag, if necessary\n if (session.getMouseoverEntity() != null && session.getMouseoverEntity().getEntityId() == entity.getEntityId()) {\n InteractiveTagManager.updateTag(session, entity);\n }\n }", "label_name": "CWE-287", "label": "287"} -{"code": " protected void initOther() throws ServletException {\n PropertyUtils.addBeanIntrospector(\n SuppressPropertiesBeanIntrospector.SUPPRESS_CLASS);\n PropertyUtils.clearDescriptors();\n\n String value = null;\n value = getServletConfig().getInitParameter(\"config\");\n if (value != null) {\n config = value;\n }\n\n // Backwards compatibility for form beans of Java wrapper classes\n // Set to true for strict Struts 1.0 compatibility\n value = getServletConfig().getInitParameter(\"convertNull\");\n if (\"true\".equalsIgnoreCase(value)\n || \"yes\".equalsIgnoreCase(value)\n || \"on\".equalsIgnoreCase(value)\n || \"y\".equalsIgnoreCase(value)\n || \"1\".equalsIgnoreCase(value)) {\n\n convertNull = true;\n }\n\n if (convertNull) {\n ConvertUtils.deregister();\n ConvertUtils.register(new BigDecimalConverter(null), BigDecimal.class);\n ConvertUtils.register(new BigIntegerConverter(null), BigInteger.class);\n ConvertUtils.register(new BooleanConverter(null), Boolean.class);\n ConvertUtils.register(new ByteConverter(null), Byte.class);\n ConvertUtils.register(new CharacterConverter(null), Character.class);\n ConvertUtils.register(new DoubleConverter(null), Double.class);\n ConvertUtils.register(new FloatConverter(null), Float.class);\n ConvertUtils.register(new IntegerConverter(null), Integer.class);\n ConvertUtils.register(new LongConverter(null), Long.class);\n ConvertUtils.register(new ShortConverter(null), Short.class);\n }\n\n }", "label_name": "CWE-20", "label": "20"} -{"code": " public void translate(ServerSpawnExpOrbPacket packet, GeyserSession session) {\n Vector3f position = Vector3f.from(packet.getX(), packet.getY(), packet.getZ());\n\n Entity entity = new ExpOrbEntity(\n packet.getExp(), packet.getEntityId(), session.getEntityCache().getNextEntityId().incrementAndGet(),\n EntityType.EXPERIENCE_ORB, position, Vector3f.ZERO, Vector3f.ZERO\n );\n\n session.getEntityCache().spawnEntity(entity);\n }", "label_name": "CWE-287", "label": "287"} -{"code": " public void newDocumentWebHomeFromURLTemplateProviderSpecifiedButOldPageTypeButOverriddenFromUIToNonTerminal()\n throws Exception\n {\n // new document = xwiki:X.Y.WebHome\n DocumentReference documentReference = new DocumentReference(\"xwiki\", Arrays.asList(\"X\", \"Y\"), \"WebHome\");\n XWikiDocument document = mock(XWikiDocument.class);\n when(document.getDocumentReference()).thenReturn(documentReference);\n when(document.isNew()).thenReturn(true);\n when(document.getLocalReferenceMaxLength()).thenReturn(255);\n context.setDoc(document);\n\n // Specifying a template provider in the URL: templateprovider=XWiki.MyTemplateProvider\n String templateProviderFullName = \"XWiki.MyTemplateProvider\";\n when(mockRequest.getParameter(\"templateprovider\")).thenReturn(templateProviderFullName);\n when(mockRequest.getParameter(\"tocreate\")).thenReturn(\"nonterminal\");\n\n // Mock 1 existing template provider\n mockExistingTemplateProviders(templateProviderFullName,\n new DocumentReference(\"xwiki\", Arrays.asList(\"XWiki\"), \"MyTemplateProvider\"), Collections.EMPTY_LIST, null,\n \"page\");\n\n // Run the action\n String result = action.render(context);\n\n // The tests are below this line!\n\n // Verify null is returned (this means the response has been returned)\n assertNull(result);\n\n // Note: We are creating the document X.Y.WebHome as non-terminal, since even if the template provider did not\n // specify a \"terminal\" property and it used the old \"page\" type, the UI explicitly asked for a non-terminal\n // document. Also using a template, as specified in the template provider.\n verify(mockURLFactory).createURL(\"X.Y\", \"WebHome\", \"edit\",\n \"template=XWiki.MyTemplate&parent=Main.WebHome&title=Y\", null, \"xwiki\", context);\n }", "label_name": "CWE-862", "label": "862"} -{"code": " public void subClassExample() throws Exception {\n assertThat(ConstraintViolations.format(validator.validate(new SubclassExample())))\n .containsExactlyInAnyOrder(\n FAILED_RESULT,\n FAILED_RESULT+\"subclass\"\n );\n assertThat(TestLoggerFactory.getAllLoggingEvents())\n .isEmpty();\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void multipleValuesPerNameIteratorEmpty() {\n final HttpHeadersBase headers = newEmptyHeaders();\n assertThat(headers.valueIterator(\"name\")).isExhausted();\n assertThatThrownBy(() -> headers.valueIterator(\"name\").next())\n .isInstanceOf(NoSuchElementException.class);\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public String compact() {\n return id.replaceAll(\"/\", \"-\").replaceAll(\"\\\\\\\\\", \"-\");\n }", "label_name": "CWE-74", "label": "74"} -{"code": " public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {\n //\u4fbf\u4e8eWappalyzer\u8bfb\u53d6\n response.addHeader(\"X-ZrLog\", BlogBuildInfoUtil.getVersion());\n boolean isPluginPath = false;\n for (String path : pluginHandlerPaths) {\n if (target.startsWith(path)) {\n isPluginPath = true;\n }\n }\n if (isPluginPath) {\n try {\n Map.Entry entry = adminTokenService.getAdminTokenVOUserEntry(request);\n if (entry != null) {\n adminTokenService.setAdminToken(entry.getValue(), entry.getKey().getSessionId(), entry.getKey().getProtocol(), request, response);\n }\n if (target.startsWith(\"/admin/plugins/\")) {\n try {\n adminPermission(target, request, response);\n } catch (IOException | InstantiationException e) {\n LOGGER.error(e);\n }\n } else if (target.startsWith(\"/plugin/\") || target.startsWith(\"/p/\")) {\n try {\n visitorPermission(target, request, response);\n } catch (IOException | InstantiationException e) {\n LOGGER.error(e);\n }\n }\n } finally {\n isHandled[0] = true;\n }\n } else {\n this.next.handle(target, request, response, isHandled);\n }\n }", "label_name": "CWE-863", "label": "863"} -{"code": "inline typename V::VectorType FBUnserializer::unserializeVector() {\n p_ += CODE_SIZE;\n\n typename V::VectorType ret = V::createVector();\n\n size_t code = nextCode();\n while (code != FB_SERIALIZE_STOP) {\n V::vectorAppend(ret, unserializeThing());\n code = nextCode();\n }\n p_ += CODE_SIZE;\n return ret;\n}", "label_name": "CWE-674", "label": "674"} -{"code": "mptctl_eventquery (unsigned long arg)\n{\n\tstruct mpt_ioctl_eventquery __user *uarg = (void __user *) arg;\n\tstruct mpt_ioctl_eventquery\t karg;\n\tMPT_ADAPTER *ioc;\n\tint iocnum;\n\n\tif (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_eventquery))) {\n\t\tprintk(KERN_ERR MYNAM \"%s@%d::mptctl_eventquery - \"\n\t\t\t\"Unable to read in mpt_ioctl_eventquery struct @ %p\\n\",\n\t\t\t\t__FILE__, __LINE__, uarg);\n\t\treturn -EFAULT;\n\t}\n\n\tif (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||\n\t (ioc == NULL)) {\n\t\tprintk(KERN_DEBUG MYNAM \"%s::mptctl_eventquery() @%d - ioc%d not found!\\n\",\n\t\t\t\t__FILE__, __LINE__, iocnum);\n\t\treturn -ENODEV;\n\t}\n\n\tdctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT \"mptctl_eventquery called.\\n\",\n\t ioc->name));\n\tkarg.eventEntries = MPTCTL_EVENT_LOG_SIZE;\n\tkarg.eventTypes = ioc->eventTypes;\n\n\t/* Copy the data from kernel memory to user memory\n\t */\n\tif (copy_to_user((char __user *)arg, &karg, sizeof(struct mpt_ioctl_eventquery))) {\n\t\tprintk(MYIOC_s_ERR_FMT \"%s@%d::mptctl_eventquery - \"\n\t\t\t\"Unable to write out mpt_ioctl_eventquery struct @ %p\\n\",\n\t\t\tioc->name, __FILE__, __LINE__, uarg);\n\t\treturn -EFAULT;\n\t}\n\treturn 0;\n}", "label_name": "CWE-362", "label": "362"} -{"code": "ECDSA_Signature_Operation::raw_sign(const uint8_t msg[], size_t msg_len,\n RandomNumberGenerator& rng)\n {\n BigInt m(msg, msg_len, m_group.get_order_bits());\n\n#if defined(BOTAN_HAS_RFC6979_GENERATOR)\n const BigInt k = generate_rfc6979_nonce(m_x, m_group.get_order(), m, m_rfc6979_hash);\n#else\n const BigInt k = m_group.random_scalar(rng);\n#endif\n\n const BigInt k_inv = m_group.inverse_mod_order(k);\n const BigInt r = m_group.mod_order(\n m_group.blinded_base_point_multiply_x(k, rng, m_ws));\n\n const BigInt xrm = m_group.mod_order(m_group.multiply_mod_order(m_x, r) + m);\n const BigInt s = m_group.multiply_mod_order(k_inv, xrm);\n\n // With overwhelming probability, a bug rather than actual zero r/s\n if(r.is_zero() || s.is_zero())\n throw Internal_Error(\"During ECDSA signature generated zero r/s\");\n\n return BigInt::encode_fixed_length_int_pair(r, s, m_group.get_order_bytes());\n }", "label_name": "CWE-200", "label": "200"} -{"code": "\tchar const* parse_int(char const* start, char const* end, char delimiter, boost::int64_t& val)\n\t{\n\t\twhile (start < end && *start != delimiter)\n\t\t{\n\t\t\tif (!is_digit(*start)) { return 0; }\n\t\t\tval *= 10;\n\t\t\tval += *start - '0';\n\t\t\t++start;\n\t\t}\n\t\treturn start;\n\t}", "label_name": "CWE-119", "label": "119"} -{"code": "ProcessTCPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize)\n{\n ULONG tcpipDataAt;\n tTcpIpPacketParsingResult res = _res;\n tcpipDataAt = ipHeaderSize + sizeof(TCPHeader);\n res.xxpStatus = ppresXxpIncomplete;\n res.TcpUdp = ppresIsTCP;\n\n if (len >= tcpipDataAt)\n {\n TCPHeader *pTcpHeader = (TCPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize);\n res.xxpStatus = ppresXxpKnown;\n tcpipDataAt = ipHeaderSize + TCP_HEADER_LENGTH(pTcpHeader);\n res.XxpIpHeaderSize = tcpipDataAt;\n }\n else\n {\n DPrintf(2, (\"tcp: %d < min headers %d\\n\", len, tcpipDataAt));\n }\n return res;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "void HeaderMapImpl::addViaMove(HeaderString&& key, HeaderString&& value) {\n // If this is an inline header, we can't addViaMove, because we'll overwrite\n // the existing value.\n auto* entry = getExistingInline(key.getStringView());\n if (entry != nullptr) {\n appendToHeader(entry->value(), value.getStringView());\n key.clear();\n value.clear();\n } else {\n insertByKey(std::move(key), std::move(value));\n }\n}", "label_name": "CWE-400", "label": "400"} -{"code": "bool ItemStackMetadata::setString(const std::string &name, const std::string &var)\n{\n\tbool result = Metadata::setString(name, var);\n\tif (name == TOOLCAP_KEY)\n\t\tupdateToolCapabilities();\n\treturn result;\n}", "label_name": "CWE-74", "label": "74"} -{"code": "void* TFE_HandleToDLPack(TFE_TensorHandle* h, TF_Status* status) {\n const Tensor* tensor = GetTensorFromHandle(h, status);\n TF_DataType data_type = static_cast(tensor->dtype());\n TensorReference tensor_ref(*tensor); // This will call buf_->Ref()\n\n auto* tf_dlm_tensor_ctx = new TfDlManagedTensorCtx(tensor_ref);\n tf_dlm_tensor_ctx->reference = tensor_ref;\n\n DLManagedTensor* dlm_tensor = &tf_dlm_tensor_ctx->tensor;\n dlm_tensor->manager_ctx = tf_dlm_tensor_ctx;\n dlm_tensor->deleter = &DLManagedTensorDeleter;\n dlm_tensor->dl_tensor.ctx = GetDlContext(h, status);\n int ndim = tensor->dims();\n dlm_tensor->dl_tensor.ndim = ndim;\n dlm_tensor->dl_tensor.data = TFE_TensorHandleDevicePointer(h, status);\n dlm_tensor->dl_tensor.dtype = GetDlDataType(data_type, status);\n\n std::vector* shape_arr = &tf_dlm_tensor_ctx->shape;\n std::vector* stride_arr = &tf_dlm_tensor_ctx->strides;\n shape_arr->resize(ndim);\n stride_arr->resize(ndim, 1);\n for (int i = 0; i < ndim; i++) {\n (*shape_arr)[i] = tensor->dim_size(i);\n }\n for (int i = ndim - 2; i >= 0; --i) {\n (*stride_arr)[i] = (*shape_arr)[i + 1] * (*stride_arr)[i + 1];\n }\n\n dlm_tensor->dl_tensor.shape = &(*shape_arr)[0];\n // There are two ways to represent compact row-major data\n // 1) nullptr indicates tensor is compact and row-majored.\n // 2) fill in the strides array as the real case for compact row-major data.\n // Here we choose option 2, since some frameworks didn't handle the strides\n // argument properly.\n dlm_tensor->dl_tensor.strides = &(*stride_arr)[0];\n dlm_tensor->dl_tensor.byte_offset =\n 0; // TF doesn't handle the strides and byte_offsets here\n return static_cast(dlm_tensor);\n}", "label_name": "CWE-20", "label": "20"} -{"code": "TEST_F(GroupVerifierTest, TestRequiresAnyWithAllowMissingButOk) {\n TestUtility::loadFromYaml(RequiresAnyConfig, proto_config_);\n proto_config_.mutable_rules(0)\n ->mutable_requires()\n ->mutable_requires_any()\n ->add_requirements()\n ->mutable_allow_missing();\n\n createAsyncMockAuthsAndVerifier(std::vector{\"example_provider\", \"other_provider\"});\n EXPECT_CALL(mock_cb_, onComplete(Status::Ok));\n\n auto headers = Http::TestRequestHeaderMapImpl{};\n context_ = Verifier::createContext(headers, parent_span_, &mock_cb_);\n verifier_->verify(context_);\n callbacks_[\"example_provider\"](Status::JwtMissed);\n callbacks_[\"other_provider\"](Status::JwtUnknownIssuer);\n}", "label_name": "CWE-287", "label": "287"} -{"code": "static inline bool isValid(const RemoteFsDevice::Details &d)\n{\n return d.isLocalFile() || RemoteFsDevice::constSshfsProtocol==d.url.scheme() ||\n RemoteFsDevice::constSambaProtocol==d.url.scheme() || RemoteFsDevice::constSambaAvahiProtocol==d.url.scheme();\n}", "label_name": "CWE-20", "label": "20"} -{"code": " RectangleRequest &operator=(const struct RectangleRequest &req)\n { \n // Not nice, but this is really faster and simpler\n memcpy(this,&req,sizeof(struct RectangleRequest));\n // Not linked in any way if this is new.\n rr_pNext = NULL;\n //\n return *this;\n }", "label_name": "CWE-119", "label": "119"} -{"code": "USHORT CNB::QueryL4HeaderOffset(PVOID PacketData, ULONG IpHeaderOffset) const\n{\n USHORT Res;\n auto ppr = ParaNdis_ReviewIPPacket(RtlOffsetToPointer(PacketData, IpHeaderOffset),\n GetDataLength(), __FUNCTION__);\n if (ppr.ipStatus != ppresNotIP)\n {\n Res = static_cast(IpHeaderOffset + ppr.ipHeaderSize);\n }\n else\n {\n DPrintf(0, (\"[%s] ERROR: NOT an IP packet - expected troubles!\\n\", __FUNCTION__));\n Res = 0;\n }\n return Res;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "mptctl_eventreport (unsigned long arg)\n{\n\tstruct mpt_ioctl_eventreport __user *uarg = (void __user *) arg;\n\tstruct mpt_ioctl_eventreport\t karg;\n\tMPT_ADAPTER\t\t *ioc;\n\tint\t\t\t iocnum;\n\tint\t\t\t numBytes, maxEvents, max;\n\n\tif (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_eventreport))) {\n\t\tprintk(KERN_ERR MYNAM \"%s@%d::mptctl_eventreport - \"\n\t\t\t\"Unable to read in mpt_ioctl_eventreport struct @ %p\\n\",\n\t\t\t\t__FILE__, __LINE__, uarg);\n\t\treturn -EFAULT;\n\t}\n\n\tif (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||\n\t (ioc == NULL)) {\n\t\tprintk(KERN_DEBUG MYNAM \"%s::mptctl_eventreport() @%d - ioc%d not found!\\n\",\n\t\t\t\t__FILE__, __LINE__, iocnum);\n\t\treturn -ENODEV;\n\t}\n\tdctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT \"mptctl_eventreport called.\\n\",\n\t ioc->name));\n\n\tnumBytes = karg.hdr.maxDataSize - sizeof(mpt_ioctl_header);\n\tmaxEvents = numBytes/sizeof(MPT_IOCTL_EVENTS);\n\n\n\tmax = MPTCTL_EVENT_LOG_SIZE < maxEvents ? MPTCTL_EVENT_LOG_SIZE : maxEvents;\n\n\t/* If fewer than 1 event is requested, there must have\n\t * been some type of error.\n\t */\n\tif ((max < 1) || !ioc->events)\n\t\treturn -ENODATA;\n\n\t/* reset this flag so SIGIO can restart */\n\tioc->aen_event_read_flag=0;\n\n\t/* Copy the data from kernel memory to user memory\n\t */\n\tnumBytes = max * sizeof(MPT_IOCTL_EVENTS);\n\tif (copy_to_user(uarg->eventData, ioc->events, numBytes)) {\n\t\tprintk(MYIOC_s_ERR_FMT \"%s@%d::mptctl_eventreport - \"\n\t\t\t\"Unable to write out mpt_ioctl_eventreport struct @ %p\\n\",\n\t\t\tioc->name, __FILE__, __LINE__, ioc->events);\n\t\treturn -EFAULT;\n\t}\n\n\treturn 0;\n}", "label_name": "CWE-362", "label": "362"} -{"code": "TEST_F(SingleAllowMissingInOrListTest, MissingIssToken) {\n EXPECT_CALL(mock_cb_, onComplete(Status::Ok));\n auto headers = Http::TestRequestHeaderMapImpl{{kExampleHeader, ES256WithoutIssToken}};\n context_ = Verifier::createContext(headers, parent_span_, &mock_cb_);\n verifier_->verify(context_);\n EXPECT_THAT(headers, JwtOutputFailedOrIgnore(kExampleHeader));\n}", "label_name": "CWE-287", "label": "287"} -{"code": "static gboolean cosine_read(wtap *wth, int *err, gchar **err_info,\n gint64 *data_offset)\n{\n\tgint64\toffset;\n\tint\tpkt_len;\n\tchar\tline[COSINE_LINE_LENGTH];\n\n\t/* Find the next packet */\n\toffset = cosine_seek_next_packet(wth, err, err_info, line);\n\tif (offset < 0)\n\t\treturn FALSE;\n\t*data_offset = offset;\n\n\t/* Parse the header */\n\tpkt_len = parse_cosine_rec_hdr(&wth->phdr, line, err, err_info);\n\tif (pkt_len == -1)\n\t\treturn FALSE;\n\n\t/* Convert the ASCII hex dump to binary data */\n\treturn parse_cosine_hex_dump(wth->fh, &wth->phdr, pkt_len,\n\t wth->frame_buffer, err, err_info);\n}", "label_name": "CWE-119", "label": "119"} -{"code": "int ZlibInStream::overrun(int itemSize, int nItems, bool wait)\n{\n if (itemSize > bufSize)\n throw Exception(\"ZlibInStream overrun: max itemSize exceeded\");\n if (!underlying)\n throw Exception(\"ZlibInStream overrun: no underlying stream\");\n\n if (end - ptr != 0)\n memmove(start, ptr, end - ptr);\n\n offset += ptr - start;\n end -= ptr - start;\n ptr = start;\n\n while (end - ptr < itemSize) {\n if (!decompress(wait))\n return 0;\n }\n\n if (itemSize * nItems > end - ptr)\n nItems = (end - ptr) / itemSize;\n\n return nItems;\n}", "label_name": "CWE-672", "label": "672"} -{"code": "\tSpawnPreparationInfo prepareSpawn(const Options &options) {\n\t\tTRACE_POINT();\n\t\tSpawnPreparationInfo info;\n\t\tprepareChroot(info, options);\n\t\tinfo.userSwitching = prepareUserSwitching(options);\n\t\tprepareSwitchingWorkingDirectory(info, options);\n\t\tinferApplicationInfo(info);\n\t\treturn info;\n\t}", "label_name": "CWE-200", "label": "200"} -{"code": "compat_mpt_command(struct file *filp, unsigned int cmd,\n\t\t\tunsigned long arg)\n{\n\tstruct mpt_ioctl_command32 karg32;\n\tstruct mpt_ioctl_command32 __user *uarg = (struct mpt_ioctl_command32 __user *) arg;\n\tstruct mpt_ioctl_command karg;\n\tMPT_ADAPTER *iocp = NULL;\n\tint iocnum, iocnumX;\n\tint nonblock = (filp->f_flags & O_NONBLOCK);\n\tint ret;\n\n\tif (copy_from_user(&karg32, (char __user *)arg, sizeof(karg32)))\n\t\treturn -EFAULT;\n\n\t/* Verify intended MPT adapter */\n\tiocnumX = karg32.hdr.iocnum & 0xFF;\n\tif (((iocnum = mpt_verify_adapter(iocnumX, &iocp)) < 0) ||\n\t (iocp == NULL)) {\n\t\tprintk(KERN_DEBUG MYNAM \"::compat_mpt_command @%d - ioc%d not found!\\n\",\n\t\t\t__LINE__, iocnumX);\n\t\treturn -ENODEV;\n\t}\n\n\tif ((ret = mptctl_syscall_down(iocp, nonblock)) != 0)\n\t\treturn ret;\n\n\tdctlprintk(iocp, printk(MYIOC_s_DEBUG_FMT \"compat_mpt_command() called\\n\",\n\t iocp->name));\n\t/* Copy data to karg */\n\tkarg.hdr.iocnum = karg32.hdr.iocnum;\n\tkarg.hdr.port = karg32.hdr.port;\n\tkarg.timeout = karg32.timeout;\n\tkarg.maxReplyBytes = karg32.maxReplyBytes;\n\n\tkarg.dataInSize = karg32.dataInSize;\n\tkarg.dataOutSize = karg32.dataOutSize;\n\tkarg.maxSenseBytes = karg32.maxSenseBytes;\n\tkarg.dataSgeOffset = karg32.dataSgeOffset;\n\n\tkarg.replyFrameBufPtr = (char __user *)(unsigned long)karg32.replyFrameBufPtr;\n\tkarg.dataInBufPtr = (char __user *)(unsigned long)karg32.dataInBufPtr;\n\tkarg.dataOutBufPtr = (char __user *)(unsigned long)karg32.dataOutBufPtr;\n\tkarg.senseDataPtr = (char __user *)(unsigned long)karg32.senseDataPtr;\n\n\t/* Pass new structure to do_mpt_command\n\t */\n\tret = mptctl_do_mpt_command (karg, &uarg->MF);\n\n\tmutex_unlock(&iocp->ioctl_cmds.mutex);\n\n\treturn ret;\n}", "label_name": "CWE-362", "label": "362"} -{"code": " ECDSA_Signature_Operation(const ECDSA_PrivateKey& ecdsa,\n const std::string& emsa) :\n PK_Ops::Signature_with_EMSA(emsa),\n m_group(ecdsa.domain()),\n m_x(ecdsa.private_value())\n {\n#if defined(BOTAN_HAS_RFC6979_GENERATOR)\n m_rfc6979_hash = hash_for_emsa(emsa);\n#endif\n }", "label_name": "CWE-200", "label": "200"} -{"code": "int ecall_restore(const char *input, uint64_t input_len, char **output,\n uint64_t *output_len) {\n if (!asylo::primitives::TrustedPrimitives::IsOutsideEnclave(input,\n input_len)) {\n asylo::primitives::TrustedPrimitives::BestEffortAbort(\n \"ecall_restore: input found to not be in untrusted memory.\");\n }\n int result = 0;\n size_t tmp_output_len;\n try {\n result = asylo::Restore(input, static_cast(input_len), output,\n &tmp_output_len);\n } catch (...) {\n LOG(FATAL) << \"Uncaught exception in enclave\";\n }\n\n if (output_len) {\n *output_len = static_cast(tmp_output_len);\n }\n return result;\n}", "label_name": "CWE-119", "label": "119"} -{"code": "void ConnectionImpl::onHeaderValue(const char* data, size_t length) {\n if (header_parsing_state_ == HeaderParsingState::Done) {\n // Ignore trailers.\n return;\n }\n\n const absl::string_view header_value = absl::string_view(data, length);\n\n if (strict_header_validation_) {\n if (!Http::HeaderUtility::headerIsValid(header_value)) {\n ENVOY_CONN_LOG(debug, \"invalid header value: {}\", connection_, header_value);\n error_code_ = Http::Code::BadRequest;\n sendProtocolError();\n throw CodecProtocolException(\"http/1.1 protocol error: header value contains invalid chars\");\n }\n } else if (header_value.find('\\0') != absl::string_view::npos) {\n // http-parser should filter for this\n // (https://tools.ietf.org/html/rfc7230#section-3.2.6), but it doesn't today. HeaderStrings\n // have an invariant that they must not contain embedded zero characters\n // (NUL, ASCII 0x0).\n throw CodecProtocolException(\"http/1.1 protocol error: header value contains NUL\");\n }\n\n header_parsing_state_ = HeaderParsingState::Value;\n current_header_value_.append(data, length);\n\n const uint32_t total =\n current_header_field_.size() + current_header_value_.size() + current_header_map_->byteSize();\n if (total > (max_request_headers_kb_ * 1024)) {\n error_code_ = Http::Code::RequestHeaderFieldsTooLarge;\n sendProtocolError();\n throw CodecProtocolException(\"headers size exceeds limit\");\n }\n}", "label_name": "CWE-400", "label": "400"} -{"code": "bool MemoryManager::validate_user_read(const Process& process, VirtualAddress vaddr) const\n{\n auto* region = region_from_vaddr(process, vaddr);\n return region && region->is_readable();\n}", "label_name": "CWE-119", "label": "119"} -{"code": "void CUser::SetClientEncoding(const CString& s) {\n m_sClientEncoding = s;\n for (CClient* pClient : GetAllClients()) {\n pClient->SetEncoding(s);\n }\n}", "label_name": "CWE-20", "label": "20"} -{"code": "void RemoteDevicePropertiesWidget::setType()\n{\n if (Type_SshFs==type->itemData(type->currentIndex()).toInt() && 0==sshPort->value()) {\n sshPort->setValue(22);\n }\n if (Type_Samba==type->itemData(type->currentIndex()).toInt() && 0==smbPort->value()) {\n smbPort->setValue(445);\n }\n}", "label_name": "CWE-20", "label": "20"} -{"code": "static const char* ConvertOneFloat(PyObject* v, T* out) {\n if (PyErr_Occurred()) {\n return nullptr;\n }\n if (TF_PREDICT_TRUE(PyFloat_Check(v))) {\n const double as_double = PyFloat_AS_DOUBLE(v);\n *out = static_cast(as_double);\n // Check for overflow\n if (TF_PREDICT_FALSE(sizeof(T) < sizeof(double) && std::isinf(*out) &&\n std::isfinite(as_double))) {\n return ErrorOutOfRangeDouble;\n }\n return nullptr;\n }\n#if PY_MAJOR_VERSION < 3\n if (PyInt_Check(v)) {\n *out = PyInt_AS_LONG(v);\n return nullptr;\n }\n#endif\n if (PyLong_Check(v)) {\n *out = PyLong_AsDouble(v);\n if (PyErr_Occurred()) return ErrorOutOfRangeDouble;\n return nullptr;\n }\n if (PyIsInstance(v, &PyFloatingArrType_Type)) { // NumPy float types\n Safe_PyObjectPtr as_float = make_safe(PyNumber_Float(v));\n if (PyErr_Occurred()) {\n return nullptr;\n }\n return ConvertOneFloat(as_float.get(), out);\n }\n if (PyIsInstance(v, &PyIntegerArrType_Type)) { // NumPy integers\n#if PY_MAJOR_VERSION < 3\n Safe_PyObjectPtr as_int = make_safe(PyNumber_Int(v));\n#else\n Safe_PyObjectPtr as_int = make_safe(PyNumber_Long(v));\n#endif\n if (PyErr_Occurred()) {\n return nullptr;\n }\n return ConvertOneFloat(as_int.get(), out);\n }\n return ErrorMixedTypes;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "void RemoteFsDevice::serviceAdded(const QString &name)\n{\n if (name==details.serviceName && constSambaAvahiProtocol==details.url.scheme()) {\n sub=tr(\"Available\");\n updateStatus();\n }\n}", "label_name": "CWE-20", "label": "20"} -{"code": "set PipeSocketHandler::listen(const SocketEndpoint& endpoint) {\n lock_guard guard(globalMutex);\n\n string pipePath = endpoint.name();\n if (pipeServerSockets.find(pipePath) != pipeServerSockets.end()) {\n throw runtime_error(\"Tried to listen twice on the same path\");\n }\n\n sockaddr_un local;\n\n int fd = socket(AF_UNIX, SOCK_STREAM, 0);\n FATAL_FAIL(fd);\n initServerSocket(fd);\n local.sun_family = AF_UNIX; /* local is declared before socket() ^ */\n strcpy(local.sun_path, pipePath.c_str());\n unlink(local.sun_path);\n\n FATAL_FAIL(::bind(fd, (struct sockaddr*)&local, sizeof(sockaddr_un)));\n ::listen(fd, 5);\n#ifndef WIN32\n FATAL_FAIL(::chmod(local.sun_path, S_IRUSR | S_IWUSR | S_IXUSR));\n#endif\n\n pipeServerSockets[pipePath] = set({fd});\n return pipeServerSockets[pipePath];\n}", "label_name": "CWE-362", "label": "362"} -{"code": "static inline ulong encode_twos_comp(long n, int prec)\n{\n\tulong result;\n\tassert(prec >= 2);\n\tjas_eprintf(\"warning: support for signed data is untested\\n\");\n\t// NOTE: Is this correct?\n\tif (n < 0) {\n\t\tresult = -n;\n\t\tresult = (result ^ 0xffffffffUL) + 1;\n\t\tresult &= (1 << prec) - 1;\n\t} else {\n\t\tresult = n;\n\t}\n\treturn result;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "TcpOption *tcpGetOption(TcpHeader *segment, uint8_t kind)\n{\n size_t length;\n uint_t i;\n TcpOption *option;\n\n //Make sure the TCP header is valid\n if(segment->dataOffset < 5)\n return NULL;\n\n //Compute the length of the options field\n length = segment->dataOffset * 4 - sizeof(TcpHeader);\n\n //Point to the very first option\n i = 0;\n\n //Parse TCP options\n while(i < length)\n {\n //Point to the current option\n option = (TcpOption *) (segment->options + i);\n\n //NOP option detected?\n if(option->kind == TCP_OPTION_NOP)\n {\n i++;\n continue;\n }\n //END option detected?\n if(option->kind == TCP_OPTION_END)\n break;\n //Check option length\n if((i + 1) >= length || (i + option->length) > length)\n break;\n\n //Current option kind match the specified one?\n if(option->kind == kind)\n return option;\n\n //Jump to next the next option\n i += option->length;\n }\n\n //Specified option code not found\n return NULL;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "jas_matrix_t *jas_seq2d_create(int xstart, int ystart, int xend, int yend)\n{\n\tjas_matrix_t *matrix;\n\tassert(xstart <= xend && ystart <= yend);\n\tif (!(matrix = jas_matrix_create(yend - ystart, xend - xstart))) {\n\t\treturn 0;\n\t}\n\tmatrix->xstart_ = xstart;\n\tmatrix->ystart_ = ystart;\n\tmatrix->xend_ = xend;\n\tmatrix->yend_ = yend;\n\treturn matrix;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "void jas_matrix_asr(jas_matrix_t *matrix, int n)\n{\n\tint i;\n\tint j;\n\tjas_seqent_t *rowstart;\n\tint rowstep;\n\tjas_seqent_t *data;\n\n\tassert(n >= 0);\n\tif (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {\n\t\tassert(matrix->rows_);\n\t\trowstep = jas_matrix_rowstep(matrix);\n\t\tfor (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,\n\t\t rowstart += rowstep) {\n\t\t\tfor (j = matrix->numcols_, data = rowstart; j > 0; --j,\n\t\t\t ++data) {\n\t\t\t\t//*data >>= n;\n\t\t\t\t*data = jas_seqent_asr(*data, n);\n\t\t\t}\n\t\t}\n\t}\n}", "label_name": "CWE-20", "label": "20"} -{"code": "void HttpIntegrationTest::waitForNextUpstreamRequest(uint64_t upstream_index) {\n waitForNextUpstreamRequest(std::vector({upstream_index}));\n}", "label_name": "CWE-400", "label": "400"} -{"code": "CString CZNC::FixupEncoding(const CString& sEncoding) const {\n if (sEncoding.empty() && m_uiForceEncoding) {\n return \"UTF-8\";\n }\n return sEncoding;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "static int mptctl_do_reset(unsigned long arg)\n{\n\tstruct mpt_ioctl_diag_reset __user *urinfo = (void __user *) arg;\n\tstruct mpt_ioctl_diag_reset krinfo;\n\tMPT_ADAPTER\t\t*iocp;\n\n\tif (copy_from_user(&krinfo, urinfo, sizeof(struct mpt_ioctl_diag_reset))) {\n\t\tprintk(KERN_ERR MYNAM \"%s@%d::mptctl_do_reset - \"\n\t\t\t\t\"Unable to copy mpt_ioctl_diag_reset struct @ %p\\n\",\n\t\t\t\t__FILE__, __LINE__, urinfo);\n\t\treturn -EFAULT;\n\t}\n\n\tif (mpt_verify_adapter(krinfo.hdr.iocnum, &iocp) < 0) {\n\t\tprintk(KERN_DEBUG MYNAM \"%s@%d::mptctl_do_reset - ioc%d not found!\\n\",\n\t\t\t\t__FILE__, __LINE__, krinfo.hdr.iocnum);\n\t\treturn -ENODEV; /* (-6) No such device or address */\n\t}\n\n\tdctlprintk(iocp, printk(MYIOC_s_DEBUG_FMT \"mptctl_do_reset called.\\n\",\n\t iocp->name));\n\n\tif (mpt_HardResetHandler(iocp, CAN_SLEEP) != 0) {\n\t\tprintk (MYIOC_s_ERR_FMT \"%s@%d::mptctl_do_reset - reset failed.\\n\",\n\t\t\tiocp->name, __FILE__, __LINE__);\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}", "label_name": "CWE-362", "label": "362"} -{"code": "R_API RBinJavaAnnotation *r_bin_java_annotation_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {\n\tut32 i = 0;\n\tRBinJavaAnnotation *annotation = NULL;\n\tRBinJavaElementValuePair *evps = NULL;\n\tut64 offset = 0;\n\tannotation = R_NEW0 (RBinJavaAnnotation);\n\tif (!annotation) {\n\t\treturn NULL;\n\t}\n\t// (ut16) read and set annotation_value.type_idx;\n\tannotation->type_idx = R_BIN_JAVA_USHORT (buffer, offset);\n\toffset += 2;\n\t// (ut16) read and set annotation_value.num_element_value_pairs;\n\tannotation->num_element_value_pairs = R_BIN_JAVA_USHORT (buffer, offset);\n\toffset += 2;\n\tannotation->element_value_pairs = r_list_newf (r_bin_java_element_pair_free);\n\t// read annotation_value.num_element_value_pairs, and append to annotation_value.element_value_pairs\n\tfor (i = 0; i < annotation->num_element_value_pairs; i++) {\n\t\tif (offset > sz) {\n\t\t\tbreak;\n\t\t}\n\t\tevps = r_bin_java_element_pair_new (buffer + offset, sz - offset, buf_offset + offset);\n\t\tif (evps) {\n\t\t\toffset += evps->size;\n\t\t\tr_list_append (annotation->element_value_pairs, (void *) evps);\n\t\t}\n\t}\n\tannotation->size = offset;\n\treturn annotation;\n}", "label_name": "CWE-119", "label": "119"} -{"code": "set PipeSocketHandler::listen(const SocketEndpoint& endpoint) {\n lock_guard guard(globalMutex);\n\n string pipePath = endpoint.name();\n if (pipeServerSockets.find(pipePath) != pipeServerSockets.end()) {\n throw runtime_error(\"Tried to listen twice on the same path\");\n }\n\n sockaddr_un local;\n\n int fd = socket(AF_UNIX, SOCK_STREAM, 0);\n FATAL_FAIL(fd);\n initServerSocket(fd);\n local.sun_family = AF_UNIX; /* local is declared before socket() ^ */\n strcpy(local.sun_path, pipePath.c_str());\n unlink(local.sun_path);\n\n FATAL_FAIL(::bind(fd, (struct sockaddr*)&local, sizeof(sockaddr_un)));\n ::listen(fd, 5);\n#ifndef WIN32\n FATAL_FAIL(::chmod(local.sun_path, S_IRUSR | S_IWUSR | S_IXUSR));\n#endif\n\n pipeServerSockets[pipePath] = set({fd});\n return pipeServerSockets[pipePath];\n}", "label_name": "CWE-362", "label": "362"} -{"code": "\t\tvoid Phase2() final {\n\t\t\tLocal context_handle = Deref(context);\n\t\t\tContext::Scope context_scope{context_handle};\n\t\t\tLocal object = Local::Cast(Deref(reference));\n\t\t\tresult = Unmaybe(object->Delete(context_handle, key->CopyInto()));\n\t\t}", "label_name": "CWE-913", "label": "913"} -{"code": "static inline char *parse_ip_address_ex(const char *str, size_t str_len, int *portno, int get_err, zend_string **err)\n{\n\tchar *colon;\n\tchar *host = NULL;\n\n#ifdef HAVE_IPV6\n\tchar *p;\n\n\tif (*(str) == '[' && str_len > 1) {\n\t\t/* IPV6 notation to specify raw address with port (i.e. [fe80::1]:80) */\n\t\tp = memchr(str + 1, ']', str_len - 2);\n\t\tif (!p || *(p + 1) != ':') {\n\t\t\tif (get_err) {\n\t\t\t\t*err = strpprintf(0, \"Failed to parse IPv6 address \\\"%s\\\"\", str);\n\t\t\t}\n\t\t\treturn NULL;\n\t\t}\n\t\t*portno = atoi(p + 2);\n\t\treturn estrndup(str + 1, p - str - 1);\n\t}\n#endif\n\tif (str_len) {\n\t\tcolon = memchr(str, ':', str_len - 1);\n\t} else {\n\t\tcolon = NULL;\n\t}\n\tif (colon) {\n\t\t*portno = atoi(colon + 1);\n\t\thost = estrndup(str, colon - str);\n\t} else {\n\t\tif (get_err) {\n\t\t\t*err = strpprintf(0, \"Failed to parse address \\\"%s\\\"\", str);\n\t\t}\n\t\treturn NULL;\n\t}\n\n\treturn host;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "ECDSA_PrivateKey::create_signature_op(RandomNumberGenerator& /*rng*/,\n const std::string& params,\n const std::string& provider) const\n {\n#if defined(BOTAN_HAS_BEARSSL)\n if(provider == \"bearssl\" || provider.empty())\n {\n try\n {\n return make_bearssl_ecdsa_sig_op(*this, params);\n }\n catch(Lookup_Error& e)\n {\n if(provider == \"bearssl\")\n throw;\n }\n }\n#endif\n\n#if defined(BOTAN_HAS_OPENSSL)\n if(provider == \"openssl\" || provider.empty())\n {\n try\n {\n return make_openssl_ecdsa_sig_op(*this, params);\n }\n catch(Lookup_Error& e)\n {\n if(provider == \"openssl\")\n throw;\n }\n }\n#endif\n\n if(provider == \"base\" || provider.empty())\n return std::unique_ptr(new ECDSA_Signature_Operation(*this, params));\n\n throw Provider_Not_Found(algo_name(), provider);\n }", "label_name": "CWE-200", "label": "200"} -{"code": "static bool is_legal_file(const std::string &filename)\n{\n\tDBG_FS << \"Looking for '\" << filename << \"'.\\n\";\n\n\tif (filename.empty()) {\n\t\tLOG_FS << \" invalid filename\\n\";\n\t\treturn false;\n\t}\n\n\tif (filename.find(\"..\") != std::string::npos) {\n\t\tERR_FS << \"Illegal path '\" << filename << \"' (\\\"..\\\" not allowed).\\n\";\n\t\treturn false;\n\t}\n\n\tif (ends_with(filename, \".pbl\")) {\n\t\tERR_FS << \"Illegal path '\" << filename << \"' (.pbl files are not allowed).\" << std::endl;\n\t\treturn false;\n\t}\n\n\treturn true;\n}", "label_name": "CWE-200", "label": "200"} -{"code": "int CLASS parse_jpeg(int offset)\n{\n int len, save, hlen, mark;\n fseek(ifp, offset, SEEK_SET);\n if (fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8)\n return 0;\n\n while (fgetc(ifp) == 0xff && (mark = fgetc(ifp)) != 0xda)\n {\n order = 0x4d4d;\n len = get2() - 2;\n save = ftell(ifp);\n if (mark == 0xc0 || mark == 0xc3 || mark == 0xc9)\n {\n fgetc(ifp);\n raw_height = get2();\n raw_width = get2();\n }\n order = get2();\n hlen = get4();\n if (get4() == 0x48454150) /* \"HEAP\" */\n {\n#ifdef LIBRAW_LIBRARY_BUILD\n imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;\n imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;\n#endif\n parse_ciff(save + hlen, len - hlen, 0);\n }\n if (parse_tiff(save + 6))\n apply_tiff();\n fseek(ifp, save + len, SEEK_SET);\n }\n return 1;\n}", "label_name": "CWE-119", "label": "119"} -{"code": "int linenoiseHistorySave(const char* filename) {\n FILE* fp = fopen(filename, \"wt\");\n if (fp == NULL) {\n return -1;\n }\n\n for (int j = 0; j < historyLen; ++j) {\n if (history[j][0] != '\\0') {\n fprintf(fp, \"%s\\n\", history[j]);\n }\n }\n fclose(fp);\n return 0;\n}", "label_name": "CWE-200", "label": "200"} -{"code": "uint64_t HeaderMapImpl::byteSize() const {\n uint64_t byte_size = 0;\n for (const HeaderEntryImpl& header : headers_) {\n byte_size += header.key().size();\n byte_size += header.value().size();\n }\n\n return byte_size;\n}", "label_name": "CWE-400", "label": "400"} -{"code": "void RemoteFsDevice::serviceRemoved(const QString &name)\n{\n if (name==details.serviceName && constSambaAvahiProtocol==details.url.scheme()) {\n sub=tr(\"Not Available\");\n updateStatus();\n }\n}", "label_name": "CWE-20", "label": "20"} -{"code": "CAMLprim value caml_blit_string(value s1, value ofs1, value s2, value ofs2,\n value n)\n{\n memmove(&Byte(s2, Long_val(ofs2)), &Byte(s1, Long_val(ofs1)), Int_val(n));\n return Val_unit;\n}", "label_name": "CWE-119", "label": "119"} -{"code": "void CIRCNetwork::SetEncoding(const CString& s) {\n m_sEncoding = s;\n if (GetIRCSock()) {\n GetIRCSock()->SetEncoding(s);\n }\n}", "label_name": "CWE-20", "label": "20"} -{"code": " static port::StatusOr Create(\n GpuExecutor* parent, int max_seq_length, int batch_size, int data_size,\n const absl::Span& seq_lengths, bool time_major,\n cudnnDataType_t data_type) {\n CHECK_GT(max_seq_length, 0);\n int dims[] = {batch_size, data_size, 1};\n int strides[] = {dims[1] * dims[2], dims[2], 1};\n TensorDescriptor tensor_desc = CreateTensorDescriptor();\n RETURN_IF_CUDNN_ERROR(cudnnSetTensorNdDescriptor(\n /*tensorDesc=*/tensor_desc.get(), /*dataType=*/data_type,\n /*nbDims=*/sizeof(dims) / sizeof(dims[0]), /*dimA=*/dims,\n /*strideA=*/strides));\n const int* seq_lengths_array = seq_lengths.data();\n RNNDataDescriptor data_desc = CreateRNNDataDescriptor();\n float padding_fill = 0.0f;\n cudnnRNNDataLayout_t layout;\n if (time_major) {\n layout = CUDNN_RNN_DATA_LAYOUT_SEQ_MAJOR_UNPACKED;\n } else {\n layout = CUDNN_RNN_DATA_LAYOUT_BATCH_MAJOR_UNPACKED;\n }\n RETURN_IF_CUDNN_ERROR(cudnnSetRNNDataDescriptor(\n /*RNNDataDesc=*/data_desc.get(), /*dataType*/ data_type,\n /*layout=*/layout,\n /*maxSeqLength=*/max_seq_length,\n /*batchSize=*/batch_size, /*vectorSize=*/data_size,\n /*seqLengthArray=*/seq_lengths_array,\n /*paddingFill*/ (void*)&padding_fill));\n return CudnnRnnSequenceTensorDescriptor(\n parent, max_seq_length, batch_size, data_size, data_type,\n std::move(data_desc), std::move(tensor_desc));\n }", "label_name": "CWE-20", "label": "20"} -{"code": "void ftoa_bounded_extra(JsVarFloat val,char *str, size_t len, int radix, int fractionalDigits) {\n const JsVarFloat stopAtError = 0.0000001;\n if (isnan(val)) strncpy(str,\"NaN\",len);\n else if (!isfinite(val)) {\n if (val<0) strncpy(str,\"-Infinity\",len);\n else strncpy(str,\"Infinity\",len);\n } else {\n if (val<0) {\n if (--len <= 0) { *str=0; return; } // bounds check\n *(str++) = '-';\n val = -val;\n }\n\n // what if we're really close to an integer? Just use that...\n if (((JsVarInt)(val+stopAtError)) == (1+(JsVarInt)val))\n val = (JsVarFloat)(1+(JsVarInt)val);\n\n JsVarFloat d = 1;\n while (d*radix <= val) d*=radix;\n while (d >= 1) {\n int v = (int)(val / d);\n val -= v*d;\n if (--len <= 0) { *str=0; return; } // bounds check\n *(str++) = itoch(v);\n d /= radix;\n }\n#ifndef USE_NO_FLOATS\n if (((fractionalDigits<0) && val>0) || fractionalDigits>0) {\n bool hasPt = false;\n val*=radix;\n while (((fractionalDigits<0) && (fractionalDigits>-12) && (val > stopAtError)) || (fractionalDigits > 0)) {\n int v = (int)(val+((fractionalDigits==1) ? 0.4 : 0.00000001) );\n val = (val-v)*radix;\n\tif (v==radix) v=radix-1;\n if (!hasPt) {\t\n\t hasPt = true;\n if (--len <= 0) { *str=0; return; } // bounds check\n *(str++)='.';\n }\n if (--len <= 0) { *str=0; return; } // bounds check\n *(str++)=itoch(v);\n fractionalDigits--;\n }\n }\n#endif\n\n *(str++)=0;\n }\n}", "label_name": "CWE-119", "label": "119"} -{"code": "R_API RBinJavaAttrInfo *r_bin_java_rtv_annotations_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {\n\tut32 i = 0;\n\tut64 offset = 0;\n\tif (buf_offset + 8 > sz) {\n\t\treturn NULL;\n\t}\n\tRBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);\n\toffset += 6;\n\tif (attr) {\n\t\tattr->type = R_BIN_JAVA_ATTR_TYPE_RUNTIME_VISIBLE_ANNOTATION_ATTR;\n\t\tattr->info.annotation_array.num_annotations = R_BIN_JAVA_USHORT (buffer, offset);\n\t\toffset += 2;\n\t\tattr->info.annotation_array.annotations = r_list_newf (r_bin_java_annotation_free);\n\t\tfor (i = 0; i < attr->info.annotation_array.num_annotations; i++) {\n\t\t\tif (offset >= sz) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tRBinJavaAnnotation *annotation = r_bin_java_annotation_new (buffer + offset, sz - offset, buf_offset + offset);\n\t\t\tif (annotation) {\n\t\t\t\toffset += annotation->size;\n\t\t\t\tr_list_append (attr->info.annotation_array.annotations, (void *) annotation);\n\t\t\t}\n\t\t}\n\t\tattr->size = offset;\n\t}\n\treturn attr;\n}", "label_name": "CWE-119", "label": "119"} -{"code": "int jas_seq2d_output(jas_matrix_t *matrix, FILE *out)\n{\n#define MAXLINELEN\t80\n\tint i;\n\tint j;\n\tjas_seqent_t x;\n\tchar buf[MAXLINELEN + 1];\n\tchar sbuf[MAXLINELEN + 1];\n\tint n;\n\n\tfprintf(out, \"%\"PRIiFAST32\" %\"PRIiFAST32\"\\n\", jas_seq2d_xstart(matrix),\n\t jas_seq2d_ystart(matrix));\n\tfprintf(out, \"%\"PRIiFAST32\" %\"PRIiFAST32\"\\n\", jas_matrix_numcols(matrix),\n\t jas_matrix_numrows(matrix));\n\n\tbuf[0] = '\\0';\n\tfor (i = 0; i < jas_matrix_numrows(matrix); ++i) {\n\t\tfor (j = 0; j < jas_matrix_numcols(matrix); ++j) {\n\t\t\tx = jas_matrix_get(matrix, i, j);\n\t\t\tsprintf(sbuf, \"%s%4ld\", (strlen(buf) > 0) ? \" \" : \"\",\n\t\t\t JAS_CAST(long, x));\n\t\t\tn = JAS_CAST(int, strlen(buf));\n\t\t\tif (n + JAS_CAST(int, strlen(sbuf)) > MAXLINELEN) {\n\t\t\t\tfputs(buf, out);\n\t\t\t\tfputs(\"\\n\", out);\n\t\t\t\tbuf[0] = '\\0';\n\t\t\t}\n\t\t\tstrcat(buf, sbuf);\n\t\t\tif (j == jas_matrix_numcols(matrix) - 1) {\n\t\t\t\tfputs(buf, out);\n\t\t\t\tfputs(\"\\n\", out);\n\t\t\t\tbuf[0] = '\\0';\n\t\t\t}\n\t\t}\n\t}\n\tfputs(buf, out);\n\n\treturn 0;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "CAMLprim value caml_bitvect_test(value bv, value n)\n{\n int pos = Int_val(n);\n return Val_int(Byte_u(bv, pos >> 3) & (1 << (pos & 7)));\n}", "label_name": "CWE-119", "label": "119"} -{"code": "static int em_fxsave(struct x86_emulate_ctxt *ctxt)\n{\n\tstruct fxregs_state fx_state;\n\tsize_t size;\n\tint rc;\n\n\trc = check_fxsr(ctxt);\n\tif (rc != X86EMUL_CONTINUE)\n\t\treturn rc;\n\n\tctxt->ops->get_fpu(ctxt);\n\n\trc = asm_safe(\"fxsave %[fx]\", , [fx] \"+m\"(fx_state));\n\n\tctxt->ops->put_fpu(ctxt);\n\n\tif (rc != X86EMUL_CONTINUE)\n\t\treturn rc;\n\n\tif (ctxt->ops->get_cr(ctxt, 4) & X86_CR4_OSFXSR)\n\t\tsize = offsetof(struct fxregs_state, xmm_space[8 * 16/4]);\n\telse\n\t\tsize = offsetof(struct fxregs_state, xmm_space[0]);\n\n\treturn segmented_write(ctxt, ctxt->memop.addr.mem, &fx_state, size);\n}", "label_name": "CWE-200", "label": "200"} -{"code": "int jas_matrix_resize(jas_matrix_t *matrix, int numrows, int numcols)\n{\n\tint size;\n\tint i;\n\n\tsize = numrows * numcols;\n\tif (size > matrix->datasize_ || numrows > matrix->maxrows_) {\n\t\treturn -1;\n\t}\n\n\tmatrix->numrows_ = numrows;\n\tmatrix->numcols_ = numcols;\n\n\tfor (i = 0; i < numrows; ++i) {\n\t\tmatrix->rows_[i] = &matrix->data_[numcols * i];\n\t}\n\n\treturn 0;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "void RemoteFsDevice::unmount()\n{\n if (details.isLocalFile()) {\n return;\n }\n\n if (!isConnected() || proc) {\n return;\n }\n\n if (messageSent) {\n return;\n }\n if (constSambaProtocol==details.url.scheme() || constSambaAvahiProtocol==details.url.scheme()) {\n mounter()->umount(mountPoint(details, false), getpid());\n setStatusMessage(tr(\"Disconnecting...\"));\n messageSent=true;\n return;\n }\n\n QString cmd;\n QStringList args;\n if (!details.isLocalFile()) {\n QString mp=mountPoint(details, false);\n if (!mp.isEmpty()) {\n cmd=Utils::findExe(\"fusermount\");\n if (!cmd.isEmpty()) {\n args << QLatin1String(\"-u\") << QLatin1String(\"-z\") << mp;\n } else {\n emit error(tr(\"\\\"fusermount\\\" is not installed!\"));\n }\n }\n }\n\n if (!cmd.isEmpty()) {\n setStatusMessage(tr(\"Disconnecting...\"));\n proc=new QProcess(this);\n proc->setProperty(\"unmount\", true);\n connect(proc, SIGNAL(finished(int)), SLOT(procFinished(int)));\n proc->start(cmd, args, QIODevice::ReadOnly);\n }\n}", "label_name": "CWE-20", "label": "20"} -{"code": "error_t tcpCheckSeqNum(Socket *socket, TcpHeader *segment, size_t length)\n{\n //Acceptability test for an incoming segment\n bool_t acceptable = FALSE;\n\n //Case where both segment length and receive window are zero\n if(!length && !socket->rcvWnd)\n {\n //Make sure that SEG.SEQ = RCV.NXT\n if(segment->seqNum == socket->rcvNxt)\n {\n acceptable = TRUE;\n }\n }\n //Case where segment length is zero and receive window is non zero\n else if(!length && socket->rcvWnd)\n {\n //Make sure that RCV.NXT <= SEG.SEQ < RCV.NXT+RCV.WND\n if(TCP_CMP_SEQ(segment->seqNum, socket->rcvNxt) >= 0 &&\n TCP_CMP_SEQ(segment->seqNum, socket->rcvNxt + socket->rcvWnd) < 0)\n {\n acceptable = TRUE;\n }\n }\n //Case where both segment length and receive window are non zero\n else if(length && socket->rcvWnd)\n {\n //Check whether RCV.NXT <= SEG.SEQ < RCV.NXT+RCV.WND\n if(TCP_CMP_SEQ(segment->seqNum, socket->rcvNxt) >= 0 &&\n TCP_CMP_SEQ(segment->seqNum, socket->rcvNxt + socket->rcvWnd) < 0)\n {\n acceptable = TRUE;\n }\n //or RCV.NXT <= SEG.SEQ+SEG.LEN-1 < RCV.NXT+RCV.WND\n else if(TCP_CMP_SEQ(segment->seqNum + length - 1, socket->rcvNxt) >= 0 &&\n TCP_CMP_SEQ(segment->seqNum + length - 1, socket->rcvNxt + socket->rcvWnd) < 0)\n {\n acceptable = TRUE;\n }\n }\n\n //Non acceptable sequence number?\n if(!acceptable)\n {\n //Debug message\n TRACE_WARNING(\"Sequence number is not acceptable!\\r\\n\");\n\n //If an incoming segment is not acceptable, an acknowledgment\n //should be sent in reply (unless the RST bit is set)\n if(!(segment->flags & TCP_FLAG_RST))\n tcpSendSegment(socket, TCP_FLAG_ACK, socket->sndNxt, socket->rcvNxt, 0, FALSE);\n\n //Return status code\n return ERROR_FAILURE;\n }\n\n //Sequence number is acceptable\n return NO_ERROR;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "void HeaderMapImpl::appendToHeader(HeaderString& header, absl::string_view data) {\n if (data.empty()) {\n return;\n }\n if (!header.empty()) {\n header.append(\",\", 1);\n }\n header.append(data.data(), data.size());\n}", "label_name": "CWE-400", "label": "400"} -{"code": "void ZlibInStream::deinit()\n{\n assert(zs != NULL);\n removeUnderlying();\n inflateEnd(zs);\n delete zs;\n zs = NULL;\n}", "label_name": "CWE-672", "label": "672"} -{"code": "parse_cosine_hex_dump(FILE_T fh, struct wtap_pkthdr *phdr, int pkt_len,\n Buffer* buf, int *err, gchar **err_info)\n{\n\tguint8 *pd;\n\tgchar\tline[COSINE_LINE_LENGTH];\n\tint\ti, hex_lines, n, caplen = 0;\n\n\t/* Make sure we have enough room for the packet */\n\tws_buffer_assure_space(buf, COSINE_MAX_PACKET_LEN);\n\tpd = ws_buffer_start_ptr(buf);\n\n\t/* Calculate the number of hex dump lines, each\n\t * containing 16 bytes of data */\n\thex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0);\n\n\tfor (i = 0; i < hex_lines; i++) {\n\t\tif (file_gets(line, COSINE_LINE_LENGTH, fh) == NULL) {\n\t\t\t*err = file_error(fh, err_info);\n\t\t\tif (*err == 0) {\n\t\t\t\t*err = WTAP_ERR_SHORT_READ;\n\t\t\t}\n\t\t\treturn FALSE;\n\t\t}\n\t\tif (empty_line(line)) {\n\t\t\tbreak;\n\t\t}\n\t\tif ((n = parse_single_hex_dump_line(line, pd, i*16)) == -1) {\n\t\t\t*err = WTAP_ERR_BAD_FILE;\n\t\t\t*err_info = g_strdup(\"cosine: hex dump line doesn't have 16 numbers\");\n\t\t\treturn FALSE;\n\t\t}\n\t\tcaplen += n;\n\t}\n\tphdr->caplen = caplen;\n\treturn TRUE;\n}", "label_name": "CWE-119", "label": "119"} -{"code": "RemoteDevicePropertiesWidget::RemoteDevicePropertiesWidget(QWidget *parent)\n : QWidget(parent)\n , modified(false)\n , saveable(false)\n{\n setupUi(this);\n if (qobject_cast(parent)) {\n verticalLayout->setMargin(4);\n }\n type->addItem(tr(\"Samba Share\"), (int)Type_Samba);\n type->addItem(tr(\"Samba Share (Auto-discover host and port)\"), (int)Type_SambaAvahi);\n type->addItem(tr(\"Secure Shell (sshfs)\"), (int)Type_SshFs);\n type->addItem(tr(\"Locally Mounted Folder\"), (int)Type_File);\n}", "label_name": "CWE-20", "label": "20"} -{"code": "compat_mptfwxfer_ioctl(struct file *filp, unsigned int cmd,\n\t\t\tunsigned long arg)\n{\n\tstruct mpt_fw_xfer32 kfw32;\n\tstruct mpt_fw_xfer kfw;\n\tMPT_ADAPTER *iocp = NULL;\n\tint iocnum, iocnumX;\n\tint nonblock = (filp->f_flags & O_NONBLOCK);\n\tint ret;\n\n\n\tif (copy_from_user(&kfw32, (char __user *)arg, sizeof(kfw32)))\n\t\treturn -EFAULT;\n\n\t/* Verify intended MPT adapter */\n\tiocnumX = kfw32.iocnum & 0xFF;\n\tif (((iocnum = mpt_verify_adapter(iocnumX, &iocp)) < 0) ||\n\t (iocp == NULL)) {\n\t\tprintk(KERN_DEBUG MYNAM \"::compat_mptfwxfer_ioctl @%d - ioc%d not found!\\n\",\n\t\t\t__LINE__, iocnumX);\n\t\treturn -ENODEV;\n\t}\n\n\tif ((ret = mptctl_syscall_down(iocp, nonblock)) != 0)\n\t\treturn ret;\n\n\tdctlprintk(iocp, printk(MYIOC_s_DEBUG_FMT \"compat_mptfwxfer_ioctl() called\\n\",\n\t iocp->name));\n\tkfw.iocnum = iocnum;\n\tkfw.fwlen = kfw32.fwlen;\n\tkfw.bufp = compat_ptr(kfw32.bufp);\n\n\tret = mptctl_do_fw_download(kfw.iocnum, kfw.bufp, kfw.fwlen);\n\n\tmutex_unlock(&iocp->ioctl_cmds.mutex);\n\n\treturn ret;\n}", "label_name": "CWE-362", "label": "362"} -{"code": " void readStructEnd() {\n lastFieldId_ = nestedStructFieldIds_.back();\n nestedStructFieldIds_.pop_back();\n }", "label_name": "CWE-674", "label": "674"} -{"code": "void skip(Protocol_& prot, TType arg_type) {\n switch (arg_type) {\n case TType::T_BOOL: {\n bool boolv;\n prot.readBool(boolv);\n return;\n }\n case TType::T_BYTE: {\n int8_t bytev;\n prot.readByte(bytev);\n return;\n }\n case TType::T_I16: {\n int16_t i16;\n prot.readI16(i16);\n return;\n }\n case TType::T_I32: {\n int32_t i32;\n prot.readI32(i32);\n return;\n }\n case TType::T_I64: {\n int64_t i64;\n prot.readI64(i64);\n return;\n }\n case TType::T_DOUBLE: {\n double dub;\n prot.readDouble(dub);\n return;\n }\n case TType::T_FLOAT: {\n float flt;\n prot.readFloat(flt);\n return;\n }\n case TType::T_STRING: {\n std::string str;\n prot.readBinary(str);\n return;\n }\n case TType::T_STRUCT: {\n std::string name;\n int16_t fid;\n TType ftype;\n prot.readStructBegin(name);\n while (true) {\n prot.readFieldBegin(name, ftype, fid);\n if (ftype == TType::T_STOP) {\n break;\n }\n apache::thrift::skip(prot, ftype);\n prot.readFieldEnd();\n }\n prot.readStructEnd();\n return;\n }\n case TType::T_MAP: {\n TType keyType;\n TType valType;\n uint32_t i, size;\n prot.readMapBegin(keyType, valType, size);\n for (i = 0; i < size; i++) {\n apache::thrift::skip(prot, keyType);\n apache::thrift::skip(prot, valType);\n }\n prot.readMapEnd();\n return;\n }\n case TType::T_SET: {\n TType elemType;\n uint32_t i, size;\n prot.readSetBegin(elemType, size);\n for (i = 0; i < size; i++) {\n apache::thrift::skip(prot, elemType);\n }\n prot.readSetEnd();\n return;\n }\n case TType::T_LIST: {\n TType elemType;\n uint32_t i, size;\n prot.readListBegin(elemType, size);\n for (i = 0; i < size; i++) {\n apache::thrift::skip(prot, elemType);\n }\n prot.readListEnd();\n return;\n }\n default:\n return;\n }\n}", "label_name": "CWE-755", "label": "755"} -{"code": "\t\tvoid Phase2() final {\n\t\t\tLocal context_handle = Deref(context);\n\t\t\tContext::Scope context_scope{context_handle};\n\t\t\tLocal key_inner = key->CopyInto();\n\t\t\tLocal object = Local::Cast(Deref(reference));\n\t\t\tbool allow = [&]() {\n\t\t\t\tif (!inherit) {\n\t\t\t\t\tif (key_inner->IsName()) {\n\t\t\t\t\t\treturn Unmaybe(object->HasRealNamedProperty(context_handle, key_inner.As()));\n\t\t\t\t\t} else if (key_inner->IsNumber()) {\n\t\t\t\t\t\treturn Unmaybe(object->HasRealIndexedProperty(context_handle, HandleCast(key_inner)));\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}();\n\t\t\tLocal value = allow ?\n\t\t\t\tUnmaybe(object->Get(context_handle, key_inner)) :\n\t\t\t\tUndefined(Isolate::GetCurrent()).As();\n\t\t\tret = TransferOut(value, options);\n\t\t}", "label_name": "CWE-913", "label": "913"} -{"code": "boost::optional SaplingNotePlaintext::decrypt(\n const SaplingEncCiphertext &ciphertext,\n const uint256 &ivk,\n const uint256 &epk,\n const uint256 &cmu\n)\n{\n auto pt = AttemptSaplingEncDecryption(ciphertext, ivk, epk);\n if (!pt) {\n return boost::none;\n }\n\n // Deserialize from the plaintext\n CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);\n ss << pt.get();\n\n SaplingNotePlaintext ret;\n ss >> ret;\n\n assert(ss.size() == 0);\n\n uint256 pk_d;\n if (!librustzcash_ivk_to_pkd(ivk.begin(), ret.d.data(), pk_d.begin())) {\n return boost::none;\n }\n\n uint256 cmu_expected;\n if (!librustzcash_sapling_compute_cm(\n ret.d.data(),\n pk_d.begin(),\n ret.value(),\n ret.rcm.begin(),\n cmu_expected.begin()\n ))\n {\n return boost::none;\n }\n\n if (cmu_expected != cmu) {\n return boost::none;\n }\n\n return ret;\n}", "label_name": "CWE-755", "label": "755"} -{"code": "static int em_ret_far(struct x86_emulate_ctxt *ctxt)\n{\n\tint rc;\n\tunsigned long eip, cs;\n\tu16 old_cs;\n\tint cpl = ctxt->ops->cpl(ctxt);\n\tstruct desc_struct old_desc, new_desc;\n\tconst struct x86_emulate_ops *ops = ctxt->ops;\n\n\tif (ctxt->mode == X86EMUL_MODE_PROT64)\n\t\tops->get_segment(ctxt, &old_cs, &old_desc, NULL,\n\t\t\t\t VCPU_SREG_CS);\n\n\trc = emulate_pop(ctxt, &eip, ctxt->op_bytes);\n\tif (rc != X86EMUL_CONTINUE)\n\t\treturn rc;\n\trc = emulate_pop(ctxt, &cs, ctxt->op_bytes);\n\tif (rc != X86EMUL_CONTINUE)\n\t\treturn rc;\n\t/* Outer-privilege level return is not implemented */\n\tif (ctxt->mode >= X86EMUL_MODE_PROT16 && (cs & 3) > cpl)\n\t\treturn X86EMUL_UNHANDLEABLE;\n\trc = __load_segment_descriptor(ctxt, (u16)cs, VCPU_SREG_CS, cpl,\n\t\t\t\t X86_TRANSFER_RET,\n\t\t\t\t &new_desc);\n\tif (rc != X86EMUL_CONTINUE)\n\t\treturn rc;\n\trc = assign_eip_far(ctxt, eip, &new_desc);\n\tif (rc != X86EMUL_CONTINUE) {\n\t\tWARN_ON(ctxt->mode != X86EMUL_MODE_PROT64);\n\t\tops->set_segment(ctxt, old_cs, &old_desc, 0, VCPU_SREG_CS);\n\t}\n\treturn rc;\n}", "label_name": "CWE-200", "label": "200"} -{"code": "void ComparisonQuantized(const TfLiteTensor* input1, const TfLiteTensor* input2,\n TfLiteTensor* output, bool requires_broadcast) {\n if (input1->type == kTfLiteUInt8 || input1->type == kTfLiteInt8) {\n auto input1_offset = -input1->params.zero_point;\n auto input2_offset = -input2->params.zero_point;\n const int left_shift = 8;\n\n int32 input1_multiplier;\n int input1_shift;\n QuantizeMultiplierSmallerThanOneExp(input1->params.scale,\n &input1_multiplier, &input1_shift);\n int32 input2_multiplier;\n int input2_shift;\n QuantizeMultiplierSmallerThanOneExp(input2->params.scale,\n &input2_multiplier, &input2_shift);\n\n ComparisonParams op_params;\n op_params.left_shift = left_shift;\n op_params.input1_offset = input1_offset;\n op_params.input1_multiplier = input1_multiplier;\n op_params.input1_shift = input1_shift;\n op_params.input2_offset = input2_offset;\n op_params.input2_multiplier = input2_multiplier;\n op_params.input2_shift = input2_shift;\n if (requires_broadcast) {\n reference_ops::BroadcastComparison4DSlowWithScaling(\n op_params, GetTensorShape(input1), GetTensorData(input1),\n GetTensorShape(input2), GetTensorData(input2),\n GetTensorShape(output), GetTensorData(output));\n } else {\n reference_ops::ComparisonWithScaling(\n op_params, GetTensorShape(input1), GetTensorData(input1),\n GetTensorShape(input2), GetTensorData(input2),\n GetTensorShape(output), GetTensorData(output));\n }\n }\n}", "label_name": "CWE-20", "label": "20"} -{"code": "static int em_jmp_far(struct x86_emulate_ctxt *ctxt)\n{\n\tint rc;\n\tunsigned short sel, old_sel;\n\tstruct desc_struct old_desc, new_desc;\n\tconst struct x86_emulate_ops *ops = ctxt->ops;\n\tu8 cpl = ctxt->ops->cpl(ctxt);\n\n\t/* Assignment of RIP may only fail in 64-bit mode */\n\tif (ctxt->mode == X86EMUL_MODE_PROT64)\n\t\tops->get_segment(ctxt, &old_sel, &old_desc, NULL,\n\t\t\t\t VCPU_SREG_CS);\n\n\tmemcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2);\n\n\trc = __load_segment_descriptor(ctxt, sel, VCPU_SREG_CS, cpl,\n\t\t\t\t X86_TRANSFER_CALL_JMP,\n\t\t\t\t &new_desc);\n\tif (rc != X86EMUL_CONTINUE)\n\t\treturn rc;\n\n\trc = assign_eip_far(ctxt, ctxt->src.val, &new_desc);\n\tif (rc != X86EMUL_CONTINUE) {\n\t\tWARN_ON(ctxt->mode != X86EMUL_MODE_PROT64);\n\t\t/* assigning eip failed; restore the old cs */\n\t\tops->set_segment(ctxt, old_sel, &old_desc, 0, VCPU_SREG_CS);\n\t\treturn rc;\n\t}\n\treturn rc;\n}", "label_name": "CWE-200", "label": "200"} -{"code": "inline typename V::VariantType FBUnserializer::unserializeThing() {\n size_t code = nextCode();\n\n switch (code) {\n case FB_SERIALIZE_BYTE:\n case FB_SERIALIZE_I16:\n case FB_SERIALIZE_I32:\n case FB_SERIALIZE_I64:\n return V::fromInt64(unserializeInt64());\n case FB_SERIALIZE_VARCHAR:\n case FB_SERIALIZE_STRING:\n return V::fromString(unserializeString());\n case FB_SERIALIZE_STRUCT:\n return V::fromMap(unserializeMap());\n case FB_SERIALIZE_NULL:\n ++p_;\n return V::createNull();\n case FB_SERIALIZE_DOUBLE:\n return V::fromDouble(unserializeDouble());\n case FB_SERIALIZE_BOOLEAN:\n return V::fromBool(unserializeBoolean());\n case FB_SERIALIZE_VECTOR:\n return V::fromVector(unserializeVector());\n case FB_SERIALIZE_LIST:\n return V::fromVector(unserializeList());\n case FB_SERIALIZE_SET:\n return V::fromSet(unserializeSet());\n default:\n throw UnserializeError(\"Invalid code: \" + folly::to(code)\n + \" at location \" + folly::to(p_));\n }\n}", "label_name": "CWE-674", "label": "674"} -{"code": "boost::optional SaplingOutgoingPlaintext::decrypt(\n const SaplingOutCiphertext &ciphertext,\n const uint256& ovk,\n const uint256& cv,\n const uint256& cm,\n const uint256& epk\n)\n{\n auto pt = AttemptSaplingOutDecryption(ciphertext, ovk, cv, cm, epk);\n if (!pt) {\n return boost::none;\n }\n\n // Deserialize from the plaintext\n CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);\n ss << pt.get();\n\n SaplingOutgoingPlaintext ret;\n ss >> ret;\n\n assert(ss.size() == 0);\n\n return ret;\n}", "label_name": "CWE-755", "label": "755"} -{"code": " static port::StatusOr Create(\n GpuExecutor* parent, int max_seq_length, int batch_size, int data_size,\n cudnnDataType_t data_type) {\n CHECK_GT(max_seq_length, 0);\n int dims[] = {batch_size, data_size, 1};\n int strides[] = {dims[1] * dims[2], dims[2], 1};\n TensorDescriptor tensor_desc = CreateTensorDescriptor();\n RETURN_IF_CUDNN_ERROR(cudnnSetTensorNdDescriptor(\n /*tensorDesc=*/tensor_desc.get(), /*dataType=*/data_type,\n /*nbDims=*/sizeof(dims) / sizeof(dims[0]), /*dimA=*/dims,\n /*strideA=*/strides));\n return CudnnRnnSequenceTensorDescriptor(parent, max_seq_length, batch_size,\n data_size, data_type,\n nullptr,\n std::move(tensor_desc));\n }", "label_name": "CWE-20", "label": "20"} -{"code": "void jas_matrix_bindsub(jas_matrix_t *mat0, jas_matrix_t *mat1, int r0,\n int c0, int r1, int c1)\n{\n\tint i;\n\n\tif (mat0->data_) {\n\t\tif (!(mat0->flags_ & JAS_MATRIX_REF)) {\n\t\t\tjas_free(mat0->data_);\n\t\t}\n\t\tmat0->data_ = 0;\n\t\tmat0->datasize_ = 0;\n\t}\n\tif (mat0->rows_) {\n\t\tjas_free(mat0->rows_);\n\t\tmat0->rows_ = 0;\n\t}\n\tmat0->flags_ |= JAS_MATRIX_REF;\n\tmat0->numrows_ = r1 - r0 + 1;\n\tmat0->numcols_ = c1 - c0 + 1;\n\tmat0->maxrows_ = mat0->numrows_;\n\tif (!(mat0->rows_ = jas_alloc2(mat0->maxrows_, sizeof(jas_seqent_t *)))) {\n\t\t/*\n\t\t\tThere is no way to indicate failure to the caller.\n\t\t\tSo, we have no choice but to abort.\n\t\t\tIdeally, this function should have a non-void return type.\n\t\t\tIn practice, a non-void return type probably would not help\n\t\t\tmuch anyways as the caller would just have to terminate anyways.\n\t\t*/\n\t\tabort();\n\t}\n\n\tfor (i = 0; i < mat0->numrows_; ++i) {\n\t\tmat0->rows_[i] = mat1->rows_[r0 + i] + c0;\n\t}\n\n\tmat0->xstart_ = mat1->xstart_ + c0;\n\tmat0->ystart_ = mat1->ystart_ + r0;\n\tmat0->xend_ = mat0->xstart_ + mat0->numcols_;\n\tmat0->yend_ = mat0->ystart_ + mat0->numrows_;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "auto ReferenceHandle::Get(Local key_handle, MaybeLocal maybe_options) -> Local {\n\treturn ThreePhaseTask::Run(*isolate, *this, key_handle, maybe_options, inherit);\n}", "label_name": "CWE-913", "label": "913"} -{"code": "void CLASS panasonic_load_raw()\n{\n int row, col, i, j, sh = 0, pred[2], nonz[2];\n\n pana_bits(0);\n for (row = 0; row < height; row++)\n {\n#ifdef LIBRAW_LIBRARY_BUILD\n checkCancel();\n#endif\n for (col = 0; col < raw_width; col++)\n {\n if ((i = col % 14) == 0)\n pred[0] = pred[1] = nonz[0] = nonz[1] = 0;\n if (i % 3 == 2)\n sh = 4 >> (3 - pana_bits(2));\n if (nonz[i & 1])\n {\n if ((j = pana_bits(8)))\n {\n if ((pred[i & 1] -= 0x80 << sh) < 0 || sh == 4)\n pred[i & 1] &= ~((~0u) << sh);\n pred[i & 1] += j << sh;\n }\n }\n else if ((nonz[i & 1] = pana_bits(8)) || i > 11)\n pred[i & 1] = nonz[i & 1] << 4 | pana_bits(4);\n if ((RAW(row, col) = pred[col & 1]) > 4098 && col < width)\n derror();\n }\n }\n}", "label_name": "CWE-119", "label": "119"} -{"code": "CAMLprim value caml_blit_string(value s1, value ofs1, value s2, value ofs2,\n value n)\n{\n memmove(&Byte(s2, Long_val(ofs2)), &Byte(s1, Long_val(ofs1)), Int_val(n));\n return Val_unit;\n}", "label_name": "CWE-200", "label": "200"} -{"code": "bool DNP3_Base::ParseAppLayer(Endpoint* endp)\n\t{\n\tbool orig = (endp == &orig_state);\n\tbinpac::DNP3::DNP3_Flow* flow = orig ? interp->upflow() : interp->downflow();\n\n\tu_char* data = endp->buffer + PSEUDO_TRANSPORT_INDEX; // The transport layer byte counts as app-layer it seems.\n\tint len = endp->pkt_length - 5;\n\n\t// DNP3 Packet : DNP3 Pseudo Link Layer | DNP3 Pseudo Transport Layer | DNP3 Pseudo Application Layer\n\t// DNP3 Serial Transport Layer data is always 1 byte.\n\t// Get FIN FIR seq field in transport header.\n\t// FIR indicate whether the following DNP3 Serial Application Layer is first chunk of bytes or not.\n\t// FIN indicate whether the following DNP3 Serial Application Layer is last chunk of bytes or not.\n\n\tint is_first = (endp->tpflags & 0x40) >> 6; // Initial chunk of data in this packet.\n\tint is_last = (endp->tpflags & 0x80) >> 7; // Last chunk of data in this packet.\n\n\tint transport = PSEUDO_TRANSPORT_LEN;\n\n\tint i = 0;\n\twhile ( len > 0 )\n\t\t{\n\t\tint n = min(len, 16);\n\n\t\t// Make sure chunk has a correct checksum.\n\t\tif ( ! CheckCRC(n, data, data + n, \"app_chunk\") )\n\t\t\treturn false;\n\n\t\t// Pass on to BinPAC.\n\t\tassert(data + n < endp->buffer + endp->buffer_len);\n\t\tflow->flow_buffer()->BufferData(data + transport, data + n);\n\t\ttransport = 0;\n\n\t\tdata += n + 2;\n\t\tlen -= n;\n\t\t}\n\n\tif ( is_first )\n\t\tendp->encountered_first_chunk = true;\n\n\tif ( ! is_first && ! endp->encountered_first_chunk )\n\t\t{\n\t\t// We lost the first chunk.\n\t\tanalyzer->Weird(\"dnp3_first_application_layer_chunk_missing\");\n\t\treturn false;\n\t\t}\n\n\tif ( is_last )\n\t\t{\n\t\tflow->flow_buffer()->FinishBuffer();\n\t\tflow->FlowEOF();\n\t\tClearEndpointState(orig);\n\t\t}\n\n\treturn true;\n\t}", "label_name": "CWE-119", "label": "119"} -{"code": "std::string get_wml_location(const std::string &filename, const std::string ¤t_dir)\n{\n\tDBG_FS << \"Looking for '\" << filename << \"'.\" << std::endl;\n\n\tassert(game_config::path.empty() == false);\n\n\tstd::string result;\n\n\tif (filename.empty()) {\n\t\tLOG_FS << \" invalid filename\" << std::endl;\n\t\treturn result;\n\t}\n\n\tif (filename.find(\"..\") != std::string::npos) {\n\t\tERR_FS << \"Illegal path '\" << filename << \"' (\\\"..\\\" not allowed).\" << std::endl;\n\t\treturn result;\n\t}\n\n\tif (ends_with(filename, \".pbl\")) {\n\t\tERR_FS << \"Illegal path '\" << filename << \"' (.pbl files are not allowed).\" << std::endl;\n\t\treturn result;\n\t}\n\n\tbool already_found = false;\n\n\tif (filename[0] == '~')\n\t{\n\t\t// If the filename starts with '~', look in the user data directory.\n\t\tresult = get_user_data_dir() + \"/data/\" + filename.substr(1);\n\t\tDBG_FS << \" trying '\" << result << \"'\" << std::endl;\n\n\t\talready_found = file_exists(result) || is_directory(result);\n\t}\n\telse if (filename.size() >= 2 && filename[0] == '.' && filename[1] == '/')\n\t{\n\t\t// If the filename begins with a \"./\", look in the same directory\n\t\t// as the file currently being preprocessed.\n\n\t\tif (!current_dir.empty())\n\t\t{\n\t\t\tresult = current_dir;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tresult = game_config::path;\n\t\t}\n\n\t\tresult += filename.substr(2);\n\t}\n\telse if (!game_config::path.empty())\n\t\tresult = game_config::path + \"/data/\" + filename;\n\n\tDBG_FS << \" trying '\" << result << \"'\" << std::endl;\n\n\tif (result.empty() ||\n\t (!already_found && !file_exists(result) && !is_directory(result)))\n\t{\n\t\tDBG_FS << \" not found\" << std::endl;\n\t\tresult.clear();\n\t}\n\telse\n\t\tDBG_FS << \" found: '\" << result << \"'\" << std::endl;\n\n\treturn result;\n}", "label_name": "CWE-200", "label": "200"} -{"code": "\tCmdResult HandleLocal(LocalUser* user, const Params& parameters) CXX11_OVERRIDE\n\t{\n\t\tsize_t origin = parameters.size() > 1 ? 1 : 0;\n\t\tif (parameters[origin].empty())\n\t\t{\n\t\t\tuser->WriteNumeric(ERR_NOORIGIN, \"No origin specified\");\n\t\t\treturn CMD_FAILURE;\n\t\t}\n\n\t\tClientProtocol::Messages::Pong pong(parameters[0], origin ? parameters[1] : \"\");\n\t\tuser->Send(ServerInstance->GetRFCEvents().pong, pong);\n\t\treturn CMD_SUCCESS;\n\t}", "label_name": "CWE-732", "label": "732"} -{"code": "set_ssl_ciphers(SCHANNEL_CRED *schannel_cred, char *ciphers)\n{\n char *startCur = ciphers;\n int algCount = 0;\n static ALG_ID algIds[45]; /*There are 45 listed in the MS headers*/\n while(startCur && (0 != *startCur) && (algCount < 45)) {\n long alg = strtol(startCur, 0, 0);\n if(!alg)\n alg = get_alg_id_by_name(startCur);\n if(alg)\n algIds[algCount++] = alg;\n else if(!strncmp(startCur, \"USE_STRONG_CRYPTO\",\n sizeof(\"USE_STRONG_CRYPTO\") - 1) ||\n !strncmp(startCur, \"SCH_USE_STRONG_CRYPTO\",\n sizeof(\"SCH_USE_STRONG_CRYPTO\") - 1))\n schannel_cred->dwFlags |= SCH_USE_STRONG_CRYPTO;\n else\n return CURLE_SSL_CIPHER;\n startCur = strchr(startCur, ':');\n if(startCur)\n startCur++;\n }\n schannel_cred->palgSupportedAlgs = algIds;\n schannel_cred->cSupportedAlgs = algCount;\n return CURLE_OK;\n}", "label_name": "CWE-668", "label": "668"} -{"code": "static int em_sysenter(struct x86_emulate_ctxt *ctxt)\n{\n\tconst struct x86_emulate_ops *ops = ctxt->ops;\n\tstruct desc_struct cs, ss;\n\tu64 msr_data;\n\tu16 cs_sel, ss_sel;\n\tu64 efer = 0;\n\n\tops->get_msr(ctxt, MSR_EFER, &efer);\n\t/* inject #GP if in real mode */\n\tif (ctxt->mode == X86EMUL_MODE_REAL)\n\t\treturn emulate_gp(ctxt, 0);\n\n\t/*\n\t * Not recognized on AMD in compat mode (but is recognized in legacy\n\t * mode).\n\t */\n\tif ((ctxt->mode == X86EMUL_MODE_PROT32) && (efer & EFER_LMA)\n\t && !vendor_intel(ctxt))\n\t\treturn emulate_ud(ctxt);\n\n\t/* sysenter/sysexit have not been tested in 64bit mode. */\n\tif (ctxt->mode == X86EMUL_MODE_PROT64)\n\t\treturn X86EMUL_UNHANDLEABLE;\n\n\tsetup_syscalls_segments(ctxt, &cs, &ss);\n\n\tops->get_msr(ctxt, MSR_IA32_SYSENTER_CS, &msr_data);\n\tswitch (ctxt->mode) {\n\tcase X86EMUL_MODE_PROT32:\n\t\tif ((msr_data & 0xfffc) == 0x0)\n\t\t\treturn emulate_gp(ctxt, 0);\n\t\tbreak;\n\tcase X86EMUL_MODE_PROT64:\n\t\tif (msr_data == 0x0)\n\t\t\treturn emulate_gp(ctxt, 0);\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n\n\tctxt->eflags &= ~(EFLG_VM | EFLG_IF);\n\tcs_sel = (u16)msr_data;\n\tcs_sel &= ~SELECTOR_RPL_MASK;\n\tss_sel = cs_sel + 8;\n\tss_sel &= ~SELECTOR_RPL_MASK;\n\tif (ctxt->mode == X86EMUL_MODE_PROT64 || (efer & EFER_LMA)) {\n\t\tcs.d = 0;\n\t\tcs.l = 1;\n\t}\n\n\tops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS);\n\tops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS);\n\n\tops->get_msr(ctxt, MSR_IA32_SYSENTER_EIP, &msr_data);\n\tctxt->_eip = msr_data;\n\n\tops->get_msr(ctxt, MSR_IA32_SYSENTER_ESP, &msr_data);\n\t*reg_write(ctxt, VCPU_REGS_RSP) = msr_data;\n\n\treturn X86EMUL_CONTINUE;\n}", "label_name": "CWE-269", "label": "269"} -{"code": "int LibRaw::subtract_black()\n{\n\tCHECK_ORDER_LOW(LIBRAW_PROGRESS_RAW2_IMAGE);\n\n\ttry {\n if(!is_phaseone_compressed() && (C.cblack[0] || C.cblack[1] || C.cblack[2] || C.cblack[3]))\n {\n#define BAYERC(row,col,c) imgdata.image[((row) >> IO.shrink)*S.iwidth + ((col) >> IO.shrink)][c] \n int cblk[4],i;\n for(i=0;i<4;i++)\n cblk[i] = C.cblack[i];\n\n int size = S.iheight * S.iwidth;\n#define MIN(a,b) ((a) < (b) ? (a) : (b))\n#define MAX(a,b) ((a) > (b) ? (a) : (b))\n#define LIM(x,min,max) MAX(min,MIN(x,max))\n#define CLIP(x) LIM(x,0,65535)\n\n for(i=0; i< size*4; i++)\n {\n int val = imgdata.image[0][i];\n val -= cblk[i & 3];\n imgdata.image[0][i] = CLIP(val);\n if(C.data_maximum < val) C.data_maximum = val;\n }\n#undef MIN\n#undef MAX\n#undef LIM\n#undef CLIP\n C.maximum -= C.black;\n ZERO(C.cblack);\n C.black = 0;\n#undef BAYERC\n }\n else\n {\n // Nothing to Do, maximum is already calculated, black level is 0, so no change\n // only calculate channel maximum;\n int idx;\n ushort *p = (ushort*)imgdata.image;\n C.data_maximum = 0;\n for(idx=0;idxflags_ = 0;\n\tmatrix->numrows_ = numrows;\n\tmatrix->numcols_ = numcols;\n\tmatrix->rows_ = 0;\n\tmatrix->maxrows_ = numrows;\n\tmatrix->data_ = 0;\n\tmatrix->datasize_ = 0;\n\n\t// matrix->datasize_ = numrows * numcols;\n\tif (!jas_safe_size_mul(numrows, numcols, &size)) {\n\t\tgoto error;\n\t}\n\tmatrix->datasize_ = size;\n\n\tif (matrix->maxrows_ > 0) {\n\t\tif (!(matrix->rows_ = jas_alloc2(matrix->maxrows_,\n\t\t sizeof(jas_seqent_t *)))) {\n\t\t\tgoto error;\n\t\t}\n\t}\n\n\tif (matrix->datasize_ > 0) {\n\t\tif (!(matrix->data_ = jas_alloc2(matrix->datasize_,\n\t\t sizeof(jas_seqent_t)))) {\n\t\t\tgoto error;\n\t\t}\n\t}\n\n\tfor (i = 0; i < numrows; ++i) {\n\t\tmatrix->rows_[i] = &matrix->data_[i * matrix->numcols_];\n\t}\n\n\tfor (i = 0; i < matrix->datasize_; ++i) {\n\t\tmatrix->data_[i] = 0;\n\t}\n\n\tmatrix->xstart_ = 0;\n\tmatrix->ystart_ = 0;\n\tmatrix->xend_ = matrix->numcols_;\n\tmatrix->yend_ = matrix->numrows_;\n\n\treturn matrix;\n\nerror:\n\tif (matrix) {\n\t\tjas_matrix_destroy(matrix);\n\t}\n\treturn 0;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "error_t coapServerFormatReset(CoapServerContext *context, uint16_t mid)\n{\n CoapMessageHeader *header;\n\n //Point to the CoAP response header\n header = (CoapMessageHeader *) context->response.buffer;\n\n //Format Reset message\n header->version = COAP_VERSION_1;\n header->type = COAP_TYPE_RST;\n header->tokenLen = 0;\n header->code = COAP_CODE_EMPTY;\n\n //The Reset message message must echo the message ID of the confirmable\n //message and must be empty (refer to RFC 7252, section 4.2)\n header->mid = htons(mid);\n\n //Set the length of the CoAP message\n context->response.length = sizeof(CoapMessageHeader);\n\n //Sucessful processing\n return NO_ERROR;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "static inline bool isMountable(const RemoteFsDevice::Details &d)\n{\n return RemoteFsDevice::constSshfsProtocol==d.url.scheme() ||\n RemoteFsDevice::constSambaProtocol==d.url.scheme() || RemoteFsDevice::constSambaAvahiProtocol==d.url.scheme();\n}", "label_name": "CWE-20", "label": "20"} -{"code": " void operator = (const IniSection &s)\n\t{\n\t if (&s == this)\n\t {\n\t\treturn;\n\t } \n\t IniBase::operator = (s);\n\t ip = s.ip;\n\t end_comment = s.end_comment; rewrite_by = s.rewrite_by;\n\t container = s.container;\n\n\t reindex ();\n\t}", "label_name": "CWE-200", "label": "200"} -{"code": "char *QuotedString::extractFrom(char *input, char **endPtr) {\n char firstChar = *input;\n\n if (!isQuote(firstChar)) {\n // must start with a quote\n return NULL;\n }\n\n char stopChar = firstChar; // closing quote is the same as opening quote\n\n char *startPtr = input + 1; // skip the quote\n char *readPtr = startPtr;\n char *writePtr = startPtr;\n char c;\n\n for (;;) {\n c = *readPtr++;\n\n if (c == '\\0') {\n // premature ending\n return NULL;\n }\n\n if (c == stopChar) {\n // closing quote\n break;\n }\n\n if (c == '\\\\') {\n // replace char\n c = unescapeChar(*readPtr++);\n }\n\n *writePtr++ = c;\n }\n\n // end the string here\n *writePtr = '\\0';\n\n // update end ptr\n *endPtr = readPtr;\n\n return startPtr;\n}", "label_name": "CWE-119", "label": "119"} -{"code": "mptctl_replace_fw (unsigned long arg)\n{\n\tstruct mpt_ioctl_replace_fw __user *uarg = (void __user *) arg;\n\tstruct mpt_ioctl_replace_fw\t karg;\n\tMPT_ADAPTER\t\t *ioc;\n\tint\t\t\t iocnum;\n\tint\t\t\t newFwSize;\n\n\tif (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_replace_fw))) {\n\t\tprintk(KERN_ERR MYNAM \"%s@%d::mptctl_replace_fw - \"\n\t\t\t\"Unable to read in mpt_ioctl_replace_fw struct @ %p\\n\",\n\t\t\t\t__FILE__, __LINE__, uarg);\n\t\treturn -EFAULT;\n\t}\n\n\tif (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||\n\t (ioc == NULL)) {\n\t\tprintk(KERN_DEBUG MYNAM \"%s::mptctl_replace_fw() @%d - ioc%d not found!\\n\",\n\t\t\t\t__FILE__, __LINE__, iocnum);\n\t\treturn -ENODEV;\n\t}\n\n\tdctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT \"mptctl_replace_fw called.\\n\",\n\t ioc->name));\n\t/* If caching FW, Free the old FW image\n\t */\n\tif (ioc->cached_fw == NULL)\n\t\treturn 0;\n\n\tmpt_free_fw_memory(ioc);\n\n\t/* Allocate memory for the new FW image\n\t */\n\tnewFwSize = ALIGN(karg.newImageSize, 4);\n\n\tmpt_alloc_fw_memory(ioc, newFwSize);\n\tif (ioc->cached_fw == NULL)\n\t\treturn -ENOMEM;\n\n\t/* Copy the data from user memory to kernel space\n\t */\n\tif (copy_from_user(ioc->cached_fw, uarg->newImage, newFwSize)) {\n\t\tprintk(MYIOC_s_ERR_FMT \"%s@%d::mptctl_replace_fw - \"\n\t\t\t\t\"Unable to read in mpt_ioctl_replace_fw image \"\n\t\t\t\t\"@ %p\\n\", ioc->name, __FILE__, __LINE__, uarg);\n\t\tmpt_free_fw_memory(ioc);\n\t\treturn -EFAULT;\n\t}\n\n\t/* Update IOCFactsReply\n\t */\n\tioc->facts.FWImageSize = newFwSize;\n\treturn 0;\n}", "label_name": "CWE-362", "label": "362"} -{"code": "\tbool is_print(char c) { return c >= 32 && c < 127; }", "label_name": "CWE-119", "label": "119"} -{"code": "\t\tvoid Phase2() final {\n\t\t\tLocal context_handle = Deref(context);\n\t\t\tContext::Scope context_scope{context_handle};\n\t\t\tLocal key_inner = key->CopyInto();\n\t\t\tLocal object = Local::Cast(Deref(reference));\n\t\t\t// Delete key before transferring in, potentially freeing up some v8 heap\n\t\t\tUnmaybe(object->Delete(context_handle, key_inner));\n\t\t\tLocal val_inner = val->TransferIn();\n\t\t\tdid_set = Unmaybe(object->Set(context_handle, key_inner, val_inner));\n\t\t}", "label_name": "CWE-913", "label": "913"} -{"code": "CAMLprim value caml_bitvect_test(value bv, value n)\n{\n int pos = Int_val(n);\n return Val_int(Byte_u(bv, pos >> 3) & (1 << (pos & 7)));\n}", "label_name": "CWE-200", "label": "200"} -{"code": "jas_matrix_t *jas_matrix_copy(jas_matrix_t *x)\n{\n\tjas_matrix_t *y;\n\tint i;\n\tint j;\n\ty = jas_matrix_create(x->numrows_, x->numcols_);\n\tfor (i = 0; i < x->numrows_; ++i) {\n\t\tfor (j = 0; j < x->numcols_; ++j) {\n\t\t\t*jas_matrix_getref(y, i, j) = jas_matrix_get(x, i, j);\n\t\t}\n\t}\n\treturn y;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "char *Hub::inflate(char *data, size_t &length) {\n dynamicInflationBuffer.clear();\n\n inflationStream.next_in = (Bytef *) data;\n inflationStream.avail_in = length;\n\n int err;\n do {\n inflationStream.next_out = (Bytef *) inflationBuffer;\n inflationStream.avail_out = LARGE_BUFFER_SIZE;\n err = ::inflate(&inflationStream, Z_FINISH);\n if (!inflationStream.avail_in) {\n break;\n }\n dynamicInflationBuffer.append(inflationBuffer, LARGE_BUFFER_SIZE - inflationStream.avail_out);\n } while (err == Z_BUF_ERROR);\n\n inflateReset(&inflationStream);\n\n if (err != Z_BUF_ERROR && err != Z_OK) {\n length = 0;\n return nullptr;\n }\n\n if (dynamicInflationBuffer.length()) {\n dynamicInflationBuffer.append(inflationBuffer, LARGE_BUFFER_SIZE - inflationStream.avail_out);\n\n length = dynamicInflationBuffer.length();\n return (char *) dynamicInflationBuffer.data();\n }\n\n length = LARGE_BUFFER_SIZE - inflationStream.avail_out;\n return inflationBuffer;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "bool ParseAttrValue(StringPiece type, StringPiece text, AttrValue* out) {\n // Parse type.\n string field_name;\n bool is_list = absl::ConsumePrefix(&type, \"list(\");\n if (absl::ConsumePrefix(&type, \"string\")) {\n field_name = \"s\";\n } else if (absl::ConsumePrefix(&type, \"int\")) {\n field_name = \"i\";\n } else if (absl::ConsumePrefix(&type, \"float\")) {\n field_name = \"f\";\n } else if (absl::ConsumePrefix(&type, \"bool\")) {\n field_name = \"b\";\n } else if (absl::ConsumePrefix(&type, \"type\")) {\n field_name = \"type\";\n } else if (absl::ConsumePrefix(&type, \"shape\")) {\n field_name = \"shape\";\n } else if (absl::ConsumePrefix(&type, \"tensor\")) {\n field_name = \"tensor\";\n } else if (absl::ConsumePrefix(&type, \"func\")) {\n field_name = \"func\";\n } else if (absl::ConsumePrefix(&type, \"placeholder\")) {\n field_name = \"placeholder\";\n } else {\n return false;\n }\n if (is_list && !absl::ConsumePrefix(&type, \")\")) {\n return false;\n }\n\n // Construct a valid text proto message to parse.\n string to_parse;\n if (is_list) {\n // TextFormat parser considers \"i: 7\" to be the same as \"i: [7]\",\n // but we only want to allow list values with [].\n StringPiece cleaned = text;\n str_util::RemoveLeadingWhitespace(&cleaned);\n str_util::RemoveTrailingWhitespace(&cleaned);\n if (cleaned.size() < 2 || cleaned[0] != '[' ||\n cleaned[cleaned.size() - 1] != ']') {\n return false;\n }\n cleaned.remove_prefix(1);\n str_util::RemoveLeadingWhitespace(&cleaned);\n if (cleaned.size() == 1) {\n // User wrote \"[]\", so return empty list without invoking the TextFormat\n // parse which returns an error for \"i: []\".\n out->Clear();\n out->mutable_list();\n return true;\n }\n to_parse = strings::StrCat(\"list { \", field_name, \": \", text, \" }\");\n } else {\n to_parse = strings::StrCat(field_name, \": \", text);\n }\n\n return ProtoParseFromString(to_parse, out);\n}", "label_name": "CWE-674", "label": "674"} -{"code": "jas_image_t *jas_image_create(int numcmpts, jas_image_cmptparm_t *cmptparms,\n int clrspc)\n{\n\tjas_image_t *image;\n\tuint_fast32_t rawsize;\n\tuint_fast32_t inmem;\n\tint cmptno;\n\tjas_image_cmptparm_t *cmptparm;\n\n\tif (!(image = jas_image_create0())) {\n\t\treturn 0;\n\t}\n\n\timage->clrspc_ = clrspc;\n\timage->maxcmpts_ = numcmpts;\n\timage->inmem_ = true;\n\n\t/* Allocate memory for the per-component information. */\n\tif (!(image->cmpts_ = jas_alloc2(image->maxcmpts_,\n\t sizeof(jas_image_cmpt_t *)))) {\n\t\tjas_image_destroy(image);\n\t\treturn 0;\n\t}\n\t/* Initialize in case of failure. */\n\tfor (cmptno = 0; cmptno < image->maxcmpts_; ++cmptno) {\n\t\timage->cmpts_[cmptno] = 0;\n\t}\n\n\t/* Compute the approximate raw size of the image. */\n\trawsize = 0;\n\tfor (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno,\n\t ++cmptparm) {\n\t\trawsize += cmptparm->width * cmptparm->height *\n\t\t (cmptparm->prec + 7) / 8;\n\t}\n\t/* Decide whether to buffer the image data in memory, based on the\n\t raw size of the image. */\n\tinmem = (rawsize < JAS_IMAGE_INMEMTHRESH);\n\n\t/* Create the individual image components. */\n\tfor (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno,\n\t ++cmptparm) {\n\t\tif (!(image->cmpts_[cmptno] = jas_image_cmpt_create(cmptparm->tlx,\n\t\t cmptparm->tly, cmptparm->hstep, cmptparm->vstep,\n\t\t cmptparm->width, cmptparm->height, cmptparm->prec,\n\t\t cmptparm->sgnd, inmem))) {\n\t\t\tjas_image_destroy(image);\n\t\t\treturn 0;\n\t\t}\n\t\t++image->numcmpts_;\n\t}\n\n\t/* Determine the bounding box for all of the components on the\n\t reference grid (i.e., the image area) */\n\tjas_image_setbbox(image);\n\n\treturn image;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "armv6pmu_handle_irq(int irq_num,\n\t\t void *dev)\n{\n\tunsigned long pmcr = armv6_pmcr_read();\n\tstruct perf_sample_data data;\n\tstruct cpu_hw_events *cpuc;\n\tstruct pt_regs *regs;\n\tint idx;\n\n\tif (!armv6_pmcr_has_overflowed(pmcr))\n\t\treturn IRQ_NONE;\n\n\tregs = get_irq_regs();\n\n\t/*\n\t * The interrupts are cleared by writing the overflow flags back to\n\t * the control register. All of the other bits don't have any effect\n\t * if they are rewritten, so write the whole value back.\n\t */\n\tarmv6_pmcr_write(pmcr);\n\n\tperf_sample_data_init(&data, 0);\n\n\tcpuc = &__get_cpu_var(cpu_hw_events);\n\tfor (idx = 0; idx <= armpmu->num_events; ++idx) {\n\t\tstruct perf_event *event = cpuc->events[idx];\n\t\tstruct hw_perf_event *hwc;\n\n\t\tif (!test_bit(idx, cpuc->active_mask))\n\t\t\tcontinue;\n\n\t\t/*\n\t\t * We have a single interrupt for all counters. Check that\n\t\t * each counter has overflowed before we process it.\n\t\t */\n\t\tif (!armv6_pmcr_counter_has_overflowed(pmcr, idx))\n\t\t\tcontinue;\n\n\t\thwc = &event->hw;\n\t\tarmpmu_event_update(event, hwc, idx, 1);\n\t\tdata.period = event->hw.last_period;\n\t\tif (!armpmu_event_set_period(event, hwc, idx))\n\t\t\tcontinue;\n\n\t\tif (perf_event_overflow(event, 0, &data, regs))\n\t\t\tarmpmu->disable(hwc, idx);\n\t}\n\n\t/*\n\t * Handle the pending perf events.\n\t *\n\t * Note: this call *must* be run with interrupts disabled. For\n\t * platforms that can have the PMU interrupts raised as an NMI, this\n\t * will not work.\n\t */\n\tirq_work_run();\n\n\treturn IRQ_HANDLED;\n}", "label_name": "CWE-400", "label": "400"} -{"code": " static const char* ConvertScalar(PyObject* v, Eigen::half* out) {\n // NOTE(nareshmodi): Is there a way to convert to C double without the\n // intermediate Python double? This will help with ConvertOneFloat as well.\n Safe_PyObjectPtr as_float = make_safe(PyNumber_Float(v));\n double v_double = PyFloat_AS_DOUBLE(as_float.get());\n *out = Eigen::half(v_double);\n\n return nullptr;\n }", "label_name": "CWE-20", "label": "20"} -{"code": "int bmp_validate(jas_stream_t *in)\n{\n\tint n;\n\tint i;\n\tuchar buf[2];\n\n\tassert(JAS_STREAM_MAXPUTBACK >= 2);\n\n\t/* Read the first two characters that constitute the signature. */\n\tif ((n = jas_stream_read(in, (char *) buf, 2)) < 0) {\n\t\treturn -1;\n\t}\n\t/* Put the characters read back onto the stream. */\n\tfor (i = n - 1; i >= 0; --i) {\n\t\tif (jas_stream_ungetc(in, buf[i]) == EOF) {\n\t\t\treturn -1;\n\t\t}\n\t}\n\t/* Did we read enough characters? */\n\tif (n < 2) {\n\t\treturn -1;\n\t}\n\t/* Is the signature correct for the BMP format? */\n\tif (buf[0] == (BMP_MAGIC & 0xff) && buf[1] == (BMP_MAGIC >> 8)) {\n\t\treturn 0;\n\t}\n\treturn -1;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "void HeaderMapImpl::addCopy(const LowerCaseString& key, const std::string& value) {\n auto* entry = getExistingInline(key.get());\n if (entry != nullptr) {\n appendToHeader(entry->value(), value);\n return;\n }\n HeaderString new_key;\n new_key.setCopy(key.get().c_str(), key.get().size());\n HeaderString new_value;\n new_value.setCopy(value.c_str(), value.size());\n insertByKey(std::move(new_key), std::move(new_value));\n ASSERT(new_key.empty()); // NOLINT(bugprone-use-after-move)\n ASSERT(new_value.empty()); // NOLINT(bugprone-use-after-move)\n}", "label_name": "CWE-400", "label": "400"} -{"code": "void Ogg::XiphComment::parse(const ByteVector &data)\n{\n // The first thing in the comment data is the vendor ID length, followed by a\n // UTF8 string with the vendor ID.\n\n int pos = 0;\n\n int vendorLength = data.mid(0, 4).toUInt(false);\n pos += 4;\n\n d->vendorID = String(data.mid(pos, vendorLength), String::UTF8);\n pos += vendorLength;\n\n // Next the number of fields in the comment vector.\n\n int commentFields = data.mid(pos, 4).toUInt(false);\n pos += 4;\n\n for(int i = 0; i < commentFields; i++) {\n\n // Each comment field is in the format \"KEY=value\" in a UTF8 string and has\n // 4 bytes before the text starts that gives the length.\n\n int commentLength = data.mid(pos, 4).toUInt(false);\n pos += 4;\n\n String comment = String(data.mid(pos, commentLength), String::UTF8);\n pos += commentLength;\n\n int commentSeparatorPosition = comment.find(\"=\");\n\n String key = comment.substr(0, commentSeparatorPosition);\n String value = comment.substr(commentSeparatorPosition + 1);\n\n addField(key, value, false);\n }\n}", "label_name": "CWE-20", "label": "20"} -{"code": "R_API RBinJavaVerificationObj *r_bin_java_verification_info_from_type(RBinJavaObj *bin, R_BIN_JAVA_STACKMAP_TYPE type, ut32 value) {\n\tRBinJavaVerificationObj *se = R_NEW0 (RBinJavaVerificationObj);\n\tif (!se) {\n\t\treturn NULL;\n\t}\n\tse->tag = type;\n\tif (se->tag == R_BIN_JAVA_STACKMAP_OBJECT) {\n\t\tse->info.obj_val_cp_idx = (ut16) value;\n\t} else if (se->tag == R_BIN_JAVA_STACKMAP_UNINIT) {\n\t\t/*if (bin->offset_sz == 4) {\n\t\tse->info.uninit_offset = value;\n\t\t} else {\n\t\tse->info.uninit_offset = (ut16) value;\n\t\t}*/\n\t\tse->info.uninit_offset = (ut16) value;\n\t}\n\treturn se;\n}", "label_name": "CWE-119", "label": "119"} -{"code": "void CZNC::ForceEncoding() {\n m_uiForceEncoding++;\n#ifdef HAVE_ICU\n for (Csock* pSock : GetManager()) {\n if (pSock->GetEncoding().empty()) {\n pSock->SetEncoding(\"UTF-8\");\n }\n }\n#endif\n}", "label_name": "CWE-20", "label": "20"} -{"code": "void ZlibInStream::removeUnderlying()\n{\n ptr = end = start;\n if (!underlying) return;\n\n while (bytesIn > 0) {\n decompress(true);\n end = start; // throw away any data\n }\n underlying = 0;\n}", "label_name": "CWE-672", "label": "672"} -{"code": "HttpIntegrationTest::waitForNextUpstreamRequest(const std::vector& upstream_indices) {\n uint64_t upstream_with_request;\n // If there is no upstream connection, wait for it to be established.\n if (!fake_upstream_connection_) {\n\n AssertionResult result = AssertionFailure();\n for (auto upstream_index : upstream_indices) {\n result = fake_upstreams_[upstream_index]->waitForHttpConnection(\n *dispatcher_, fake_upstream_connection_, TestUtility::DefaultTimeout,\n max_request_headers_kb_);\n if (result) {\n upstream_with_request = upstream_index;\n break;\n }\n }\n RELEASE_ASSERT(result, result.message());\n }\n // Wait for the next stream on the upstream connection.\n AssertionResult result =\n fake_upstream_connection_->waitForNewStream(*dispatcher_, upstream_request_);\n RELEASE_ASSERT(result, result.message());\n // Wait for the stream to be completely received.\n result = upstream_request_->waitForEndStream(*dispatcher_);\n RELEASE_ASSERT(result, result.message());\n\n return upstream_with_request;\n}", "label_name": "CWE-400", "label": "400"} -{"code": "void skip(Protocol_& prot, TType arg_type) {\n switch (arg_type) {\n case TType::T_BOOL: {\n bool boolv;\n prot.readBool(boolv);\n return;\n }\n case TType::T_BYTE: {\n int8_t bytev;\n prot.readByte(bytev);\n return;\n }\n case TType::T_I16: {\n int16_t i16;\n prot.readI16(i16);\n return;\n }\n case TType::T_I32: {\n int32_t i32;\n prot.readI32(i32);\n return;\n }\n case TType::T_I64: {\n int64_t i64;\n prot.readI64(i64);\n return;\n }\n case TType::T_DOUBLE: {\n double dub;\n prot.readDouble(dub);\n return;\n }\n case TType::T_FLOAT: {\n float flt;\n prot.readFloat(flt);\n return;\n }\n case TType::T_STRING: {\n std::string str;\n prot.readBinary(str);\n return;\n }\n case TType::T_STRUCT: {\n std::string name;\n int16_t fid;\n TType ftype;\n prot.readStructBegin(name);\n while (true) {\n prot.readFieldBegin(name, ftype, fid);\n if (ftype == TType::T_STOP) {\n break;\n }\n apache::thrift::skip(prot, ftype);\n prot.readFieldEnd();\n }\n prot.readStructEnd();\n return;\n }\n case TType::T_MAP: {\n TType keyType;\n TType valType;\n uint32_t i, size;\n prot.readMapBegin(keyType, valType, size);\n for (i = 0; i < size; i++) {\n apache::thrift::skip(prot, keyType);\n apache::thrift::skip(prot, valType);\n }\n prot.readMapEnd();\n return;\n }\n case TType::T_SET: {\n TType elemType;\n uint32_t i, size;\n prot.readSetBegin(elemType, size);\n for (i = 0; i < size; i++) {\n apache::thrift::skip(prot, elemType);\n }\n prot.readSetEnd();\n return;\n }\n case TType::T_LIST: {\n TType elemType;\n uint32_t i, size;\n prot.readListBegin(elemType, size);\n for (i = 0; i < size; i++) {\n apache::thrift::skip(prot, elemType);\n }\n prot.readListEnd();\n return;\n }\n default:\n return;\n }\n}", "label_name": "CWE-755", "label": "755"} -{"code": "void SSecurityTLS::initGlobal()\n{\n static bool globalInitDone = false;\n\n if (!globalInitDone) {\n if (gnutls_global_init() != GNUTLS_E_SUCCESS)\n throw AuthFailureException(\"gnutls_global_init failed\");\n globalInitDone = true;\n }\n}", "label_name": "CWE-119", "label": "119"} -{"code": "jas_seq2d_t *jas_seq2d_copy(jas_seq2d_t *x)\n{\n\tjas_matrix_t *y;\n\tint i;\n\tint j;\n\ty = jas_seq2d_create(jas_seq2d_xstart(x), jas_seq2d_ystart(x),\n\t jas_seq2d_xend(x), jas_seq2d_yend(x));\n\tassert(y);\n\tfor (i = 0; i < x->numrows_; ++i) {\n\t\tfor (j = 0; j < x->numcols_; ++j) {\n\t\t\t*jas_matrix_getref(y, i, j) = jas_matrix_get(x, i, j);\n\t\t}\n\t}\n\treturn y;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "auto ReferenceHandle::New(Local value, MaybeLocal options) -> unique_ptr {\n\tauto inherit = ReadOption(options, StringTable::Get().inheritUnsafe, false);\n\treturn std::make_unique(value, inherit);\n}", "label_name": "CWE-913", "label": "913"} -{"code": "void jslGetTokenString(char *str, size_t len) {\n if (lex->tk == LEX_ID) {\n strncpy(str, \"ID:\", len);\n strncat(str, jslGetTokenValueAsString(), len);\n } else if (lex->tk == LEX_STR) {\n strncpy(str, \"String:'\", len);\n strncat(str, jslGetTokenValueAsString(), len);\n strncat(str, \"'\", len);\n } else\n jslTokenAsString(lex->tk, str, len);\n}", "label_name": "CWE-119", "label": "119"} -{"code": "void LibRaw::exp_bef(float shift, float smooth)\n{\n // params limits\n if(shift>8) shift = 8;\n if(shift<0.25) shift = 0.25;\n if(smooth < 0.0) smooth = 0.0;\n if(smooth > 1.0) smooth = 1.0;\n \n unsigned short *lut = (ushort*)malloc((TBLN+1)*sizeof(unsigned short));\n\n if(shift <=1.0)\n {\n for(int i=0;i<=TBLN;i++)\n lut[i] = (unsigned short)((float)i*shift);\n }\n else\n {\n float x1,x2,y1,y2;\n\n float cstops = log(shift)/log(2.0f);\n float room = cstops*2;\n float roomlin = powf(2.0f,room);\n x2 = (float)TBLN;\n x1 = (x2+1)/roomlin-1;\n y1 = x1*shift;\n y2 = x2*(1+(1-smooth)*(shift-1));\n float sq3x=powf(x1*x1*x2,1.0f/3.0f);\n float B = (y2-y1+shift*(3*x1-3.0f*sq3x)) / (x2+2.0f*x1-3.0f*sq3x);\n float A = (shift - B)*3.0f*powf(x1*x1,1.0f/3.0f);\n float CC = y2 - A*powf(x2,1.0f/3.0f)-B*x2;\n for(int i=0;i<=TBLN;i++)\n {\n float X = (float)i;\n float Y = A*powf(X,1.0f/3.0f)+B*X+CC;\n if(iTBLN?TBLN:(unsigned short)(Y));\n }\n }\n for(int i=0; i< S.height*S.width; i++)\n {\n imgdata.image[i][0] = lut[imgdata.image[i][0]];\n imgdata.image[i][1] = lut[imgdata.image[i][1]];\n imgdata.image[i][2] = lut[imgdata.image[i][2]];\n imgdata.image[i][3] = lut[imgdata.image[i][3]];\n }\n\n C.data_maximum = lut[C.data_maximum];\n C.maximum = lut[C.maximum];\n // no need to adjust the minumum, black is already subtracted\n free(lut);\n}", "label_name": "CWE-119", "label": "119"} -{"code": "mptctl_eventenable (unsigned long arg)\n{\n\tstruct mpt_ioctl_eventenable __user *uarg = (void __user *) arg;\n\tstruct mpt_ioctl_eventenable\t karg;\n\tMPT_ADAPTER *ioc;\n\tint iocnum;\n\n\tif (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_eventenable))) {\n\t\tprintk(KERN_ERR MYNAM \"%s@%d::mptctl_eventenable - \"\n\t\t\t\"Unable to read in mpt_ioctl_eventenable struct @ %p\\n\",\n\t\t\t\t__FILE__, __LINE__, uarg);\n\t\treturn -EFAULT;\n\t}\n\n\tif (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||\n\t (ioc == NULL)) {\n\t\tprintk(KERN_DEBUG MYNAM \"%s::mptctl_eventenable() @%d - ioc%d not found!\\n\",\n\t\t\t\t__FILE__, __LINE__, iocnum);\n\t\treturn -ENODEV;\n\t}\n\n\tdctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT \"mptctl_eventenable called.\\n\",\n\t ioc->name));\n\tif (ioc->events == NULL) {\n\t\t/* Have not yet allocated memory - do so now.\n\t\t */\n\t\tint sz = MPTCTL_EVENT_LOG_SIZE * sizeof(MPT_IOCTL_EVENTS);\n\t\tioc->events = kzalloc(sz, GFP_KERNEL);\n\t\tif (!ioc->events) {\n\t\t\tprintk(MYIOC_s_ERR_FMT\n\t\t\t \": ERROR - Insufficient memory to add adapter!\\n\",\n\t\t\t ioc->name);\n\t\t\treturn -ENOMEM;\n\t\t}\n\t\tioc->alloc_total += sz;\n\n\t\tioc->eventContext = 0;\n }\n\n\t/* Update the IOC event logging flag.\n\t */\n\tioc->eventTypes = karg.eventTypes;\n\n\treturn 0;\n}", "label_name": "CWE-362", "label": "362"} -{"code": "void ModifiablePixelBuffer::fillRect(const Rect& r, const void* pix)\n{\n int stride;\n U8 *buf;\n int w, h, b;\n\n w = r.width();\n h = r.height();\n b = format.bpp/8;\n\n if (h == 0)\n return;\n\n buf = getBufferRW(r, &stride);\n\n if (b == 1) {\n while (h--) {\n memset(buf, *(const U8*)pix, w);\n buf += stride * b;\n }\n } else {\n U8 *start;\n int w1;\n\n start = buf;\n\n w1 = w;\n while (w1--) {\n memcpy(buf, pix, b);\n buf += b;\n }\n buf += (stride - w) * b;\n h--;\n\n while (h--) {\n memcpy(buf, start, w * b);\n buf += stride * b;\n }\n }\n\n commitBufferRW(r);\n}", "label_name": "CWE-119", "label": "119"} -{"code": "void jas_matrix_clip(jas_matrix_t *matrix, jas_seqent_t minval,\n jas_seqent_t maxval)\n{\n\tint i;\n\tint j;\n\tjas_seqent_t v;\n\tjas_seqent_t *rowstart;\n\tjas_seqent_t *data;\n\tint rowstep;\n\n\tif (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {\n\t\tassert(matrix->rows_);\n\t\trowstep = jas_matrix_rowstep(matrix);\n\t\tfor (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,\n\t\t rowstart += rowstep) {\n\t\t\tdata = rowstart;\n\t\t\tfor (j = matrix->numcols_, data = rowstart; j > 0; --j,\n\t\t\t ++data) {\n\t\t\t\tv = *data;\n\t\t\t\tif (v < minval) {\n\t\t\t\t\t*data = minval;\n\t\t\t\t} else if (v > maxval) {\n\t\t\t\t\t*data = maxval;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "label_name": "CWE-20", "label": "20"} -{"code": "\tboost::int64_t lazy_entry::int_value() const\n\t{\n\t\tTORRENT_ASSERT(m_type == int_t);\n\t\tboost::int64_t val = 0;\n\t\tbool negative = false;\n\t\tif (*m_data.start == '-') negative = true;\n\t\tparse_int(negative?m_data.start+1:m_data.start, m_data.start + m_size, 'e', val);\n\t\tif (negative) val = -val;\n\t\treturn val;\n\t}", "label_name": "CWE-119", "label": "119"} -{"code": "mptctl_fw_download(unsigned long arg)\n{\n\tstruct mpt_fw_xfer __user *ufwdl = (void __user *) arg;\n\tstruct mpt_fw_xfer\t kfwdl;\n\n\tif (copy_from_user(&kfwdl, ufwdl, sizeof(struct mpt_fw_xfer))) {\n\t\tprintk(KERN_ERR MYNAM \"%s@%d::_ioctl_fwdl - \"\n\t\t\t\t\"Unable to copy mpt_fw_xfer struct @ %p\\n\",\n\t\t\t\t__FILE__, __LINE__, ufwdl);\n\t\treturn -EFAULT;\n\t}\n\n\treturn mptctl_do_fw_download(kfwdl.iocnum, kfwdl.bufp, kfwdl.fwlen);\n}", "label_name": "CWE-362", "label": "362"} -{"code": "static int intel_pmu_handle_irq(struct pt_regs *regs)\n{\n\tstruct perf_sample_data data;\n\tstruct cpu_hw_events *cpuc;\n\tint bit, loops;\n\tu64 status;\n\tint handled;\n\n\tperf_sample_data_init(&data, 0);\n\n\tcpuc = &__get_cpu_var(cpu_hw_events);\n\n\t/*\n\t * Some chipsets need to unmask the LVTPC in a particular spot\n\t * inside the nmi handler. As a result, the unmasking was pushed\n\t * into all the nmi handlers.\n\t *\n\t * This handler doesn't seem to have any issues with the unmasking\n\t * so it was left at the top.\n\t */\n\tapic_write(APIC_LVTPC, APIC_DM_NMI);\n\n\tintel_pmu_disable_all();\n\thandled = intel_pmu_drain_bts_buffer();\n\tstatus = intel_pmu_get_status();\n\tif (!status) {\n\t\tintel_pmu_enable_all(0);\n\t\treturn handled;\n\t}\n\n\tloops = 0;\nagain:\n\tintel_pmu_ack_status(status);\n\tif (++loops > 100) {\n\t\tWARN_ONCE(1, \"perfevents: irq loop stuck!\\n\");\n\t\tperf_event_print_debug();\n\t\tintel_pmu_reset();\n\t\tgoto done;\n\t}\n\n\tinc_irq_stat(apic_perf_irqs);\n\n\tintel_pmu_lbr_read();\n\n\t/*\n\t * PEBS overflow sets bit 62 in the global status register\n\t */\n\tif (__test_and_clear_bit(62, (unsigned long *)&status)) {\n\t\thandled++;\n\t\tx86_pmu.drain_pebs(regs);\n\t}\n\n\tfor_each_set_bit(bit, (unsigned long *)&status, X86_PMC_IDX_MAX) {\n\t\tstruct perf_event *event = cpuc->events[bit];\n\n\t\thandled++;\n\n\t\tif (!test_bit(bit, cpuc->active_mask))\n\t\t\tcontinue;\n\n\t\tif (!intel_pmu_save_and_restart(event))\n\t\t\tcontinue;\n\n\t\tdata.period = event->hw.last_period;\n\n\t\tif (perf_event_overflow(event, 1, &data, regs))\n\t\t\tx86_pmu_stop(event, 0);\n\t}\n\n\t/*\n\t * Repeat if there is more work to be done:\n\t */\n\tstatus = intel_pmu_get_status();\n\tif (status)\n\t\tgoto again;\n\ndone:\n\tintel_pmu_enable_all(0);\n\treturn handled;\n}", "label_name": "CWE-400", "label": "400"} -{"code": "static jas_image_cmpt_t *jas_image_cmpt_create(int_fast32_t tlx,\n int_fast32_t tly, int_fast32_t hstep, int_fast32_t vstep,\n int_fast32_t width, int_fast32_t height, uint_fast16_t depth, bool sgnd,\n uint_fast32_t inmem)\n{\n\tjas_image_cmpt_t *cmpt;\n\tsize_t size;\n\n\tcmpt = 0;\n\tif (width < 0 || height < 0 || hstep <= 0 || vstep <= 0) {\n\t\tgoto error;\n\t}\n\tif (!jas_safe_intfast32_add(tlx, width, 0) ||\n\t !jas_safe_intfast32_add(tly, height, 0)) {\n\t\tgoto error;\n\t}\n\n\tif (!(cmpt = jas_malloc(sizeof(jas_image_cmpt_t)))) {\n\t\tgoto error;\n\t}\n\n\tcmpt->type_ = JAS_IMAGE_CT_UNKNOWN;\n\tcmpt->tlx_ = tlx;\n\tcmpt->tly_ = tly;\n\tcmpt->hstep_ = hstep;\n\tcmpt->vstep_ = vstep;\n\tcmpt->width_ = width;\n\tcmpt->height_ = height;\n\tcmpt->prec_ = depth;\n\tcmpt->sgnd_ = sgnd;\n\tcmpt->stream_ = 0;\n\tcmpt->cps_ = (depth + 7) / 8;\n\n\t// Compute the number of samples in the image component, while protecting\n\t// against overflow.\n\t// size = cmpt->width_ * cmpt->height_ * cmpt->cps_;\n\tif (!jas_safe_size_mul(cmpt->width_, cmpt->height_, &size) ||\n\t !jas_safe_size_mul(size, cmpt->cps_, &size)) {\n\t\tgoto error;\n\t}\n\tcmpt->stream_ = (inmem) ? jas_stream_memopen2(0, size) :\n\t jas_stream_tmpfile();\n\tif (!cmpt->stream_) {\n\t\tgoto error;\n\t}\n\n\t/* Zero the component data. This isn't necessary, but it is\n\tconvenient for debugging purposes. */\n\t/* Note: conversion of size - 1 to long can overflow */\n\tif (size > 0) {\n\t\tif (size - 1 > LONG_MAX) {\n\t\t\tgoto error;\n\t\t}\n\t\tif (jas_stream_seek(cmpt->stream_, size - 1, SEEK_SET) < 0 ||\n\t\t jas_stream_putc(cmpt->stream_, 0) == EOF ||\n\t\t jas_stream_seek(cmpt->stream_, 0, SEEK_SET) < 0) {\n\t\t\tgoto error;\n\t\t}\n\t}\n\n\treturn cmpt;\n\nerror:\n\tif (cmpt) {\n\t\tjas_image_cmpt_destroy(cmpt);\n\t}\n\treturn 0;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "Status TensorSliceReader::GetTensor(\n const string& name, std::unique_ptr* out_tensor) const {\n DataType type;\n TensorShape shape;\n TensorSlice slice;\n {\n mutex_lock l(mu_);\n const TensorSliceSet* tss = gtl::FindPtrOrNull(tensors_, name);\n if (tss == nullptr) {\n return errors::NotFound(name, \" not found in checkpoint file\");\n }\n\n if (tss->Slices().size() > 1) {\n // TODO(sherrym): Support multi-slice checkpoints.\n return errors::Unimplemented(\"Sliced checkpoints are not supported\");\n }\n\n type = tss->type();\n shape = tss->shape();\n slice = tss->Slices().begin()->second.slice;\n }\n\n std::unique_ptr t(new tensorflow::Tensor(type, shape));\n bool success = false;\n\n#define READER_COPY(dt) \\\n case dt: \\\n success = CopySliceData(name, slice, \\\n t->flat::Type>().data()); \\\n break;\n\n switch (type) {\n READER_COPY(DT_FLOAT);\n READER_COPY(DT_DOUBLE);\n READER_COPY(DT_INT32);\n READER_COPY(DT_UINT8);\n READER_COPY(DT_INT16);\n READER_COPY(DT_INT8);\n READER_COPY(DT_INT64);\n READER_COPY(DT_STRING);\n default:\n return errors::Unimplemented(\"Data type not supported\");\n }\n#undef READER_COPY\n\n if (!success) {\n return errors::NotFound(name, \" not found in checkpoint file\");\n }\n std::swap(*out_tensor, t);\n\n return Status::OK();\n}", "label_name": "CWE-345", "label": "345"} -{"code": "MpdCantataMounterInterface * RemoteFsDevice::mounter()\n{\n if (!mounterIface) {\n if (!QDBusConnection::systemBus().interface()->isServiceRegistered(MpdCantataMounterInterface::staticInterfaceName())) {\n QDBusConnection::systemBus().interface()->startService(MpdCantataMounterInterface::staticInterfaceName());\n }\n mounterIface=new MpdCantataMounterInterface(MpdCantataMounterInterface::staticInterfaceName(),\n \"/Mounter\", QDBusConnection::systemBus(), this);\n connect(mounterIface, SIGNAL(mountStatus(const QString &, int, int)), SLOT(mountStatus(const QString &, int, int)));\n connect(mounterIface, SIGNAL(umountStatus(const QString &, int, int)), SLOT(umountStatus(const QString &, int, int)));\n }\n return mounterIface;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "std::shared_ptr getTestDBC() {\n auto dbc = SQLiteDBManager::getUnique();\n char* err = nullptr;\n std::vector queries = {\n \"CREATE TABLE test_table (username varchar(30) primary key, age int)\",\n \"INSERT INTO test_table VALUES (\\\"mike\\\", 23)\",\n \"INSERT INTO test_table VALUES (\\\"matt\\\", 24)\"};\n\n for (auto q : queries) {\n sqlite3_exec(dbc->db(), q.c_str(), nullptr, nullptr, &err);\n if (err != nullptr) {\n throw std::domain_error(std::string(\"Cannot create testing DBC's db: \") +\n err);\n }\n }\n\n return dbc;\n}", "label_name": "CWE-77", "label": "77"} -{"code": "int pnm_validate(jas_stream_t *in)\n{\n\tuchar buf[2];\n\tint i;\n\tint n;\n\n\tassert(JAS_STREAM_MAXPUTBACK >= 2);\n\n\t/* Read the first two characters that constitute the signature. */\n\tif ((n = jas_stream_read(in, buf, 2)) < 0) {\n\t\treturn -1;\n\t}\n\t/* Put these characters back to the stream. */\n\tfor (i = n - 1; i >= 0; --i) {\n\t\tif (jas_stream_ungetc(in, buf[i]) == EOF) {\n\t\t\treturn -1;\n\t\t}\n\t}\n\t/* Did we read enough data? */\n\tif (n < 2) {\n\t\treturn -1;\n\t}\n\t/* Is this the correct signature for a PNM file? */\n\tif (buf[0] == 'P' && isdigit(buf[1])) {\n\t\treturn 0;\n\t}\n\treturn -1;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "R_API RBinJavaAttrInfo *r_bin_java_annotation_default_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {\n\tut64 offset = 0;\n\tRBinJavaAttrInfo *attr = NULL;\n\tattr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);\n\toffset += 6;\n\tif (attr && sz >= offset) {\n\t\tattr->type = R_BIN_JAVA_ATTR_TYPE_ANNOTATION_DEFAULT_ATTR;\n\t\tattr->info.annotation_default_attr.default_value = r_bin_java_element_value_new (buffer + offset, sz - offset, buf_offset + offset);\n\t\tif (attr->info.annotation_default_attr.default_value) {\n\t\t\toffset += attr->info.annotation_default_attr.default_value->size;\n\t\t}\n\t}\n\tr_bin_java_print_annotation_default_attr_summary (attr);\n\treturn attr;\n}", "label_name": "CWE-119", "label": "119"} -{"code": "\tPong(const std::string& cookie, const std::string& server = \"\")\n\t\t: ClientProtocol::Message(\"PONG\", ServerInstance->Config->GetServerName())\n\t{\n\t\tPushParamRef(ServerInstance->Config->GetServerName());\n\t\tif (!server.empty())\n\t\t\tPushParamRef(server);\n\t\tPushParamRef(cookie);\n\t}", "label_name": "CWE-732", "label": "732"} -{"code": "DSA_Signature_Operation::raw_sign(const uint8_t msg[], size_t msg_len,\n RandomNumberGenerator& rng)\n {\n const BigInt& q = m_group.get_q();\n\n BigInt i(msg, msg_len, q.bits());\n\n while(i >= q)\n i -= q;\n\n#if defined(BOTAN_HAS_RFC6979_GENERATOR)\n BOTAN_UNUSED(rng);\n const BigInt k = generate_rfc6979_nonce(m_x, q, i, m_rfc6979_hash);\n#else\n const BigInt k = BigInt::random_integer(rng, 1, q);\n#endif\n\n BigInt s = inverse_mod(k, q);\n const BigInt r = m_mod_q.reduce(m_group.power_g_p(k));\n\n s = m_mod_q.multiply(s, mul_add(m_x, r, i));\n\n // With overwhelming probability, a bug rather than actual zero r/s\n if(r.is_zero() || s.is_zero())\n throw Internal_Error(\"Computed zero r/s during DSA signature\");\n\n return BigInt::encode_fixed_length_int_pair(r, s, q.bytes());\n }", "label_name": "CWE-200", "label": "200"} -{"code": "MpdCantataMounterInterface * RemoteFsDevice::mounter()\n{\n if (!mounterIface) {\n if (!QDBusConnection::systemBus().interface()->isServiceRegistered(MpdCantataMounterInterface::staticInterfaceName())) {\n QDBusConnection::systemBus().interface()->startService(MpdCantataMounterInterface::staticInterfaceName());\n }\n mounterIface=new MpdCantataMounterInterface(MpdCantataMounterInterface::staticInterfaceName(),\n \"/Mounter\", QDBusConnection::systemBus(), this);\n connect(mounterIface, SIGNAL(mountStatus(const QString &, int, int)), SLOT(mountStatus(const QString &, int, int)));\n connect(mounterIface, SIGNAL(umountStatus(const QString &, int, int)), SLOT(umountStatus(const QString &, int, int)));\n }\n return mounterIface;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "static int em_fxrstor(struct x86_emulate_ctxt *ctxt)\n{\n\tstruct fxregs_state fx_state;\n\tint rc;\n\n\trc = check_fxsr(ctxt);\n\tif (rc != X86EMUL_CONTINUE)\n\t\treturn rc;\n\n\trc = segmented_read(ctxt, ctxt->memop.addr.mem, &fx_state, 512);\n\tif (rc != X86EMUL_CONTINUE)\n\t\treturn rc;\n\n\tif (fx_state.mxcsr >> 16)\n\t\treturn emulate_gp(ctxt, 0);\n\n\tctxt->ops->get_fpu(ctxt);\n\n\tif (ctxt->mode < X86EMUL_MODE_PROT64)\n\t\trc = fxrstor_fixup(ctxt, &fx_state);\n\n\tif (rc == X86EMUL_CONTINUE)\n\t\trc = asm_safe(\"fxrstor %[fx]\", : [fx] \"m\"(fx_state));\n\n\tctxt->ops->put_fpu(ctxt);\n\n\treturn rc;\n}", "label_name": "CWE-200", "label": "200"} -{"code": " int Bind(const Node& node, int max_retry) override {\n receiver_ = zmq_socket(context_, ZMQ_ROUTER);\n CHECK(receiver_ != NULL)\n << \"create receiver socket failed: \" << zmq_strerror(errno);\n int local = GetEnv(\"DMLC_LOCAL\", 0);\n std::string addr = local ? \"ipc:///tmp/\" : \"tcp://*:\";\n int port = node.port;\n unsigned seed = static_cast(time(NULL)+port);\n for (int i = 0; i < max_retry+1; ++i) {\n auto address = addr + std::to_string(port);\n if (zmq_bind(receiver_, address.c_str()) == 0) break;\n if (i == max_retry) {\n port = -1;\n } else {\n port = 10000 + rand_r(&seed) % 40000;\n }\n }\n return port;\n }", "label_name": "CWE-200", "label": "200"} -{"code": " DSA_Signature_Operation(const DSA_PrivateKey& dsa, const std::string& emsa) :\n PK_Ops::Signature_with_EMSA(emsa),\n m_group(dsa.get_group()),\n m_x(dsa.get_x()),\n m_mod_q(dsa.group_q())\n {\n#if defined(BOTAN_HAS_RFC6979_GENERATOR)\n m_rfc6979_hash = hash_for_emsa(emsa);\n#endif\n }", "label_name": "CWE-200", "label": "200"} -{"code": " void Init(void)\n {\n for(int i = 0;i < 18;i++) {\n X[i].Init();\n M[i].Init();\n }\n }", "label_name": "CWE-119", "label": "119"} -{"code": "R_API RBinJavaAttrInfo *r_bin_java_annotation_default_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {\n\tut64 offset = 0;\n\tRBinJavaAttrInfo *attr = NULL;\n\tattr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);\n\toffset += 6;\n\tif (attr && sz >= offset) {\n\t\tattr->type = R_BIN_JAVA_ATTR_TYPE_ANNOTATION_DEFAULT_ATTR;\n\t\tattr->info.annotation_default_attr.default_value = r_bin_java_element_value_new (buffer + offset, sz - offset, buf_offset + offset);\n\t\tif (attr->info.annotation_default_attr.default_value) {\n\t\t\toffset += attr->info.annotation_default_attr.default_value->size;\n\t\t}\n\t}\n\tr_bin_java_print_annotation_default_attr_summary (attr);\n\treturn attr;\n}", "label_name": "CWE-119", "label": "119"} -{"code": "int my_redel(const char *org_name, const char *tmp_name,\n time_t backup_time_stamp, myf MyFlags)\n{\n int error=1;\n DBUG_ENTER(\"my_redel\");\n DBUG_PRINT(\"my\",(\"org_name: '%s' tmp_name: '%s' MyFlags: %d\",\n\t\t org_name,tmp_name,MyFlags));\n\n if (my_copystat(org_name,tmp_name,MyFlags) < 0)\n goto end;\n if (MyFlags & MY_REDEL_MAKE_BACKUP)\n {\n char name_buff[FN_REFLEN + MY_BACKUP_NAME_EXTRA_LENGTH]; \n my_create_backup_name(name_buff, org_name, backup_time_stamp);\n if (my_rename(org_name, name_buff, MyFlags))\n goto end;\n }\n else if (my_delete(org_name, MyFlags))\n goto end;\n if (my_rename(tmp_name,org_name,MyFlags))\n goto end;\n\n error=0;\nend:\n DBUG_RETURN(error);\n} /* my_redel */", "label_name": "CWE-362", "label": "362"} -{"code": " IniSection (const IniParser *p, string n)\n\t: IniBase (n),\n\t ip (p),\n\t end_comment (), rewrite_by(0),\n\t container(), ivalues (), isections ()\n\t {}", "label_name": "CWE-200", "label": "200"} -{"code": "static int StreamTcpTest10 (void)\n{\n Packet *p = SCMalloc(SIZE_OF_PACKET);\n FAIL_IF(unlikely(p == NULL));\n Flow f;\n ThreadVars tv;\n StreamTcpThread stt;\n TCPHdr tcph;\n uint8_t payload[4];\n memset(p, 0, SIZE_OF_PACKET);\n PacketQueue pq;\n memset(&pq,0,sizeof(PacketQueue));\n memset (&f, 0, sizeof(Flow));\n memset(&tv, 0, sizeof (ThreadVars));\n memset(&stt, 0, sizeof (StreamTcpThread));\n memset(&tcph, 0, sizeof (TCPHdr));\n FLOW_INITIALIZE(&f);\n p->flow = &f;\n\n StreamTcpUTInit(&stt.ra_ctx);\n stream_config.async_oneside = TRUE;\n\n tcph.th_win = htons(5480);\n tcph.th_seq = htonl(10);\n tcph.th_ack = htonl(11);\n tcph.th_flags = TH_SYN;\n p->tcph = &tcph;\n\n FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);\n\n p->tcph->th_seq = htonl(11);\n p->tcph->th_ack = htonl(11);\n p->tcph->th_flags = TH_ACK;\n p->flowflags = FLOW_PKT_TOSERVER;\n\n FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);\n\n p->tcph->th_seq = htonl(11);\n p->tcph->th_ack = htonl(11);\n p->tcph->th_flags = TH_ACK|TH_PUSH;\n p->flowflags = FLOW_PKT_TOSERVER;\n\n StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/\n p->payload = payload;\n p->payload_len = 3;\n\n FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);\n\n p->tcph->th_seq = htonl(6);\n p->tcph->th_ack = htonl(11);\n p->tcph->th_flags = TH_ACK|TH_PUSH;\n p->flowflags = FLOW_PKT_TOSERVER;\n\n StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/\n p->payload = payload;\n p->payload_len = 3;\n\n FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);\n\n FAIL_IF(((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED);\n\n FAIL_IF(! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC));\n\n FAIL_IF(((TcpSession *)(p->flow->protoctx))->client.last_ack != 6 &&\n ((TcpSession *)(p->flow->protoctx))->server.next_seq != 11);\n\n StreamTcpSessionClear(p->flow->protoctx);\n\n SCFree(p);\n FLOW_DESTROY(&f);\n StreamTcpUTDeinit(stt.ra_ctx);\n PASS;\n}", "label_name": "CWE-436", "label": "436"} -{"code": "inline typename V::VectorType FBUnserializer::unserializeList() {\n p_ += CODE_SIZE;\n\n // the list size is written so we can reserve it in the vector\n // in future. Skip past it for now.\n unserializeInt64();\n\n typename V::VectorType ret = V::createVector();\n\n size_t code = nextCode();\n while (code != FB_SERIALIZE_STOP) {\n V::vectorAppend(ret, unserializeThing());\n code = nextCode();\n }\n p_ += CODE_SIZE;\n return ret;\n}", "label_name": "CWE-674", "label": "674"} -{"code": "R_API RBinJavaAttrInfo *r_bin_java_source_code_file_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {\n\tif (!sz) {\n\t\treturn NULL;\n\t}\n\tut64 offset = 0;\n\tRBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);\n\toffset += 6;\n\tif (!attr) {\n\t\treturn NULL;\n\t}\n\tattr->type = R_BIN_JAVA_ATTR_TYPE_SOURCE_FILE_ATTR;\n\t// if (buffer + offset > buffer + sz) return NULL;\n\tattr->info.source_file_attr.sourcefile_idx = R_BIN_JAVA_USHORT (buffer, offset);\n\toffset += 2;\n\tattr->size = offset;\n\t// IFDBG r_bin_java_print_source_code_file_attr_summary(attr);\n\treturn attr;\n}", "label_name": "CWE-119", "label": "119"} -{"code": "void RemoteFsDevice::unmount()\n{\n if (details.isLocalFile()) {\n return;\n }\n\n if (!isConnected() || proc) {\n return;\n }\n\n if (messageSent) {\n return;\n }\n if (constSambaProtocol==details.url.scheme() || constSambaAvahiProtocol==details.url.scheme()) {\n mounter()->umount(mountPoint(details, false), getpid());\n setStatusMessage(tr(\"Disconnecting...\"));\n messageSent=true;\n return;\n }\n\n QString cmd;\n QStringList args;\n if (!details.isLocalFile()) {\n QString mp=mountPoint(details, false);\n if (!mp.isEmpty()) {\n cmd=Utils::findExe(\"fusermount\");\n if (!cmd.isEmpty()) {\n args << QLatin1String(\"-u\") << QLatin1String(\"-z\") << mp;\n } else {\n emit error(tr(\"\\\"fusermount\\\" is not installed!\"));\n }\n }\n }\n\n if (!cmd.isEmpty()) {\n setStatusMessage(tr(\"Disconnecting...\"));\n proc=new QProcess(this);\n proc->setProperty(\"unmount\", true);\n connect(proc, SIGNAL(finished(int)), SLOT(procFinished(int)));\n proc->start(cmd, args, QIODevice::ReadOnly);\n }\n}", "label_name": "CWE-20", "label": "20"} -{"code": "int jas_memdump(FILE *out, void *data, size_t len)\n{\n\tsize_t i;\n\tsize_t j;\n\tuchar *dp;\n\tdp = data;\n\tfor (i = 0; i < len; i += 16) {\n\t\tfprintf(out, \"%04zx:\", i);\n\t\tfor (j = 0; j < 16; ++j) {\n\t\t\tif (i + j < len) {\n\t\t\t\tfprintf(out, \" %02x\", dp[i + j]);\n\t\t\t}\n\t\t}\n\t\tfprintf(out, \"\\n\");\n\t}\n\treturn 0;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "\t\tauto Phase3() -> Local final {\n\t\t\treturn Boolean::New(Isolate::GetCurrent(), did_set);\n\t\t}", "label_name": "CWE-913", "label": "913"} -{"code": "TEST_F(AllowMissingInAndOfOrListTest, GoodAndBadJwts) {\n EXPECT_CALL(mock_cb_, onComplete(Status::Ok));\n // Use the token with example.com issuer for x-other.\n auto headers =\n Http::TestRequestHeaderMapImpl{{kExampleHeader, GoodToken}, {kOtherHeader, GoodToken}};\n context_ = Verifier::createContext(headers, parent_span_, &mock_cb_);\n verifier_->verify(context_);\n EXPECT_THAT(headers, JwtOutputSuccess(kExampleHeader));\n EXPECT_THAT(headers, JwtOutputFailedOrIgnore(kOtherHeader));\n}", "label_name": "CWE-287", "label": "287"} -{"code": "tTcpIpPacketParsingResult ParaNdis_CheckSumVerifyFlat(\n PVOID pBuffer,\n ULONG ulDataLength,\n ULONG flags,\n LPCSTR caller)\n{\n tCompletePhysicalAddress SGBuffer;\n SGBuffer.Virtual = pBuffer;\n SGBuffer.size = ulDataLength;\n return ParaNdis_CheckSumVerify(&SGBuffer, ulDataLength, 0, flags, caller);\n}", "label_name": "CWE-20", "label": "20"} -{"code": "bool WebContents::SendIPCMessageToFrame(bool internal,\n int32_t frame_id,\n const std::string& channel,\n v8::Local args) {\n v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();\n blink::CloneableMessage message;\n if (!gin::ConvertFromV8(isolate, args, &message)) {\n isolate->ThrowException(v8::Exception::Error(\n gin::StringToV8(isolate, \"Failed to serialize arguments\")));\n return false;\n }\n auto frames = web_contents()->GetAllFrames();\n auto iter = std::find_if(frames.begin(), frames.end(), [frame_id](auto* f) {\n return f->GetRoutingID() == frame_id;\n });\n if (iter == frames.end())\n return false;\n if (!(*iter)->IsRenderFrameLive())\n return false;\n\n mojo::AssociatedRemote electron_renderer;\n (*iter)->GetRemoteAssociatedInterfaces()->GetInterface(&electron_renderer);\n electron_renderer->Message(internal, channel, std::move(message),\n 0 /* sender_id */);\n return true;\n}", "label_name": "CWE-668", "label": "668"} -{"code": "v8::Local CreateNativeEvent(\n v8::Isolate* isolate,\n v8::Local sender,\n content::RenderFrameHost* frame,\n electron::mojom::ElectronBrowser::MessageSyncCallback callback) {\n v8::Local event;\n if (frame && callback) {\n gin::Handle native_event = Event::Create(isolate);\n native_event->SetCallback(std::move(callback));\n event = v8::Local::Cast(native_event.ToV8());\n } else {\n // No need to create native event if we do not need to send reply.\n event = CreateEvent(isolate);\n }\n\n Dictionary dict(isolate, event);\n dict.Set(\"sender\", sender);\n // Should always set frameId even when callback is null.\n if (frame)\n dict.Set(\"frameId\", frame->GetRoutingID());\n return event;\n}", "label_name": "CWE-668", "label": "668"} -{"code": "void HeaderMapImpl::addCopy(const LowerCaseString& key, uint64_t value) {\n auto* entry = getExistingInline(key.get());\n if (entry != nullptr) {\n char buf[32];\n StringUtil::itoa(buf, sizeof(buf), value);\n appendToHeader(entry->value(), buf);\n return;\n }\n HeaderString new_key;\n new_key.setCopy(key.get().c_str(), key.get().size());\n HeaderString new_value;\n new_value.setInteger(value);\n insertByKey(std::move(new_key), std::move(new_value));\n ASSERT(new_key.empty()); // NOLINT(bugprone-use-after-move)\n ASSERT(new_value.empty()); // NOLINT(bugprone-use-after-move)\n}", "label_name": "CWE-400", "label": "400"} -{"code": "bool DNP3_Base::ParseAppLayer(Endpoint* endp)\n\t{\n\tbool orig = (endp == &orig_state);\n\tbinpac::DNP3::DNP3_Flow* flow = orig ? interp->upflow() : interp->downflow();\n\n\tu_char* data = endp->buffer + PSEUDO_TRANSPORT_INDEX; // The transport layer byte counts as app-layer it seems.\n\tint len = endp->pkt_length - 5;\n\n\t// DNP3 Packet : DNP3 Pseudo Link Layer | DNP3 Pseudo Transport Layer | DNP3 Pseudo Application Layer\n\t// DNP3 Serial Transport Layer data is always 1 byte.\n\t// Get FIN FIR seq field in transport header.\n\t// FIR indicate whether the following DNP3 Serial Application Layer is first chunk of bytes or not.\n\t// FIN indicate whether the following DNP3 Serial Application Layer is last chunk of bytes or not.\n\n\tint is_first = (endp->tpflags & 0x40) >> 6; // Initial chunk of data in this packet.\n\tint is_last = (endp->tpflags & 0x80) >> 7; // Last chunk of data in this packet.\n\n\tint transport = PSEUDO_TRANSPORT_LEN;\n\n\tint i = 0;\n\twhile ( len > 0 )\n\t\t{\n\t\tint n = min(len, 16);\n\n\t\t// Make sure chunk has a correct checksum.\n\t\tif ( ! CheckCRC(n, data, data + n, \"app_chunk\") )\n\t\t\treturn false;\n\n\t\t// Pass on to BinPAC.\n\t\tassert(data + n < endp->buffer + endp->buffer_len);\n\t\tflow->flow_buffer()->BufferData(data + transport, data + n);\n\t\ttransport = 0;\n\n\t\tdata += n + 2;\n\t\tlen -= n;\n\t\t}\n\n\tif ( is_first )\n\t\tendp->encountered_first_chunk = true;\n\n\tif ( ! is_first && ! endp->encountered_first_chunk )\n\t\t{\n\t\t// We lost the first chunk.\n\t\tanalyzer->Weird(\"dnp3_first_application_layer_chunk_missing\");\n\t\treturn false;\n\t\t}\n\n\tif ( is_last )\n\t\t{\n\t\tflow->flow_buffer()->FinishBuffer();\n\t\tflow->FlowEOF();\n\t\tClearEndpointState(orig);\n\t\t}\n\n\treturn true;\n\t}", "label_name": "CWE-119", "label": "119"} -{"code": " IniSection (const IniParser *p)\n\t: IniBase (-1),\n\t ip (p),\n\t end_comment (), rewrite_by(-1),\n\t container (), ivalues (), isections ()\n\t {}", "label_name": "CWE-200", "label": "200"} -{"code": "void CNB::DoIPHdrCSO(PVOID IpHeader, ULONG EthPayloadLength) const\n{\n ParaNdis_CheckSumVerifyFlat(IpHeader,\n EthPayloadLength,\n pcrIpChecksum | pcrFixIPChecksum,\n __FUNCTION__);\n}", "label_name": "CWE-20", "label": "20"} -{"code": "void SSecurityTLS::shutdown()\n{\n if (session) {\n if (gnutls_bye(session, GNUTLS_SHUT_RDWR) != GNUTLS_E_SUCCESS) {\n /* FIXME: Treat as non-fatal error */\n vlog.error(\"TLS session wasn't terminated gracefully\");\n }\n }\n\n if (dh_params) {\n gnutls_dh_params_deinit(dh_params);\n dh_params = 0;\n }\n\n if (anon_cred) {\n gnutls_anon_free_server_credentials(anon_cred);\n anon_cred = 0;\n }\n\n if (cert_cred) {\n gnutls_certificate_free_credentials(cert_cred);\n cert_cred = 0;\n }\n\n if (session) {\n gnutls_deinit(session);\n session = 0;\n\n gnutls_global_deinit();\n }\n}", "label_name": "CWE-119", "label": "119"} -{"code": "void RemoteFsDevice::load()\n{\n if (RemoteFsDevice::constSambaAvahiProtocol==details.url.scheme()) {\n // Start Avahi listener...\n Avahi::self();\n QUrlQuery q(details.url);\n if (q.hasQueryItem(constServiceNameQuery)) {\n details.serviceName=q.queryItemValue(constServiceNameQuery);\n }\n\n if (!details.serviceName.isEmpty()) {\n AvahiService *srv=Avahi::self()->getService(details.serviceName);\n if (!srv || srv->getHost().isEmpty()) {\n sub=tr(\"Not Available\");\n } else {\n sub=tr(\"Available\");\n }\n }\n connect(Avahi::self(), SIGNAL(serviceAdded(QString)), SLOT(serviceAdded(QString)));\n connect(Avahi::self(), SIGNAL(serviceRemoved(QString)), SLOT(serviceRemoved(QString)));\n }\n\n if (isConnected()) {\n setAudioFolder();\n readOpts(settingsFileName(), opts, true);\n rescan(false); // Read from cache if we have it!\n }\n}", "label_name": "CWE-20", "label": "20"} -{"code": "static int putint(jas_stream_t *out, int sgnd, int prec, long val)\n{\n\tint n;\n\tint c;\n\tbool s;\n\tulong tmp;\n\tassert((!sgnd && prec >= 1) || (sgnd && prec >= 2));\n\tif (sgnd) {\n\t\tval = encode_twos_comp(val, prec);\n\t}\n\tassert(val >= 0);\n\tval &= (1 << prec) - 1;\n\tn = (prec + 7) / 8;\n\twhile (--n >= 0) {\n\t\tc = (val >> (n * 8)) & 0xff;\n\t\tif (jas_stream_putc(out, c) != c)\n\t\t\treturn -1;\n\t}\n\treturn 0;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "void RemoteFsDevice::serviceRemoved(const QString &name)\n{\n if (name==details.serviceName && constSambaAvahiProtocol==details.url.scheme()) {\n sub=tr(\"Not Available\");\n updateStatus();\n }\n}", "label_name": "CWE-20", "label": "20"} -{"code": "TEST_F(QuantizedConv2DTest, Small32Bit) {\n const int stride = 1;\n TF_ASSERT_OK(NodeDefBuilder(\"quantized_conv_op\", \"QuantizedConv2D\")\n .Input(FakeInput(DT_QUINT8))\n .Input(FakeInput(DT_QUINT8))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Attr(\"out_type\", DataTypeToEnum::v())\n .Attr(\"strides\", {1, stride, stride, 1})\n .Attr(\"padding\", \"SAME\")\n .Finalize(node_def()));\n TF_ASSERT_OK(InitOp());\n\n const int depth = 1;\n const int image_width = 4;\n const int image_height = 3;\n const int image_batch_count = 1;\n AddInputFromArray(\n TensorShape({image_batch_count, image_height, image_width, depth}),\n {10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120});\n const int filter_size = 3;\n const int filter_count = 1;\n AddInputFromArray(\n TensorShape({filter_size, filter_size, depth, filter_count}),\n {10, 40, 70, 20, 50, 80, 30, 60, 90});\n AddInputFromArray(TensorShape({1}), {0});\n AddInputFromArray(TensorShape({1}), {255.0f});\n AddInputFromArray(TensorShape({1}), {0});\n AddInputFromArray(TensorShape({1}), {255.0f});\n\n TF_ASSERT_OK(RunOpKernel());\n const int expected_width = image_width;\n const int expected_height = image_height * filter_count;\n Tensor expected(DT_QINT32, TensorShape({image_batch_count, expected_height,\n expected_width, filter_count}));\n test::FillValues(\n &expected, {10500, 15000, 18300, 9500, 23500, 31200, 35700, 17800, 18700,\n 23400, 26100, 12100});\n test::ExpectTensorEqual(expected, *GetOutput(0));\n}", "label_name": "CWE-20", "label": "20"} -{"code": "static Variant HHVM_FUNCTION(simplexml_import_dom,\n const Object& node,\n const String& class_name /* = \"SimpleXMLElement\" */) {\n auto domnode = Native::data(node);\n xmlNodePtr nodep = domnode->nodep();\n\n if (nodep) {\n if (nodep->doc == nullptr) {\n raise_warning(\"Imported Node must have associated Document\");\n return init_null();\n }\n if (nodep->type == XML_DOCUMENT_NODE ||\n nodep->type == XML_HTML_DOCUMENT_NODE) {\n nodep = xmlDocGetRootElement((xmlDocPtr) nodep);\n }\n }\n\n if (nodep && nodep->type == XML_ELEMENT_NODE) {\n auto cls = class_from_name(class_name, \"simplexml_import_dom\");\n if (!cls) {\n return init_null();\n }\n Object obj = create_object(cls->nameStr(), Array(), false);\n auto sxe = Native::data(obj.get());\n sxe->node = libxml_register_node(nodep);\n return obj;\n } else {\n raise_warning(\"Invalid Nodetype to import\");\n return init_null();\n }\n return false;\n}", "label_name": "CWE-345", "label": "345"} -{"code": "void TensorSliceReader::LoadShard(int shard) const {\n CHECK_LT(shard, sss_.size());\n if (sss_[shard] || !status_.ok()) {\n return; // Already loaded, or invalid.\n }\n string value;\n SavedTensorSlices sts;\n const string fname = fnames_[shard];\n VLOG(1) << \"Reading meta data from file \" << fname << \"...\";\n Table* table;\n Status s = open_function_(fname, &table);\n if (!s.ok()) {\n status_ = errors::DataLoss(\"Unable to open table file \", fname, \": \",\n s.ToString());\n return;\n }\n sss_[shard].reset(table);\n if (!(table->Get(kSavedTensorSlicesKey, &value) &&\n ParseProtoUnlimited(&sts, value))) {\n status_ = errors::Internal(\n \"Failed to find the saved tensor slices at the beginning of the \"\n \"checkpoint file: \",\n fname);\n return;\n }\n status_ = CheckVersions(sts.meta().versions(), TF_CHECKPOINT_VERSION,\n TF_CHECKPOINT_VERSION_MIN_PRODUCER, \"Checkpoint\",\n \"checkpoint\");\n if (!status_.ok()) return;\n for (const SavedSliceMeta& ssm : sts.meta().tensor()) {\n TensorShape ssm_shape;\n status_ = TensorShape::BuildTensorShapeBase(ssm.shape(), &ssm_shape);\n if (!status_.ok()) return;\n for (const TensorSliceProto& tsp : ssm.slice()) {\n TensorSlice ss_slice(tsp);\n status_ = RegisterTensorSlice(ssm.name(), ssm_shape, ssm.type(), fname,\n ss_slice, &tensors_);\n if (!status_.ok()) return;\n }\n }\n}", "label_name": "CWE-345", "label": "345"} -{"code": "bool VariableUnserializer::matchString(folly::StringPiece str) {\n const char* p = m_buf;\n assertx(p <= m_end);\n int total = 0;\n if (*p == 'S') {\n total = 2 + 8 + 1;\n if (p + total > m_end) return false;\n p++;\n if (*p++ != ':') return false;\n auto const sd = *reinterpret_cast(p);\n assertx(sd->isStatic());\n if (str.compare(sd->slice()) != 0) return false;\n p += size_t(8);\n } else {\n const auto ss = str.size();\n if (ss >= 100) return false;\n int digits = ss >= 10 ? 2 : 1;\n total = 2 + digits + 2 + ss + 2;\n if (p + total > m_end) return false;\n if (*p++ != 's') return false;\n if (*p++ != ':') return false;\n if (digits == 2) {\n if (*p++ != '0' + ss/10) return false;\n if (*p++ != '0' + ss%10) return false;\n } else {\n if (*p++ != '0' + ss) return false;\n }\n if (*p++ != ':') return false;\n if (*p++ != '\\\"') return false;\n if (memcmp(p, str.data(), ss)) return false;\n p += ss;\n if (*p++ != '\\\"') return false;\n }\n if (*p++ != ';') return false;\n assertx(m_buf + total == p);\n m_buf = p;\n return true;\n}", "label_name": "CWE-119", "label": "119"} -{"code": " DSA_Verification_Operation(const DSA_PublicKey& dsa,\n const std::string& emsa) :\n PK_Ops::Verification_with_EMSA(emsa),\n m_group(dsa.get_group()),\n m_y(dsa.get_y()),\n m_mod_q(dsa.group_q())\n {}", "label_name": "CWE-200", "label": "200"} -{"code": "void CarbonProtocolReader::skip(const FieldType ft) {\n switch (ft) {\n case FieldType::True:\n case FieldType::False: {\n break;\n }\n case FieldType::Int8: {\n readRaw();\n break;\n }\n case FieldType::Int16: {\n readRaw();\n break;\n }\n case FieldType::Int32: {\n readRaw();\n break;\n }\n case FieldType::Int64: {\n readRaw();\n break;\n }\n case FieldType::Double: {\n readRaw();\n break;\n }\n case FieldType::Float: {\n readRaw();\n break;\n }\n case FieldType::Binary: {\n readRaw();\n break;\n }\n case FieldType::List: {\n skipLinearContainer();\n break;\n }\n case FieldType::Struct: {\n readStructBegin();\n while (true) {\n const auto fieldType = readFieldHeader().first;\n if (fieldType == FieldType::Stop) {\n break;\n }\n skip(fieldType);\n }\n readStructEnd();\n break;\n }\n case FieldType::Set: {\n skipLinearContainer();\n break;\n }\n case FieldType::Map: {\n skipKVContainer();\n break;\n }\n default: { break; }\n }\n}", "label_name": "CWE-674", "label": "674"} -{"code": "void CConfig::Write(CFile& File, unsigned int iIndentation) {\n CString sIndentation = CString(iIndentation, '\\t');\n\n for (const auto& it : m_ConfigEntries) {\n for (const CString& sValue : it.second) {\n File.Write(sIndentation + it.first + \" = \" + sValue + \"\\n\");\n }\n }\n\n for (const auto& it : m_SubConfigs) {\n for (const auto& it2 : it.second) {\n File.Write(\"\\n\");\n\n File.Write(sIndentation + \"<\" + it.first + \" \" + it2.first + \">\\n\");\n it2.second.m_pSubConfig->Write(File, iIndentation + 1);\n File.Write(sIndentation + \"\\n\");\n }\n }\n}", "label_name": "CWE-20", "label": "20"} -{"code": "void RemoteDevicePropertiesWidget::checkSaveable()\n{\n RemoteFsDevice::Details det=details();\n modified=det!=orig;\n saveable=!det.isEmpty();\n if (saveable && Type_SambaAvahi==type->itemData(type->currentIndex()).toInt()) {\n saveable=!smbAvahiName->text().trimmed().isEmpty();\n }\n emit updated();\n}", "label_name": "CWE-20", "label": "20"} -{"code": " void onComplete(const Status& status, ContextImpl& context) const override {\n auto& completion_state = context.getCompletionState(this);\n if (completion_state.is_completed_) {\n return;\n }\n\n // If any of children is OK, return OK\n if (Status::Ok == status) {\n completion_state.is_completed_ = true;\n completeWithStatus(status, context);\n return;\n }\n\n // Then wait for all children to be done.\n if (++completion_state.number_completed_children_ == verifiers_.size()) {\n // Aggregate all children status into a final status.\n // JwtMissing should be treated differently than other failure status\n // since it simply means there is not Jwt token for the required provider.\n // If there is a failure status other than JwtMissing in the children,\n // it should be used as the final status.\n Status final_status = Status::JwtMissed;\n for (const auto& it : verifiers_) {\n // If a Jwt is extracted from a location not specified by the required provider,\n // the authenticator returns JwtUnknownIssuer. It should be treated the same as\n // JwtMissed.\n Status child_status = context.getCompletionState(it.get()).status_;\n if (child_status != Status::JwtMissed && child_status != Status::JwtUnknownIssuer) {\n final_status = child_status;\n }\n }\n\n if (is_allow_missing_or_failed_) {\n final_status = Status::Ok;\n } else if (is_allow_missing_ && final_status == Status::JwtMissed) {\n final_status = Status::Ok;\n }\n completion_state.is_completed_ = true;\n completeWithStatus(final_status, context);\n }\n }", "label_name": "CWE-287", "label": "287"} -{"code": "TEST_F(QuantizedConv2DTest, OddPaddingBatch) {\n const int stride = 2;\n TF_ASSERT_OK(NodeDefBuilder(\"quantized_conv_op\", \"QuantizedConv2D\")\n .Input(FakeInput(DT_QUINT8))\n .Input(FakeInput(DT_QUINT8))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Attr(\"out_type\", DataTypeToEnum::v())\n .Attr(\"strides\", {1, stride, stride, 1})\n .Attr(\"padding\", \"SAME\")\n .Finalize(node_def()));\n TF_ASSERT_OK(InitOp());\n\n const int depth = 1;\n const int image_width = 4;\n const int image_height = 4;\n const int image_batch_count = 3;\n AddInputFromArray(\n TensorShape({image_batch_count, image_height, image_width, depth}),\n {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,\n 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,\n 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16});\n const int filter_size = 3;\n const int filter_count = 1;\n AddInputFromArray(\n TensorShape({filter_size, filter_size, depth, filter_count}),\n {1, 2, 3, 4, 5, 6, 7, 8, 9});\n AddInputFromArray(TensorShape({1}), {0});\n AddInputFromArray(TensorShape({1}), {255.0f});\n AddInputFromArray(TensorShape({1}), {0});\n AddInputFromArray(TensorShape({1}), {255.0f});\n\n TF_ASSERT_OK(RunOpKernel());\n const int expected_width = image_width / stride;\n const int expected_height = (image_height * filter_count) / stride;\n Tensor expected(DT_QINT32, TensorShape({image_batch_count, expected_height,\n expected_width, filter_count}));\n test::FillValues(&expected, {348, 252, 274, 175, //\n 348, 252, 274, 175, //\n 348, 252, 274, 175});\n test::ExpectTensorEqual(expected, *GetOutput(0));\n}", "label_name": "CWE-20", "label": "20"} -{"code": "Integer InvertibleRWFunction::CalculateInverse(RandomNumberGenerator &rng, const Integer &x) const\n{\n\tDoQuickSanityCheck();\n\tModularArithmetic modn(m_n);\n\tInteger r, rInv;\n\tdo {\t// do this in a loop for people using small numbers for testing\n\t\tr.Randomize(rng, Integer::One(), m_n - Integer::One());\n\t\trInv = modn.MultiplicativeInverse(r);\n\t} while (rInv.IsZero());\n\tInteger re = modn.Square(r);\n\tre = modn.Multiply(re, x);\t\t\t// blind\n\n\tInteger cp=re%m_p, cq=re%m_q;\n\tif (Jacobi(cp, m_p) * Jacobi(cq, m_q) != 1)\n\t{\n\t\tcp = cp.IsOdd() ? (cp+m_p) >> 1 : cp >> 1;\n\t\tcq = cq.IsOdd() ? (cq+m_q) >> 1 : cq >> 1;\n\t}\n\n\t#pragma omp parallel\n\t\t#pragma omp sections\n\t\t{\n\t\t\t#pragma omp section\n\t\t\t\tcp = ModularSquareRoot(cp, m_p);\n\t\t\t#pragma omp section\n\t\t\t\tcq = ModularSquareRoot(cq, m_q);\n\t\t}\n\n\tInteger y = CRT(cq, m_q, cp, m_p, m_u);\n\ty = modn.Multiply(y, rInv);\t\t\t\t// unblind\n\ty = STDMIN(y, m_n-y);\n\tif (ApplyFunction(y) != x)\t\t\t\t// check\n\t\tthrow Exception(Exception::OTHER_ERROR, \"InvertibleRWFunction: computational error during private key operation\");\n\treturn y;\n}", "label_name": "CWE-200", "label": "200"} -{"code": "TEST_F(RouterTest, MissingRequiredHeaders) {\n NiceMock encoder;\n Http::ResponseDecoder* response_decoder = nullptr;\n expectNewStreamWithImmediateEncoder(encoder, &response_decoder, Http::Protocol::Http10);\n expectResponseTimerCreate();\n\n Http::TestRequestHeaderMapImpl headers;\n HttpTestUtility::addDefaultHeaders(headers);\n headers.removeMethod();\n\n EXPECT_CALL(encoder, encodeHeaders(_, _))\n .WillOnce(Invoke([](const Http::RequestHeaderMap& headers, bool) -> Http::Status {\n return Http::HeaderUtility::checkRequiredRequestHeaders(headers);\n }));\n EXPECT_CALL(\n callbacks_,\n sendLocalReply(Http::Code::ServiceUnavailable,\n testing::Eq(\"missing required header: :method\"), _, _,\n \"filter_removed_required_request_headers{missing_required_header:_:method}\"))\n .WillOnce(testing::InvokeWithoutArgs([] {}));\n router_.decodeHeaders(headers, true);\n router_.onDestroy();\n}", "label_name": "CWE-670", "label": "670"} -{"code": "void CSecurityTLS::initGlobal()\n{\n static bool globalInitDone = false;\n\n if (!globalInitDone) {\n gnutls_global_init();\n globalInitDone = true;\n }\n}", "label_name": "CWE-119", "label": "119"} -{"code": "void *UntrustedCacheMalloc::GetBuffer() {\n void **buffers = nullptr;\n void *buffer;\n bool is_pool_empty;\n\n {\n LockGuard spin_lock(&lock_);\n is_pool_empty = buffer_pool_.empty();\n if (is_pool_empty) {\n buffers =\n primitives::AllocateUntrustedBuffers(kPoolIncrement, kPoolEntrySize);\n for (int i = 0; i < kPoolIncrement; i++) {\n if (!buffers[i] ||\n !TrustedPrimitives::IsOutsideEnclave(buffers[i], kPoolEntrySize)) {\n abort();\n }\n buffer_pool_.push(buffers[i]);\n }\n }\n buffer = buffer_pool_.top();\n buffer_pool_.pop();\n busy_buffers_.insert(buffer);\n }\n\n if (is_pool_empty) {\n // Free memory held by the array of buffer pointers returned by\n // AllocateUntrustedBuffers.\n Free(buffers);\n }\n return buffer;\n}", "label_name": "CWE-668", "label": "668"} -{"code": "void RemoteDevicePropertiesWidget::setType()\n{\n if (Type_SshFs==type->itemData(type->currentIndex()).toInt() && 0==sshPort->value()) {\n sshPort->setValue(22);\n }\n if (Type_Samba==type->itemData(type->currentIndex()).toInt() && 0==smbPort->value()) {\n smbPort->setValue(445);\n }\n}", "label_name": "CWE-20", "label": "20"} -{"code": " CdsIntegrationTest()\n : HttpIntegrationTest(Http::CodecType::HTTP2, ipVersion(),\n ConfigHelper::discoveredClustersBootstrap(\n sotwOrDelta() == Grpc::SotwOrDelta::Sotw ||\n sotwOrDelta() == Grpc::SotwOrDelta::UnifiedSotw\n ? \"GRPC\"\n : \"DELTA_GRPC\")) {\n if (sotwOrDelta() == Grpc::SotwOrDelta::UnifiedSotw ||\n sotwOrDelta() == Grpc::SotwOrDelta::UnifiedDelta) {\n config_helper_.addRuntimeOverride(\"envoy.reloadable_features.unified_mux\", \"true\");\n }\n use_lds_ = false;\n sotw_or_delta_ = sotwOrDelta();\n }", "label_name": "CWE-674", "label": "674"} -{"code": " bool PamBackend::start(const QString &user) {\n bool result;\n\n QString service = QStringLiteral(\"sddm\");\n\n if (user == QStringLiteral(\"sddm\") && m_greeter)\n service = QStringLiteral(\"sddm-greeter\");\n else if (m_app->session()->path().isEmpty())\n service = QStringLiteral(\"sddm-check\");\n else if (m_autologin)\n service = QStringLiteral(\"sddm-autologin\");\n result = m_pam->start(service, user);\n\n if (!result)\n m_app->error(m_pam->errorString(), Auth::ERROR_INTERNAL);\n\n return result;\n }", "label_name": "CWE-287", "label": "287"} -{"code": "\t\tauto Phase3() -> Local final {\n\t\t\treturn Boolean::New(Isolate::GetCurrent(), result);\n\t\t}", "label_name": "CWE-913", "label": "913"} -{"code": "int jas_matrix_cmp(jas_matrix_t *mat0, jas_matrix_t *mat1)\n{\n\tint i;\n\tint j;\n\n\tif (mat0->numrows_ != mat1->numrows_ || mat0->numcols_ !=\n\t mat1->numcols_) {\n\t\treturn 1;\n\t}\n\tfor (i = 0; i < mat0->numrows_; i++) {\n\t\tfor (j = 0; j < mat0->numcols_; j++) {\n\t\t\tif (jas_matrix_get(mat0, i, j) != jas_matrix_get(mat1, i, j)) {\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "void RemoteFsDevice::load()\n{\n if (RemoteFsDevice::constSambaAvahiProtocol==details.url.scheme()) {\n // Start Avahi listener...\n Avahi::self();\n QUrlQuery q(details.url);\n if (q.hasQueryItem(constServiceNameQuery)) {\n details.serviceName=q.queryItemValue(constServiceNameQuery);\n }\n\n if (!details.serviceName.isEmpty()) {\n AvahiService *srv=Avahi::self()->getService(details.serviceName);\n if (!srv || srv->getHost().isEmpty()) {\n sub=tr(\"Not Available\");\n } else {\n sub=tr(\"Available\");\n }\n }\n connect(Avahi::self(), SIGNAL(serviceAdded(QString)), SLOT(serviceAdded(QString)));\n connect(Avahi::self(), SIGNAL(serviceRemoved(QString)), SLOT(serviceRemoved(QString)));\n }\n\n if (isConnected()) {\n setAudioFolder();\n readOpts(settingsFileName(), opts, true);\n rescan(false); // Read from cache if we have it!\n }\n}", "label_name": "CWE-20", "label": "20"} -{"code": "RemoteFsDevice::RemoteFsDevice(MusicLibraryModel *m, const Details &d)\n : FsDevice(m, d.name, createUdi(d.name))\n , mountToken(0)\n , currentMountStatus(false)\n , details(d)\n , proc(0)\n , mounterIface(0)\n , messageSent(false)\n{\n// details.path=Utils::fixPath(details.path);\n setup();\n icn=MonoIcon::icon(details.isLocalFile()\n ? FontAwesome::foldero\n : constSshfsProtocol==details.url.scheme()\n ? FontAwesome::linux_os\n : FontAwesome::windows, Utils::monoIconColor());\n}", "label_name": "CWE-20", "label": "20"} -{"code": "int CServer::SendMsg(CMsgPacker *pMsg, int Flags, int ClientID)\n{\n\tCNetChunk Packet;\n\tif(!pMsg)\n\t\treturn -1;\n\n\t// drop packet to dummy client\n\tif(0 <= ClientID && ClientID < MAX_CLIENTS && GameServer()->IsClientBot(ClientID))\n\t\treturn 0;\n\n\tmem_zero(&Packet, sizeof(CNetChunk));\n\tPacket.m_ClientID = ClientID;\n\tPacket.m_pData = pMsg->Data();\n\tPacket.m_DataSize = pMsg->Size();\n\n\tif(Flags&MSGFLAG_VITAL)\n\t\tPacket.m_Flags |= NETSENDFLAG_VITAL;\n\tif(Flags&MSGFLAG_FLUSH)\n\t\tPacket.m_Flags |= NETSENDFLAG_FLUSH;\n\n\t// write message to demo recorder\n\tif(!(Flags&MSGFLAG_NORECORD))\n\t\tm_DemoRecorder.RecordMessage(pMsg->Data(), pMsg->Size());\n\n\tif(!(Flags&MSGFLAG_NOSEND))\n\t{\n\t\tif(ClientID == -1)\n\t\t{\n\t\t\t// broadcast\n\t\t\tint i;\n\t\t\tfor(i = 0; i < MAX_CLIENTS; i++)\n\t\t\t\tif(m_aClients[i].m_State == CClient::STATE_INGAME && !m_aClients[i].m_Quitting)\n\t\t\t\t{\n\t\t\t\t\tPacket.m_ClientID = i;\n\t\t\t\t\tm_NetServer.Send(&Packet);\n\t\t\t\t}\n\t\t}\n\t\telse\n\t\t\tm_NetServer.Send(&Packet);\n\t}\n\treturn 0;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "bool DNP3_Base::AddToBuffer(Endpoint* endp, int target_len, const u_char** data, int* len)\n\t{\n\tif ( ! target_len )\n\t\treturn true;\n\n\tint to_copy = min(*len, target_len - endp->buffer_len);\n\n\tmemcpy(endp->buffer + endp->buffer_len, *data, to_copy);\n\t*data += to_copy;\n\t*len -= to_copy;\n\tendp->buffer_len += to_copy;\n\n\treturn endp->buffer_len == target_len;\n\t}", "label_name": "CWE-119", "label": "119"} -{"code": "void CLASS panasonic_load_raw()\n{\n int row, col, i, j, sh = 0, pred[2], nonz[2];\n\n pana_bits(0);\n for (row = 0; row < height; row++)\n {\n#ifdef LIBRAW_LIBRARY_BUILD\n checkCancel();\n#endif\n for (col = 0; col < raw_width; col++)\n {\n if ((i = col % 14) == 0)\n pred[0] = pred[1] = nonz[0] = nonz[1] = 0;\n if (i % 3 == 2)\n sh = 4 >> (3 - pana_bits(2));\n if (nonz[i & 1])\n {\n if ((j = pana_bits(8)))\n {\n if ((pred[i & 1] -= 0x80 << sh) < 0 || sh == 4)\n pred[i & 1] &= ~((~0u) << sh);\n pred[i & 1] += j << sh;\n }\n }\n else if ((nonz[i & 1] = pana_bits(8)) || i > 11)\n pred[i & 1] = nonz[i & 1] << 4 | pana_bits(4);\n if ((RAW(row, col) = pred[col & 1]) > 4098 && col < width)\n derror();\n }\n }\n}", "label_name": "CWE-119", "label": "119"} -{"code": "inline typename V::SetType FBUnserializer::unserializeSet() {\n p_ += CODE_SIZE;\n\n // the set size is written so we can reserve it in the set\n // in future. Skip past it for now.\n unserializeInt64();\n\n typename V::SetType ret = V::createSet();\n\n size_t code = nextCode();\n while (code != FB_SERIALIZE_STOP) {\n V::setAppend(ret, unserializeThing());\n code = nextCode();\n }\n p_ += CODE_SIZE;\n return ret;\n}", "label_name": "CWE-674", "label": "674"} -{"code": " void Init(bool hi) \n {\n for(int i = 0;i < 18;i++) {\n char string[5] = \"xl00\";\n string[1] = (hi)?('h'):('l');\n string[2] = (i / 10) + '0';\n string[3] = (i % 10) + '0';\n X[i].Init(string);\n string[0] = 'm';\n M[i].Init(string);\n }\n }", "label_name": "CWE-119", "label": "119"} -{"code": "int CLASS parse_jpeg(int offset)\n{\n int len, save, hlen, mark;\n fseek(ifp, offset, SEEK_SET);\n if (fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8)\n return 0;\n\n while (fgetc(ifp) == 0xff && (mark = fgetc(ifp)) != 0xda)\n {\n order = 0x4d4d;\n len = get2() - 2;\n save = ftell(ifp);\n if (mark == 0xc0 || mark == 0xc3 || mark == 0xc9)\n {\n fgetc(ifp);\n raw_height = get2();\n raw_width = get2();\n }\n order = get2();\n hlen = get4();\n if (get4() == 0x48454150) /* \"HEAP\" */\n {\n#ifdef LIBRAW_LIBRARY_BUILD\n imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;\n imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;\n#endif\n parse_ciff(save + hlen, len - hlen, 0);\n }\n if (parse_tiff(save + 6))\n apply_tiff();\n fseek(ifp, save + len, SEEK_SET);\n }\n return 1;\n}", "label_name": "CWE-119", "label": "119"} -{"code": "R_API RBinJavaVerificationObj *r_bin_java_verification_info_from_type(RBinJavaObj *bin, R_BIN_JAVA_STACKMAP_TYPE type, ut32 value) {\n\tRBinJavaVerificationObj *se = R_NEW0 (RBinJavaVerificationObj);\n\tif (!se) {\n\t\treturn NULL;\n\t}\n\tse->tag = type;\n\tif (se->tag == R_BIN_JAVA_STACKMAP_OBJECT) {\n\t\tse->info.obj_val_cp_idx = (ut16) value;\n\t} else if (se->tag == R_BIN_JAVA_STACKMAP_UNINIT) {\n\t\t/*if (bin->offset_sz == 4) {\n\t\tse->info.uninit_offset = value;\n\t\t} else {\n\t\tse->info.uninit_offset = (ut16) value;\n\t\t}*/\n\t\tse->info.uninit_offset = (ut16) value;\n\t}\n\treturn se;\n}", "label_name": "CWE-119", "label": "119"} -{"code": "void TestSocketLineReader::initTestCase()\n{\n m_server = new Server(this);\n\n QVERIFY2(m_server->listen(QHostAddress::LocalHost, 8694), \"Failed to create local tcp server\");\n\n m_timer.setInterval(4000);//For second is more enough to send some data via local socket\n m_timer.setSingleShot(true);\n connect(&m_timer, &QTimer::timeout, &m_loop, &QEventLoop::quit);\n\n m_conn = new QSslSocket(this);\n m_conn->connectToHost(QHostAddress::LocalHost, 8694);\n connect(m_conn, &QAbstractSocket::connected, &m_loop, &QEventLoop::quit);\n m_timer.start();\n m_loop.exec();\n\n QVERIFY2(m_conn->isOpen(), \"Could not connect to local tcp server\");\n}", "label_name": "CWE-400", "label": "400"} -{"code": "\t\tDeleteRunner(ReferenceHandle& that, Local key_handle) :\n\t\t\t\tkey{ExternalCopy::CopyIfPrimitive(key_handle)},\n\t\t\t\tcontext{that.context},\n\t\t\t\treference{that.reference} {\n\t\t\tthat.CheckDisposed();\n\t\t\tif (!key) {\n\t\t\t\tthrow RuntimeTypeError(\"Invalid `key`\");\n\t\t\t}\n\t\t}", "label_name": "CWE-913", "label": "913"} -{"code": "void jas_matrix_asl(jas_matrix_t *matrix, int n)\n{\n\tint i;\n\tint j;\n\tjas_seqent_t *rowstart;\n\tint rowstep;\n\tjas_seqent_t *data;\n\n\tif (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) {\n\t\tassert(matrix->rows_);\n\t\trowstep = jas_matrix_rowstep(matrix);\n\t\tfor (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i,\n\t\t rowstart += rowstep) {\n\t\t\tfor (j = matrix->numcols_, data = rowstart; j > 0; --j,\n\t\t\t ++data) {\n\t\t\t\t//*data <<= n;\n\t\t\t\t*data = jas_seqent_asl(*data, n);\n\t\t\t}\n\t\t}\n\t}\n}", "label_name": "CWE-20", "label": "20"} -{"code": " void JavascriptArray::SliceHelper(JavascriptArray* pArr, JavascriptArray* pnewArr, uint32 start, uint32 newLen)\n {\n SparseArraySegment* headSeg = (SparseArraySegment*)pArr->head;\n SparseArraySegment* pnewHeadSeg = (SparseArraySegment*)pnewArr->head;\n\n // Fill the newly created sliced array\n js_memcpy_s(pnewHeadSeg->elements, sizeof(T) * newLen, headSeg->elements + start, sizeof(T) * newLen);\n pnewHeadSeg->length = newLen;\n\n Assert(pnewHeadSeg->length <= pnewHeadSeg->size);\n // Prototype lookup for missing elements\n if (!pArr->HasNoMissingValues())\n {\n for (uint32 i = 0; i < newLen; i++)\n {\n // array type might be changed in the below call to DirectGetItemAtFull\n // need recheck array type before checking array item [i + start]\n if (pArr->IsMissingItem(i + start))\n {\n Var element;\n pnewArr->SetHasNoMissingValues(false);\n if (pArr->DirectGetItemAtFull(i + start, &element))\n {\n pnewArr->SetItem(i, element, PropertyOperation_None);\n }\n }\n }\n }\n#ifdef DBG\n else\n {\n for (uint32 i = 0; i < newLen; i++)\n {\n AssertMsg(!SparseArraySegment::IsMissingItem(&headSeg->elements[i+start]), \"Array marked incorrectly as having missing value\");\n }\n }\n\n#endif\n }", "label_name": "CWE-200", "label": "200"} -{"code": "TEST_F(QuantizedConv2DTest, OddPadding) {\n const int stride = 2;\n TF_ASSERT_OK(NodeDefBuilder(\"quantized_conv_op\", \"QuantizedConv2D\")\n .Input(FakeInput(DT_QUINT8))\n .Input(FakeInput(DT_QUINT8))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Input(FakeInput(DT_FLOAT))\n .Attr(\"out_type\", DataTypeToEnum::v())\n .Attr(\"strides\", {1, stride, stride, 1})\n .Attr(\"padding\", \"SAME\")\n .Finalize(node_def()));\n TF_ASSERT_OK(InitOp());\n\n const int depth = 1;\n const int image_width = 4;\n const int image_height = 4;\n const int image_batch_count = 1;\n AddInputFromArray(\n TensorShape({image_batch_count, image_height, image_width, depth}),\n {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16});\n const int filter_size = 3;\n const int filter_count = 1;\n AddInputFromArray(\n TensorShape({filter_size, filter_size, depth, filter_count}),\n {1, 2, 3, 4, 5, 6, 7, 8, 9});\n AddInputFromArray(TensorShape({1}), {0});\n AddInputFromArray(TensorShape({1}), {255.0f});\n AddInputFromArray(TensorShape({1}), {0});\n AddInputFromArray(TensorShape({1}), {255.0f});\n\n TF_ASSERT_OK(RunOpKernel());\n const int expected_width = image_width / stride;\n const int expected_height = (image_height * filter_count) / stride;\n Tensor expected(DT_QINT32, TensorShape({image_batch_count, expected_height,\n expected_width, filter_count}));\n test::FillValues(&expected, {348, 252, 274, 175});\n test::ExpectTensorEqual(expected, *GetOutput(0));\n}", "label_name": "CWE-20", "label": "20"} -{"code": "static Status ValidateSavedTensors(const GraphDef& graph_def) {\n for (const auto& node : graph_def.node()) {\n const auto node_iterator = node.attr().find(\"value\");\n if (node_iterator != node.attr().end()) {\n AttrValue node_value = node_iterator->second;\n if (node_value.has_tensor()) {\n const PartialTensorShape node_shape(node_value.tensor().tensor_shape());\n if (node_shape.num_elements() < 0) {\n return errors::FailedPrecondition(\n \"Saved model contains node \\\"\", node.name(), \"\\\" (op \\\"\",\n node.op(), \"\\\") which initializes from a tensor with \",\n node_shape.num_elements(), \" elements\");\n }\n }\n } else if (node.op() == \"Const\") {\n return errors::FailedPrecondition(\n \"Saved model contains node \\\"\", node.name(),\n \"\\\" which is a constant tensor but no value has been provided\");\n }\n }\n return Status::OK();\n}", "label_name": "CWE-20", "label": "20"} -{"code": "TEST_F(RouterTest, RetryUpstreamResetResponseStarted) {\n NiceMock encoder1;\n Http::ResponseDecoder* response_decoder = nullptr;\n expectNewStreamWithImmediateEncoder(encoder1, &response_decoder, Http::Protocol::Http10);\n\n expectResponseTimerCreate();\n\n Http::TestRequestHeaderMapImpl headers{{\"x-envoy-retry-on\", \"5xx\"}, {\"x-envoy-internal\", \"true\"}};\n HttpTestUtility::addDefaultHeaders(headers);\n router_.decodeHeaders(headers, true);\n EXPECT_EQ(1U,\n callbacks_.route_->route_entry_.virtual_cluster_.stats().upstream_rq_total_.value());\n\n // Since the response is already started we don't retry.\n EXPECT_CALL(*router_.retry_state_, shouldRetryHeaders(_, _, _)).WillOnce(Return(RetryStatus::No));\n EXPECT_CALL(callbacks_, encodeHeaders_(_, false));\n Http::ResponseHeaderMapPtr response_headers(\n new Http::TestResponseHeaderMapImpl{{\":status\", \"200\"}});\n EXPECT_CALL(cm_.thread_local_cluster_.conn_pool_.host_->outlier_detector_,\n putHttpResponseCode(200));\n response_decoder->decodeHeaders(std::move(response_headers), false);\n EXPECT_CALL(cm_.thread_local_cluster_.conn_pool_.host_->outlier_detector_,\n putResult(Upstream::Outlier::Result::LocalOriginConnectFailed, _));\n // Normally, sendLocalReply will actually send the reply, but in this case the\n // HCM will detect the headers have already been sent and not route through\n // the encoder again.\n EXPECT_CALL(callbacks_, sendLocalReply(_, _, _, _, _)).WillOnce(testing::InvokeWithoutArgs([] {\n }));\n encoder1.stream_.resetStream(Http::StreamResetReason::RemoteReset);\n // For normal HTTP, once we have a 200 we consider this a success, even if a\n // later reset occurs.\n EXPECT_TRUE(verifyHostUpstreamStats(1, 0));\n EXPECT_EQ(1U,\n callbacks_.route_->route_entry_.virtual_cluster_.stats().upstream_rq_total_.value());\n}", "label_name": "CWE-670", "label": "670"} -{"code": "error_t ssiProcessExecCommand(HttpConnection *connection, const char_t *tag, size_t length)\n{\n char_t *separator;\n char_t *attribute;\n char_t *value;\n\n //First, check whether CGI is supported by the server\n if(connection->settings->cgiCallback == NULL)\n return ERROR_INVALID_TAG;\n\n //Discard invalid SSI directives\n if(length < 4 || length >= HTTP_SERVER_BUFFER_SIZE)\n return ERROR_INVALID_TAG;\n\n //Skip the SSI exec command (4 bytes)\n osMemcpy(connection->buffer, tag + 4, length - 4);\n //Ensure the resulting string is NULL-terminated\n connection->buffer[length - 4] = '\\0';\n\n //Check whether a separator is present\n separator = strchr(connection->buffer, '=');\n //Separator not found?\n if(!separator)\n return ERROR_INVALID_TAG;\n\n //Split the tag\n *separator = '\\0';\n\n //Get attribute name and value\n attribute = strTrimWhitespace(connection->buffer);\n value = strTrimWhitespace(separator + 1);\n\n //Remove leading simple or double quote\n if(value[0] == '\\'' || value[0] == '\\\"')\n value++;\n\n //Get the length of the attribute value\n length = osStrlen(value);\n\n //Remove trailing simple or double quote\n if(length > 0)\n {\n if(value[length - 1] == '\\'' || value[length - 1] == '\\\"')\n value[length - 1] = '\\0';\n }\n\n //Enforce attribute name\n if(osStrcasecmp(attribute, \"cgi\") && osStrcasecmp(attribute, \"cmd\") && osStrcasecmp(attribute, \"cmd_argument\"))\n return ERROR_INVALID_TAG;\n //Check the length of the CGI parameter\n if(osStrlen(value) > HTTP_SERVER_CGI_PARAM_MAX_LEN)\n return ERROR_INVALID_TAG;\n\n //The scratch buffer may be altered by the user-defined callback.\n //So the CGI parameter must be copied prior to function invocation\n osStrcpy(connection->cgiParam, value);\n\n //Invoke user-defined callback\n return connection->settings->cgiCallback(connection, connection->cgiParam);\n}", "label_name": "CWE-20", "label": "20"} -{"code": "QString Helper::temporaryMountDevice(const QString &device, const QString &name, bool readonly)\n{\n QString mount_point = mountPoint(device);\n\n if (!mount_point.isEmpty())\n return mount_point;\n\n mount_point = \"%1/.%2/mount/%3\";\n const QStringList &tmp_paths = QStandardPaths::standardLocations(QStandardPaths::TempLocation);\n\n mount_point = mount_point.arg(tmp_paths.isEmpty() ? \"/tmp\" : tmp_paths.first()).arg(qApp->applicationName()).arg(name);\n\n if (!QDir::current().mkpath(mount_point)) {\n dCError(\"mkpath \\\"%s\\\" failed\", qPrintable(mount_point));\n\n return QString();\n }\n\n if (!mountDevice(device, mount_point, readonly)) {\n dCError(\"Mount the device \\\"%s\\\" to \\\"%s\\\" failed\", qPrintable(device), qPrintable(mount_point));\n\n return QString();\n }\n\n return mount_point;\n}", "label_name": "CWE-362", "label": "362"} -{"code": "mptctl_mpt_command (unsigned long arg)\n{\n\tstruct mpt_ioctl_command __user *uarg = (void __user *) arg;\n\tstruct mpt_ioctl_command karg;\n\tMPT_ADAPTER\t*ioc;\n\tint\t\tiocnum;\n\tint\t\trc;\n\n\n\tif (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_command))) {\n\t\tprintk(KERN_ERR MYNAM \"%s@%d::mptctl_mpt_command - \"\n\t\t\t\"Unable to read in mpt_ioctl_command struct @ %p\\n\",\n\t\t\t\t__FILE__, __LINE__, uarg);\n\t\treturn -EFAULT;\n\t}\n\n\tif (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||\n\t (ioc == NULL)) {\n\t\tprintk(KERN_DEBUG MYNAM \"%s::mptctl_mpt_command() @%d - ioc%d not found!\\n\",\n\t\t\t\t__FILE__, __LINE__, iocnum);\n\t\treturn -ENODEV;\n\t}\n\n\trc = mptctl_do_mpt_command (karg, &uarg->MF);\n\n\treturn rc;\n}", "label_name": "CWE-362", "label": "362"} -{"code": "RemoteFsDevice::RemoteFsDevice(MusicLibraryModel *m, const Details &d)\n : FsDevice(m, d.name, createUdi(d.name))\n , mountToken(0)\n , currentMountStatus(false)\n , details(d)\n , proc(0)\n , mounterIface(0)\n , messageSent(false)\n{\n// details.path=Utils::fixPath(details.path);\n setup();\n icn=MonoIcon::icon(details.isLocalFile()\n ? FontAwesome::foldero\n : constSshfsProtocol==details.url.scheme()\n ? FontAwesome::linux_os\n : FontAwesome::windows, Utils::monoIconColor());\n}", "label_name": "CWE-20", "label": "20"} -{"code": "R_API RBinJavaAnnotation *r_bin_java_annotation_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {\n\tut32 i = 0;\n\tRBinJavaAnnotation *annotation = NULL;\n\tRBinJavaElementValuePair *evps = NULL;\n\tut64 offset = 0;\n\tannotation = R_NEW0 (RBinJavaAnnotation);\n\tif (!annotation) {\n\t\treturn NULL;\n\t}\n\t// (ut16) read and set annotation_value.type_idx;\n\tannotation->type_idx = R_BIN_JAVA_USHORT (buffer, offset);\n\toffset += 2;\n\t// (ut16) read and set annotation_value.num_element_value_pairs;\n\tannotation->num_element_value_pairs = R_BIN_JAVA_USHORT (buffer, offset);\n\toffset += 2;\n\tannotation->element_value_pairs = r_list_newf (r_bin_java_element_pair_free);\n\t// read annotation_value.num_element_value_pairs, and append to annotation_value.element_value_pairs\n\tfor (i = 0; i < annotation->num_element_value_pairs; i++) {\n\t\tif (offset > sz) {\n\t\t\tbreak;\n\t\t}\n\t\tevps = r_bin_java_element_pair_new (buffer + offset, sz - offset, buf_offset + offset);\n\t\tif (evps) {\n\t\t\toffset += evps->size;\n\t\t\tr_list_append (annotation->element_value_pairs, (void *) evps);\n\t\t}\n\t}\n\tannotation->size = offset;\n\treturn annotation;\n}", "label_name": "CWE-119", "label": "119"} -{"code": "bool MemoryManager::validate_user_write(const Process& process, VirtualAddress vaddr) const\n{\n auto* region = region_from_vaddr(process, vaddr);\n return region && region->is_writable();\n}", "label_name": "CWE-119", "label": "119"} -{"code": "R_API RBinJavaAttrInfo *r_bin_java_synthetic_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {\n\tut64 offset = 0;\n\tRBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);\n\tif (!attr) {\n\t\treturn NULL;\n\t}\n\toffset += 6;\n\tattr->type = R_BIN_JAVA_ATTR_TYPE_SYNTHETIC_ATTR;\n\tattr->size = offset;\n\treturn attr;\n}", "label_name": "CWE-119", "label": "119"} -{"code": "void InferenceContext::PreInputInit(\n const OpDef& op_def, const std::vector& input_tensors,\n const std::vector& input_tensors_as_shapes) {\n // TODO(mdan): This is also done at graph construction. Run only here instead?\n const auto ret = full_type::SpecializeType(attrs_, op_def);\n DCHECK(ret.status().ok()) << \"while instantiating types: \" << ret.status();\n ret_types_ = ret.ValueOrDie();\n\n input_tensors_ = input_tensors;\n input_tensors_as_shapes_ = input_tensors_as_shapes;\n\n construction_status_ =\n NameRangesForNode(attrs_, op_def, &input_name_map_, &output_name_map_);\n if (!construction_status_.ok()) return;\n\n int num_outputs = 0;\n for (const auto& e : output_name_map_) {\n num_outputs = std::max(num_outputs, e.second.second);\n }\n outputs_.assign(num_outputs, nullptr);\n output_handle_shapes_and_types_.resize(num_outputs);\n}", "label_name": "CWE-754", "label": "754"} -{"code": "\tbool is_digit(char c) { return c >= '0' && c <= '9'; }", "label_name": "CWE-119", "label": "119"} -{"code": "R_API RBinJavaAttrInfo *r_bin_java_synthetic_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {\n\tut64 offset = 0;\n\tRBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);\n\tif (!attr) {\n\t\treturn NULL;\n\t}\n\toffset += 6;\n\tattr->type = R_BIN_JAVA_ATTR_TYPE_SYNTHETIC_ATTR;\n\tattr->size = offset;\n\treturn attr;\n}", "label_name": "CWE-119", "label": "119"} -{"code": "mptctl_readtest (unsigned long arg)\n{\n\tstruct mpt_ioctl_test __user *uarg = (void __user *) arg;\n\tstruct mpt_ioctl_test\t karg;\n\tMPT_ADAPTER *ioc;\n\tint iocnum;\n\n\tif (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_test))) {\n\t\tprintk(KERN_ERR MYNAM \"%s@%d::mptctl_readtest - \"\n\t\t\t\"Unable to read in mpt_ioctl_test struct @ %p\\n\",\n\t\t\t\t__FILE__, __LINE__, uarg);\n\t\treturn -EFAULT;\n\t}\n\n\tif (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||\n\t (ioc == NULL)) {\n\t\tprintk(KERN_DEBUG MYNAM \"%s::mptctl_readtest() @%d - ioc%d not found!\\n\",\n\t\t\t\t__FILE__, __LINE__, iocnum);\n\t\treturn -ENODEV;\n\t}\n\n\tdctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT \"mptctl_readtest called.\\n\",\n\t ioc->name));\n\t/* Fill in the data and return the structure to the calling\n\t * program\n\t */\n\n#ifdef MFCNT\n\tkarg.chip_type = ioc->mfcnt;\n#else\n\tkarg.chip_type = ioc->pcidev->device;\n#endif\n\tstrncpy (karg.name, ioc->name, MPT_MAX_NAME);\n\tkarg.name[MPT_MAX_NAME-1]='\\0';\n\tstrncpy (karg.product, ioc->prod_name, MPT_PRODUCT_LENGTH);\n\tkarg.product[MPT_PRODUCT_LENGTH-1]='\\0';\n\n\t/* Copy the data from kernel memory to user memory\n\t */\n\tif (copy_to_user((char __user *)arg, &karg, sizeof(struct mpt_ioctl_test))) {\n\t\tprintk(MYIOC_s_ERR_FMT \"%s@%d::mptctl_readtest - \"\n\t\t\t\"Unable to write out mpt_ioctl_test struct @ %p\\n\",\n\t\t\tioc->name, __FILE__, __LINE__, uarg);\n\t\treturn -EFAULT;\n\t}\n\n\treturn 0;\n}", "label_name": "CWE-362", "label": "362"} -{"code": "error_t coapServerInitResponse(CoapServerContext *context)\n{\n CoapMessageHeader *requestHeader;\n CoapMessageHeader *responseHeader;\n\n //Point to the CoAP request header\n requestHeader = (CoapMessageHeader *) context->request.buffer;\n //Point to the CoAP response header\n responseHeader = (CoapMessageHeader *) context->response.buffer;\n\n //Format message header\n responseHeader->version = COAP_VERSION_1;\n responseHeader->tokenLen = requestHeader->tokenLen;\n responseHeader->code = COAP_CODE_INTERNAL_SERVER;\n responseHeader->mid = requestHeader->mid;\n\n //If immediately available, the response to a request carried in a\n //Confirmable message is carried in an Acknowledgement (ACK) message\n if(requestHeader->type == COAP_TYPE_CON)\n {\n responseHeader->type = COAP_TYPE_ACK;\n }\n else\n {\n responseHeader->type = COAP_TYPE_NON;\n }\n\n //The token is used to match a response with a request\n osMemcpy(responseHeader->token, requestHeader->token,\n requestHeader->tokenLen);\n\n //Set the length of the CoAP message\n context->response.length = sizeof(CoapMessageHeader) + responseHeader->tokenLen;\n context->response.pos = 0;\n\n //Sucessful processing\n return NO_ERROR;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "bool ECDSA_Verification_Operation::verify(const uint8_t msg[], size_t msg_len,\n const uint8_t sig[], size_t sig_len)\n {\n if(sig_len != m_group.get_order_bytes() * 2)\n return false;\n\n const BigInt e(msg, msg_len, m_group.get_order_bits());\n\n const BigInt r(sig, sig_len / 2);\n const BigInt s(sig + sig_len / 2, sig_len / 2);\n\n if(r <= 0 || r >= m_group.get_order() || s <= 0 || s >= m_group.get_order())\n return false;\n\n const BigInt w = m_group.inverse_mod_order(s);\n\n const BigInt u1 = m_group.multiply_mod_order(e, w);\n const BigInt u2 = m_group.multiply_mod_order(r, w);\n const PointGFp R = m_gy_mul.multi_exp(u1, u2);\n\n if(R.is_zero())\n return false;\n\n const BigInt v = m_group.mod_order(R.get_affine_x());\n return (v == r);\n }", "label_name": "CWE-200", "label": "200"} -{"code": "static int emulate_store_desc_ptr(struct x86_emulate_ctxt *ctxt,\n\t\t\t\t void (*get)(struct x86_emulate_ctxt *ctxt,\n\t\t\t\t\t struct desc_ptr *ptr))\n{\n\tstruct desc_ptr desc_ptr;\n\n\tif (ctxt->mode == X86EMUL_MODE_PROT64)\n\t\tctxt->op_bytes = 8;\n\tget(ctxt, &desc_ptr);\n\tif (ctxt->op_bytes == 2) {\n\t\tctxt->op_bytes = 4;\n\t\tdesc_ptr.address &= 0x00ffffff;\n\t}\n\t/* Disable writeback. */\n\tctxt->dst.type = OP_NONE;\n\treturn segmented_write(ctxt, ctxt->dst.addr.mem,\n\t\t\t &desc_ptr, 2 + ctxt->op_bytes);\n}", "label_name": "CWE-200", "label": "200"} -{"code": "R_API RBinJavaAttrInfo *r_bin_java_source_code_file_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {\n\tif (!sz) {\n\t\treturn NULL;\n\t}\n\tut64 offset = 0;\n\tRBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);\n\toffset += 6;\n\tif (!attr) {\n\t\treturn NULL;\n\t}\n\tattr->type = R_BIN_JAVA_ATTR_TYPE_SOURCE_FILE_ATTR;\n\t// if (buffer + offset > buffer + sz) return NULL;\n\tattr->info.source_file_attr.sourcefile_idx = R_BIN_JAVA_USHORT (buffer, offset);\n\toffset += 2;\n\tattr->size = offset;\n\t// IFDBG r_bin_java_print_source_code_file_attr_summary(attr);\n\treturn attr;\n}", "label_name": "CWE-119", "label": "119"} -{"code": " explicit HashContext(const HashContext* ctx) {\n assert(ctx->ops);\n assert(ctx->ops->context_size >= 0);\n ops = ctx->ops;\n context = malloc(ops->context_size);\n ops->hash_copy(context, ctx->context);\n options = ctx->options;\n key = ctx->key ? strdup(ctx->key) : nullptr;\n }", "label_name": "CWE-200", "label": "200"} -{"code": "error_t tcpAddOption(TcpHeader *segment, uint8_t kind, const void *value,\n uint8_t length)\n{\n uint_t i;\n size_t paddingSize;\n TcpOption *option;\n\n //Length of the complete option field\n length += sizeof(TcpOption);\n\n //Make sure there is enough space to add the specified option\n if((segment->dataOffset * 4 + length) > TCP_MAX_HEADER_LENGTH)\n return ERROR_FAILURE;\n\n //Index of the first available byte\n i = segment->dataOffset * 4 - sizeof(TcpHeader);\n\n //Calculate the number of padding bytes\n paddingSize = (length % 4) ? 4 - (length % 4) : 0;\n //Write padding bytes\n while(paddingSize--)\n segment->options[i++] = TCP_OPTION_NOP;\n\n //Point to the current location\n option = (TcpOption *) (segment->options + i);\n //Write specified option\n option->kind = kind;\n option->length = length;\n osMemcpy(option->value, value, length - sizeof(TcpOption));\n //Adjust index value\n i += length;\n\n //Update TCP header length\n segment->dataOffset = (sizeof(TcpHeader) + i) / 4;\n\n //Option successfully added\n return NO_ERROR;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "void RemoteFsDevice::serviceAdded(const QString &name)\n{\n if (name==details.serviceName && constSambaAvahiProtocol==details.url.scheme()) {\n sub=tr(\"Available\");\n updateStatus();\n }\n}", "label_name": "CWE-20", "label": "20"} -{"code": "untrusted_launcher_response_callback (GtkDialog *dialog,\n int response_id,\n ActivateParametersDesktop *parameters)\n{\n GdkScreen *screen;\n char *uri;\n GFile *file;\n\n switch (response_id)\n {\n case RESPONSE_RUN:\n {\n screen = gtk_widget_get_screen (GTK_WIDGET (parameters->parent_window));\n uri = nautilus_file_get_uri (parameters->file);\n DEBUG (\"Launching untrusted launcher %s\", uri);\n nautilus_launch_desktop_file (screen, uri, NULL,\n parameters->parent_window);\n g_free (uri);\n }\n break;\n\n case RESPONSE_MARK_TRUSTED:\n {\n file = nautilus_file_get_location (parameters->file);\n nautilus_file_mark_desktop_file_trusted (file,\n parameters->parent_window,\n TRUE,\n NULL, NULL);\n g_object_unref (file);\n }\n break;\n\n default:\n {\n /* Just destroy dialog */\n }\n break;\n }\n\n gtk_widget_destroy (GTK_WIDGET (dialog));\n activate_parameters_desktop_free (parameters);\n}", "label_name": "CWE-20", "label": "20"} -{"code": "void jas_seq2d_bindsub(jas_matrix_t *s, jas_matrix_t *s1, int xstart,\n int ystart, int xend, int yend)\n{\n\tjas_matrix_bindsub(s, s1, ystart - s1->ystart_, xstart - s1->xstart_,\n\t yend - s1->ystart_ - 1, xend - s1->xstart_ - 1);\n}", "label_name": "CWE-20", "label": "20"} -{"code": "jas_image_t *jas_image_create0()\n{\n\tjas_image_t *image;\n\n\tif (!(image = jas_malloc(sizeof(jas_image_t)))) {\n\t\treturn 0;\n\t}\n\n\timage->tlx_ = 0;\n\timage->tly_ = 0;\n\timage->brx_ = 0;\n\timage->bry_ = 0;\n\timage->clrspc_ = JAS_CLRSPC_UNKNOWN;\n\timage->numcmpts_ = 0;\n\timage->maxcmpts_ = 0;\n\timage->cmpts_ = 0;\n\timage->inmem_ = true;\n\timage->cmprof_ = 0;\n\n\treturn image;\n}", "label_name": "CWE-20", "label": "20"} -{"code": "cosine_seek_read(wtap *wth, gint64 seek_off, struct wtap_pkthdr *phdr,\n\tBuffer *buf, int *err, gchar **err_info)\n{\n\tint\tpkt_len;\n\tchar\tline[COSINE_LINE_LENGTH];\n\n\tif (file_seek(wth->random_fh, seek_off, SEEK_SET, err) == -1)\n\t\treturn FALSE;\n\n\tif (file_gets(line, COSINE_LINE_LENGTH, wth->random_fh) == NULL) {\n\t\t*err = file_error(wth->random_fh, err_info);\n\t\tif (*err == 0) {\n\t\t\t*err = WTAP_ERR_SHORT_READ;\n\t\t}\n\t\treturn FALSE;\n\t}\n\n\t/* Parse the header */\n\tpkt_len = parse_cosine_rec_hdr(phdr, line, err, err_info);\n\tif (pkt_len == -1)\n\t\treturn FALSE;\n\n\t/* Convert the ASCII hex dump to binary data */\n\treturn parse_cosine_hex_dump(wth->random_fh, phdr, pkt_len, buf, err,\n\t err_info);\n}", "label_name": "CWE-119", "label": "119"} -{"code": " void Compute(OpKernelContext* ctx) override {\n const Tensor& values_tensor = ctx->input(0);\n const Tensor& value_range_tensor = ctx->input(1);\n const Tensor& nbins_tensor = ctx->input(2);\n\n OP_REQUIRES(ctx, TensorShapeUtils::IsVector(value_range_tensor.shape()),\n errors::InvalidArgument(\"value_range should be a vector.\"));\n OP_REQUIRES(ctx, (value_range_tensor.shape().num_elements() == 2),\n errors::InvalidArgument(\n \"value_range should be a vector of 2 elements.\"));\n OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(nbins_tensor.shape()),\n errors::InvalidArgument(\"nbins should be a scalar.\"));\n\n const auto values = values_tensor.flat();\n const auto value_range = value_range_tensor.flat();\n const auto nbins = nbins_tensor.scalar()();\n\n OP_REQUIRES(\n ctx, (value_range(0) < value_range(1)),\n errors::InvalidArgument(\"value_range should satisfy value_range[0] < \"\n \"value_range[1], but got '[\",\n value_range(0), \", \", value_range(1), \"]'\"));\n OP_REQUIRES(\n ctx, (nbins > 0),\n errors::InvalidArgument(\"nbins should be a positive number, but got '\",\n nbins, \"'\"));\n\n Tensor* out_tensor;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_output(0, TensorShape({nbins}), &out_tensor));\n auto out = out_tensor->flat();\n\n OP_REQUIRES_OK(\n ctx, functor::HistogramFixedWidthFunctor::Compute(\n ctx, values, value_range, nbins, out));\n }", "label_name": "CWE-20", "label": "20"} -{"code": " static void setAppend(SetType& set, const VariantType& v) {\n auto value_type = type(v);\n if (value_type != HPHP::serialize::Type::INT64 &&\n value_type != HPHP::serialize::Type::STRING) {\n throw HPHP::serialize::UnserializeError(\n \"Unsupported keyset element of type \" +\n folly::to(value_type));\n }\n set.append(v);\n }", "label_name": "CWE-674", "label": "674"} -{"code": "RemoteFsDevice::RemoteFsDevice(MusicLibraryModel *m, const DeviceOptions &options, const Details &d)\n : FsDevice(m, d.name, createUdi(d.name))\n , mountToken(0)\n , currentMountStatus(false)\n , details(d)\n , proc(0)\n , mounterIface(0)\n , messageSent(false)\n{\n opts=options;\n// details.path=Utils::fixPath(details.path);\n load();\n mount();\n icn=MonoIcon::icon(details.isLocalFile()\n ? FontAwesome::foldero\n : constSshfsProtocol==details.url.scheme()\n ? FontAwesome::linux_os\n : FontAwesome::windows, Utils::monoIconColor());\n}", "label_name": "CWE-20", "label": "20"} -{"code": "TPM_RC tpm_kdfa(TSS2_SYS_CONTEXT *sapi_context, TPMI_ALG_HASH hashAlg,\n TPM2B *key, char *label, TPM2B *contextU, TPM2B *contextV, UINT16 bits,\n TPM2B_MAX_BUFFER *resultKey )\n{\n TPM2B_DIGEST tmpResult;\n TPM2B_DIGEST tpm2bLabel, tpm2bBits, tpm2b_i_2;\n UINT8 *tpm2bBitsPtr = &tpm2bBits.t.buffer[0];\n UINT8 *tpm2b_i_2Ptr = &tpm2b_i_2.t.buffer[0];\n TPM2B_DIGEST *bufferList[8];\n UINT32 bitsSwizzled, i_Swizzled;\n TPM_RC rval;\n int i, j;\n UINT16 bytes = bits / 8;\n\n resultKey->t .size = 0;\n\n tpm2b_i_2.t.size = 4;\n\n tpm2bBits.t.size = 4;\n bitsSwizzled = string_bytes_endian_convert_32( bits );\n *(UINT32 *)tpm2bBitsPtr = bitsSwizzled;\n\n for(i = 0; label[i] != 0 ;i++ );\n\n tpm2bLabel.t.size = i+1;\n for( i = 0; i < tpm2bLabel.t.size; i++ )\n {\n tpm2bLabel.t.buffer[i] = label[i];\n }\n\n resultKey->t.size = 0;\n\n i = 1;\n\n while( resultKey->t.size < bytes )\n {\n // Inner loop\n\n i_Swizzled = string_bytes_endian_convert_32( i );\n *(UINT32 *)tpm2b_i_2Ptr = i_Swizzled;\n\n j = 0;\n bufferList[j++] = (TPM2B_DIGEST *)&(tpm2b_i_2.b);\n bufferList[j++] = (TPM2B_DIGEST *)&(tpm2bLabel.b);\n bufferList[j++] = (TPM2B_DIGEST *)contextU;\n bufferList[j++] = (TPM2B_DIGEST *)contextV;\n bufferList[j++] = (TPM2B_DIGEST *)&(tpm2bBits.b);\n bufferList[j++] = (TPM2B_DIGEST *)0;\n rval = tpm_hmac(sapi_context, hashAlg, key, (TPM2B **)&( bufferList[0] ), &tmpResult );\n if( rval != TPM_RC_SUCCESS )\n {\n return( rval );\n }\n\n bool res = string_bytes_concat_buffer(resultKey, &(tmpResult.b));\n if (!res) {\n return TSS2_SYS_RC_BAD_VALUE;\n }\n }\n\n // Truncate the result to the desired size.\n resultKey->t.size = bytes;\n\n return TPM_RC_SUCCESS;\n}", "label_name": "CWE-522", "label": "522"} -{"code": " def remote_address\n @request.forwarded_for || socket_address\n rescue Exception\n log_error\n nil\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def test_AES_crush\n 500.times do\n assert_nothing_raised(\"[Bug #2768]\") do\n # it caused OpenSSL SEGV by uninitialized key\n OpenSSL::Cipher::AES128.new(\"ECB\").update \".\" * 17\n end\n end\n end", "label_name": "CWE-326", "label": "326"} -{"code": " it \"queries a slave node\" do\n session.should_receive(:socket_for).with(:read).\n and_return(socket)\n session.query(query)\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def test_should_not_destroy_if_used_by_hosts\n subnet = subnets(:one)\n delete :destroy, {:id => subnet}, set_session_user\n assert_redirected_to subnets_url\n assert Subnet.exists?(subnet.id)\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"requires an account with mail\" do\n user = FactoryGirl.create(:user)\n get :index, {}, set_session_user.merge(:user => user.id)\n assert_response :redirect\n assert_redirected_to edit_user_path(user)\n assert_equal \"An email address is required, please update your account details\", flash[:error]\n end", "label_name": "CWE-200", "label": "200"} -{"code": " def munge_name(name)\n # LAK:NOTE http://snurl.com/21zf8 [groups_google_com]\n # Change to name.downcase.split(\".\",-1).reverse for FQDN support\n name.downcase.split(\".\").reverse\n end", "label_name": "CWE-287", "label": "287"} -{"code": " it 'fails when local logins is disabled' do\n SiteSetting.enable_local_logins = false\n\n get \"/session/email-login/#{email_token.token}\"\n\n expect(response.status).to eq(500)\n end", "label_name": "CWE-287", "label": "287"} -{"code": " it \"sets the object id's data\" do\n Moped::BSON::ObjectId.new(bytes).data.should == bytes\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"sets the generation time\" do\n time = Time.at((Time.now.utc - 64800).to_i).utc\n Moped::BSON::ObjectId.new(nil, time).generation_time.should == time\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def generate(time, inc = 0)\n pid = Process.pid % 0xFFFF\n\n [\n time >> 24 & 0xFF, # 4 bytes time (network order)\n time >> 16 & 0xFF,\n time >> 8 & 0xFF,\n time & 0xFF,\n @machine_id[0], # 3 bytes machine\n @machine_id[1],\n @machine_id[2],\n pid >> 8 & 0xFF, # 2 bytes process id\n pid & 0xFF,\n inc >> 16 & 0xFF, # 3 bytes increment\n inc >> 8 & 0xFF,\n inc & 0xFF,\n ]\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def generation_time\n Time.at(@data.pack(\"C4\").unpack(\"N\")[0]).utc\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"returns the living socket\" do\n cluster.socket_for(:write).should eq socket\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def one_time_password\n otp_username = $redis.get \"otp_#{params[:token]}\"\n\n if otp_username && user = User.find_by_username(otp_username)\n log_on_user(user)\n $redis.del \"otp_#{params[:token]}\"\n return redirect_to path(\"/\")\n else\n @error = I18n.t('user_api_key.invalid_token')\n end\n\n render layout: 'no_ember'\n end", "label_name": "CWE-287", "label": "287"} -{"code": " it \"memoizes the database\" do\n database = session.current_database\n session.current_database.should equal(database)\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"raises an exception\" do\n expect { session.current_database }.to raise_exception\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"removes the socket\" do\n cluster.should_receive(:remove).with(dead_server)\n cluster.socket_for :write\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def self.publish_unread(post)\n return unless post.topic.regular?\n # TODO at high scale we are going to have to defer this,\n # perhaps cut down to users that are around in the last 7 days as well\n\n group_ids =\n if post.post_type == Post.types[:whisper]\n [Group::AUTO_GROUPS[:staff]]\n else\n post.topic.category && post.topic.category.secure_group_ids\n end\n\n tags = nil\n tag_ids = nil\n if include_tags_in_report?\n tag_ids, tags = post.topic.tags.pluck(:id, :name).transpose\n end\n\n TopicUser\n .tracking(post.topic_id)\n .includes(user: :user_stat)\n .select([:user_id, :last_read_post_number, :notification_level])\n .each do |tu|\n\n payload = {\n last_read_post_number: tu.last_read_post_number,\n highest_post_number: post.post_number,\n updated_at: post.topic.updated_at,\n created_at: post.created_at,\n category_id: post.topic.category_id,\n notification_level: tu.notification_level,\n archetype: post.topic.archetype,\n first_unread_at: tu.user.user_stat.first_unread_at,\n unread_not_too_old: true\n }\n\n if tags\n payload[:tags] = tags\n payload[:topic_tag_ids] = tag_ids\n end\n\n message = {\n topic_id: post.topic_id,\n message_type: UNREAD_MESSAGE_TYPE,\n payload: payload\n }\n\n MessageBus.publish(self.unread_channel_key(tu.user_id), message.as_json, group_ids: group_ids)\n end\n\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"returns false\" do\n indexes.drop(other: 1).should be_false\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"does not raise error if record is not pending\" do\n reviewable = ReviewableUser.needs_review!(target: Fabricate(:user, email: invite.email), created_by: invite.invited_by)\n reviewable.status = Reviewable.statuses[:ignored]\n reviewable.save!\n invite_redeemer.redeem\n\n reviewable.reload\n expect(reviewable.status).to eq(Reviewable.statuses[:ignored])\n end", "label_name": "CWE-863", "label": "863"} -{"code": " it \"raises a QueryFailure exception\" do\n expect {\n session.query(query)\n }.to raise_exception(Moped::Errors::QueryFailure)\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"updates a hostgroup with a parent parameter\" do\n child = FactoryGirl.create(:hostgroup, :parent => @base)\n as_admin do\n assert_equal \"original\", child.parameters[\"x\"]\n end\n post :update, {\"id\" => child.id, \"hostgroup\" => {\"name\" => child.name,\n :group_parameters_attributes => {\"0\" => {:name => \"x\", :value =>\"overridden\", :_destroy => \"\"}}}}, set_session_user\n assert_redirected_to hostgroups_url\n child.reload\n assert_equal \"overridden\", child.parameters[\"x\"]\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"stores the collection name\" do\n collection.name.should eq :users\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def socket_for(mode)\n if options[:retain_socket]\n @socket ||= cluster.socket_for(mode)\n else\n cluster.socket_for(mode)\n end\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it 'fails when local logins via email is disabled' do\n SiteSetting.enable_local_logins_via_email = false\n\n get \"/session/email-login/#{email_token.token}\"\n\n expect(response.status).to eq(404)\n end", "label_name": "CWE-287", "label": "287"} -{"code": " it \"should redeem the invite if invited by non staff and approve if staff not required to approve\" do\n inviter = invite.invited_by\n user = invite_redeemer.redeem\n\n expect(user.name).to eq(name)\n expect(user.username).to eq(username)\n expect(user.invited_by).to eq(inviter)\n expect(inviter.notifications.count).to eq(1)\n expect(user.approved).to eq(true)\n end", "label_name": "CWE-863", "label": "863"} -{"code": " def known_addresses\n [].tap do |addresses|\n addresses.concat seeds\n addresses.concat dynamic_seeds\n addresses.concat servers.map { |server| server.address }\n end.uniq\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def default_ids_hash(populate_values = false)\n ids = HashWithIndifferentAccess.new\n hash_keys.each do |col|\n ids[col] = populate_values ? Array(self.send(col)) : []\n end\n ids\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"approves user if invited by staff\" do\n SiteSetting.must_approve_users = true\n\n invite = Fabricate(:invite, email: 'test@example.com', invited_by: Fabricate(:admin))\n user = InviteRedeemer.create_user_from_invite(invite: invite, email: invite.email, username: 'test')\n expect(user.approved).to eq(true)\n end", "label_name": "CWE-863", "label": "863"} -{"code": " it \"should unstage user\" do\n staged_user = Fabricate(:staged, email: 'staged@account.com', active: true, username: 'staged1', name: 'Stage Name')\n invite = Fabricate(:invite, email: 'staged@account.com')\n user = InviteRedeemer.create_user_from_invite(invite: invite, email: invite.email, username: 'walter', name: 'Walter White')\n\n expect(user.id).to eq(staged_user.id)\n expect(user.username).to eq('walter')\n expect(user.name).to eq('Walter White')\n expect(user.staged).to eq(false)\n expect(user.email).to eq('staged@account.com')\n expect(user.approved).to eq(true)\n end", "label_name": "CWE-863", "label": "863"} -{"code": " def reconnect\n @servers = servers.map { |server| Server.new(server.address) }\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"adds the server to the list\" do\n cluster.sync_server server\n cluster.servers.should include server\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"creates an index with the provided name\" do\n indexes.create(key, name: \"custom_index_name\")\n indexes[key][\"name\"].should eq \"custom_index_name\"\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"drops the collection\" do\n database.should_receive(:command).with(drop: :users)\n collection.drop\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def write!(headers)\n if @orig_disable_profiling != @disable_profiling || @orig_backtrace_level != @backtrace_level || @cookie.nil?\n settings = {\"p\" => \"t\" }\n settings[\"dp\"] = \"t\" if @disable_profiling\n settings[\"bt\"] = @backtrace_level if @backtrace_level\n settings_string = settings.map{|k,v| \"#{k}=#{v}\"}.join(\",\")\n Rack::Utils.set_cookie_header!(headers, COOKIE_NAME, :value => settings_string, :path => '/')\n end\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"does not drop other indexes\" do\n indexes[age: -1].should_not be_nil\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"does not drop other indexes\" do\n indexes[age: -1].should_not be_nil\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"delegates to the current database\" do\n database = mock(Moped::Database)\n session.should_receive(:current_database).and_return(database)\n database.should_receive(:drop)\n session.drop\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def test_update_valid\n put :update, {:id => Hostgroup.first, :hostgroup => { :name => Hostgroup.first.name }}, set_session_user\n assert_redirected_to hostgroups_url\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it 'does not log in with incorrect two factor' do\n post \"/session/email-login/#{email_token.token}\", params: {\n second_factor_token: \"0000\",\n second_factor_method: UserSecondFactor.methods[:totp]\n }\n\n expect(response.status).to eq(200)\n\n expect(CGI.unescapeHTML(response.body)).to include(I18n.t(\n \"login.invalid_second_factor_code\"\n ))\n end", "label_name": "CWE-287", "label": "287"} -{"code": " def email_login\n raise Discourse::NotFound if !SiteSetting.enable_local_logins_via_email\n second_factor_token = params[:second_factor_token]\n second_factor_method = params[:second_factor_method].to_i\n token = params[:token]\n valid_token = !!EmailToken.valid_token_format?(token)\n user = EmailToken.confirmable(token)&.user\n\n if valid_token && user&.totp_enabled?\n if !second_factor_token.present?\n @second_factor_required = true\n @backup_codes_enabled = true if user&.backup_codes_enabled?\n return render layout: 'no_ember'\n elsif !user.authenticate_second_factor(second_factor_token, second_factor_method)\n RateLimiter.new(nil, \"second-factor-min-#{request.remote_ip}\", 3, 1.minute).performed!\n @error = I18n.t('login.invalid_second_factor_code')\n return render layout: 'no_ember'\n end\n end\n\n if user = EmailToken.confirm(token)\n if login_not_approved_for?(user)\n @error = login_not_approved[:error]\n elsif payload = login_error_check(user)\n @error = payload[:error]\n else\n log_on_user(user)\n return redirect_to path(\"/\")\n end\n else\n @error = I18n.t('email_login.invalid_token')\n end\n\n render layout: 'no_ember'\n end", "label_name": "CWE-287", "label": "287"} -{"code": " it \"sets the query operation's limit field\" do\n query.limit(5)\n query.operation.limit.should eq 5\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"removes the first matching document\" do\n session.should_receive(:with, :consistency => :strong).\n and_yield(session)\n\n session.should_receive(:execute).with do |delete|\n delete.flags.should eq [:remove_first]\n delete.selector.should eq query.operation.selector\n end\n\n query.remove\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"stores the cluster\" do\n session.cluster.should be_a(Moped::Cluster)\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"executes a simple query\" do\n session.should_receive(:simple_query).with(query.operation)\n query.one\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"has an empty list of primaries\" do\n cluster.primaries.should be_empty\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"sets the query operation's skip field\" do\n query.skip(5)\n query.operation.skip.should eq 5\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"syncs the cluster\" do\n cluster.should_receive(:sync) do\n cluster.servers << server\n end\n cluster.socket_for :write\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def initialize(string)\n super(\"'#{string}' is not a valid object id.\")\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"stores the cluster\" do\n session.cluster.should be_a(Moped::Cluster)\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"returns a new session\" do\n session.with(new_options).should_not eql session\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"updates to a mongo advanced selector\" do\n query.explain\n query.operation.selector.should eq(\n \"$query\" => selector,\n \"$explain\" => true,\n \"$orderby\" => { _id: 1 }\n )\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def test_destroy\n domain = Domain.first\n domain.hosts.clear\n domain.hostgroups.clear\n domain.subnets.clear\n delete :destroy, {:id => domain}, set_session_user\n assert_redirected_to domains_url\n assert !Domain.exists?(domain.id)\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"adds the credentials to the auth cache\" do\n cluster.login(\"admin\", \"username\", \"password\")\n cluster.auth.should eq(\"admin\" => [\"username\", \"password\"])\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def process_invitation\n approve_account_if_needed\n add_to_private_topics_if_invited\n add_user_to_groups\n send_welcome_message\n notify_invitee\n end", "label_name": "CWE-863", "label": "863"} -{"code": " def bulk_unread_topic_ids\n topic_query = TopicQuery.new(current_user)\n\n if inbox = params[:private_message_inbox]\n filter = private_message_filter(topic_query, inbox)\n topic_query.options[:limit] = false\n\n topic_query\n .filter_private_messages_unread(current_user, filter)\n .distinct(false)\n .pluck(:id)\n else\n topics = TopicQuery.unread_filter(topic_query.joined_topic_user, staff: guardian.is_staff?).listable_topics\n topics = TopicQuery.tracked_filter(topics, current_user.id) if params[:tracked].to_s == \"true\"\n\n if params[:category_id]\n if params[:include_subcategories]\n topics = topics.where(<<~SQL, category_id: params[:category_id])\n category_id in (select id FROM categories WHERE parent_category_id = :category_id) OR\n category_id = :category_id\n SQL\n else\n topics = topics.where('category_id = ?', params[:category_id])\n end\n end\n\n if params[:tag_name].present?\n topics = topics.joins(:tags).where(\"tags.name\": params[:tag_name])\n end\n\n topics.pluck(:id)\n end\n end", "label_name": "CWE-863", "label": "863"} -{"code": " def from_string(string)\n raise Errors::InvalidObjectId.new(string) unless legal?(string)\n data = []\n 12.times { |i| data << string[i*2, 2].to_i(16) }\n new data\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def test_edit\n get :edit, {:id => Hostgroup.first}, set_session_user\n assert_template 'edit'\n end", "label_name": "CWE-200", "label": "200"} -{"code": " def create_fixed_clamp_code(nbits, signed)\n if nbits == 1 && signed == :signed\n raise \"signed bitfield must have more than one bit\"\n end\n\n if signed == :signed\n max = (1 << (nbits - 1)) - 1\n min = -(max + 1)\n else\n min = 0\n max = (1 << nbits) - 1\n end\n\n clamp = \"(val < #{min}) ? #{min} : (val > #{max}) ? #{max} : val\"\n\n if nbits == 1\n # allow single bits to be used as booleans\n clamp = \"(val == true) ? 1 : (not val) ? 0 : #{clamp}\"\n end\n\n \"val = #{clamp}\"\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def index\n @applications = Doorkeeper.config.application_model.authorized_for(current_resource_owner)\n\n respond_to do |format|\n format.html\n format.json { render json: @applications }\n end\n end", "label_name": "CWE-862", "label": "862"} -{"code": " it \"queries the master node\" do\n session.should_receive(:socket_for).with(:write).\n and_return(socket)\n session.query(query)\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it 'logs in correctly' do\n post \"/session/email-login/#{email_token.token}\", params: {\n second_factor_token: ROTP::TOTP.new(user_second_factor.data).now,\n second_factor_method: UserSecondFactor.methods[:totp]\n }\n\n expect(response).to redirect_to(\"/\")\n end", "label_name": "CWE-287", "label": "287"} -{"code": " def first\n session.simple_query(operation)\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def each\n cursor = Cursor.new(session.with(retain_socket: true), operation)\n cursor.to_enum.tap do |enum|\n enum.each do |document|\n yield document\n end if block_given?\n end\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def category_preferences_export\n return enum_for(:category_preferences_export) unless block_given?\n\n CategoryUser\n .where(user_id: @current_user.id)\n .select(:category_id, :notification_level, :last_seen_at)\n .each do |cu|\n yield [\n cu.category_id,\n piped_category_name(cu.category_id),\n NotificationLevels.all[cu.notification_level],\n cu.last_seen_at\n ]\n end\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"removes the first matching document\" do\n session.should_receive(:with, :consistency => :strong).\n and_yield(session)\n\n session.should_receive(:execute).with do |delete|\n delete.flags.should eq [:remove_first]\n delete.selector.should eq query.operation.selector\n end\n\n query.remove\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def initialize(seeds, options = {})\n @cluster = Cluster.new(seeds)\n @options = options\n @options[:consistency] ||= :eventual\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"inserts the documents\" do\n session.should_receive(:execute).with do |insert|\n insert.documents.should eq [{a: 1}, {b: 2}]\n end\n collection.insert([{a: 1}, {b: 2}])\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"raises no exception\" do\n lambda do\n cluster.sync_server server\n end.should_not raise_exception\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def test_update_invalid\n put :update, {:id => Hostgroup.first, :hostgroup => { :name => '' }}, set_session_user\n assert_template 'edit'\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"stores the database\" do\n collection.database.should eq database\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"sets the :database option\" do\n session.use :admin\n session.options[:database].should eq(:admin)\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"returns the query\" do\n query.limit(5).should eql query\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"allows you to create an account and redeems the invite successfully even if must_approve_users is enabled\" do\n SiteSetting.must_approve_users = true\n\n login_with_sso_and_invite\n\n expect(response.status).to eq(302)\n expect(response).to redirect_to(\"/\")\n expect(invite.reload.redeemed?).to eq(true)\n\n user = User.find_by_email(\"bob@bob.com\")\n expect(user.active).to eq(true)\n end", "label_name": "CWE-863", "label": "863"} -{"code": " def remove_all\n delete = Protocol::Delete.new(\n operation.database,\n operation.collection,\n operation.selector\n )\n\n session.with(consistency: :strong) do |session|\n session.execute delete\n end\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"raises an OperationFailure exception\" do\n session.stub(socket_for: socket)\n socket.stub(execute: reply)\n\n expect {\n session.execute(operation)\n }.to raise_exception(Moped::Errors::OperationFailure)\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def each\n documents = query @query_op\n documents.each { |doc| yield doc }\n\n while more?\n return kill if limited? && @get_more_op.limit <= 0\n\n documents = query @get_more_op\n documents.each { |doc| yield doc }\n end\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it 'does not log in with incorrect backup code' do\n post \"/session/email-login/#{email_token.token}\", params: {\n second_factor_token: \"0000\",\n second_factor_method: UserSecondFactor.methods[:backup_codes]\n }\n\n expect(response.status).to eq(200)\n expect(CGI.unescapeHTML(response.body)).to include(I18n.t(\n \"login.invalid_second_factor_code\"\n ))\n end", "label_name": "CWE-287", "label": "287"} -{"code": " it \"returns the new session\" do\n session.stub(with: new_session)\n session.new(new_options).should eql new_session\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def kill\n session.execute kill_cursor_op\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"returns the same hash\" do\n Moped::BSON::ObjectId.new(bytes).hash.should eq Moped::BSON::ObjectId.new(bytes).hash\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def initialize\n # Generate and cache 3 bytes of identifying information from the current\n # machine.\n @machine_id = Digest::MD5.digest(Socket.gethostname).unpack(\"C3\")\n\n @mutex = Mutex.new\n @last_timestamp = nil\n @counter = 0\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"applies the cached authentication\" do\n cluster.stub(:sync) { cluster.servers << server }\n socket.should_receive(:apply_auth).with(cluster.auth)\n cluster.socket_for(:write)\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"can set the password and ip_address\" do\n password = 's3cure5tpasSw0rD'\n ip_address = '192.168.1.1'\n invite = Fabricate(:invite, email: 'walter.white@email.com')\n user = InviteRedeemer.create_user_from_invite(invite: invite, email: invite.email, username: 'walter', name: 'Walter White', password: password, ip_address: ip_address)\n expect(user).to have_password\n expect(user.confirm_password?(password)).to eq(true)\n expect(user.approved).to eq(true)\n expect(user.ip_address).to eq(ip_address)\n expect(user.registration_ip_address).to eq(ip_address)\n end", "label_name": "CWE-863", "label": "863"} -{"code": " def remove(server)\n servers.delete(server)\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def initialize(seeds, direct = false)\n @seeds = seeds\n @direct = direct\n\n @servers = []\n @dynamic_seeds = []\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def each\n cursor = Cursor.new(session.with(retain_socket: true), operation)\n cursor.to_enum.tap do |enum|\n enum.each do |document|\n yield document\n end if block_given?\n end\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def deliver!(mail)\n envelope_from = mail.return_path || mail.sender || mail.from_addrs.first\n return_path = \"-f \" + '\"' + envelope_from.escape_for_shell + '\"' if envelope_from\n\n arguments = [settings[:arguments], return_path].compact.join(\" \")\n\n self.class.call(settings[:location], arguments, mail.destinations.collect(&:shellescape).join(\" \"), mail)\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def update\n if @application.update(application_params)\n flash[:notice] = I18n.t(:notice, scope: i18n_scope(:update))\n\n respond_to do |format|\n format.html { redirect_to oauth_application_url(@application) }\n format.json { render json: @application }\n end\n else\n respond_to do |format|\n format.html { render :edit }\n format.json do\n errors = @application.errors.full_messages\n\n render json: { errors: errors }, status: :unprocessable_entity\n end\n end\n end\n end", "label_name": "CWE-862", "label": "862"} -{"code": " it 'returns the right response' do\n get \"/session/email-login/adasdad\"\n\n expect(response.status).to eq(200)\n\n expect(CGI.unescapeHTML(response.body)).to match(\n I18n.t('email_login.invalid_token')\n )\n end", "label_name": "CWE-287", "label": "287"} -{"code": " it 'fails when local logins via email is disabled' do\n SiteSetting.enable_local_logins_via_email = false\n\n get \"/session/email-login/#{email_token.token}\"\n\n expect(response.status).to eq(404)\n end", "label_name": "CWE-287", "label": "287"} -{"code": " def self.reminders(options={})\n days = options[:days] || 7\n project = options[:project] ? Project.find(options[:project]) : nil\n tracker = options[:tracker] ? Tracker.find(options[:tracker]) : nil\n target_version_id = options[:version] ? Version.named(options[:version]).pluck(:id) : nil\n if options[:version] && target_version_id.blank?\n raise ActiveRecord::RecordNotFound.new(\"Couldn't find Version with named #{options[:version]}\")\n end\n user_ids = options[:users]\n\n scope = Issue.open.where(\"#{Issue.table_name}.assigned_to_id IS NOT NULL\" +\n \" AND #{Project.table_name}.status = #{Project::STATUS_ACTIVE}\" +\n \" AND #{Issue.table_name}.due_date <= ?\", days.day.from_now.to_date\n )\n scope = scope.where(:assigned_to_id => user_ids) if user_ids.present?\n scope = scope.where(:project_id => project.id) if project\n scope = scope.where(:fixed_version_id => target_version_id) if target_version_id.present?\n scope = scope.where(:tracker_id => tracker.id) if tracker\n issues_by_assignee = scope.includes(:status, :assigned_to, :project, :tracker).\n group_by(&:assigned_to)\n issues_by_assignee.keys.each do |assignee|\n if assignee.is_a?(Group)\n assignee.users.each do |user|\n issues_by_assignee[user] ||= []\n issues_by_assignee[user] += issues_by_assignee[assignee]\n end\n end\n end\n\n issues_by_assignee.each do |assignee, issues|\n reminder(assignee, issues, days).deliver if assignee.is_a?(User) && assignee.active?\n end\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"does not re-sync the cluster\" do\n cluster.should_receive(:sync).never\n cluster.socket_for :write\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def update(change, flags = nil)\n update = Protocol::Update.new(\n operation.database,\n operation.collection,\n operation.selector,\n change,\n flags: flags\n )\n\n session.with(consistency: :strong) do |session|\n session.execute update\n end\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def initialize(seeds, direct = false)\n @seeds = seeds\n @direct = direct\n\n @servers = []\n @dynamic_seeds = []\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"can set password\" do\n user = InviteRedeemer.new(invite: invite, email: invite.email, username: username, name: name, password: password).redeem\n expect(user).to have_password\n expect(user.confirm_password?(password)).to eq(true)\n expect(user.approved).to eq(true)\n end", "label_name": "CWE-863", "label": "863"} -{"code": " it \"updates the selector to mongo's advanced selector\" do\n query.sort(a: 1)\n query.operation.selector.should eq(\n \"$query\" => selector,\n \"$orderby\" => { a: 1 }\n )\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it 'correctly exports the CategoryUser table' do\n data, _csv_out = make_component_csv\n\n expect(data.find { |r| r['category_id'] == category.id }).to be_nil\n expect(data.length).to eq(4)\n data.sort! { |a, b| a['category_id'].to_i <=> b['category_id'].to_i }\n\n expect(data[0][:category_id]).to eq(subcategory.id.to_s)\n expect(data[0][:notification_level].to_s).to eq('tracking')\n expect(DateTime.parse(data[0][:dismiss_new_timestamp])).to eq(reset_at)\n\n expect(data[1][:category_id]).to eq(subsubcategory.id.to_s)\n expect(data[1][:category_names]).to eq(\"#{category.name}|#{subcategory.name}|#{subsubcategory.name}\")\n expect(data[1][:notification_level]).to eq('regular')\n expect(DateTime.parse(data[1][:dismiss_new_timestamp])).to eq(reset_at)\n\n expect(data[2][:category_id]).to eq(announcements.id.to_s)\n expect(data[2][:category_names]).to eq(announcements.name)\n expect(data[2][:notification_level]).to eq('watching_first_post')\n expect(data[2][:dismiss_new_timestamp]).to eq('')\n\n expect(data[3][:category_names]).to eq(data[3][:category_id])\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"recognizes and generates #index\" do\n { :get => \"/users\" }.should route_to(:controller => \"users\", :action => \"index\")\n end", "label_name": "CWE-200", "label": "200"} -{"code": " def current_database\n return @current_database if defined? @current_database\n\n if database = options[:database]\n set_current_database(database)\n else\n raise \"No database set for session. Call #use or #with before accessing the database\"\n end\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it 'avoids xss attacks' do\n h = last_response.headers['X-MiniProfiler-Ids']\n id = ::JSON.parse(h)[0]\n get \"/mini-profiler-resources/results?id=%22%3E%3Cqss%3E\"\n last_response.should_not be_ok\n last_response.body.should_not =~ //\n last_response.body.should =~ /<qss>/\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"stores whether the connection is direct\" do\n cluster.direct.should be_true\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def forwarded_for\n @env[FORWARDED_FOR]\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"returns false\" do\n indexes.drop(other: 1).should be_false\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def filter_archived(list, user, archived: true)\n # Executing an extra query instead of a sub-query because it is more\n # efficient for the PG planner. Caution should be used when changing the\n # query here as it can easily lead to an inefficient query.\n group_ids = group_with_messages_ids(user)\n\n list = list.joins(<<~SQL)\n LEFT JOIN group_archived_messages gm\n ON gm.topic_id = topics.id\n #{group_ids.present? ? \"AND gm.group_id IN (#{group_ids.join(\",\")})\" : \"\"}\n LEFT JOIN user_archived_messages um\n ON um.user_id = #{user.id.to_i}\n AND um.topic_id = topics.id\n SQL\n\n list =\n if archived\n list.where(\"um.user_id IS NOT NULL OR gm.topic_id IS NOT NULL\")\n else\n list.where(\"um.user_id IS NULL AND gm.topic_id IS NULL\")\n end\n\n list\n end", "label_name": "CWE-863", "label": "863"} -{"code": " it \"executes a count command\" do\n database.should_receive(:command).with(\n count: collection.name,\n query: selector\n ).and_return(\"n\" => 4)\n\n query.count\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def perform_accept_invitation\n params.require(:id)\n params.permit(:email, :username, :name, :password, :timezone, :email_token, user_custom_fields: {})\n\n invite = Invite.find_by(invite_key: params[:id])\n\n if invite.present?\n begin\n attrs = {\n username: params[:username],\n name: params[:name],\n password: params[:password],\n user_custom_fields: params[:user_custom_fields],\n ip_address: request.remote_ip,\n session: session\n }\n\n if invite.is_invite_link?\n params.require(:email)\n attrs[:email] = params[:email]\n else\n attrs[:email] = invite.email\n attrs[:email_token] = params[:email_token] if params[:email_token].present?\n end\n\n user = invite.redeem(**attrs)\n rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotSaved, Invite::UserExists => e\n return render json: failed_json.merge(message: e.message), status: 412\n end\n\n if user.blank?\n return render json: failed_json.merge(message: I18n.t('invite.not_found_json')), status: 404\n end\n\n log_on_user(user) if user.active?\n user.update_timezone_if_missing(params[:timezone])\n post_process_invite(user)\n create_topic_invite_notifications(invite, user)\n\n topic = invite.topics.first\n response = {}\n\n if user.present?\n if user.active?\n if user.guardian.can_see?(topic)\n response[:redirect_to] = path(topic.relative_url)\n else\n response[:redirect_to] = path(\"/\")\n end\n else\n response[:message] = I18n.t('invite.confirm_email')\n if user.guardian.can_see?(topic)\n cookies[:destination_url] = path(topic.relative_url)\n end\n end\n end\n\n render json: success_json.merge(response)\n else\n render json: failed_json.merge(message: I18n.t('invite.not_found_json')), status: 404\n end\n end", "label_name": "CWE-863", "label": "863"} -{"code": " it 'returns success' do\n get \"/session/email-login/#{email_token.token}\"\n\n expect(response).to redirect_to(\"/\")\n end", "label_name": "CWE-287", "label": "287"} -{"code": " it \"stores the list of seeds\" do\n cluster.seeds.should eq [\"127.0.0.1:27017\", \"127.0.0.1:27018\"]\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"stores the collection name\" do\n collection.name.should eq :users\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"does not activate user invited via links\" do\n invite = Fabricate(:invite, email: 'walter.white@email.com', emailed_status: Invite.emailed_status_types[:not_required])\n user = InviteRedeemer.create_user_from_invite(invite: invite, email: invite.email, username: 'walter', name: 'Walter White')\n\n expect(user.username).to eq('walter')\n expect(user.name).to eq('Walter White')\n expect(user.email).to eq('walter.white@email.com')\n expect(user.approved).to eq(true)\n expect(user.active).to eq(false)\n end", "label_name": "CWE-863", "label": "863"} -{"code": " it \"executes a simple query\" do\n session.should_receive(:simple_query).with(query.operation)\n query.one\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def has_cookie?\n !@cookie.nil?\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"raises a connection failure exception\" do\n cluster.sync_server(server).should be_empty\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def private_messages_for(user, type)\n options = @options\n options.reverse_merge!(per_page: per_page_setting)\n\n result = Topic.includes(:allowed_users)\n result = result.includes(:tags) if SiteSetting.tagging_enabled\n\n if type == :group\n result = result.joins(\n \"INNER JOIN topic_allowed_groups tag ON tag.topic_id = topics.id AND tag.group_id IN (SELECT id FROM groups WHERE LOWER(name) = '#{PG::Connection.escape_string(@options[:group_name].downcase)}')\"\n )\n\n unless user.admin?\n result = result.joins(\"INNER JOIN group_users gu ON gu.group_id = tag.group_id AND gu.user_id = #{user.id.to_i}\")\n end\n elsif type == :user\n result = result.where(\"topics.id IN (SELECT topic_id FROM topic_allowed_users WHERE user_id = #{user.id.to_i})\")\n elsif type == :all\n group_ids = group_with_messages_ids(user)\n\n result = result.joins(<<~SQL)\n LEFT JOIN topic_allowed_users tau\n ON tau.topic_id = topics.id\n AND tau.user_id = #{user.id.to_i}\n LEFT JOIN topic_allowed_groups tag\n ON tag.topic_id = topics.id\n #{group_ids.present? ? \"AND tag.group_id IN (#{group_ids.join(\",\")})\" : \"\"}\n SQL\n\n result = result\n .where(\"tag.topic_id IS NOT NULL OR tau.topic_id IS NOT NULL\")\n .distinct\n end\n\n result = result.joins(\"LEFT OUTER JOIN topic_users AS tu ON (topics.id = tu.topic_id AND tu.user_id = #{user.id.to_i})\")\n .order(\"topics.bumped_at DESC\")\n .private_messages\n\n result = result.limit(options[:per_page]) unless options[:limit] == false\n result = result.visible if options[:visible] || @user.nil? || @user.regular?\n\n if options[:page]\n offset = options[:page].to_i * options[:per_page]\n result = result.offset(offset) if offset > 0\n end\n result\n end", "label_name": "CWE-863", "label": "863"} -{"code": " def reactions_given\n params.require(:username)\n user = fetch_user_from_params(include_inactive: current_user.try(:staff?) || (current_user && SiteSetting.show_inactive_accounts))\n raise Discourse::NotFound unless guardian.can_see_profile?(user)\n\n reaction_users = DiscourseReactions::ReactionUser\n .joins(:reaction, :post)\n .includes(:user, :post, :reaction)\n .where(user_id: user.id)\n .where('discourse_reactions_reactions.reaction_users_count IS NOT NULL')\n\n if params[:before_reaction_user_id]\n reaction_users = reaction_users\n .where('discourse_reactions_reaction_users.id < ?', params[:before_reaction_user_id].to_i)\n end\n\n reaction_users = reaction_users\n .order(created_at: :desc)\n .limit(20)\n\n render_serialized(reaction_users.to_a, UserReactionSerializer)\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"has an empty list of dynamic seeds\" do\n cluster.dynamic_seeds.should be_empty\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def new(options = {})\n session = with(options)\n session.cluster.reconnect\n\n if block_given?\n yield session\n else\n session\n end\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def execute(op)\n mode = options[:consistency] == :eventual ? :read : :write\n socket = socket_for(mode)\n\n if safe?\n last_error = Protocol::Command.new(\n \"admin\", { getlasterror: 1 }.merge(safety)\n )\n\n socket.execute(op, last_error).documents.first.tap do |result|\n raise Errors::OperationFailure.new(\n op, result\n ) if result[\"err\"] || result[\"errmsg\"]\n end\n else\n socket.execute(op)\n end\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"creates an index\" do\n indexes.create(key, background: true)\n indexes[key][\"background\"].should eq true\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"returns the index with the provided key\" do\n indexes[name: 1][\"name\"].should eq \"name_1\"\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"executes a distinct command\" do\n database.should_receive(:command).with(\n distinct: collection.name,\n key: \"name\",\n query: selector\n ).and_return(\"values\" => [ \"durran\", \"bernerd\" ])\n query.distinct(:name)\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"returns the result of the block\" do\n session.with(new_options) { false }.should eq false\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"article alone should be password protected\" do\n get :redirect, params: { from: from_param }\n expect(response.body).to have_selector('input[id=\"article_password\"]', count: 1)\n end", "label_name": "CWE-863", "label": "863"} -{"code": " it 'returns success' do\n get \"/session/email-login/#{email_token.token}\"\n\n expect(response).to redirect_to(\"/\")\n end", "label_name": "CWE-287", "label": "287"} -{"code": " it \"unmemoizes the current database\" do\n db = session.current_database\n session.with(new_options) do |new_session|\n new_session.current_database.should_not eql db\n end\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def fast_forward_to_first_boundary\n loop do\n read_buffer = @io.gets\n break if read_buffer == full_boundary\n raise EOFError, \"bad content body\" if read_buffer.nil?\n end\n end", "label_name": "CWE-119", "label": "119"} -{"code": " it \"should should be a subclass of Base\" do\n Puppet::FileServing::Metadata.superclass.should equal(Puppet::FileServing::Base)\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"stores the options provided\" do\n session.options.should eq(options)\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def dup\n session = super\n session.instance_variable_set :@options, options.dup\n\n if defined? @current_database\n session.send(:remove_instance_variable, :@current_database)\n end\n\n session\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"doesn't try to set flags\" do\n session.stub(socket_for: socket)\n expect { session.query(query) }.not_to raise_exception\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"doesn't log in the user when not approved\" do\n SiteSetting.must_approve_users = true\n\n get \"/session/email-login/#{email_token.token}\"\n\n expect(response.status).to eq(200)\n\n expect(CGI.unescapeHTML(response.body)).to include(\n I18n.t(\"login.not_approved\")\n )\n end", "label_name": "CWE-287", "label": "287"} -{"code": " def initialize\n # Generate and cache 3 bytes of identifying information from the current\n # machine.\n @machine_id = Digest::MD5.digest(Socket.gethostname).unpack(\"C3\")\n\n @mutex = Mutex.new\n @last_timestamp = nil\n @counter = 0\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def generate(time, inc = 0)\n pid = Process.pid % 0xFFFF\n\n [\n time >> 24 & 0xFF, # 4 bytes time (network order)\n time >> 16 & 0xFF,\n time >> 8 & 0xFF,\n time & 0xFF,\n @machine_id[0], # 3 bytes machine\n @machine_id[1],\n @machine_id[2],\n pid >> 8 & 0xFF, # 2 bytes process id\n pid & 0xFF,\n inc >> 16 & 0xFF, # 3 bytes increment\n inc >> 8 & 0xFF,\n inc & 0xFF,\n ]\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"executes a distinct command\" do\n database.should_receive(:command).with(\n distinct: collection.name,\n key: \"name\",\n query: selector\n ).and_return(\"values\" => [ \"durran\", \"bernerd\" ])\n query.distinct(:name)\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"adds the server to the list\" do\n cluster.sync_server server\n cluster.servers.should include server\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def next\n now = Time.new.to_i\n\n counter = @mutex.synchronize do\n last_timestamp, @last_timestamp = @last_timestamp, now\n\n if last_timestamp == now\n @counter += 1\n else\n @counter = 0\n end\n end\n\n generate(now, counter)\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def self.password_reset_via_token(token, password)\n\n # check token\n user = by_reset_token(token)\n return if !user\n\n # reset password\n user.update!(password: password)\n\n # delete token\n Token.find_by(action: 'PasswordReset', name: token).destroy\n user\n end", "label_name": "CWE-863", "label": "863"} -{"code": " def logout(database)\n auth.delete(database.to_s)\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"generates the correct messages for a secure topic\" do\n Jobs.run_immediately!\n UserActionManager.enable\n\n admin = Fabricate(:admin)\n\n cat = Fabricate(:category)\n cat.set_permissions(admins: :full)\n cat.save\n\n created_post = nil\n\n messages = MessageBus.track_publish do\n created_post = PostCreator.new(admin, basic_topic_params.merge(category: cat.id)).create\n _reply = PostCreator.new(admin, raw: \"this is my test reply 123 testing\", topic_id: created_post.topic_id).create\n end\n\n messages.filter! { |m| m.channel != \"/distributed_hash\" }\n\n channels = messages.map { |m| m.channel }.sort\n\n # 2 for topic, one to notify of new topic another for tracking state\n expect(channels).to eq(\n [\n \"/new\",\n \"/u/#{admin.username}\",\n \"/u/#{admin.username}\",\n \"/unread/#{admin.id}\",\n \"/unread/#{admin.id}\",\n \"/latest\",\n \"/latest\",\n \"/topic/#{created_post.topic_id}\",\n \"/topic/#{created_post.topic_id}\",\n \"/user\",\n \"/user\",\n \"/user\"\n ].sort\n )\n\n admin_ids = [Group[:admins].id]\n expect(messages.any? { |m| m.group_ids != admin_ids && m.user_ids != [admin.id] }).to eq(false)\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"executes a count command\" do\n database.should_receive(:command).with(\n count: collection.name,\n query: selector\n ).and_return(\"n\" => 4)\n\n query.count\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"sets the query operation's fields\" do\n query.select(a: 1)\n query.operation.fields.should eq(a: 1)\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it 'should authenticate user and delete token' do\n user = Fabricate(:user)\n\n get \"/session/current.json\"\n expect(response.status).to eq(404)\n\n token = SecureRandom.hex\n $redis.setex \"otp_#{token}\", 10.minutes, user.username\n\n get \"/session/otp/#{token}\"\n\n expect(response.status).to eq(302)\n expect(response).to redirect_to(\"/\")\n expect($redis.get(\"otp_#{token}\")).to eq(nil)\n\n get \"/session/current.json\"\n expect(response.status).to eq(200)\n end", "label_name": "CWE-287", "label": "287"} -{"code": " it \"should be created correctly\" do\n invite = Fabricate(:invite, email: 'walter.white@email.com')\n user = InviteRedeemer.create_user_from_invite(invite: invite, email: invite.email, username: 'walter', name: 'Walter White')\n expect(user.username).to eq('walter')\n expect(user.name).to eq('Walter White')\n expect(user.email).to eq('walter.white@email.com')\n expect(user.approved).to eq(true)\n expect(user.active).to eq(false)\n end", "label_name": "CWE-863", "label": "863"} -{"code": " def discard_cookie!(headers)\n Rack::Utils.delete_cookie_header!(headers, COOKIE_NAME, :path => '/')\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"returns an enumerator\" do\n cursor = mock(Moped::Cursor)\n Moped::Cursor.stub(new: cursor)\n\n query.each.should be_a Enumerator\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"removes the socket\" do\n cluster.should_receive(:remove).with(dead_server)\n cluster.socket_for :write\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it 'does not log in with incorrect two factor' do\n post \"/session/email-login/#{email_token.token}\", params: {\n second_factor_token: \"0000\",\n second_factor_method: UserSecondFactor.methods[:totp]\n }\n\n expect(response.status).to eq(200)\n\n expect(CGI.unescapeHTML(response.body)).to include(I18n.t(\n \"login.invalid_second_factor_code\"\n ))\n end", "label_name": "CWE-287", "label": "287"} -{"code": " def first\n session.simple_query(operation)\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def setup_user(operation, type = \"\", search = nil, user = :one)\n @one = users(user)\n as_admin do\n permission = Permission.find_by_name(\"#{operation}_#{type}\") || FactoryGirl.create(:permission, :name => \"#{operation}_#{type}\")\n filter = FactoryGirl.build(:filter, :search => search)\n filter.permissions = [ permission ]\n role = Role.where(:name => \"#{operation}_#{type}\").first_or_create\n role.filters = [ filter ]\n role.save!\n filter.role = role\n filter.save!\n @one.roles << role\n yield(@one) if block_given?\n @one.save!\n end\n User.current = @one\n end", "label_name": "CWE-200", "label": "200"} -{"code": " def initialize(database, command)\n super database, :$cmd, command, limit: -1\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"queries a slave node\" do\n session.should_receive(:socket_for).with(:read).\n and_return(socket)\n session.query(query)\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"returns true\" do\n session.should be_safe\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"drops the index that matches the key\" do\n indexes[name: 1].should be_nil\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it 'logs in correctly' do\n post \"/session/email-login/#{email_token.token}\", params: {\n second_factor_token: ROTP::TOTP.new(user_second_factor.data).now,\n second_factor_method: UserSecondFactor.methods[:totp]\n }\n\n expect(response).to redirect_to(\"/\")\n end", "label_name": "CWE-287", "label": "287"} -{"code": " it \"stores the options provided\" do\n session.options.should eq(options)\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def crop_command\n target = @attachment.instance\n\n if target.cropping?(@attachment.name)\n w = target.send :\"#{@attachment.name}_crop_w\"\n h = target.send :\"#{@attachment.name}_crop_h\"\n x = target.send :\"#{@attachment.name}_crop_x\"\n y = target.send :\"#{@attachment.name}_crop_y\"\n [\"-crop\", \"#{w}x#{h}+#{x}+#{y}\"]\n end\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"recognizes and generates #index\" do\n { :get => \"/users\" }.should route_to(:controller => \"users\", :action => \"index\")\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"should return :file if the request key is fully qualified\" do\n @request.expects(:key).returns File.expand_path('/foo')\n @object.select_terminus(@request).should == :file\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"has an empty list of secondaries\" do\n cluster.secondaries.should be_empty\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def reconnect\n @servers = servers.map { |server| Server.new(server.address) }\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"sets the query operation's fields\" do\n query.select(a: 1)\n query.operation.fields.should eq(a: 1)\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"adds the credentials to the auth cache\" do\n cluster.login(\"admin\", \"username\", \"password\")\n cluster.auth.should eq(\"admin\" => [\"username\", \"password\"])\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"updates the record matching selector with change\" do\n session.should_receive(:with, :consistency => :strong).\n and_yield(session)\n\n session.should_receive(:execute).with do |update|\n update.flags.should eq []\n update.selector.should eq query.operation.selector\n update.update.should eq change\n end\n\n query.update change\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"stores whether the connection is direct\" do\n cluster.direct.should be_true\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def decode_compact_serialized(input, public_key_or_secret, algorithms = nil, allow_blank_payload = false)\n unless input.count('.') + 1 == NUM_OF_SEGMENTS\n raise InvalidFormat.new(\"Invalid JWS Format. JWS should include #{NUM_OF_SEGMENTS} segments.\")\n end\n header, claims, signature = input.split('.', JWS::NUM_OF_SEGMENTS).collect do |segment|\n Base64.urlsafe_decode64 segment.to_s\n end\n header = JSON.parse(header).with_indifferent_access\n if allow_blank_payload && claims == ''\n claims = nil\n else\n claims = JSON.parse(claims).with_indifferent_access\n end\n jws = new claims\n jws.header = header\n jws.signature = signature\n jws.signature_base_string = input.split('.')[0, JWS::NUM_OF_SEGMENTS - 1].join('.')\n jws.verify! public_key_or_secret, algorithms unless public_key_or_secret == :skip_verification\n jws\n end", "label_name": "CWE-287", "label": "287"} -{"code": " it \"approves pending record\" do\n reviewable = ReviewableUser.needs_review!(target: Fabricate(:user, email: invite.email), created_by: invite.invited_by)\n reviewable.status = Reviewable.statuses[:pending]\n reviewable.save!\n invite_redeemer.redeem\n\n reviewable.reload\n expect(reviewable.status).to eq(Reviewable.statuses[:approved])\n end", "label_name": "CWE-863", "label": "863"} -{"code": " it \"does not change the original session's options\" do\n original_options = options.dup\n session.with(new_options) do |new_session|\n session.options.should eql original_options\n end\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"has an empty list of secondaries\" do\n cluster.secondaries.should be_empty\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"returns the query\" do\n query.limit(5).should eql query\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"drops the index that matches the key\" do\n indexes[name: 1].should be_nil\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def primaries\n servers.select(&:primary?)\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it 'supports group' do\n topic = Fabricate(:topic, created_at: 3.months.ago)\n post = Fabricate(:post, raw: 'hi this is a test 123 123', topic: topic)\n\n group = Group.create!(name: \"Like_a_Boss\")\n GroupUser.create!(user_id: post.user_id, group_id: group.id)\n\n expect(Search.execute('group:like_a_boss').posts.length).to eq(1)\n expect(Search.execute('group:\"like a brick\"').posts.length).to eq(0)\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"sets the :database option\" do\n session.use :admin\n session.options[:database].should eq(:admin)\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def require_smart_proxy_or_login(features = nil)\n features = features.call if features.respond_to?(:call)\n allowed_smart_proxies = features.blank? ? SmartProxy.all : SmartProxy.with_features(*features)\n\n if !Setting[:restrict_registered_smart_proxies] || auth_smart_proxy(allowed_smart_proxies, Setting[:require_ssl_smart_proxies])\n set_admin_user\n return true\n end\n\n require_login\n unless User.current\n render_error 'access_denied', :status => :forbidden unless performed? && api_request?\n return false\n end\n authorize\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"creates an index\" do\n indexes.create(key, background: true)\n indexes[key][\"background\"].should eq true\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"returns the socket\" do\n cluster.stub(:sync) { cluster.servers << server }\n cluster.socket_for(:write).should eq socket\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def query(operation)\n reply = session.query operation\n\n @get_more_op.limit -= reply.count if limited?\n @get_more_op.cursor_id = reply.cursor_id\n @kill_cursor_op.cursor_ids = [reply.cursor_id]\n\n reply.documents\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def create\n @application = Doorkeeper.config.application_model.new(application_params)\n\n if @application.save\n flash[:notice] = I18n.t(:notice, scope: %i[doorkeeper flash applications create])\n flash[:application_secret] = @application.plaintext_secret\n\n respond_to do |format|\n format.html { redirect_to oauth_application_url(@application) }\n format.json { render json: @application }\n end\n else\n respond_to do |format|\n format.html { render :new }\n format.json do\n errors = @application.errors.full_messages\n\n render json: { errors: errors }, status: :unprocessable_entity\n end\n end\n end\n end", "label_name": "CWE-862", "label": "862"} -{"code": " def test_update_valid\n AuthSourceLdap.any_instance.stubs(:valid?).returns(true)\n put :update, {:id => AuthSourceLdap.first, :auth_source_ldap => {:name => AuthSourceLdap.first.name} }, set_session_user\n assert_redirected_to auth_source_ldaps_url\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"returns the database from the options\" do\n session.current_database.should eq(database)\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it 'activates user when must_approve_users? is enabled' do\n SiteSetting.must_approve_users = true\n invite.invited_by = Fabricate(:admin)\n\n user = invite.redeem\n expect(user.approved?).to eq(true)\n end", "label_name": "CWE-863", "label": "863"} -{"code": " it \"syncs each seed node\" do\n server = Moped::Server.allocate\n Moped::Server.should_receive(:new).with(\"127.0.0.1:27017\").and_return(server)\n\n cluster.should_receive(:sync_server).with(server).and_return([])\n cluster.sync\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"returns a new indexes instance\" do\n collection.indexes.should be_an_instance_of Moped::Indexes\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"upserts the record matching selector with change\" do\n query.should_receive(:update).with(change, [:upsert])\n query.upsert change\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def index\n valid_http_methods :get, :post, :put\n\n # for permission check\n if params[:package] and not [\"_repository\", \"_jobhistory\"].include?(params[:package])\n pkg = DbPackage.get_by_project_and_name( params[:project], params[:package], use_source=false )\n else\n prj = DbProject.get_by_name params[:project]\n end\n\n pass_to_backend \n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"delegates to the cluster\" do\n session.cluster.should_receive(:socket_for).with(:read)\n session.send(:socket_for, :read)\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def show\n respond_to do |format|\n format.html\n format.json { render json: @application }\n end\n end", "label_name": "CWE-862", "label": "862"} -{"code": " it \"raises an OperationFailure exception\" do\n session.stub(socket_for: socket)\n socket.stub(execute: reply)\n\n expect {\n session.execute(operation)\n }.to raise_exception(Moped::Errors::OperationFailure)\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def reset_password\n @admin_user = Motor::AdminUser.find(params[:admin_user_id])\n\n authorize!(:manage, @admin_user)\n\n Devise::Mailer.default_url_options = { host: request.host, protocol: request.protocol, port: request.port }\n\n @admin_user.send_reset_password_instructions\n\n head :ok\n end", "label_name": "CWE-116", "label": "116"} -{"code": " it \"returns true\" do\n session.should be_safe\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"stores the database\" do\n collection.database.should eq database\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"removes all matching documents\" do\n session.should_receive(:with, :consistency => :strong).\n and_yield(session)\n\n session.should_receive(:execute).with do |delete|\n delete.flags.should eq []\n delete.selector.should eq query.operation.selector\n end\n\n query.remove_all\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def check_action_permission!(skip_source = nil)\n super(skip_source)\n # only perform the following check, if we are called from\n # BsRequest.permission_check_change_state! (that is, if\n # skip_source is set to true). Always executing this check\n # would be a regression, because this code is also executed\n # if a new request is created (which could fail if User.current\n # cannot modify the source_package).\n return unless skip_source\n target_project = Project.get_by_name(self.target_project)\n return unless target_project && target_project.is_a?(Project)\n target_package = target_project.packages.find_by_name(self.target_package)\n initialize_devel_package = target_project.find_attribute('OBS', 'InitializeDevelPackage')\n return if target_package || !initialize_devel_package\n source_package = Package.get_by_project_and_name(source_project, self.source_package)\n return if !source_package || User.current.can_modify?(source_package)\n msg = 'No permission to initialize the source package as a devel package'\n raise PostRequestNoPermission, msg\n end", "label_name": "CWE-732", "label": "732"} -{"code": " it \"instructs the cluster to reconnect\" do\n session.stub(with: new_session)\n new_session.cluster.should_receive(:reconnect)\n session.new(new_options)\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def update\n article = Ticket::Article.find(params[:id])\n authorize!(article)\n\n clean_params = Ticket::Article.association_name_to_id_convert(params)\n clean_params = Ticket::Article.param_cleanup(clean_params, true)\n\n # only apply preferences changes (keep not updated keys/values)\n clean_params = article.param_preferences_merge(clean_params)\n\n article.update!(clean_params)\n\n if response_expand?\n result = article.attributes_with_association_names\n render json: result, status: :ok\n return\n end\n\n if response_full?\n full = Ticket::Article.full(params[:id])\n render json: full, status: :ok\n return\n end\n\n render json: article.attributes_with_association_names, status: :ok\n end", "label_name": "CWE-862", "label": "862"} -{"code": " it \"updates the record matching selector with change\" do\n session.should_receive(:with, :consistency => :strong).\n and_yield(session)\n\n session.should_receive(:execute).with do |update|\n update.flags.should eq []\n update.selector.should eq query.operation.selector\n update.update.should eq change\n end\n\n query.update change\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"does not automatically approve users if must_approve_users is true\" do\n SiteSetting.must_approve_users = true\n\n invite = Fabricate(:invite, email: 'test@example.com')\n user = InviteRedeemer.create_user_from_invite(invite: invite, email: invite.email, username: 'test')\n expect(user.approved).to eq(false)\n end", "label_name": "CWE-863", "label": "863"} -{"code": " def to_s\n @@string_format % data\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"initializes with the strings bytes\" do\n Moped::BSON::ObjectId.should_receive(:new).with(bytes)\n Moped::BSON::ObjectId.from_string \"4e4d66343b39b68407000001\"\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it 'returns a list of all private messages that has been archived' do\n UserArchivedMessage.archive!(user_2.id, private_message)\n GroupArchivedMessage.archive!(user_2.id, group_message)\n\n topics = TopicQuery.new(nil).list_private_messages_all_archive(user_2).topics\n\n expect(topics).to contain_exactly(private_message, group_message)\n end", "label_name": "CWE-863", "label": "863"} -{"code": " it \"updates a hostgroup with a parent parameter, allows empty values\" do\n child = FactoryGirl.create(:hostgroup, :parent => @base)\n as_admin do\n assert_equal \"original\", child.parameters[\"x\"]\n end\n post :update, {\"id\" => child.id, \"hostgroup\" => {\"name\" => child.name,\n :group_parameters_attributes => {\"0\" => {:name => \"x\", :value => \"\", :_destroy => \"\"},\n \"1\" => {:name => \"y\", :value => \"overridden\", :_destroy => \"\"}}}}, set_session_user\n assert_redirected_to hostgroups_url\n child.reload\n assert_equal \"overridden\", child.parameters[\"y\"]\n assert_equal \"\", child.parameters[\"x\"]\n end", "label_name": "CWE-200", "label": "200"} -{"code": " def get_user_archive_fields(user_archive)\n user_archive_array = []\n topic_data = user_archive.topic\n user_archive = user_archive.as_json\n topic_data = Topic.with_deleted.find_by(id: user_archive['topic_id']) if topic_data.nil?\n return user_archive_array if topic_data.nil?\n\n categories = piped_category_name(topic_data.category_id)\n is_pm = topic_data.archetype == \"private_message\" ? I18n.t(\"csv_export.boolean_yes\") : I18n.t(\"csv_export.boolean_no\")\n url = \"#{Discourse.base_url}/t/#{topic_data.slug}/#{topic_data.id}/#{user_archive['post_number']}\"\n\n topic_hash = { \"post\" => user_archive['raw'], \"topic_title\" => topic_data.title, \"categories\" => categories, \"is_pm\" => is_pm, \"url\" => url }\n user_archive.merge!(topic_hash)\n\n HEADER_ATTRS_FOR['user_archive'].each do |attr|\n user_archive_array.push(user_archive[attr])\n end\n\n user_archive_array\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"creates an index with a generated name\" do\n indexes.create(key)\n indexes[key][\"name\"].should eq \"location.latlong_2d_name_1_age_-1\"\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"returns a new indexes instance\" do\n collection.indexes.should be_an_instance_of Moped::Indexes\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"returns a session\" do\n session.with(new_options).should be_a Moped::Session\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"updates all records matching selector with change\" do\n query.should_receive(:update).with(change, [:multi])\n query.update_all change\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"recognizes and generates #destroy\" do\n { :delete => \"/users/1\" }.should route_to(:controller => \"users\", :action => \"destroy\", :id => \"1\")\n end", "label_name": "CWE-200", "label": "200"} -{"code": " def insert(documents)\n documents = [documents] unless documents.is_a? Array\n insert = Protocol::Insert.new(database.name, name, documents)\n\n database.session.with(consistency: :strong) do |session|\n session.execute insert\n end\n\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def initialize(env)\n request = ::Rack::Request.new(env)\n @cookie = request.cookies[COOKIE_NAME]\n if @cookie\n @cookie.split(\",\").map{|pair| pair.split(\"=\")}.each do |k,v|\n @orig_disable_profiling = @disable_profiling = (v=='t') if k == \"dp\"\n @backtrace_level = v.to_i if k == \"bt\"\n end\n end\n\n @backtrace_level = nil if !@backtrace_level.nil? && (@backtrace_level == 0 || @backtrace_level > BACKTRACE_NONE)\n @orig_backtrace_level = @backtrace_level\n\n end", "label_name": "CWE-200", "label": "200"} -{"code": " def known_addresses\n [].tap do |addresses|\n addresses.concat seeds\n addresses.concat dynamic_seeds\n addresses.concat servers.map { |server| server.address }\n end.uniq\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"yields all documents in the cursor\" do\n cursor = Moped::Cursor.allocate\n cursor.stub(:to_enum).and_return([1, 2].to_enum)\n\n Moped::Cursor.stub(new: cursor)\n\n query.to_a.should eq [1, 2]\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def legal?(str)\n !!str.match(/^[0-9a-f]{24}$/i)\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"returns the index with the provided key\" do\n indexes[name: 1][\"name\"].should eq \"name_1\"\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"has an empty list of dynamic seeds\" do\n cluster.dynamic_seeds.should be_empty\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def test_private_address\n assert_raises PrivateAddressCheck::PrivateConnectionAttemptedError do\n PrivateAddressCheck.only_public_connections do\n TCPSocket.new(\"localhost\", 80)\n end\n end\n end", "label_name": "CWE-362", "label": "362"} -{"code": " it \"stores the selector\" do\n query.selector.should eq selector\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def self.taxonomy_conditions\n org = Organization.expand(Organization.current) if SETTINGS[:organizations_enabled]\n loc = Location.expand(Location.current) if SETTINGS[:locations_enabled]\n conditions = {}\n conditions[:organization_id] = Array(org).map { |o| o.subtree_ids }.flatten.uniq if org.present?\n conditions[:location_id] = Array(loc).map { |l| l.subtree_ids }.flatten.uniq if loc.present?\n conditions\n end", "label_name": "CWE-200", "label": "200"} -{"code": " def authenticate!\n unless Setting['oauth_active']\n Rails.logger.warn 'Trying to authenticate with OAuth, but OAuth is not active'\n return nil\n end\n\n unless (incoming_key = OAuth::RequestProxy.proxy(request).oauth_consumer_key) == Setting['oauth_consumer_key']\n Rails.logger.warn \"oauth_consumer_key should be '#{Setting['oauth_consumer_key']}' but was '#{incoming_key}'\"\n return nil\n end\n\n if OAuth::Signature.verify(request, :consumer_secret => Setting['oauth_consumer_secret'])\n if Setting['oauth_map_users']\n user_name = request.headers['HTTP_FOREMAN_USER'].to_s\n User.find_by_login(user_name).tap do |obj|\n Rails.logger.warn \"Oauth: mapping to user '#{user_name}' failed\" if obj.nil?\n end.try(:login)\n else\n User::ANONYMOUS_API_ADMIN\n end\n else\n Rails.logger.warn \"OAuth signature verification failed.\"\n return nil\n end\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"should return :file if the URI protocol is set to 'file'\" do\n @request.expects(:protocol).returns \"file\"\n @object.select_terminus(@request).should == :file\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"sets the current database\" do\n session.should_receive(:set_current_database).with(:admin)\n session.use :admin\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it 'should return the right response' do\n email_token.update!(created_at: 999.years.ago)\n\n get \"/session/email-login/#{email_token.token}\"\n\n expect(response.status).to eq(200)\n\n expect(CGI.unescapeHTML(response.body)).to match(\n I18n.t('email_login.invalid_token')\n )\n end", "label_name": "CWE-287", "label": "287"} -{"code": " it \"applies the cached authentication\" do\n cluster.stub(:sync) { cluster.servers << server }\n socket.should_receive(:apply_auth).with(cluster.auth)\n cluster.socket_for(:write)\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def read_config(self, config, **kwargs):\n self.recaptcha_private_key = config.get(\"recaptcha_private_key\")\n self.recaptcha_public_key = config.get(\"recaptcha_public_key\")\n self.enable_registration_captcha = config.get(\n \"enable_registration_captcha\", False\n )\n self.recaptcha_siteverify_api = config.get(\n \"recaptcha_siteverify_api\",\n \"https://www.recaptcha.net/recaptcha/api/siteverify\",\n )\n self.recaptcha_template = self.read_templates(\n [\"recaptcha.html\"], autoescape=True\n )[0]", "label_name": "CWE-74", "label": "74"} -{"code": " it \"returns the new session\" do\n session.stub(with: new_session)\n session.new(new_options).should eql new_session\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def command(command)\n operation = Protocol::Command.new(name, command)\n\n result = session.with(consistency: :strong) do |session|\n session.simple_query(operation)\n end\n\n raise Errors::OperationFailure.new(\n operation, result\n ) unless result[\"ok\"] == 1.0\n\n result\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"doesn't log in the user when not approved\" do\n SiteSetting.must_approve_users = true\n\n get \"/session/email-login/#{email_token.token}\"\n\n expect(response.status).to eq(200)\n\n expect(CGI.unescapeHTML(response.body)).to include(\n I18n.t(\"login.not_approved\")\n )\n end", "label_name": "CWE-287", "label": "287"} -{"code": " it \"limits the query\" do\n session.should_receive(:query) do |query|\n query.limit.should eq(-1)\n reply\n end\n\n session.simple_query(query)\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"merges the old and new session's options\" do\n session.with(new_options) do |new_session|\n new_session.options.should eq options.merge(new_options)\n end\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"should redeem the invite if invited by non staff but not approve\" do\n SiteSetting.must_approve_users = true\n inviter = invite.invited_by\n user = invite_redeemer.redeem\n\n expect(user.name).to eq(name)\n expect(user.username).to eq(username)\n expect(user.invited_by).to eq(inviter)\n expect(inviter.notifications.count).to eq(1)\n expect(user.approved).to eq(false)\n end", "label_name": "CWE-863", "label": "863"} -{"code": " it \"drops all indexes for the collection\" do\n indexes[name: 1].should be_nil\n indexes[age: -1].should be_nil\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"doesn't try to set flags\" do\n session.stub(socket_for: socket)\n expect { session.query(query) }.not_to raise_exception\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def limited?\n @query_op.limit > 0\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def next\n now = Time.new.to_i\n\n counter = @mutex.synchronize do\n last_timestamp, @last_timestamp = @last_timestamp, now\n\n if last_timestamp == now\n @counter += 1\n else\n @counter = 0\n end\n end\n\n generate(now, counter)\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"sets the current database\" do\n session.should_receive(:set_current_database).with(:admin)\n session.use :admin\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"returns the database from the options\" do\n session.current_database.should eq(database)\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def new(options = {})\n session = with(options)\n session.cluster.reconnect\n\n if block_given?\n yield session\n else\n session\n end\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"only aquires the socket once\" do\n session.cluster.should_receive(:socket_for).\n with(:read).once.and_return(mock(Moped::Socket))\n\n session.send(:socket_for, :read)\n session.send(:socket_for, :read)\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"yields all indexes on the collection\" do\n indexes.to_a.should eq \\\n session[:\"system.indexes\"].find(ns: \"moped_test.users\").to_a\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def socket_for(mode)\n sync unless primaries.any? || (secondaries.any? && mode == :read)\n\n server = nil\n while primaries.any? || (secondaries.any? && mode == :read)\n if mode == :write || secondaries.empty?\n server = primaries.sample\n else\n server = secondaries.sample\n end\n\n if server\n socket = server.socket\n socket.connect unless socket.connection\n\n if socket.alive?\n break server\n else\n remove server\n end\n end\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def check_action_permission!(skip_source = nil)\n super(skip_source)\n # only perform the following check, if we are called from\n # BsRequest.permission_check_change_state! (that is, if\n # skip_source is set to true). Always executing this check\n # would be a regression, because this code is also executed\n # if a new request is created (which could fail if User.current\n # cannot modify the source_package).\n return unless skip_source\n target_project = Project.get_by_name(self.target_project)\n return unless target_project && target_project.is_a?(Project)\n target_package = target_project.packages.find_by_name(self.target_package)\n initialize_devel_package = target_project.find_attribute('OBS', 'InitializeDevelPackage')\n return if target_package || !initialize_devel_package\n source_package = Package.get_by_project_and_name(source_project, self.source_package)\n return if !source_package || User.current.can_modify?(source_package)\n msg = 'No permission to initialize the source package as a devel package'\n raise PostRequestNoPermission, msg\n end", "label_name": "CWE-732", "label": "732"} -{"code": " def password_policy(password)\n if Setting.get('password_min_size').to_i > password.length\n return [\"Can\\'t update password, it must be at least %s characters long!\", Setting.get('password_min_size')]\n end\n if Setting.get('password_need_digit').to_i == 1 && password !~ /\\d/\n return [\"Can't update password, it must contain at least 1 digit!\"]\n end\n if Setting.get('password_min_2_lower_2_upper_characters').to_i == 1 && ( password !~ /[A-Z].*[A-Z]/ || password !~ /[a-z].*[a-z]/ )\n return [\"Can't update password, it must contain at least 2 lowercase and 2 uppercase characters!\"]\n end\n\n true\n end", "label_name": "CWE-863", "label": "863"} -{"code": " it \"returns the master connection\" do\n cluster.socket_for(:read).should eq socket\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def deliver!(mail)\n envelope_from = mail.return_path || mail.sender || mail.from_addrs.first\n return_path = \"-f \\\"#{envelope_from.to_s.shellescape}\\\"\" if envelope_from\n arguments = [settings[:arguments], return_path].compact.join(\" \")\n self.class.call(settings[:location], arguments, mail)\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"executes the operation on a slave node\" do\n session.should_receive(:socket_for).with(:read).\n and_return(socket)\n socket.should_receive(:execute).with(operation)\n\n session.execute(operation)\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"includes plaintext secret\" do\n expect(app.as_json).to include(\"secret\" => \"123123123\")\n end", "label_name": "CWE-862", "label": "862"} -{"code": " it 'should return the right response' do\n email_token.update!(created_at: 999.years.ago)\n\n get \"/session/email-login/#{email_token.token}\"\n\n expect(response.status).to eq(200)\n\n expect(CGI.unescapeHTML(response.body)).to match(\n I18n.t('email_login.invalid_token')\n )\n end", "label_name": "CWE-287", "label": "287"} -{"code": " def initialize(database, command)\n super database, :$cmd, command, limit: -1\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"merges the old and new session's options\" do\n session.with(new_options) do |new_session|\n new_session.options.should eq options.merge(new_options)\n end\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def test_formats_valid\n AuthSourceLdap.any_instance.stubs(:valid?).returns(false)\n put :update, {:id => AuthSourceLdap.first.id, :format => \"weird\", :auth_source_ldap => {:name => AuthSourceLdap.first.name} }, set_session_user\n assert_response :success\n\n wierd_id = \"#{AuthSourceLdap.first.id}.weird\"\n put :update, {:id => wierd_id, :auth_source_ldap => {:name => AuthSourceLdap.first.name} }, set_session_user\n assert_response :success\n\n parameterized_id = \"#{AuthSourceLdap.first.id}-#{AuthSourceLdap.first.name.parameterize}\"\n put :update, {:id => parameterized_id, :auth_source_ldap => {:name => AuthSourceLdap.first.name} }, set_session_user\n assert_response :success\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"executes the operation on the master node\" do\n session.should_receive(:socket_for).with(:write).\n and_return(socket)\n socket.should_receive(:execute).with(operation)\n\n session.execute(operation)\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def show_article\n auto_discovery_feed\n respond_to do |format|\n format.html do\n @comment = Comment.new\n @page_title = this_blog.article_title_template.to_title(@article, this_blog, params)\n @description = this_blog.article_desc_template.to_title(@article, this_blog, params)\n\n @keywords = @article.tags.map(&:name).join(\", \")\n render \"articles/#{@article.post_type}\"\n end\n format.atom { render_feedback_feed(\"atom\") }\n format.rss { render_feedback_feed(\"rss\") }\n format.xml { render_feedback_feed(\"atom\") }\n end\n rescue ActiveRecord::RecordNotFound\n error!\n end", "label_name": "CWE-863", "label": "863"} -{"code": " def merge(server)\n previous = servers.find { |other| other == server }\n primary = server.primary?\n secondary = server.secondary?\n\n if previous\n previous.merge(server)\n else\n servers << server\n end\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"sets the object id's data\" do\n Moped::BSON::ObjectId.new(bytes).data.should == bytes\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"returns an enumerator\" do\n cursor = mock(Moped::Cursor)\n Moped::Cursor.stub(new: cursor)\n\n query.each.should be_a Enumerator\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"re-enabled functionality if whitelisted\" do\n Rack::MiniProfiler.config.authorization_mode = :whitelist\n expect(Rack::MiniProfiler).to receive(:request_authorized?) { true }.twice\n get '/html?pp=enable'\n last_response.body.should include('/mini-profiler-resources/includes.js')\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"should redeem the invite if invited by staff\" do\n SiteSetting.must_approve_users = true\n inviter = invite.invited_by\n inviter.admin = true\n user = invite_redeemer.redeem\n invite.reload\n\n expect(user.name).to eq(name)\n expect(user.username).to eq(username)\n expect(user.invited_by).to eq(inviter)\n expect(inviter.notifications.count).to eq(1)\n expect(user.approved).to eq(true)\n end", "label_name": "CWE-863", "label": "863"} -{"code": " def drop\n command dropDatabase: 1\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def test_update_invalid\n Subnet.any_instance.stubs(:valid?).returns(false)\n put :update, {:id => Subnet.first, :subnet => {:network => nil}}, set_session_user\n assert_template 'edit'\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it 'should overwrite the existing public key if overwrite_stored_key is set' do\n @plugin.stubs(:lookup_config_option).with('learn_public_keys').returns('1')\n @plugin.stubs(:lookup_config_option).with('publickey_dir').returns('ssh/pkd')\n @plugin.stubs(:lookup_config_option).with('overwrite_stored_keys', 'n').returns('1')\n File.stubs(:directory?).with('ssh/pkd').returns(true)\n File.stubs(:exists?).with('ssh/pkd/rspec_pub.pem').returns(true)\n File.stubs(:read).with('ssh/pkd/rspec_pub.pem').returns('ssh-rsa dcba')\n file = mock\n File.expects(:open).with('ssh/pkd/rspec_pub.pem', 'w').yields(file)\n file.expects(:puts).with('ssh-rsa abcd')\n Log.expects(:warn)\n @plugin.send(:write_key_to_disk, 'ssh-rsa abcd', 'rspec')\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it 'returns the right response' do\n get \"/session/email-login/adasdad\"\n\n expect(response.status).to eq(200)\n\n expect(CGI.unescapeHTML(response.body)).to match(\n I18n.t('email_login.invalid_token')\n )\n end", "label_name": "CWE-287", "label": "287"} -{"code": " it \"does not re-sync the cluster\" do\n cluster.should_receive(:sync).never\n cluster.socket_for :write\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"yields a session\" do\n session.with(new_options) do |new_session|\n new_session.should be_a Moped::Session\n end\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def logout\n session.cluster.logout(name)\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def test_clone\n get :clone, {:id => Hostgroup.first}, set_session_user\n assert_template 'new'\n end", "label_name": "CWE-200", "label": "200"} -{"code": " def test_jail_instances_should_have_limited_methods\n expected = [\"class\", \"inspect\", \"method_missing\", \"methods\", \"respond_to?\", \"respond_to_missing?\", \"to_jail\", \"to_s\", \"instance_variable_get\"]\n expected.delete('respond_to_missing?') if RUBY_VERSION > '1.9.3' # respond_to_missing? is private in rubies above 1.9.3\n objects.each do |object|\n assert_equal expected.sort, reject_pretty_methods(object.to_jail.methods.map(&:to_s).sort)\n end\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"returns the count\" do\n database.stub(command: { \"n\" => 4 })\n\n query.count.should eq 4\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def dup\n session = super\n session.instance_variable_set :@options, options.dup\n\n if defined? @current_database\n session.send(:remove_instance_variable, :@current_database)\n end\n\n session\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"does not change the original session's options\" do\n original_options = options.dup\n session.with(new_options) do |new_session|\n session.options.should eql original_options\n end\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def test_nest\n get :nest, {:id => Hostgroup.first.id}, set_session_user\n assert_template 'new'\n end", "label_name": "CWE-200", "label": "200"} -{"code": " def test_update_valid\n SmartProxy.any_instance.stubs(:valid?).returns(true)\n put :update, {:id => SmartProxy.first,:smart_proxy => {:url => \"http://elsewhere.com:8443\"}}, set_session_user\n assert_equal \"http://elsewhere.com:8443\", SmartProxy.first.url\n assert_redirected_to smart_proxies_url\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"activates user invited via email with a token\" do\n invite = Fabricate(:invite, invited_by: Fabricate(:admin), email: 'walter.white@email.com', emailed_status: Invite.emailed_status_types[:sent])\n user = InviteRedeemer.create_user_from_invite(invite: invite, email: invite.email, username: 'walter', name: 'Walter White', email_token: invite.email_token)\n\n expect(user.username).to eq('walter')\n expect(user.name).to eq('Walter White')\n expect(user.email).to eq('walter.white@email.com')\n expect(user.approved).to eq(true)\n expect(user.active).to eq(true)\n end", "label_name": "CWE-863", "label": "863"} -{"code": " def query(query)\n if options[:consistency] == :eventual\n query.flags |= [:slave_ok] if query.respond_to? :flags\n mode = :read\n else\n mode = :write\n end\n\n reply = socket_for(mode).execute(query)\n\n reply.tap do |reply|\n if reply.flags.include?(:query_failure)\n raise Errors::QueryFailure.new(query, reply.documents.first)\n end\n end\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def taxable_ids(loc = which_location, org = which_organization, inner_method = which_ancestry_method)\n if SETTINGS[:locations_enabled] && loc.present?\n inner_ids_loc = if Location.ignore?(self.to_s)\n self.unscoped.pluck(\"#{table_name}.id\")\n else\n inner_select(loc, inner_method)\n end\n end", "label_name": "CWE-200", "label": "200"} -{"code": " def test_jail_classes_should_have_limited_methods\n expected = [\"new\", \"methods\", \"name\", \"inherited\", \"method_added\", \"inspect\",\n \"allow\", \"allowed?\", \"allowed_methods\", \"init_allowed_methods\",\n \"<\", # < needed in Rails Object#subclasses_of\n \"ancestors\", \"==\" # ancestors and == needed in Rails::Generator::Spec#lookup_class\n ]\n objects.each do |object|\n assert_equal expected.sort, reject_pretty_methods(object.to_jail.class.methods.map(&:to_s).sort)\n end\n end", "label_name": "CWE-200", "label": "200"} -{"code": " def logout\n session.cluster.logout(name)\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"should choose :rest when a server is specified\" do\n @request.stubs(:protocol).returns \"puppet\"\n @request.expects(:server).returns \"foo\"\n @object.select_terminus(@request).should == :rest\n end", "label_name": "CWE-200", "label": "200"} -{"code": " def login(username, password)\n session.cluster.login(name, username, password)\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"raises a connection failure exception\" do\n cluster.sync_server(server).should be_empty\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"returns a random slave connection\" do\n secondaries = [server]\n cluster.stub(secondaries: secondaries)\n secondaries.should_receive(:sample).and_return(server)\n cluster.socket_for(:read).should eq socket\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"executes the operation on a slave node\" do\n session.should_receive(:socket_for).with(:read).\n and_return(socket)\n socket.should_receive(:execute).with(operation)\n\n session.execute(operation)\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def test_update_valid\n Domain.any_instance.stubs(:valid?).returns(true)\n put :update, {:id => Domain.first.to_param, :domain => {:name => Domain.first.name }}, set_session_user\n assert_redirected_to domains_url\n end", "label_name": "CWE-200", "label": "200"} -{"code": " def restrict_user_fields?(user)\n user.trust_level == TrustLevel[0] && anonymous?\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"has an empty list of primaries\" do\n cluster.primaries.should be_empty\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def as_json(options = {})\n hash = super\n\n hash[\"secret\"] = plaintext_secret if hash.key?(\"secret\")\n hash\n end", "label_name": "CWE-862", "label": "862"} -{"code": " it \"should choose :file_server when the settings name is 'puppet' and no server is specified\" do\n modules = mock 'modules'\n\n @request.expects(:protocol).returns \"puppet\"\n @request.expects(:server).returns nil\n Puppet.settings.expects(:value).with(:name).returns \"puppet\"\n @object.select_terminus(@request).should == :file_server\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"fails when user is suspended\" do\n user.update!(\n suspended_till: 2.days.from_now,\n suspended_at: Time.zone.now\n )\n\n get \"/session/email-login/#{email_token.token}\"\n\n expect(response.status).to eq(200)\n\n expect(CGI.unescapeHTML(response.body)).to include(I18n.t(\"login.suspended\",\n date: I18n.l(user.suspended_till, format: :date_only)\n ))\n end", "label_name": "CWE-287", "label": "287"} -{"code": " def test_update_invalid\n AuthSourceLdap.any_instance.stubs(:valid?).returns(false)\n put :update, {:id => AuthSourceLdap.first, :auth_source_ldap => {:name => AuthSourceLdap.first.name} }, set_session_user\n assert_template 'edit'\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"should escape evil haxxor attemptes\" do\n Mail.defaults do\n delivery_method :sendmail, :arguments => nil\n end\n \n mail = Mail.new do\n from '\"foo\\\";touch /tmp/PWNED;\\\"\"@blah.com'\n to 'marcel@test.lindsaar.net'\n subject 'invalid RFC2822'\n end\n \n Mail::Sendmail.should_receive(:call).with('/usr/sbin/sendmail', \n \"-f \\\"\\\\\\\"foo\\\\\\\\\\\\\\\"\\\\;touch /tmp/PWNED\\\\;\\\\\\\\\\\\\\\"\\\\\\\"@blah.com\\\"\", \n 'marcel@test.lindsaar.net', \n mail)\n mail.deliver!\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"stores the collection\" do\n query.collection.should eq collection\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def generation_time\n Time.at(@data.pack(\"C4\").unpack(\"N\")[0]).utc\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"returns true\" do\n Moped::BSON::ObjectId.new(bytes).should == Moped::BSON::ObjectId.new(bytes)\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"sets the generation time\" do\n time = Time.at((Time.now.utc - 64800).to_i).utc\n Moped::BSON::ObjectId.new(nil, time).generation_time.should == time\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def spec_summary entry, spec\n entry << \"\\n\\n\" << format_text(spec.summary, 68, 4)\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def seed\n # Authorisation is disabled usually when run from a rake db:* task\n User.current = FactoryGirl.build(:user, :admin => true)\n load File.expand_path('../../../../db/seeds.rb', __FILE__)\n end", "label_name": "CWE-200", "label": "200"} -{"code": " def __bson_load__(io)\n new io.read(12).unpack('C*')\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def command(command)\n operation = Protocol::Command.new(name, command)\n\n result = session.with(consistency: :strong) do |session|\n session.simple_query(operation)\n end\n\n raise Errors::OperationFailure.new(\n operation, result\n ) unless result[\"ok\"] == 1.0\n\n result\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def initialize(session, query_operation)\n @session = session\n @query_op = query_operation.dup\n\n @get_more_op = Protocol::GetMore.new(\n @query_op.database,\n @query_op.collection,\n 0,\n @query_op.limit\n )\n\n @kill_cursor_op = Protocol::KillCursors.new([0])\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"removes the stored credentials\" do\n cluster.logout :admin\n cluster.auth.should be_empty\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"drops the collection\" do\n database.should_receive(:command).with(drop: :users)\n collection.drop\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"delegates to the cluster\" do\n session.cluster.should_receive(:socket_for).with(:read)\n session.send(:socket_for, :read)\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"inserts the documents\" do\n session.should_receive(:execute).with do |insert|\n insert.documents.should eq [{a: 1}, {b: 2}]\n end\n collection.insert([{a: 1}, {b: 2}])\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def limited?\n @query_op.limit > 0\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def test_parse_bigger\n xml = <<-XML.strip_heredoc\n \n \n \n \n \n cleanup\n \n \n \n critical\n \n No comment\n \n \n \n \n review1\n \n \n please accept\n \n Left blank\n \n XML\n req = BsRequest.new_from_xml(xml)\n req.save!\n # number got increased by one\n assert_equal 1027, req.number\n\n newxml = req.render_xml\n assert_equal xml, newxml\n\n wi = req.webui_infos(diffs: false)\n # iggy is *not* target maintainer\n assert_equal false, wi['is_target_maintainer']\n assert_equal wi['actions'][0], type: :submit,\n sprj: 'home:Iggy',\n spkg: 'TestPack',\n srev: '1',\n tprj: 'kde4',\n tpkg: 'mypackage',\n name: 'Submit TestPack'\n end", "label_name": "CWE-862", "label": "862"} -{"code": " def with_taxonomy_scope(loc = Location.current, org = Organization.current, inner_method = :subtree_ids)\n self.which_ancestry_method = inner_method\n self.which_location = Location.expand(loc) if SETTINGS[:locations_enabled]\n self.which_organization = Organization.expand(org) if SETTINGS[:organizations_enabled]\n scope = block_given? ? yield : where('1=1')\n scope = scope_by_taxable_ids(scope)\n scope.readonly(false)\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"delegates to #with\" do\n session.should_receive(:with).with(new_options).and_return(new_session)\n session.new(new_options)\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def login(database, username, password)\n auth[database.to_s] = [username, password]\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"changes the $orderby\" do\n query.sort(a: 1)\n query.sort(a: 2)\n query.operation.selector.should eq(\n \"$query\" => selector,\n \"$orderby\" => { a: 2 }\n )\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"should allow requests that are whitelisted\" do\n set_cookie(\"__profilin=stylin\")\n get '/whitelisted'\n last_response.headers['X-MiniProfiler-Ids'].should_not be_nil\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"stores the selector\" do\n query.selector.should eq selector\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"returns a random slave connection\" do\n secondaries = [server]\n cluster.stub(secondaries: secondaries)\n secondaries.should_receive(:sample).and_return(server)\n cluster.socket_for(:read).should eq socket\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def test_update_invalid\n Medium.any_instance.stubs(:valid?).returns(false)\n put :update, {:id => Medium.first, :medium => {:name => nil}}, set_session_user\n assert_template 'edit'\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"adds the node to the master set\" do\n cluster.sync_server server\n cluster.primaries.should include server\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"changes the $orderby\" do\n query.sort(a: 1)\n query.sort(a: 2)\n query.operation.selector.should eq(\n \"$query\" => selector,\n \"$orderby\" => { a: 2 }\n )\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def legal?(string)\n string.to_s =~ /^[0-9a-f]{24}$/i ? true : false\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def sync_server(server)\n [].tap do |hosts|\n socket = server.socket\n\n if socket.connect\n info = socket.simple_query Protocol::Command.new(:admin, ismaster: 1)\n\n if info[\"ismaster\"]\n server.primary = true\n end\n\n if info[\"secondary\"]\n server.secondary = true\n end\n\n if info[\"primary\"]\n hosts.push info[\"primary\"]\n end\n\n if info[\"hosts\"]\n hosts.concat info[\"hosts\"]\n end\n\n if info[\"passives\"]\n hosts.concat info[\"passives\"]\n end\n\n merge(server)\n\n end\n end.uniq\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def handle_meta(message, local, &callback)\n method = Channel.parse(message['channel'])[1]\n\n unless META_METHODS.include?(method)\n response = make_response(message)\n response['error'] = Faye::Error.channel_forbidden(message['channel'])\n response['successful'] = false\n return callback.call([response])\n end\n\n __send__(method, message, local) do |responses|\n responses = [responses].flatten\n responses.each { |r| advize(r, message['connectionType']) }\n callback.call(responses)\n end\n end", "label_name": "CWE-287", "label": "287"} -{"code": " def legal?(string)\n string.to_s =~ /^[0-9a-f]{24}$/i ? true : false\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def primaries\n servers.select(&:primary?)\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def api_endpoint(uri)\n host = uri.host\n\n begin\n res = @dns.getresource \"_rubygems._tcp.#{host}\",\n Resolv::DNS::Resource::IN::SRV\n rescue Resolv::ResolvError => e\n verbose \"Getting SRV record failed: #{e}\"\n uri\n else\n target = res.target.to_s.strip\n\n if /\\.#{Regexp.quote(host)}\\z/ =~ target\n return URI.parse \"#{uri.scheme}://#{target}#{uri.path}\"\n end\n\n uri\n end\n end", "label_name": "CWE-346", "label": "346"} -{"code": " it \"inserts the document\" do\n session.should_receive(:execute).with do |insert|\n insert.documents.should eq [{a: 1}]\n end\n collection.insert(a: 1)\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"executes the operation on the master node\" do\n session.should_receive(:socket_for).with(:write).\n and_return(socket)\n socket.should_receive(:execute).with(operation)\n\n session.execute(operation)\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def secondaries\n servers.select(&:secondary?)\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"yields all indexes on the collection\" do\n indexes.to_a.should eq \\\n session[:\"system.indexes\"].find(ns: \"moped_test.users\").to_a\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def query(query)\n if options[:consistency] == :eventual\n query.flags |= [:slave_ok] if query.respond_to? :flags\n mode = :read\n else\n mode = :write\n end\n\n reply = socket_for(mode).execute(query)\n\n reply.tap do |reply|\n if reply.flags.include?(:query_failure)\n raise Errors::QueryFailure.new(query, reply.documents.first)\n end\n end\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def from_string(string)\n raise Errors::InvalidObjectId.new(string) unless legal?(string)\n data = []\n 12.times { |i| data << string[i*2, 2].to_i(16) }\n new data\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def drop\n command dropDatabase: 1\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it 'should write the public key to disk if its the first time its been seen' do\n @plugin.stubs(:lookup_config_option).with('learn_public_keys').returns('1')\n @plugin.stubs(:lookup_config_option).with('publickey_dir').returns('ssh/pkd')\n File.stubs(:directory?).with('ssh/pkd').returns(true)\n File.stubs(:exists?).with('ssh/pkd/rspec_pub.pem').returns(false)\n file = mock\n File.expects(:open).with('ssh/pkd/rspec_pub.pem', 'w').yields(file)\n file.expects(:puts).with('ssh-rsa abcd')\n @plugin.send(:write_key_to_disk, 'ssh-rsa abcd', 'rspec')\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def kill\n session.execute kill_cursor_op\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def access?(query)\n return false if record.internal == true && !user.permissions?('ticket.agent')\n\n ticket = Ticket.lookup(id: record.ticket_id)\n Pundit.authorize(user, ticket, query)\n end", "label_name": "CWE-862", "label": "862"} -{"code": " it 'should not choke on valueless attributes' do\n @s.fragment('foo foo bar')\n .must_equal 'foo foo bar'\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"should redeem the invite if invited by non staff and approve if email in auto_approve_email_domains setting\" do\n SiteSetting.must_approve_users = true\n SiteSetting.auto_approve_email_domains = \"example.com\"\n user = invite_redeemer.redeem\n\n expect(user.name).to eq(name)\n expect(user.username).to eq(username)\n expect(user.approved).to eq(true)\n end", "label_name": "CWE-863", "label": "863"} -{"code": " def legal?(str)\n !!str.match(/^[0-9a-f]{24}$/i)\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"memoizes the database\" do\n database = session.current_database\n session.current_database.should equal(database)\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"returns a hex string representation of the id\" do\n Moped::BSON::ObjectId.new(bytes).to_s.should eq \"4e4d66343b39b68407000001\"\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"creates a new cursor\" do\n cursor = mock(Moped::Cursor, next: nil)\n Moped::Cursor.should_receive(:new).\n with(session, query.operation).and_return(cursor)\n\n query.each\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def socket_for(mode)\n sync unless primaries.any? || (secondaries.any? && mode == :read)\n\n server = nil\n while primaries.any? || (secondaries.any? && mode == :read)\n if mode == :write || secondaries.empty?\n server = primaries.sample\n else\n server = secondaries.sample\n end\n\n if server\n socket = server.socket\n socket.connect unless socket.connection\n\n if socket.alive?\n break server\n else\n remove server\n end\n end\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def setup\n FactoryGirl.create(:host)\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"yields a session\" do\n session.with(new_options) do |new_session|\n new_session.should be_a Moped::Session\n end\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def email_login\n raise Discourse::NotFound if !SiteSetting.enable_local_logins_via_email\n second_factor_token = params[:second_factor_token]\n second_factor_method = params[:second_factor_method].to_i\n token = params[:token]\n valid_token = !!EmailToken.valid_token_format?(token)\n user = EmailToken.confirmable(token)&.user\n\n if valid_token && user&.totp_enabled?\n if !second_factor_token.present?\n @second_factor_required = true\n @backup_codes_enabled = true if user&.backup_codes_enabled?\n return render layout: 'no_ember'\n elsif !user.authenticate_second_factor(second_factor_token, second_factor_method)\n RateLimiter.new(nil, \"second-factor-min-#{request.remote_ip}\", 3, 1.minute).performed!\n @error = I18n.t('login.invalid_second_factor_code')\n return render layout: 'no_ember'\n end\n end\n\n if user = EmailToken.confirm(token)\n if login_not_approved_for?(user)\n @error = login_not_approved[:error]\n elsif payload = login_error_check(user)\n @error = payload[:error]\n else\n log_on_user(user)\n return redirect_to path(\"/\")\n end\n else\n @error = I18n.t('email_login.invalid_token')\n end\n\n render layout: 'no_ember'\n end", "label_name": "CWE-287", "label": "287"} -{"code": " def insert(documents)\n documents = [documents] unless documents.is_a? Array\n insert = Protocol::Insert.new(database.name, name, documents)\n\n database.session.with(consistency: :strong) do |session|\n session.execute insert\n end\n\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"initializes with the strings bytes\" do\n Moped::BSON::ObjectId.should_receive(:new).with(bytes)\n Moped::BSON::ObjectId.from_string \"4e4d66343b39b68407000001\"\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def initialize(session, query_operation)\n @session = session\n @query_op = query_operation.dup\n\n @get_more_op = Protocol::GetMore.new(\n @query_op.database,\n @query_op.collection,\n 0,\n @query_op.limit\n )\n\n @kill_cursor_op = Protocol::KillCursors.new([0])\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"yields the new session\" do\n session.stub(with: new_session)\n session.new(new_options) do |session|\n session.should eql new_session\n end\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"returns a new session\" do\n session.with(new_options).should_not eql session\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def sync\n known = known_addresses.shuffle\n seen = {}\n\n sync_seed = ->(seed) do\n server = Server.new seed\n\n unless seen[server.resolved_address]\n seen[server.resolved_address] = true\n\n hosts = sync_server(server)\n\n hosts.each do |host|\n sync_seed[host]\n end\n end\n end\n\n known.each do |seed|\n sync_seed[seed]\n end\n\n unless servers.empty?\n @dynamic_seeds = servers.map(&:address)\n end\n\n true\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"returns the document\" do\n session.simple_query(query).should eq(a: 1)\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"returns the living socket\" do\n cluster.socket_for(:write).should eq socket\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def test_login_should_not_redirect_to_another_host\n post :login, :username => 'jsmith', :password => 'jsmith', :back_url => 'http://test.foo/fake'\n assert_redirected_to '/my/page'\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it 'fails when local logins is disabled' do\n SiteSetting.enable_local_logins = false\n\n get \"/session/email-login/#{email_token.token}\"\n\n expect(response.status).to eq(500)\n end", "label_name": "CWE-287", "label": "287"} -{"code": " def test_update_valid\n Realm.any_instance.stubs(:valid?).returns(true)\n put :update, {:id => Realm.first.name,\n :realm => { :realm_proxy_id => SmartProxy.first.id } }, set_session_user\n assert_equal SmartProxy.first.id, Realm.first.realm_proxy_id\n assert_redirected_to realms_url\n end", "label_name": "CWE-200", "label": "200"} -{"code": " def initialize(image_path, colors=16, depth=8)\n output = `convert #{image_path} -resize 400x400 -format %c -dither None -quantize YIQ -colors #{colors} -depth #{depth} histogram:info:-`\n @lines = output.lines.sort.reverse.map(&:strip).reject(&:empty?)\n end", "label_name": "CWE-77", "label": "77"} -{"code": " def selected_ids\n return @selected_ids if @selected_ids\n ids = default_ids_hash\n #types NOT ignored - get ids that are selected\n hash_keys.each do |col|\n ids[col] = Array(taxonomy.send(col))\n end\n #types that ARE ignored - get ALL ids for object\n Array(taxonomy.ignore_types).each do |taxonomy_type|\n ids[\"#{taxonomy_type.tableize.singularize}_ids\"] = taxonomy_type.constantize.pluck(:id)\n end\n\n ids[\"#{opposite_taxonomy_type}_ids\"] = Array(taxonomy.send(\"#{opposite_taxonomy_type}_ids\"))\n @selected_ids = ids\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"sets slave_ok on the query flags\" do\n session.stub(socket_for: socket)\n socket.should_receive(:execute) do |query|\n query.flags.should include :slave_ok\n end\n\n session.query(query)\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def initialize(string)\n super(\"'#{string}' is not a valid object id.\")\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def redirect_back_or_default(default, options={})\n back_url = params[:back_url].to_s\n if back_url.present?\n begin\n uri = URI.parse(back_url)\n # do not redirect user to another host or to the login or register page\n if (uri.relative? || (uri.host == request.host)) && !uri.path.match(%r{/(login|account/register)})\n redirect_to(back_url)\n return\n end\n rescue URI::InvalidURIError\n logger.warn(\"Could not redirect to invalid URL #{back_url}\")\n # redirect to default\n end\n elsif options[:referer]\n redirect_to_referer_or default\n return\n end\n redirect_to default\n false\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"adds the node to the master set\" do\n cluster.sync_server server\n cluster.primaries.should include server\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def login(database, username, password)\n auth[database.to_s] = [username, password]\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"yields a new session\" do\n session.with(new_options) do |new_session|\n new_session.should_not eql session\n end\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def sync_server(server)\n [].tap do |hosts|\n socket = server.socket\n\n if socket.connect\n info = socket.simple_query Protocol::Command.new(:admin, ismaster: 1)\n\n if info[\"ismaster\"]\n server.primary = true\n end\n\n if info[\"secondary\"]\n server.secondary = true\n end\n\n if info[\"primary\"]\n hosts.push info[\"primary\"]\n end\n\n if info[\"hosts\"]\n hosts.concat info[\"hosts\"]\n end\n\n if info[\"passives\"]\n hosts.concat info[\"passives\"]\n end\n\n merge(server)\n\n end\n end.uniq\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def request(args = {})\n { :ip => '10.1.1.1', :node => 'host.domain.com', :key => 'key', :authenticated => true }.each do |k,v|\n args[k] ||= v\n end\n ['test', :find, args[:key], args]\n end", "label_name": "CWE-287", "label": "287"} -{"code": " it \"returns nothing\" do\n socket.stub(connect: false)\n\n cluster.sync_server(server).should be_empty\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def test_create_valid\n AuthSourceLdap.any_instance.stubs(:valid?).returns(true)\n post :create, {:auth_source_ldap => {:name => AuthSourceLdap.first.name}}, set_session_user\n assert_redirected_to auth_source_ldaps_url\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"creates a new cursor\" do\n cursor = mock(Moped::Cursor, next: nil)\n Moped::Cursor.should_receive(:new).\n with(session, query.operation).and_return(cursor)\n\n query.each\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def __bson_load__(io)\n new io.read(12).unpack('C*')\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"delegates to #with\" do\n session.should_receive(:with).with(new_options).and_return(new_session)\n session.new(new_options)\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def initialize(data = nil, time = nil)\n if data\n @data = data\n elsif time\n @data = @@generator.generate(time.to_i)\n else\n @data = @@generator.next\n end\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def initialize(remote_host, remote_port, local_host = nil, local_port = nil)\n if Thread.current[:private_address_check] && PrivateAddressCheck.resolves_to_private_address?(remote_host)\n raise PrivateAddressCheck::PrivateConnectionAttemptedError\n end\n\n initialize_without_private_address_check(remote_host, remote_port, local_host, local_port)\n end", "label_name": "CWE-362", "label": "362"} -{"code": " def write_key_to_disk(key, identity)\n\n # Writing is disabled. Don't bother checking any other states.\n return unless lookup_config_option('learn_public_keys') =~ /^1|y/\n\n publickey_dir = lookup_config_option('publickey_dir')\n\n unless publickey_dir\n Log.info(\"Public key sent with request but no publickey_dir defined in configuration. Not writing key to disk.\")\n return\n end\n\n if File.directory?(publickey_dir)\n if File.exists?(old_keyfile = File.join(publickey_dir, \"#{identity}_pub.pem\"))\n old_key = File.read(old_keyfile).chomp\n\n unless old_key == key\n unless lookup_config_option('overwrite_stored_keys', 'n') =~ /^1|y/\n Log.warn(\"Public key sent from '%s' does not match the stored key. Not overwriting.\" % identity)\n else\n Log.warn(\"Public key sent from '%s' does not match the stored key. Overwriting.\" % identity)\n File.open(File.join(publickey_dir, \"#{identity}_pub.pem\"), 'w') { |f| f.puts key }\n end\n end\n else\n Log.debug(\"Discovered a new public key for '%s'. Writing to '%s'\" % [identity, publickey_dir])\n File.open(File.join(publickey_dir, \"#{identity}_pub.pem\"), 'w') { |f| f.puts key }\n end\n else\n raise(\"Cannot write public key to '%s'. Directory does not exist.\" % publickey_dir)\n end\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def piped_category_name(category_id)\n return \"-\" unless category_id\n category = Category.find_by(id: category_id)\n return \"#{category_id}\" unless category\n categories = [category.name]\n while category.parent_category_id && category = category.parent_category\n categories << category.name\n end\n categories.reverse.join(\"|\")\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"returns the same hash\" do\n Moped::BSON::ObjectId.new(bytes).hash.should eq Moped::BSON::ObjectId.new(bytes).hash\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def select_terminus(request)\n # We rely on the request's parsing of the URI.\n\n # Short-circuit to :file if it's a fully-qualified path or specifies a 'file' protocol.\n return PROTOCOL_MAP[\"file\"] if Puppet::Util.absolute_path?(request.key)\n return PROTOCOL_MAP[\"file\"] if request.protocol == \"file\"\n\n # We're heading over the wire the protocol is 'puppet' and we've got a server name or we're not named 'apply' or 'puppet'\n if request.protocol == \"puppet\" and (request.server or ![\"puppet\",\"apply\"].include?(Puppet.settings[:name]))\n return PROTOCOL_MAP[\"puppet\"]\n end\n\n if request.protocol and PROTOCOL_MAP[request.protocol].nil?\n raise(ArgumentError, \"URI protocol '#{request.protocol}' is not currently supported for file serving\")\n end\n\n # If we're still here, we're using the file_server or modules.\n :file_server\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"instructs the cluster to reconnect\" do\n session.stub(with: new_session)\n new_session.cluster.should_receive(:reconnect)\n session.new(new_options)\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"should should include the IndirectionHooks module in its indirection\" do\n Puppet::FileServing::Content.indirection.singleton_class.included_modules.should include(Puppet::FileServing::IndirectionHooks)\n end", "label_name": "CWE-200", "label": "200"} -{"code": " def to_s\n @@string_format % data\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def remove\n delete = Protocol::Delete.new(\n operation.database,\n operation.collection,\n operation.selector,\n flags: [:remove_first]\n )\n\n session.with(consistency: :strong) do |session|\n session.execute delete\n end\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"returns the master connection\" do\n cluster.socket_for(:read).should eq socket\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def approve_account_if_needed\n if invited_user.present? && reviewable_user = ReviewableUser.find_by(target: invited_user, status: Reviewable.statuses[:pending])\n reviewable_user.perform(\n invite.invited_by,\n :approve_user,\n send_email: false,\n approved_by_invite: true\n )\n end\n end", "label_name": "CWE-863", "label": "863"} -{"code": " def email_verify_send\n\n raise Exceptions::UnprocessableEntity, 'No email!' if !params[:email]\n\n user = User.find_by(email: params[:email].downcase)\n if !user\n # result is always positive to avoid leaking of existing user accounts\n render json: { message: 'ok' }, status: :ok\n return\n end\n\n #if user.verified == true\n # render json: { error: 'Already verified!' }, status: :unprocessable_entity\n # return\n #end\n\n Token.create(action: 'Signup', user_id: user.id)\n\n result = User.signup_new_token(user)\n if result && result[:token]\n user = result[:user]\n NotificationFactory::Mailer.notification(\n template: 'signup',\n user: user,\n objects: result\n )\n\n # only if system is in develop mode, send token back to browser for browser tests\n if Setting.get('developer_mode') == true\n render json: { message: 'ok', token: result[:token].name }, status: :ok\n return\n end\n\n # token sent to user, send ok to browser\n render json: { message: 'ok' }, status: :ok\n return\n end\n\n # unable to generate token\n render json: { message: 'failed' }, status: :ok\n end", "label_name": "CWE-863", "label": "863"} -{"code": " it \"updates the selector to mongo's advanced selector\" do\n query.sort(a: 1)\n query.operation.selector.should eq(\n \"$query\" => selector,\n \"$orderby\" => { a: 1 }\n )\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"returns a session\" do\n session.with(new_options).should be_a Moped::Session\n end", "label_name": "CWE-20", "label": "20"} -{"code": " def private_messages_for(user, type)\n options = @options\n options.reverse_merge!(per_page: per_page_setting)\n\n result = Topic.includes(:allowed_users)\n result = result.includes(:tags) if SiteSetting.tagging_enabled\n\n if type == :group\n result = result.joins(\n \"INNER JOIN topic_allowed_groups tag ON tag.topic_id = topics.id AND tag.group_id IN (SELECT id FROM groups WHERE LOWER(name) = '#{PG::Connection.escape_string(@options[:group_name].downcase)}')\"\n )\n\n unless user.admin?\n result = result.joins(\"INNER JOIN group_users gu ON gu.group_id = tag.group_id AND gu.user_id = #{user.id.to_i}\")\n end\n elsif type == :user\n result = result.where(\"topics.id IN (SELECT topic_id FROM topic_allowed_users WHERE user_id = #{user.id.to_i})\")\n elsif type == :all\n result = result.where(\"topics.id IN (\n SELECT topic_id\n FROM topic_allowed_users\n WHERE user_id = #{user.id.to_i}\n UNION ALL\n SELECT topic_id FROM topic_allowed_groups\n WHERE group_id IN (\n SELECT group_id FROM group_users WHERE user_id = #{user.id.to_i}\n )\n )\")\n end\n\n result = result.joins(\"LEFT OUTER JOIN topic_users AS tu ON (topics.id = tu.topic_id AND tu.user_id = #{user.id.to_i})\")\n .order(\"topics.bumped_at DESC\")\n .private_messages\n\n result = result.limit(options[:per_page]) unless options[:limit] == false\n result = result.visible if options[:visible] || @user.nil? || @user.regular?\n\n if options[:page]\n offset = options[:page].to_i * options[:per_page]\n result = result.offset(offset) if offset > 0\n end\n result\n end", "label_name": "CWE-863", "label": "863"} -{"code": " def current_user\n User.except_hidden.find_by_login(self.user)\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it 'should return a second factor prompt' do\n get \"/session/email-login/#{email_token.token}\"\n\n expect(response.status).to eq(200)\n\n response_body = CGI.unescapeHTML(response.body)\n\n expect(response_body).to include(I18n.t(\n \"login.second_factor_title\"\n ))\n\n expect(response_body).to_not include(I18n.t(\n \"login.invalid_second_factor_code\"\n ))\n end", "label_name": "CWE-287", "label": "287"} -{"code": " def user_with_viewer_rights_should_fail_to_edit_a_domain\n setup_users\n get :edit, {:id => Domain.first.id}\n assert @response.status == '403 Forbidden'\n end", "label_name": "CWE-200", "label": "200"} -{"code": " def Sendmail.call(path, arguments, destinations, mail)\n IO.popen(\"#{path} #{arguments} #{destinations}\", \"w+\") do |io|\n io.puts mail.encoded.to_lf\n io.flush\n end\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"should should include the IndirectionHooks module in its indirection\" do\n Puppet::FileServing::Metadata.indirection.singleton_class.included_modules.should include(Puppet::FileServing::IndirectionHooks)\n end", "label_name": "CWE-200", "label": "200"} -{"code": " def current_database\n return @current_database if defined? @current_database\n\n if database = options[:database]\n set_current_database(database)\n else\n raise \"No database set for session. Call #use or #with before accessing the database\"\n end\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def simple_query(query)\n query.limit = -1\n\n query(query).documents.first\n end", "label_name": "CWE-400", "label": "400"} -{"code": " it \"raises an exception\" do\n expect { session.current_database }.to raise_exception\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"stores the list of seeds\" do\n cluster.seeds.should eq [\"127.0.0.1:27017\", \"127.0.0.1:27018\"]\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"should should be a subclass of Base\" do\n Puppet::FileServing::Content.superclass.should equal(Puppet::FileServing::Base)\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"returns all other known hosts\" do\n cluster.sync_server(server).should =~ [\"localhost:61085\", \"localhost:61086\", \"localhost:61084\"]\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"syncs the cluster\" do\n cluster.should_receive(:sync) do\n cluster.servers << server\n end\n cluster.socket_for :write\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def merge(server)\n previous = servers.find { |other| other == server }\n primary = server.primary?\n secondary = server.secondary?\n\n if previous\n previous.merge(server)\n else\n servers << server\n end\n end", "label_name": "CWE-400", "label": "400"} -{"code": " def test_update_valid\n Subnet.any_instance.stubs(:valid?).returns(true)\n put :update, {:id => Subnet.first, :subnet => {:network => '192.168.100.10'}}, set_session_user\n assert_equal '192.168.100.10', Subnet.first.network\n assert_redirected_to subnets_url\n end", "label_name": "CWE-200", "label": "200"} -{"code": " it \"limits the query\" do\n session.should_receive(:query) do |query|\n query.limit.should eq(-1)\n reply\n end\n\n session.simple_query(query)\n end", "label_name": "CWE-20", "label": "20"} -{"code": " it \"yields a new session\" do\n session.with(new_options) do |new_session|\n new_session.should_not eql session\n end\n end", "label_name": "CWE-20", "label": "20"} -{"code": "func remount(m *configs.Mount, rootfs string) error {\n\tvar (\n\t\tdest = m.Destination\n\t)\n\tif !strings.HasPrefix(dest, rootfs) {\n\t\tdest = filepath.Join(rootfs, dest)\n\t}\n\treturn unix.Mount(m.Source, dest, m.Device, uintptr(m.Flags|unix.MS_REMOUNT), \"\")\n}", "label_name": "CWE-362", "label": "362"} -{"code": "func prepareBindMount(m *configs.Mount, rootfs string) error {\n\tstat, err := os.Stat(m.Source)\n\tif err != nil {\n\t\t// error out if the source of a bind mount does not exist as we will be\n\t\t// unable to bind anything to it.\n\t\treturn err\n\t}\n\t// ensure that the destination of the bind mount is resolved of symlinks at mount time because\n\t// any previous mounts can invalidate the next mount's destination.\n\t// this can happen when a user specifies mounts within other mounts to cause breakouts or other\n\t// evil stuff to try to escape the container's rootfs.\n\tvar dest string\n\tif dest, err = securejoin.SecureJoin(rootfs, m.Destination); err != nil {\n\t\treturn err\n\t}\n\tif err := checkProcMount(rootfs, dest, m.Source); err != nil {\n\t\treturn err\n\t}\n\t// update the mount with the correct dest after symlinks are resolved.\n\tm.Destination = dest\n\tif err := createIfNotExists(dest, stat.IsDir()); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "label_name": "CWE-362", "label": "362"} -{"code": "func (mgr *MetricsManager) OnConfigChange(ctx context.Context, cfg *Config) {\n\tmgr.mu.Lock()\n\tdefer mgr.mu.Unlock()\n\n\tmgr.updateInfo(cfg)\n\tmgr.updateServer(cfg)\n}", "label_name": "CWE-200", "label": "200"} -{"code": "func (c *linuxContainer) makeCriuRestoreMountpoints(m *configs.Mount) error {\n\tswitch m.Device {\n\tcase \"cgroup\":\n\t\t// No mount point(s) need to be created:\n\t\t//\n\t\t// * for v1, mount points are saved by CRIU because\n\t\t// /sys/fs/cgroup is a tmpfs mount\n\t\t//\n\t\t// * for v2, /sys/fs/cgroup is a real mount, but\n\t\t// the mountpoint appears as soon as /sys is mounted\n\t\treturn nil\n\tcase \"bind\":\n\t\t// The prepareBindMount() function checks if source\n\t\t// exists. So it cannot be used for other filesystem types.\n\t\tif err := prepareBindMount(m, c.config.Rootfs); err != nil {\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\t// for all other filesystems just create the mountpoints\n\t\tdest, err := securejoin.SecureJoin(c.config.Rootfs, m.Destination)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := checkProcMount(c.config.Rootfs, dest, \"\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tm.Destination = dest\n\t\tif err := os.MkdirAll(dest, 0755); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "label_name": "CWE-362", "label": "362"} -{"code": "func (svc *Service) OSVersions(ctx context.Context, teamID *uint, platform *string) (*fleet.OSVersions, error) {\n\tif err := svc.authz.Authorize(ctx, &fleet.Host{TeamID: teamID}, fleet.ActionList); err != nil {\n\t\treturn nil, err\n\t}\n\n\tosVersions, err := svc.ds.OSVersions(ctx, teamID, platform)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn osVersions, nil\n\n}", "label_name": "CWE-863", "label": "863"} -{"code": "func (p *GitLabProvider) PrefixAllowedGroups() (groups []string) {\n\n\tfor _, val := range p.Groups {\n\t\tgroups = append(groups, fmt.Sprintf(\"group:%s\", val))\n\t}\n\n\tfor _, val := range p.Projects {\n\t\tgroups = append(groups, fmt.Sprintf(\"project:%s\", val.Name))\n\t}\n\n\treturn groups\n}", "label_name": "CWE-863", "label": "863"} -{"code": "func createDeviceNode(rootfs string, node *devices.Device, bind bool) error {\n\tif node.Path == \"\" {\n\t\t// The node only exists for cgroup reasons, ignore it here.\n\t\treturn nil\n\t}\n\tdest := filepath.Join(rootfs, node.Path)\n\tif err := os.MkdirAll(filepath.Dir(dest), 0755); err != nil {\n\t\treturn err\n\t}\n\tif bind {\n\t\treturn bindMountDeviceNode(dest, node)\n\t}\n\tif err := mknodDevice(dest, node); err != nil {\n\t\tif os.IsExist(err) {\n\t\t\treturn nil\n\t\t} else if os.IsPermission(err) {\n\t\t\treturn bindMountDeviceNode(dest, node)\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}", "label_name": "CWE-362", "label": "362"} -{"code": "func LoadDir(dirname string) (*Plugin, error) {\n\tdata, err := ioutil.ReadFile(filepath.Join(dirname, PluginFileName))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tplug := &Plugin{Dir: dirname}\n\tif err := yaml.Unmarshal(data, &plug.Metadata); err != nil {\n\t\treturn nil, err\n\t}\n\treturn plug, nil\n}", "label_name": "CWE-74", "label": "74"} -{"code": "func makeStreamDistributedQueryCampaignResultsHandler(svc kolide.Service, jwtKey string, logger kitlog.Logger) http.Handler {\n\topt := sockjs.DefaultOptions\n\topt.Websocket = true\n\topt.RawWebsocket = true\n\treturn sockjs.NewHandler(\"/api/v1/kolide/results\", opt, func(session sockjs.Session) {\n\t\tdefer session.Close(0, \"none\")\n\n\t\tconn := &websocket.Conn{Session: session}\n\n\t\t// Receive the auth bearer token\n\t\ttoken, err := conn.ReadAuthToken()\n\t\tif err != nil {\n\t\t\tlogger.Log(\"err\", err, \"msg\", \"failed to read auth token\")\n\t\t\treturn\n\t\t}\n\n\t\t// Authenticate with the token\n\t\tvc, err := authViewer(context.Background(), jwtKey, token, svc)\n\t\tif err != nil || !vc.CanPerformActions() {\n\t\t\tlogger.Log(\"err\", err, \"msg\", \"unauthorized viewer\")\n\t\t\tconn.WriteJSONError(\"unauthorized\")\n\t\t\treturn\n\t\t}\n\n\t\tctx := viewer.NewContext(context.Background(), *vc)\n\n\t\tmsg, err := conn.ReadJSONMessage()\n\t\tif err != nil {\n\t\t\tlogger.Log(\"err\", err, \"msg\", \"reading select_campaign JSON\")\n\t\t\tconn.WriteJSONError(\"error reading select_campaign\")\n\t\t\treturn\n\t\t}\n\t\tif msg.Type != \"select_campaign\" {\n\t\t\tlogger.Log(\"err\", \"unexpected msg type, expected select_campaign\", \"msg-type\", msg.Type)\n\t\t\tconn.WriteJSONError(\"expected select_campaign\")\n\t\t\treturn\n\t\t}\n\n\t\tvar info struct {\n\t\t\tCampaignID uint `json:\"campaign_id\"`\n\t\t}\n\t\terr = json.Unmarshal(*(msg.Data.(*json.RawMessage)), &info)\n\t\tif err != nil {\n\t\t\tlogger.Log(\"err\", err, \"msg\", \"unmarshaling select_campaign data\")\n\t\t\tconn.WriteJSONError(\"error unmarshaling select_campaign data\")\n\t\t\treturn\n\t\t}\n\t\tif info.CampaignID == 0 {\n\t\t\tlogger.Log(\"err\", \"campaign ID not set\")\n\t\t\tconn.WriteJSONError(\"0 is not a valid campaign ID\")\n\t\t\treturn\n\t\t}\n\n\t\tsvc.StreamCampaignResults(ctx, conn, info.CampaignID)\n\n\t})\n}", "label_name": "CWE-400", "label": "400"} -{"code": "func (svc Service) TeamScheduleQuery(ctx context.Context, teamID uint, q *fleet.ScheduledQuery) (*fleet.ScheduledQuery, error) {\n\tif err := svc.authz.Authorize(ctx, &fleet.Pack{TeamIDs: []uint{teamID}}, fleet.ActionWrite); err != nil {\n\t\treturn nil, err\n\t}\n\n\tgp, err := svc.ds.EnsureTeamPack(ctx, teamID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tq.PackID = gp.ID\n\n\treturn svc.unauthorizedScheduleQuery(ctx, q)\n}", "label_name": "CWE-863", "label": "863"} -{"code": "func (svc *Service) GetHost(ctx context.Context, id uint) (*fleet.HostDetail, error) {\n\talreadyAuthd := svc.authz.IsAuthenticatedWith(ctx, authz_ctx.AuthnDeviceToken)\n\tif !alreadyAuthd {\n\t\t// First ensure the user has access to list hosts, then check the specific\n\t\t// host once team_id is loaded.\n\t\tif err := svc.authz.Authorize(ctx, &fleet.Host{}, fleet.ActionList); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\thost, err := svc.ds.Host(ctx, id, false)\n\tif err != nil {\n\t\treturn nil, ctxerr.Wrap(ctx, err, \"get host\")\n\t}\n\n\tif !alreadyAuthd {\n\t\t// Authorize again with team loaded now that we have team_id\n\t\tif err := svc.authz.Authorize(ctx, host, fleet.ActionRead); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn svc.getHostDetails(ctx, host)\n}", "label_name": "CWE-863", "label": "863"} -{"code": "func (svc Service) CountSoftware(ctx context.Context, opt fleet.SoftwareListOptions) (int, error) {\n\tif err := svc.authz.Authorize(ctx, &fleet.Software{}, fleet.ActionRead); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn svc.ds.CountSoftware(ctx, opt)\n}", "label_name": "CWE-863", "label": "863"} -{"code": "func (a *AuthenticatorOAuth2Introspection) tokenToCache(config *AuthenticatorOAuth2IntrospectionConfiguration, i *AuthenticatorOAuth2IntrospectionResult, token string) {\n\tif !config.Cache.Enabled {\n\t\treturn\n\t}\n\n\tif a.cacheTTL != nil {\n\t\ta.tokenCache.SetWithTTL(token, i, 1, *a.cacheTTL)\n\t} else {\n\t\ta.tokenCache.Set(token, i, 1)\n\t}\n}", "label_name": "CWE-863", "label": "863"} -{"code": "func (f *Fosite) writeJsonError(rw http.ResponseWriter, err error) {\n\trw.Header().Set(\"Content-Type\", \"application/json;charset=UTF-8\")\n\trw.Header().Set(\"Cache-Control\", \"no-store\")\n\trw.Header().Set(\"Pragma\", \"no-cache\")\n\n\trfcerr := ErrorToRFC6749Error(err)\n\tif !f.SendDebugMessagesToClients {\n\t\trfcerr = rfcerr.Sanitize()\n\t}\n\n\tjs, err := json.Marshal(rfcerr)\n\tif err != nil {\n\t\tif f.SendDebugMessagesToClients {\n\t\t\terrorMessage := EscapeJSONString(err.Error())\n\t\t\thttp.Error(rw, fmt.Sprintf(`{\"error\":\"server_error\",\"error_description\":\"%s\"}`, errorMessage), http.StatusInternalServerError)\n\t\t} else {\n\t\t\thttp.Error(rw, `{\"error\":\"server_error\"}`, http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\n\trw.WriteHeader(rfcerr.Code)\n\trw.Write(js)\n}", "label_name": "CWE-755", "label": "755"} -{"code": "func (evpool *Pool) AddEvidence(ev types.Evidence) error {\n\tevpool.logger.Debug(\"Attempting to add evidence\", \"ev\", ev)\n\n\t// We have already verified this piece of evidence - no need to do it again\n\tif evpool.isPending(ev) {\n\t\tevpool.logger.Info(\"Evidence already pending, ignoring this one\", \"ev\", ev)\n\t\treturn nil\n\t}\n\n\t// check that the evidence isn't already committed\n\tif evpool.isCommitted(ev) {\n\t\t// this can happen if the peer that sent us the evidence is behind so we shouldn't\n\t\t// punish the peer.\n\t\tevpool.logger.Debug(\"Evidence was already committed, ignoring this one\", \"ev\", ev)\n\t\treturn nil\n\t}\n\n\t// 1) Verify against state.\n\terr := evpool.verify(ev)\n\tif err != nil {\n\t\treturn types.NewErrInvalidEvidence(ev, err)\n\t}\n\n\t// 2) Save to store.\n\tif err := evpool.addPendingEvidence(ev); err != nil {\n\t\treturn fmt.Errorf(\"can't add evidence to pending list: %w\", err)\n\t}\n\n\t// 3) Add evidence to clist.\n\tevpool.evidenceList.PushBack(ev)\n\n\tevpool.logger.Info(\"Verified new evidence of byzantine behavior\", \"evidence\", ev)\n\n\treturn nil\n}", "label_name": "CWE-400", "label": "400"} -{"code": "func (svc *Service) DeleteGlobalScheduledQueries(ctx context.Context, id uint) error {\n\tif err := svc.authz.Authorize(ctx, &fleet.Pack{}, fleet.ActionWrite); err != nil {\n\t\treturn err\n\t}\n\n\treturn svc.DeleteScheduledQuery(ctx, id)\n}", "label_name": "CWE-863", "label": "863"} -{"code": "func (mgr *MetricsManager) updateInfo(cfg *Config) {\n\tserviceName := telemetry.ServiceName(cfg.Options.Services)\n\tif serviceName == mgr.serviceName {\n\t\treturn\n\t}\n\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\tlog.Error(context.TODO()).Err(err).Msg(\"telemetry/metrics: failed to get OS hostname\")\n\t\thostname = \"__unknown__\"\n\t}\n\n\tmetrics.SetBuildInfo(serviceName, hostname, cfg.EnvoyVersion)\n\tmgr.serviceName = serviceName\n}", "label_name": "CWE-200", "label": "200"} -{"code": "func bindMountDeviceNode(dest string, node *devices.Device) error {\n\tf, err := os.Create(dest)\n\tif err != nil && !os.IsExist(err) {\n\t\treturn err\n\t}\n\tif f != nil {\n\t\tf.Close()\n\t}\n\treturn unix.Mount(node.Path, dest, \"bind\", unix.MS_BIND, \"\")\n}", "label_name": "CWE-362", "label": "362"} -{"code": "func (AppModuleBasic) ConsensusVersion() uint64 {\n\treturn 1\n}", "label_name": "CWE-287", "label": "287"} -{"code": "func TestMsgGrantAuthorization(t *testing.T) {\n\ttests := []struct {\n\t\ttitle string\n\t\tgranter, grantee sdk.AccAddress\n\t\tauthorization authz.Authorization\n\t\texpiration time.Time\n\t\texpectErr bool\n\t\texpectPass bool\n\t}{\n\t\t{\"nil granter address\", nil, grantee, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now(), false, false},\n\t\t{\"nil grantee address\", granter, nil, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now(), false, false},\n\t\t{\"nil granter and grantee address\", nil, nil, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now(), false, false},\n\t\t{\"nil authorization\", granter, grantee, nil, time.Now(), true, false},\n\t\t{\"valid test case\", granter, grantee, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now().AddDate(0, 1, 0), false, true},\n\t\t{\"past time\", granter, grantee, &banktypes.SendAuthorization{SpendLimit: coinsPos}, time.Now().AddDate(0, 0, -1), false, false},\n\t}\n\tfor i, tc := range tests {\n\t\tmsg, err := authz.NewMsgGrant(\n\t\t\ttc.granter, tc.grantee, tc.authorization, tc.expiration,\n\t\t)\n\t\tif !tc.expectErr {\n\t\t\trequire.NoError(t, err)\n\t\t} else {\n\t\t\tcontinue\n\t\t}\n\t\tif tc.expectPass {\n\t\t\trequire.NoError(t, msg.ValidateBasic(), \"test: %v\", i)\n\t\t} else {\n\t\t\trequire.Error(t, msg.ValidateBasic(), \"test: %v\", i)\n\t\t}\n\t}\n}", "label_name": "CWE-754", "label": "754"} -{"code": "func httpProxyValid(proxy *contourv1.HTTPProxy) bool {\n\treturn proxy != nil && proxy.Status.CurrentStatus == \"valid\"\n}", "label_name": "CWE-610", "label": "610"} -{"code": "func New(\n\tlocalGRPCAddress string,\n\tlocalHTTPAddress string,\n\tfileManager *filemgr.Manager,\n\treproxyHandler *reproxy.Handler,\n) *Builder {\n\treturn &Builder{\n\t\tlocalGRPCAddress: localGRPCAddress,\n\t\tlocalHTTPAddress: localHTTPAddress,\n\t\tfilemgr: fileManager,\n\t\treproxy: reproxyHandler,\n\t}\n}", "label_name": "CWE-200", "label": "200"} -{"code": "func Test_buildRouteConfiguration(t *testing.T) {\n\tb := New(\"local-grpc\", \"local-http\", nil, nil)\n\tvirtualHosts := make([]*envoy_config_route_v3.VirtualHost, 10)\n\trouteConfig, err := b.buildRouteConfiguration(\"test-route-configuration\", virtualHosts)\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"test-route-configuration\", routeConfig.GetName())\n\tassert.Equal(t, virtualHosts, routeConfig.GetVirtualHosts())\n\tassert.False(t, routeConfig.GetValidateClusters().GetValue())\n}", "label_name": "CWE-200", "label": "200"} -{"code": "func TestWrapHandler(t *testing.T) {\n\trouter := http.NewServeMux()\n\n\trouter.Handle(\"/\", Handler(DocExpansion(\"none\"), DomID(\"#swagger-ui\")))\n\n\tw1 := performRequest(\"GET\", \"/index.html\", router)\n\tassert.Equal(t, 200, w1.Code)\n\tassert.Equal(t, w1.Header()[\"Content-Type\"][0], \"text/html; charset=utf-8\")\n\n\tw2 := performRequest(\"GET\", \"/doc.json\", router)\n\tassert.Equal(t, 500, w2.Code)\n\n\tswag.Register(swag.Name, &mockedSwag{})\n\tw2 = performRequest(\"GET\", \"/doc.json\", router)\n\tassert.Equal(t, 200, w2.Code)\n\tassert.Equal(t, \"application/json; charset=utf-8\", w2.Header().Get(\"content-type\"))\n\n\tw3 := performRequest(\"GET\", \"/favicon-16x16.png\", router)\n\tassert.Equal(t, 200, w3.Code)\n\tassert.Equal(t, w3.Header()[\"Content-Type\"][0], \"image/png\")\n\n\tw4 := performRequest(\"GET\", \"/swagger-ui.css\", router)\n\tassert.Equal(t, 200, w4.Code)\n\tassert.Equal(t, w4.Header()[\"Content-Type\"][0], \"text/css; charset=utf-8\")\n\n\tw5 := performRequest(\"GET\", \"/swagger-ui-bundle.js\", router)\n\tassert.Equal(t, 200, w5.Code)\n\tassert.Equal(t, w5.Header()[\"Content-Type\"][0], \"application/javascript\")\n\n\tw6 := performRequest(\"GET\", \"/notfound\", router)\n\tassert.Equal(t, 404, w6.Code)\n\n\tw7 := performRequest(\"GET\", \"/\", router)\n\tassert.Equal(t, 301, w7.Code)\n}", "label_name": "CWE-755", "label": "755"} -{"code": "func (a *AuthenticatorOAuth2Introspection) traceRequest(ctx context.Context, req *http.Request) func() {\n\ttracer := opentracing.GlobalTracer()\n\tif tracer == nil {\n\t\treturn func() {}\n\t}\n\n\tparentSpan := opentracing.SpanFromContext(ctx)\n\topts := make([]opentracing.StartSpanOption, 0, 1)\n\tif parentSpan != nil {\n\t\topts = append(opts, opentracing.ChildOf(parentSpan.Context()))\n\t}\n\n\turlStr := req.URL.String()\n\tclientSpan := tracer.StartSpan(req.Method+\" \"+urlStr, opts...)\n\n\text.SpanKindRPCClient.Set(clientSpan)\n\text.HTTPUrl.Set(clientSpan, urlStr)\n\text.HTTPMethod.Set(clientSpan, req.Method)\n\n\ttracer.Inject(clientSpan.Context(), opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(req.Header))\n\treturn clientSpan.Finish\n}", "label_name": "CWE-863", "label": "863"} -{"code": "func (r *TokenRevocationHandler) RevokeToken(ctx context.Context, token string, tokenType fosite.TokenType, client fosite.Client) error {\n\tdiscoveryFuncs := []func() (request fosite.Requester, err error){\n\t\tfunc() (request fosite.Requester, err error) {\n\t\t\t// Refresh token\n\t\t\tsignature := r.RefreshTokenStrategy.RefreshTokenSignature(token)\n\t\t\treturn r.TokenRevocationStorage.GetRefreshTokenSession(ctx, signature, nil)\n\t\t},\n\t\tfunc() (request fosite.Requester, err error) {\n\t\t\t// Access token\n\t\t\tsignature := r.AccessTokenStrategy.AccessTokenSignature(token)\n\t\t\treturn r.TokenRevocationStorage.GetAccessTokenSession(ctx, signature, nil)\n\t\t},\n\t}\n\n\t// Token type hinting\n\tif tokenType == fosite.AccessToken {\n\t\tdiscoveryFuncs[0], discoveryFuncs[1] = discoveryFuncs[1], discoveryFuncs[0]\n\t}\n\n\tvar ar fosite.Requester\n\tvar err error\n\tif ar, err = discoveryFuncs[0](); err != nil {\n\t\tar, err = discoveryFuncs[1]()\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif ar.GetClient().GetID() != client.GetID() {\n\t\treturn errors.WithStack(fosite.ErrRevocationClientMismatch)\n\t}\n\n\trequestID := ar.GetID()\n\tr.TokenRevocationStorage.RevokeRefreshToken(ctx, requestID)\n\tr.TokenRevocationStorage.RevokeAccessToken(ctx, requestID)\n\n\treturn nil\n}", "label_name": "CWE-755", "label": "755"} -{"code": "func (svc *Service) User(ctx context.Context, id uint) (*fleet.User, error) {\n\tif err := svc.authz.Authorize(ctx, &fleet.User{ID: id}, fleet.ActionRead); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn svc.ds.UserByID(ctx, id)\n}", "label_name": "CWE-863", "label": "863"} -{"code": "func testExternalNameServiceInsecure(namespace string) {\n\tSpecify(\"external name services work over http\", func() {\n\t\tt := f.T()\n\n\t\tf.Fixtures.Echo.Deploy(namespace, \"ingress-conformance-echo\")\n\n\t\texternalNameService := &corev1.Service{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: namespace,\n\t\t\t\tName: \"external-name-service\",\n\t\t\t},\n\t\t\tSpec: corev1.ServiceSpec{\n\t\t\t\tType: corev1.ServiceTypeExternalName,\n\t\t\t\tExternalName: \"ingress-conformance-echo.\" + namespace,\n\t\t\t\tPorts: []corev1.ServicePort{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: \"http\",\n\t\t\t\t\t\tPort: 80,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\trequire.NoError(t, f.Client.Create(context.TODO(), externalNameService))\n\n\t\tp := &contourv1.HTTPProxy{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: namespace,\n\t\t\t\tName: \"external-name-proxy\",\n\t\t\t},\n\t\t\tSpec: contourv1.HTTPProxySpec{\n\t\t\t\tVirtualHost: &contourv1.VirtualHost{\n\t\t\t\t\tFqdn: \"externalnameservice.projectcontour.io\",\n\t\t\t\t},\n\t\t\t\tRoutes: []contourv1.Route{\n\t\t\t\t\t{\n\t\t\t\t\t\tServices: []contourv1.Service{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tName: externalNameService.Name,\n\t\t\t\t\t\t\t\tPort: 80,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tRequestHeadersPolicy: &contourv1.HeadersPolicy{\n\t\t\t\t\t\t\tSet: []contourv1.HeaderValue{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tName: \"Host\",\n\t\t\t\t\t\t\t\t\tValue: externalNameService.Spec.ExternalName,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\tf.CreateHTTPProxyAndWaitFor(p, httpProxyValid)\n\n\t\tres, ok := f.HTTP.RequestUntil(&e2e.HTTPRequestOpts{\n\t\t\tHost: p.Spec.VirtualHost.Fqdn,\n\t\t\tCondition: e2e.HasStatusCode(200),\n\t\t})\n\t\trequire.Truef(t, ok, \"expected 200 response code, got %d\", res.StatusCode)\n\t})\n}", "label_name": "CWE-610", "label": "610"} -{"code": "\t\taction := args[2].(func(child argoappv1.ResourceNode, appName string))\n\t\tappName := \"\"\n\t\tif res, ok := data.namespacedResources[key]; ok {\n\t\t\tappName = res.AppName\n\t\t}\n\t\taction(argoappv1.ResourceNode{ResourceRef: argoappv1.ResourceRef{Kind: key.Kind, Group: key.Group, Namespace: key.Namespace, Name: key.Name}}, appName)\n\t}).Return(nil)", "label_name": "CWE-269", "label": "269"} -{"code": "func logNamespaceDiagnostics(spec *specs.Spec) {\n\tsawMountNS := false\n\tsawUserNS := false\n\tsawUTSNS := false\n\tfor _, ns := range spec.Linux.Namespaces {\n\t\tswitch ns.Type {\n\t\tcase specs.CgroupNamespace:\n\t\t\tif ns.Path != \"\" {\n\t\t\t\tlogrus.Debugf(\"unable to join cgroup namespace, sorry about that\")\n\t\t\t} else {\n\t\t\t\tlogrus.Debugf(\"unable to create cgroup namespace, sorry about that\")\n\t\t\t}\n\t\tcase specs.IPCNamespace:\n\t\t\tif ns.Path != \"\" {\n\t\t\t\tlogrus.Debugf(\"unable to join IPC namespace, sorry about that\")\n\t\t\t} else {\n\t\t\t\tlogrus.Debugf(\"unable to create IPC namespace, sorry about that\")\n\t\t\t}\n\t\tcase specs.MountNamespace:\n\t\t\tif ns.Path != \"\" {\n\t\t\t\tlogrus.Debugf(\"unable to join mount namespace %q, creating a new one\", ns.Path)\n\t\t\t}\n\t\t\tsawMountNS = true\n\t\tcase specs.NetworkNamespace:\n\t\t\tif ns.Path != \"\" {\n\t\t\t\tlogrus.Debugf(\"unable to join network namespace, sorry about that\")\n\t\t\t} else {\n\t\t\t\tlogrus.Debugf(\"unable to create network namespace, sorry about that\")\n\t\t\t}\n\t\tcase specs.PIDNamespace:\n\t\t\tif ns.Path != \"\" {\n\t\t\t\tlogrus.Debugf(\"unable to join PID namespace, sorry about that\")\n\t\t\t} else {\n\t\t\t\tlogrus.Debugf(\"unable to create PID namespace, sorry about that\")\n\t\t\t}\n\t\tcase specs.UserNamespace:\n\t\t\tif ns.Path != \"\" {\n\t\t\t\tlogrus.Debugf(\"unable to join user namespace %q, creating a new one\", ns.Path)\n\t\t\t}\n\t\t\tsawUserNS = true\n\t\tcase specs.UTSNamespace:\n\t\t\tif ns.Path != \"\" {\n\t\t\t\tlogrus.Debugf(\"unable to join UTS namespace %q, creating a new one\", ns.Path)\n\t\t\t}\n\t\t\tsawUTSNS = true\n\t\t}\n\t}\n\tif !sawMountNS {\n\t\tlogrus.Debugf(\"mount namespace not requested, but creating a new one anyway\")\n\t}\n\tif !sawUserNS {\n\t\tlogrus.Debugf(\"user namespace not requested, but creating a new one anyway\")\n\t}\n\tif !sawUTSNS {\n\t\tlogrus.Debugf(\"UTS namespace not requested, but creating a new one anyway\")\n\t}\n}", "label_name": "CWE-200", "label": "200"} -{"code": "func mountNewCgroup(m *configs.Mount) error {\n\tvar (\n\t\tdata = m.Data\n\t\tsource = m.Source\n\t)\n\tif data == \"systemd\" {\n\t\tdata = cgroups.CgroupNamePrefix + data\n\t\tsource = \"systemd\"\n\t}\n\tif err := unix.Mount(source, m.Destination, m.Device, uintptr(m.Flags), data); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "label_name": "CWE-362", "label": "362"} -{"code": "func (f *Fosite) WriteRevocationResponse(rw http.ResponseWriter, err error) {\n\trw.Header().Set(\"Cache-Control\", \"no-store\")\n\trw.Header().Set(\"Pragma\", \"no-cache\")\n\n\tif err == nil {\n\t\trw.WriteHeader(http.StatusOK)\n\t\treturn\n\t}\n\n\tif errors.Is(err, ErrInvalidRequest) {\n\t\trw.Header().Set(\"Content-Type\", \"application/json;charset=UTF-8\")\n\n\t\tjs, err := json.Marshal(ErrInvalidRequest)\n\t\tif err != nil {\n\t\t\thttp.Error(rw, fmt.Sprintf(`{\"error\": \"%s\"}`, err.Error()), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\trw.WriteHeader(ErrInvalidRequest.Code)\n\t\trw.Write(js)\n\t} else if errors.Is(err, ErrInvalidClient) {\n\t\trw.Header().Set(\"Content-Type\", \"application/json;charset=UTF-8\")\n\n\t\tjs, err := json.Marshal(ErrInvalidClient)\n\t\tif err != nil {\n\t\t\thttp.Error(rw, fmt.Sprintf(`{\"error\": \"%s\"}`, err.Error()), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\trw.WriteHeader(ErrInvalidClient.Code)\n\t\trw.Write(js)\n\t} else {\n\t\t// 200 OK\n\t\trw.WriteHeader(http.StatusOK)\n\t}\n}", "label_name": "CWE-755", "label": "755"} -{"code": "\tif rf, ok := ret.Get(0).(func(string, kube.ResourceKey, func(v1alpha1.ResourceNode, string)) error); ok {\n\t\tr0 = rf(server, key, action)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "label_name": "CWE-269", "label": "269"} -{"code": "func (svc *Service) MacadminsData(ctx context.Context, id uint) (*fleet.MacadminsData, error) {\n\tif !svc.authz.IsAuthenticatedWith(ctx, authz_ctx.AuthnDeviceToken) {\n\t\tif err := svc.authz.Authorize(ctx, &fleet.Host{}, fleet.ActionList); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\thost, err := svc.ds.HostLite(ctx, id)\n\t\tif err != nil {\n\t\t\treturn nil, ctxerr.Wrap(ctx, err, \"find host for macadmins\")\n\t\t}\n\n\t\tif err := svc.authz.Authorize(ctx, host, fleet.ActionRead); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tvar munkiInfo *fleet.HostMunkiInfo\n\tswitch version, err := svc.ds.GetMunkiVersion(ctx, id); {\n\tcase err != nil && !fleet.IsNotFound(err):\n\t\treturn nil, err\n\tcase err == nil:\n\t\tmunkiInfo = &fleet.HostMunkiInfo{Version: version}\n\t}\n\n\tvar mdm *fleet.HostMDM\n\tswitch enrolled, serverURL, installedFromDep, err := svc.ds.GetMDM(ctx, id); {\n\tcase err != nil && !fleet.IsNotFound(err):\n\t\treturn nil, err\n\tcase err == nil:\n\t\tenrollmentStatus := \"Unenrolled\"\n\t\tif enrolled && !installedFromDep {\n\t\t\tenrollmentStatus = \"Enrolled (manual)\"\n\t\t} else if enrolled && installedFromDep {\n\t\t\tenrollmentStatus = \"Enrolled (automated)\"\n\t\t}\n\t\tmdm = &fleet.HostMDM{\n\t\t\tEnrollmentStatus: enrollmentStatus,\n\t\t\tServerURL: serverURL,\n\t\t}\n\t}\n\n\tif munkiInfo == nil && mdm == nil {\n\t\treturn nil, nil\n\t}\n\n\tdata := &fleet.MacadminsData{\n\t\tMunki: munkiInfo,\n\t\tMDM: mdm,\n\t}\n\n\treturn data, nil\n}", "label_name": "CWE-863", "label": "863"} -{"code": "func (b *Builder) buildMetricsHTTPConnectionManagerFilter() (*envoy_config_listener_v3.Filter, error) {\n\trc, err := b.buildRouteConfiguration(\"metrics\", []*envoy_config_route_v3.VirtualHost{{\n\t\tName: \"metrics\",\n\t\tDomains: []string{\"*\"},\n\t\tRoutes: []*envoy_config_route_v3.Route{{\n\t\t\tName: \"metrics\",\n\t\t\tMatch: &envoy_config_route_v3.RouteMatch{\n\t\t\t\tPathSpecifier: &envoy_config_route_v3.RouteMatch_Prefix{Prefix: \"/\"},\n\t\t\t},\n\t\t\tAction: &envoy_config_route_v3.Route_Route{\n\t\t\t\tRoute: &envoy_config_route_v3.RouteAction{\n\t\t\t\t\tClusterSpecifier: &envoy_config_route_v3.RouteAction_Cluster{\n\t\t\t\t\t\tCluster: \"pomerium-control-plane-http\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}},\n\t}})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttc := marshalAny(&envoy_http_connection_manager.HttpConnectionManager{\n\t\tCodecType: envoy_http_connection_manager.HttpConnectionManager_AUTO,\n\t\tStatPrefix: \"metrics\",\n\t\tRouteSpecifier: &envoy_http_connection_manager.HttpConnectionManager_RouteConfig{\n\t\t\tRouteConfig: rc,\n\t\t},\n\t\tHttpFilters: []*envoy_http_connection_manager.HttpFilter{{\n\t\t\tName: \"envoy.filters.http.router\",\n\t\t}},\n\t})\n\n\treturn &envoy_config_listener_v3.Filter{\n\t\tName: \"envoy.filters.network.http_connection_manager\",\n\t\tConfigType: &envoy_config_listener_v3.Filter_TypedConfig{\n\t\t\tTypedConfig: tc,\n\t\t},\n\t}, nil\n}", "label_name": "CWE-200", "label": "200"} -{"code": "func (proj AppProject) IsLiveResourcePermitted(un *unstructured.Unstructured, server string, name string) bool {\n\tif !proj.IsGroupKindPermitted(un.GroupVersionKind().GroupKind(), un.GetNamespace() != \"\") {\n\t\treturn false\n\t}\n\tif un.GetNamespace() != \"\" {\n\t\treturn proj.IsDestinationPermitted(ApplicationDestination{Server: server, Namespace: un.GetNamespace(), Name: name})\n\t}\n\treturn true\n}", "label_name": "CWE-269", "label": "269"} -{"code": "func Skip(self Protocol, fieldType Type, maxDepth int) (err error) {\n\n\tif maxDepth <= 0 {\n\t\treturn NewProtocolExceptionWithType(DEPTH_LIMIT, errors.New(\"Depth limit exceeded\"))\n\t}\n\n\tswitch fieldType {\n\tcase STOP:\n\t\treturn\n\tcase BOOL:\n\t\t_, err = self.ReadBool()\n\t\treturn\n\tcase BYTE:\n\t\t_, err = self.ReadByte()\n\t\treturn\n\tcase I16:\n\t\t_, err = self.ReadI16()\n\t\treturn\n\tcase I32:\n\t\t_, err = self.ReadI32()\n\t\treturn\n\tcase I64:\n\t\t_, err = self.ReadI64()\n\t\treturn\n\tcase DOUBLE:\n\t\t_, err = self.ReadDouble()\n\t\treturn\n\tcase FLOAT:\n\t\t_, err = self.ReadFloat()\n\t\treturn\n\tcase STRING:\n\t\t_, err = self.ReadString()\n\t\treturn\n\tcase STRUCT:\n\t\tif _, err = self.ReadStructBegin(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor {\n\t\t\t_, typeId, _, _ := self.ReadFieldBegin()\n\t\t\tif typeId == STOP {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\terr := Skip(self, typeId, maxDepth-1)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tself.ReadFieldEnd()\n\t\t}\n\t\treturn self.ReadStructEnd()\n\tcase MAP:\n\t\tkeyType, valueType, size, err := self.ReadMapBegin()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor i := 0; i < size; i++ {\n\t\t\terr := Skip(self, keyType, maxDepth-1)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tself.Skip(valueType)\n\t\t}\n\t\treturn self.ReadMapEnd()\n\tcase SET:\n\t\telemType, size, err := self.ReadSetBegin()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor i := 0; i < size; i++ {\n\t\t\terr := Skip(self, elemType, maxDepth-1)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn self.ReadSetEnd()\n\tcase LIST:\n\t\telemType, size, err := self.ReadListBegin()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor i := 0; i < size; i++ {\n\t\t\terr := Skip(self, elemType, maxDepth-1)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn self.ReadListEnd()\n\t}\n\treturn nil\n}", "label_name": "CWE-755", "label": "755"} -{"code": "func (c *liveStateCache) IterateHierarchy(server string, key kube.ResourceKey, action func(child appv1.ResourceNode, appName string)) error {\n\tclusterInfo, err := c.getSyncedCluster(server)\n\tif err != nil {\n\t\treturn err\n\t}\n\tclusterInfo.IterateHierarchy(key, func(resource *clustercache.Resource, namespaceResources map[kube.ResourceKey]*clustercache.Resource) {\n\t\taction(asResourceNode(resource), getApp(resource, namespaceResources))\n\t})\n\treturn nil\n}", "label_name": "CWE-269", "label": "269"} -{"code": "func (svc *Service) DeleteUser(ctx context.Context, id uint) error {\n\tif err := svc.authz.Authorize(ctx, &fleet.User{ID: id}, fleet.ActionWrite); err != nil {\n\t\treturn err\n\t}\n\n\treturn svc.ds.DeleteUser(ctx, id)\n}", "label_name": "CWE-863", "label": "863"} -{"code": "func doesPolicySignatureV4Match(formValues http.Header) APIErrorCode {\n\t// Server region.\n\tregion := globalServerRegion\n\n\t// Parse credential tag.\n\tcredHeader, s3Err := parseCredentialHeader(\"Credential=\"+formValues.Get(xhttp.AmzCredential), region, serviceS3)\n\tif s3Err != ErrNone {\n\t\treturn s3Err\n\t}\n\n\tcred, _, s3Err := checkKeyValid(credHeader.accessKey)\n\tif s3Err != ErrNone {\n\t\treturn s3Err\n\t}\n\n\t// Get signing key.\n\tsigningKey := getSigningKey(cred.SecretKey, credHeader.scope.date, credHeader.scope.region, serviceS3)\n\n\t// Get signature.\n\tnewSignature := getSignature(signingKey, formValues.Get(\"Policy\"))\n\n\t// Verify signature.\n\tif !compareSignatureV4(newSignature, formValues.Get(xhttp.AmzSignature)) {\n\t\treturn ErrSignatureDoesNotMatch\n\t}\n\n\t// Success.\n\treturn ErrNone\n}", "label_name": "CWE-285", "label": "285"} -{"code": "func LoadAll(basedir string) ([]*Plugin, error) {\n\tplugins := []*Plugin{}\n\t// We want basedir/*/plugin.yaml\n\tscanpath := filepath.Join(basedir, \"*\", PluginFileName)\n\tmatches, err := filepath.Glob(scanpath)\n\tif err != nil {\n\t\treturn plugins, err\n\t}\n\n\tif matches == nil {\n\t\treturn plugins, nil\n\t}\n\n\tfor _, yaml := range matches {\n\t\tdir := filepath.Dir(yaml)\n\t\tp, err := LoadDir(dir)\n\t\tif err != nil {\n\t\t\treturn plugins, err\n\t\t}\n\t\tplugins = append(plugins, p)\n\t}\n\treturn plugins, nil\n}", "label_name": "CWE-74", "label": "74"} -{"code": "func (sys *IAMSys) CreateUser(ctx context.Context, accessKey string, uinfo madmin.UserInfo) error {\n\tif !sys.Initialized() {\n\t\treturn errServerNotInitialized\n\t}\n\n\tif sys.usersSysType != MinIOUsersSysType {\n\t\treturn errIAMActionNotAllowed\n\t}\n\n\tif !auth.IsAccessKeyValid(accessKey) {\n\t\treturn auth.ErrInvalidAccessKeyLength\n\t}\n\n\tif !auth.IsSecretKeyValid(uinfo.SecretKey) {\n\t\treturn auth.ErrInvalidSecretKeyLength\n\t}\n\n\terr := sys.store.AddUser(ctx, accessKey, uinfo)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsys.notifyForUser(ctx, accessKey, false)\n\treturn nil\n}", "label_name": "CWE-863", "label": "863"} -{"code": "func TestAddEvidenceFromConsensus(t *testing.T) {\n\tvar height int64 = 10\n\tpool, val := defaultTestPool(height)\n\tev := types.NewMockDuplicateVoteEvidenceWithValidator(height, defaultEvidenceTime, val, evidenceChainID)\n\n\trequire.NoError(t, pool.AddEvidenceFromConsensus(ev))\n\n\t// evidence from consensus should not be added immediately but reside in the consensus buffer\n\tevList, evSize := pool.PendingEvidence(defaultEvidenceMaxBytes)\n\trequire.Empty(t, evList)\n\trequire.Zero(t, evSize)\n\n\tnext := pool.EvidenceFront()\n\trequire.Nil(t, next)\n\n\t// move to next height and update state and evidence pool\n\tstate := pool.State()\n\tstate.LastBlockHeight++\n\tpool.Update(state, []types.Evidence{})\n\n\t// should be able to retrieve evidence from pool\n\tevList, _ = pool.PendingEvidence(defaultEvidenceMaxBytes)\n\trequire.Equal(t, []types.Evidence{ev}, evList)\n\n\t// shouldn't be able to submit the same evidence twice\n\trequire.NoError(t, pool.AddEvidenceFromConsensus(ev))\n\tstate = pool.State()\n\tstate.LastBlockHeight++\n\tpool.Update(state, []types.Evidence{})\n\tevList2, _ := pool.PendingEvidence(defaultEvidenceMaxBytes)\n\trequire.Equal(t, evList, evList2)\n}", "label_name": "CWE-400", "label": "400"} -{"code": "func (p *GatewayAPIProcessor) validateForwardTo(serviceName *string, port *gatewayapi_v1alpha1.PortNumber, namespace string) (*Service, error) {\n\t// Verify the service is valid\n\tif serviceName == nil {\n\t\treturn nil, fmt.Errorf(\"Spec.Rules.ForwardTo.ServiceName must be specified\")\n\t}\n\n\t// TODO: Do not require port to be present (#3352).\n\tif port == nil {\n\t\treturn nil, fmt.Errorf(\"Spec.Rules.ForwardTo.ServicePort must be specified\")\n\t}\n\n\tmeta := types.NamespacedName{Name: *serviceName, Namespace: namespace}\n\n\t// TODO: Refactor EnsureService to take an int32 so conversion to intstr is not needed.\n\tservice, err := p.dag.EnsureService(meta, intstr.FromInt(int(*port)), p.source)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"service %q does not exist\", meta.Name)\n\t}\n\n\treturn service, nil\n}", "label_name": "CWE-610", "label": "610"} -{"code": "func (svc Service) GetTeamScheduledQueries(ctx context.Context, teamID uint, opts fleet.ListOptions) ([]*fleet.ScheduledQuery, error) {\n\tif err := svc.authz.Authorize(ctx, &fleet.Pack{TeamIDs: []uint{teamID}}, fleet.ActionRead); err != nil {\n\t\treturn nil, err\n\t}\n\n\tgp, err := svc.ds.EnsureTeamPack(ctx, teamID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn svc.ds.ListScheduledQueriesInPackWithStats(ctx, gp.ID, opts)\n}", "label_name": "CWE-863", "label": "863"} -{"code": "func (f *ScmpFilter) addRuleWrapper(call ScmpSyscall, action ScmpAction, exact bool, cond C.scmp_cast_t) error {\n\tvar length C.uint\n\tif cond != nil {\n\t\tlength = 1\n\t} else {\n\t\tlength = 0\n\t}\n\n\tvar retCode C.int\n\tif exact {\n\t\tretCode = C.seccomp_rule_add_exact_array(f.filterCtx, action.toNative(), C.int(call), length, cond)\n\t} else {\n\t\tretCode = C.seccomp_rule_add_array(f.filterCtx, action.toNative(), C.int(call), length, cond)\n\t}\n\n\tif syscall.Errno(-1*retCode) == syscall.EFAULT {\n\t\treturn fmt.Errorf(\"unrecognized syscall\")\n\t} else if syscall.Errno(-1*retCode) == syscall.EPERM {\n\t\treturn fmt.Errorf(\"requested action matches default action of filter\")\n\t} else if retCode != 0 {\n\t\treturn syscall.Errno(-1 * retCode)\n\t}\n\n\treturn nil\n}", "label_name": "CWE-20", "label": "20"} -{"code": "func mountPropagate(m *configs.Mount, rootfs string, mountLabel string) error {\n\tvar (\n\t\tdest = m.Destination\n\t\tdata = label.FormatMountLabel(m.Data, mountLabel)\n\t\tflags = m.Flags\n\t)\n\tif libcontainerUtils.CleanPath(dest) == \"/dev\" {\n\t\tflags &= ^unix.MS_RDONLY\n\t}\n\n\t// Mount it rw to allow chmod operation. A remount will be performed\n\t// later to make it ro if set.\n\tif m.Device == \"tmpfs\" {\n\t\tflags &= ^unix.MS_RDONLY\n\t}\n\n\tcopyUp := m.Extensions&configs.EXT_COPYUP == configs.EXT_COPYUP\n\tif !(copyUp || strings.HasPrefix(dest, rootfs)) {\n\t\tdest = filepath.Join(rootfs, dest)\n\t}\n\n\tif err := unix.Mount(m.Source, dest, m.Device, uintptr(flags), data); err != nil {\n\t\treturn err\n\t}\n\n\tfor _, pflag := range m.PropagationFlags {\n\t\tif err := unix.Mount(\"\", dest, \"\", uintptr(pflag), \"\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "label_name": "CWE-362", "label": "362"} -{"code": "func (s *Service) handleMessage(stream StepStream, addr string, exp *certificateExpirationCheck) error {\n\trequest, err := stream.Recv()\n\tif err == io.EOF {\n\t\treturn err\n\t}\n\tif err != nil {\n\t\ts.Logger.Warningf(\"Stream read from %s failed: %v\", addr, err)\n\t\treturn err\n\t}\n\n\texp.checkExpiration(time.Now(), extractChannel(request))\n\n\tif s.StepLogger.IsEnabledFor(zap.DebugLevel) {\n\t\tnodeName := commonNameFromContext(stream.Context())\n\t\ts.StepLogger.Debugf(\"Received message from %s(%s): %v\", nodeName, addr, requestAsString(request))\n\t}\n\n\tif submitReq := request.GetSubmitRequest(); submitReq != nil {\n\t\tnodeName := commonNameFromContext(stream.Context())\n\t\ts.Logger.Debugf(\"Received message from %s(%s): %v\", nodeName, addr, requestAsString(request))\n\t\treturn s.handleSubmit(submitReq, stream, addr)\n\t}\n\n\t// Else, it's a consensus message.\n\treturn s.Dispatcher.DispatchConsensus(stream.Context(), request.GetConsensusRequest())\n}", "label_name": "CWE-20", "label": "20"} -{"code": "func (mgr *MetricsManager) updateServer(cfg *Config) {\n\tif cfg.Options.MetricsAddr == mgr.addr &&\n\t\tcfg.Options.MetricsBasicAuth == mgr.basicAuth &&\n\t\tcfg.Options.InstallationID == mgr.installationID {\n\t\treturn\n\t}\n\n\tmgr.addr = cfg.Options.MetricsAddr\n\tmgr.basicAuth = cfg.Options.MetricsBasicAuth\n\tmgr.installationID = cfg.Options.InstallationID\n\tmgr.handler = nil\n\n\tif mgr.addr == \"\" {\n\t\tlog.Info(context.TODO()).Msg(\"metrics: http server disabled\")\n\t\treturn\n\t}\n\n\thandler, err := metrics.PrometheusHandler(EnvoyAdminURL, mgr.installationID)\n\tif err != nil {\n\t\tlog.Error(context.TODO()).Err(err).Msg(\"metrics: failed to create prometheus handler\")\n\t\treturn\n\t}\n\n\tif username, password, ok := cfg.Options.GetMetricsBasicAuth(); ok {\n\t\thandler = middleware.RequireBasicAuth(username, password)(handler)\n\t}\n\n\tmgr.handler = handler\n}", "label_name": "CWE-200", "label": "200"} -{"code": "func TestDoesPolicySignatureMatch(t *testing.T) {\n\tcredentialTemplate := \"%s/%s/%s/s3/aws4_request\"\n\tnow := UTCNow()\n\taccessKey := globalActiveCred.AccessKey\n\n\ttestCases := []struct {\n\t\tform http.Header\n\t\texpected APIErrorCode\n\t}{\n\t\t// (0) It should fail if 'X-Amz-Credential' is missing.\n\t\t{\n\t\t\tform: http.Header{},\n\t\t\texpected: ErrCredMalformed,\n\t\t},\n\t\t// (1) It should fail if the access key is incorrect.\n\t\t{\n\t\t\tform: http.Header{\n\t\t\t\t\"X-Amz-Credential\": []string{fmt.Sprintf(credentialTemplate, \"EXAMPLEINVALIDEXAMPL\", now.Format(yyyymmdd), globalMinioDefaultRegion)},\n\t\t\t},\n\t\t\texpected: ErrInvalidAccessKeyID,\n\t\t},\n\t\t// (2) It should fail with a bad signature.\n\t\t{\n\t\t\tform: http.Header{\n\t\t\t\t\"X-Amz-Credential\": []string{fmt.Sprintf(credentialTemplate, accessKey, now.Format(yyyymmdd), globalMinioDefaultRegion)},\n\t\t\t\t\"X-Amz-Date\": []string{now.Format(iso8601Format)},\n\t\t\t\t\"X-Amz-Signature\": []string{\"invalidsignature\"},\n\t\t\t\t\"Policy\": []string{\"policy\"},\n\t\t\t},\n\t\t\texpected: ErrSignatureDoesNotMatch,\n\t\t},\n\t\t// (3) It should succeed if everything is correct.\n\t\t{\n\t\t\tform: http.Header{\n\t\t\t\t\"X-Amz-Credential\": []string{\n\t\t\t\t\tfmt.Sprintf(credentialTemplate, accessKey, now.Format(yyyymmdd), globalMinioDefaultRegion),\n\t\t\t\t},\n\t\t\t\t\"X-Amz-Date\": []string{now.Format(iso8601Format)},\n\t\t\t\t\"X-Amz-Signature\": []string{\n\t\t\t\t\tgetSignature(getSigningKey(globalActiveCred.SecretKey, now,\n\t\t\t\t\t\tglobalMinioDefaultRegion, serviceS3), \"policy\"),\n\t\t\t\t},\n\t\t\t\t\"Policy\": []string{\"policy\"},\n\t\t\t},\n\t\t\texpected: ErrNone,\n\t\t},\n\t}\n\n\t// Run each test case individually.\n\tfor i, testCase := range testCases {\n\t\tcode := doesPolicySignatureMatch(testCase.form)\n\t\tif code != testCase.expected {\n\t\t\tt.Errorf(\"(%d) expected to get %s, instead got %s\", i, niceError(testCase.expected), niceError(code))\n\t\t}\n\t}\n}", "label_name": "CWE-285", "label": "285"} -{"code": "func doesPolicySignatureMatch(formValues http.Header) APIErrorCode {\n\t// For SignV2 - Signature field will be valid\n\tif _, ok := formValues[\"Signature\"]; ok {\n\t\treturn doesPolicySignatureV2Match(formValues)\n\t}\n\treturn doesPolicySignatureV4Match(formValues)\n}", "label_name": "CWE-285", "label": "285"} -{"code": "func TestAuthorizeTeamPacks(t *testing.T) {\n\tt.Parallel()\n\n\trunTestCases(t, []authTestCase{\n\t\t// Team maintainer can read packs of the team.\n\t\t{\n\t\t\tuser: test.UserTeamMaintainerTeam1,\n\t\t\tobject: &fleet.Pack{\n\t\t\t\tTeamIDs: []uint{1},\n\t\t\t},\n\t\t\taction: read,\n\t\t\tallow: true,\n\t\t},\n\t\t// Team observer cannot read packs of the team.\n\t\t{\n\t\t\tuser: test.UserTeamObserverTeam1TeamAdminTeam2,\n\t\t\tobject: &fleet.Pack{\n\t\t\t\tTeamIDs: []uint{1},\n\t\t\t},\n\t\t\taction: read,\n\t\t\tallow: false,\n\t\t},\n\t\t// Team observer cannot write packs of the team.\n\t\t{\n\t\t\tuser: test.UserTeamObserverTeam1TeamAdminTeam2,\n\t\t\tobject: &fleet.Pack{\n\t\t\t\tTeamIDs: []uint{1},\n\t\t\t},\n\t\t\taction: write,\n\t\t\tallow: false,\n\t\t},\n\t\t// Members of a team cannot read packs of another team.\n\t\t{\n\t\t\tuser: test.UserTeamAdminTeam1,\n\t\t\tobject: &fleet.Pack{\n\t\t\t\tTeamIDs: []uint{2},\n\t\t\t},\n\t\t\taction: read,\n\t\t\tallow: false,\n\t\t},\n\t\t// Members of a team cannot read packs of another team.\n\t\t{\n\t\t\tuser: test.UserTeamAdminTeam1,\n\t\t\tobject: &fleet.Pack{\n\t\t\t\tTeamIDs: []uint{2},\n\t\t\t},\n\t\t\taction: read,\n\t\t\tallow: false,\n\t\t},\n\t\t// Team maintainers can read global packs.\n\t\t{\n\t\t\tuser: test.UserTeamMaintainerTeam1,\n\t\t\tobject: &fleet.Pack{},\n\t\t\taction: read,\n\t\t\tallow: true,\n\t\t},\n\t\t// Team admins can read global packs.\n\t\t{\n\t\t\tuser: test.UserTeamAdminTeam1,\n\t\t\tobject: &fleet.Pack{},\n\t\t\taction: read,\n\t\t\tallow: true,\n\t\t},\n\t\t// Team admins cannot write global packs.\n\t\t{\n\t\t\tuser: test.UserTeamAdminTeam1,\n\t\t\tobject: &fleet.Pack{},\n\t\t\taction: write,\n\t\t\tallow: false,\n\t\t},\n\t})\n}", "label_name": "CWE-863", "label": "863"} -{"code": "func (p *GitLabProvider) addProjectsToSession(ctx context.Context, s *sessions.SessionState) {\n\t// Iterate over projects, check if oauth2-proxy can get project information on behalf of the user\n\tfor _, project := range p.Projects {\n\t\tprojectInfo, err := p.getProjectInfo(ctx, s, project.Name)\n\n\t\tif err != nil {\n\t\t\tlogger.Errorf(\"Warning: project info request failed: %v\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tif !projectInfo.Archived {\n\t\t\tperms := projectInfo.Permissions.ProjectAccess\n\t\t\tif perms == nil {\n\t\t\t\t// use group project access as fallback\n\t\t\t\tperms = projectInfo.Permissions.GroupAccess\n\t\t\t\t// group project access is not set for this user then we give up\n\t\t\t\tif perms == nil {\n\t\t\t\t\tlogger.Errorf(\"Warning: user %q has no project level access to %s\", s.Email, project.Name)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif perms != nil && perms.AccessLevel >= project.AccessLevel {\n\t\t\t\ts.Groups = append(s.Groups, fmt.Sprintf(\"project:%s\", project.Name))\n\t\t\t} else {\n\t\t\t\tlogger.Errorf(\"Warning: user %q does not have the minimum required access level for project %q\", s.Email, project.Name)\n\t\t\t}\n\t\t} else {\n\t\t\tlogger.Errorf(\"Warning: project %s is archived\", project.Name)\n\t\t}\n\n\t}\n\n}", "label_name": "CWE-863", "label": "863"} -{"code": "func (f *Fosite) WriteAccessResponse(rw http.ResponseWriter, requester AccessRequester, responder AccessResponder) {\n\trw.Header().Set(\"Cache-Control\", \"no-store\")\n\trw.Header().Set(\"Pragma\", \"no-cache\")\n\n\tjs, err := json.Marshal(responder.ToMap())\n\tif err != nil {\n\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\trw.Header().Set(\"Content-Type\", \"application/json;charset=UTF-8\")\n\n\trw.WriteHeader(http.StatusOK)\n\trw.Write(js)\n}", "label_name": "CWE-755", "label": "755"} -{"code": "func (svc *Service) RefetchHost(ctx context.Context, id uint) error {\n\tif !svc.authz.IsAuthenticatedWith(ctx, authz_ctx.AuthnDeviceToken) {\n\t\tif err := svc.authz.Authorize(ctx, &fleet.Host{}, fleet.ActionList); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\thost, err := svc.ds.HostLite(ctx, id)\n\t\tif err != nil {\n\t\t\treturn ctxerr.Wrap(ctx, err, \"find host for refetch\")\n\t\t}\n\n\t\t// We verify fleet.ActionRead instead of fleet.ActionWrite because we want to allow\n\t\t// observers to be able to refetch hosts.\n\t\tif err := svc.authz.Authorize(ctx, host, fleet.ActionRead); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := svc.ds.UpdateHostRefetchRequested(ctx, id, true); err != nil {\n\t\treturn ctxerr.Wrap(ctx, err, \"save host\")\n\t}\n\n\treturn nil\n}", "label_name": "CWE-863", "label": "863"} -{"code": "func MkdirSecure(pth string) (err error) {\n\terr = os.MkdirAll(pth, 0755)\n\tif err != nil {\n\t\terr = &errortypes.WriteError{\n\t\t\terrors.Wrap(err, \"utils: Failed to create directory\"),\n\t\t}\n\t\treturn\n\t}\n\n\terr = acl.Apply(\n\t\tpth,\n\t\ttrue,\n\t\tfalse,\n\t\tacl.GrantName(windows.GENERIC_ALL, \"CREATOR OWNER\"),\n\t\tacl.GrantName(windows.GENERIC_ALL, \"SYSTEM\"),\n\t\tacl.GrantName(windows.GENERIC_ALL, \"Administrators\"),\n\t)\n\tif err != nil {\n\t\terr = &errortypes.WriteError{\n\t\t\terrors.Wrap(err, \"utils: Failed to acl directory\"),\n\t\t}\n\t\treturn\n\t}\n\n\treturn\n}", "label_name": "CWE-269", "label": "269"} -{"code": "func (evpool *Pool) CheckEvidence(evList types.EvidenceList) error {\n\thashes := make([][]byte, len(evList))\n\tfor idx, ev := range evList {\n\n\t\tok := evpool.fastCheck(ev)\n\n\t\tif !ok {\n\t\t\t// check that the evidence isn't already committed\n\t\t\tif evpool.isCommitted(ev) {\n\t\t\t\treturn &types.ErrInvalidEvidence{Evidence: ev, Reason: errors.New(\"evidence was already committed\")}\n\t\t\t}\n\n\t\t\terr := evpool.verify(ev)\n\t\t\tif err != nil {\n\t\t\t\treturn &types.ErrInvalidEvidence{Evidence: ev, Reason: err}\n\t\t\t}\n\n\t\t\tif err := evpool.addPendingEvidence(ev); err != nil {\n\t\t\t\t// Something went wrong with adding the evidence but we already know it is valid\n\t\t\t\t// hence we log an error and continue\n\t\t\t\tevpool.logger.Error(\"Can't add evidence to pending list\", \"err\", err, \"ev\", ev)\n\t\t\t}\n\n\t\t\tevpool.logger.Info(\"Verified new evidence of byzantine behavior\", \"evidence\", ev)\n\t\t}\n\n\t\t// check for duplicate evidence. We cache hashes so we don't have to work them out again.\n\t\thashes[idx] = ev.Hash()\n\t\tfor i := idx - 1; i >= 0; i-- {\n\t\t\tif bytes.Equal(hashes[i], hashes[idx]) {\n\t\t\t\treturn &types.ErrInvalidEvidence{Evidence: ev, Reason: errors.New(\"duplicate evidence\")}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "label_name": "CWE-400", "label": "400"} -{"code": " getReturnAddressWithDisplayName(identityId) {\n check(identityId, String);\n const identity = this.getIdentity(identityId);\n const displayName = identity.profile.name + \" (via \" + this.getServerTitle() + \")\";\n\n // First remove any instances of characters that cause trouble for SimpleSmtp. Ideally,\n // we could escape such characters with a backslash, but that does not seem to help here.\n const sanitized = displayName.replace(/\"|<|>|\\\\|\\r/g, \"\");\n\n return \"\\\"\" + sanitized + \"\\\" <\" + this.getReturnAddress() + \">\";\n },", "label_name": "CWE-287", "label": "287"} -{"code": "func (i *IDTokenHandleHelper) GetAccessTokenHash(ctx context.Context, requester fosite.AccessRequester, responder fosite.AccessResponder) string {\n\ttoken := responder.GetAccessToken()\n\n\tbuffer := bytes.NewBufferString(token)\n\thash := sha256.New()\n\thash.Write(buffer.Bytes())\n\thashBuf := bytes.NewBuffer(hash.Sum([]byte{}))\n\tlen := hashBuf.Len()\n\n\treturn base64.RawURLEncoding.EncodeToString(hashBuf.Bytes()[:len/2])\n}", "label_name": "CWE-755", "label": "755"} -{"code": "func (svc Service) DeleteTeamScheduledQueries(ctx context.Context, teamID uint, scheduledQueryID uint) error {\n\tif err := svc.authz.Authorize(ctx, &fleet.Pack{TeamIDs: []uint{teamID}}, fleet.ActionWrite); err != nil {\n\t\treturn err\n\t}\n\treturn svc.ds.DeleteScheduledQuery(ctx, scheduledQueryID)\n}", "label_name": "CWE-863", "label": "863"} -{"code": "func (c *linuxContainer) prepareCriuRestoreMounts(mounts []*configs.Mount) error {\n\t// First get a list of a all tmpfs mounts\n\ttmpfs := []string{}\n\tfor _, m := range mounts {\n\t\tswitch m.Device {\n\t\tcase \"tmpfs\":\n\t\t\ttmpfs = append(tmpfs, m.Destination)\n\t\t}\n\t}\n\t// Now go through all mounts and create the mountpoints\n\t// if the mountpoints are not on a tmpfs, as CRIU will\n\t// restore the complete tmpfs content from its checkpoint.\n\tumounts := []string{}\n\tdefer func() {\n\t\tfor _, u := range umounts {\n\t\t\tif e := unix.Unmount(u, unix.MNT_DETACH); e != nil {\n\t\t\t\tif e != unix.EINVAL {\n\t\t\t\t\t// Ignore EINVAL as it means 'target is not a mount point.'\n\t\t\t\t\t// It probably has already been unmounted.\n\t\t\t\t\tlogrus.Warnf(\"Error during cleanup unmounting of %q (%v)\", u, e)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\tfor _, m := range mounts {\n\t\tif !isPathInPrefixList(m.Destination, tmpfs) {\n\t\t\tif err := c.makeCriuRestoreMountpoints(m); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// If the mount point is a bind mount, we need to mount\n\t\t\t// it now so that runc can create the necessary mount\n\t\t\t// points for mounts in bind mounts.\n\t\t\t// This also happens during initial container creation.\n\t\t\t// Without this CRIU restore will fail\n\t\t\t// See: https://github.com/opencontainers/runc/issues/2748\n\t\t\t// It is also not necessary to order the mount points\n\t\t\t// because during initial container creation mounts are\n\t\t\t// set up in the order they are configured.\n\t\t\tif m.Device == \"bind\" {\n\t\t\t\tif err := unix.Mount(m.Source, m.Destination, \"\", unix.MS_BIND|unix.MS_REC, \"\"); err != nil {\n\t\t\t\t\treturn errorsf.Wrapf(err, \"unable to bind mount %q to %q\", m.Source, m.Destination)\n\t\t\t\t}\n\t\t\t\tumounts = append(umounts, m.Destination)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "label_name": "CWE-362", "label": "362"} -{"code": "func (a *AuthenticatorOAuth2Introspection) tokenFromCache(config *AuthenticatorOAuth2IntrospectionConfiguration, token string) (*AuthenticatorOAuth2IntrospectionResult, bool) {\n\tif !config.Cache.Enabled {\n\t\treturn nil, false\n\t}\n\n\titem, found := a.tokenCache.Get(token)\n\tif !found {\n\t\treturn nil, false\n\t}\n\n\ti := item.(*AuthenticatorOAuth2IntrospectionResult)\n\texpires := time.Unix(i.Expires, 0)\n\tif expires.Before(time.Now()) {\n\t\ta.tokenCache.Del(token)\n\t\treturn nil, false\n\t}\n\n\treturn i, true\n}", "label_name": "CWE-863", "label": "863"} -{"code": "func mountCgroupV2(m *configs.Mount, c *mountConfig) error {\n\tdest, err := securejoin.SecureJoin(c.root, m.Destination)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := os.MkdirAll(dest, 0755); err != nil {\n\t\treturn err\n\t}\n\tif err := unix.Mount(m.Source, dest, \"cgroup2\", uintptr(m.Flags), m.Data); err != nil {\n\t\t// when we are in UserNS but CgroupNS is not unshared, we cannot mount cgroup2 (#2158)\n\t\tif err == unix.EPERM || err == unix.EBUSY {\n\t\t\tsrc := fs2.UnifiedMountpoint\n\t\t\tif c.cgroupns && c.cgroup2Path != \"\" {\n\t\t\t\t// Emulate cgroupns by bind-mounting\n\t\t\t\t// the container cgroup path rather than\n\t\t\t\t// the whole /sys/fs/cgroup.\n\t\t\t\tsrc = c.cgroup2Path\n\t\t\t}\n\t\t\terr = unix.Mount(src, dest, \"\", uintptr(m.Flags)|unix.MS_BIND, \"\")\n\t\t\tif err == unix.ENOENT && c.rootlessCgroups {\n\t\t\t\terr = nil\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}", "label_name": "CWE-362", "label": "362"} -{"code": "func (b *Builder) buildControlPlanePrefixRoute(prefix string, protected bool) (*envoy_config_route_v3.Route, error) {\n\tr := &envoy_config_route_v3.Route{\n\t\tName: \"pomerium-prefix-\" + prefix,\n\t\tMatch: &envoy_config_route_v3.RouteMatch{\n\t\t\tPathSpecifier: &envoy_config_route_v3.RouteMatch_Prefix{Prefix: prefix},\n\t\t},\n\t\tAction: &envoy_config_route_v3.Route_Route{\n\t\t\tRoute: &envoy_config_route_v3.RouteAction{\n\t\t\t\tClusterSpecifier: &envoy_config_route_v3.RouteAction_Cluster{\n\t\t\t\t\tCluster: httpCluster,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tif !protected {\n\t\tr.TypedPerFilterConfig = map[string]*any.Any{\n\t\t\t\"envoy.filters.http.ext_authz\": disableExtAuthz,\n\t\t}\n\t}\n\treturn r, nil\n}", "label_name": "CWE-200", "label": "200"} -{"code": "func (evpool *Pool) flushConsensusBuffer() {\n\tfor _, ev := range evpool.consensusBuffer {\n\t\tif err := evpool.addPendingEvidence(ev); err != nil {\n\t\t\tevpool.logger.Error(\"failed to flush evidence from consensus buffer to pending list: %w\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tevpool.evidenceList.PushBack(ev)\n\t}\n\t// reset consensus buffer\n\tevpool.consensusBuffer = make([]types.Evidence, 0)\n}", "label_name": "CWE-400", "label": "400"} -{"code": "func TestAddDebug(t *testing.T) {\n\terr := ErrRevocationClientMismatch.WithDebug(\"debug\")\n\tassert.NotEqual(t, err, ErrRevocationClientMismatch)\n\tassert.Empty(t, ErrRevocationClientMismatch.Debug)\n\tassert.NotEmpty(t, err.Debug)\n}", "label_name": "CWE-755", "label": "755"} -{"code": "func InitGenesis(\n\tctx sdk.Context,\n\tk keeper.Keeper,\n\tak types.AccountKeeper,\n\tsk types.StakingKeeper,\n\tdata types.GenesisState,\n) {\n\t// Ensure inflation module account is set on genesis\n\tif acc := ak.GetModuleAccount(ctx, types.ModuleName); acc == nil {\n\t\tpanic(\"the inflation module account has not been set\")\n\t}\n\n\t// Set genesis state\n\tparams := data.Params\n\tk.SetParams(ctx, params)\n\n\tperiod := data.Period\n\tk.SetPeriod(ctx, period)\n\n\tepochIdentifier := data.EpochIdentifier\n\tk.SetEpochIdentifier(ctx, epochIdentifier)\n\n\tepochsPerPeriod := data.EpochsPerPeriod\n\tk.SetEpochsPerPeriod(ctx, epochsPerPeriod)\n\n\t// Get bondedRatio\n\tbondedRatio := sk.BondedRatio(ctx)\n\n\t// Calculate epoch mint provision\n\tepochMintProvision := types.CalculateEpochMintProvision(\n\t\tparams,\n\t\tperiod,\n\t\tepochsPerPeriod,\n\t\tbondedRatio,\n\t)\n\tk.SetEpochMintProvision(ctx, epochMintProvision)\n}", "label_name": "CWE-287", "label": "287"} -{"code": "func TestCheckValid(t *testing.T) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\tobjLayer, fsDir, err := prepareFS()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(fsDir)\n\tif err = newTestConfig(globalMinioDefaultRegion, objLayer); err != nil {\n\t\tt.Fatalf(\"unable initialize config file, %s\", err)\n\t}\n\n\tnewAllSubsystems()\n\n\tinitConfigSubsystem(ctx, objLayer)\n\n\tglobalIAMSys.Init(ctx, objLayer, globalEtcdClient, globalNotificationSys, 2*time.Second)\n\n\treq, err := newTestRequest(http.MethodGet, \"http://example.com:9000/bucket/object\", 0, nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif err = signRequestV4(req, globalActiveCred.AccessKey, globalActiveCred.SecretKey); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t_, owner, s3Err := checkKeyValid(req, globalActiveCred.AccessKey)\n\tif s3Err != ErrNone {\n\t\tt.Fatalf(\"Unexpected failure with %v\", errorCodes.ToAPIErr(s3Err))\n\t}\n\n\tif !owner {\n\t\tt.Fatalf(\"Expected owner to be 'true', found %t\", owner)\n\t}\n\n\t_, _, s3Err = checkKeyValid(req, \"does-not-exist\")\n\tif s3Err != ErrInvalidAccessKeyID {\n\t\tt.Fatalf(\"Expected error 'ErrInvalidAccessKeyID', found %v\", s3Err)\n\t}\n\n\tucreds, err := auth.CreateCredentials(\"myuser1\", \"mypassword1\")\n\tif err != nil {\n\t\tt.Fatalf(\"unable create credential, %s\", err)\n\t}\n\n\tglobalIAMSys.CreateUser(ctx, ucreds.AccessKey, madmin.UserInfo{\n\t\tSecretKey: ucreds.SecretKey,\n\t\tStatus: madmin.AccountEnabled,\n\t})\n\n\t_, owner, s3Err = checkKeyValid(req, ucreds.AccessKey)\n\tif s3Err != ErrNone {\n\t\tt.Fatalf(\"Unexpected failure with %v\", errorCodes.ToAPIErr(s3Err))\n\t}\n\n\tif owner {\n\t\tt.Fatalf(\"Expected owner to be 'false', found %t\", owner)\n\t}\n}", "label_name": "CWE-863", "label": "863"} -{"code": "func (cs *State) tryAddVote(vote *types.Vote, peerID p2p.ID) (bool, error) {\n\tadded, err := cs.addVote(vote, peerID)\n\tif err != nil {\n\t\t// If the vote height is off, we'll just ignore it,\n\t\t// But if it's a conflicting sig, add it to the cs.evpool.\n\t\t// If it's otherwise invalid, punish peer.\n\t\t// nolint: gocritic\n\t\tif voteErr, ok := err.(*types.ErrVoteConflictingVotes); ok {\n\t\t\tif cs.privValidatorPubKey == nil {\n\t\t\t\treturn false, errPubKeyIsNotSet\n\t\t\t}\n\n\t\t\tif bytes.Equal(vote.ValidatorAddress, cs.privValidatorPubKey.Address()) {\n\t\t\t\tcs.Logger.Error(\n\t\t\t\t\t\"Found conflicting vote from ourselves. Did you unsafe_reset a validator?\",\n\t\t\t\t\t\"height\",\n\t\t\t\t\tvote.Height,\n\t\t\t\t\t\"round\",\n\t\t\t\t\tvote.Round,\n\t\t\t\t\t\"type\",\n\t\t\t\t\tvote.Type)\n\t\t\t\treturn added, err\n\t\t\t}\n\t\t\tvar timestamp time.Time\n\t\t\tif voteErr.VoteA.Height == cs.state.InitialHeight {\n\t\t\t\ttimestamp = cs.state.LastBlockTime // genesis time\n\t\t\t} else {\n\t\t\t\ttimestamp = sm.MedianTime(cs.LastCommit.MakeCommit(), cs.LastValidators)\n\t\t\t}\n\t\t\t// form duplicate vote evidence from the conflicting votes and send it across to the\n\t\t\t// evidence pool\n\t\t\tev := types.NewDuplicateVoteEvidence(voteErr.VoteA, voteErr.VoteB, timestamp, cs.Validators)\n\t\t\tevidenceErr := cs.evpool.AddEvidenceFromConsensus(ev)\n\t\t\tif evidenceErr != nil {\n\t\t\t\tcs.Logger.Error(\"Failed to add evidence to the evidence pool\", \"err\", evidenceErr)\n\t\t\t} else {\n\t\t\t\tcs.Logger.Debug(\"Added evidence to the evidence pool\", \"ev\", ev)\n\t\t\t}\n\t\t\treturn added, err\n\t\t} else if err == types.ErrVoteNonDeterministicSignature {\n\t\t\tcs.Logger.Debug(\"Vote has non-deterministic signature\", \"err\", err)\n\t\t} else {\n\t\t\t// Either\n\t\t\t// 1) bad peer OR\n\t\t\t// 2) not a bad peer? this can also err sometimes with \"Unexpected step\" OR\n\t\t\t// 3) tmkms use with multiple validators connecting to a single tmkms instance\n\t\t\t// \t\t(https://github.com/tendermint/tendermint/issues/3839).\n\t\t\tcs.Logger.Info(\"Error attempting to add vote\", \"err\", err)\n\t\t\treturn added, ErrAddingVote\n\t\t}\n\t}\n\treturn added, nil\n}", "label_name": "CWE-400", "label": "400"} -{"code": "func (evpool *Pool) AddEvidenceFromConsensus(ev types.Evidence) error {\n\n\t// we already have this evidence, log this but don't return an error.\n\tif evpool.isPending(ev) {\n\t\tevpool.logger.Info(\"Evidence already pending, ignoring this one\", \"ev\", ev)\n\t\treturn nil\n\t}\n\n\t// add evidence to a buffer which will pass the evidence to the pool at the following height.\n\t// This avoids the issue of some nodes verifying and proposing evidence at a height where the\n\t// block hasn't been committed on cause others to potentially fail.\n\tevpool.mtx.Lock()\n\tdefer evpool.mtx.Unlock()\n\tevpool.consensusBuffer = append(evpool.consensusBuffer, ev)\n\tevpool.logger.Info(\"received new evidence of byzantine behavior from consensus\", \"evidence\", ev)\n\n\treturn nil\n}", "label_name": "CWE-400", "label": "400"} -{"code": "func (EmptyEvidencePool) Update(State, types.EvidenceList) {}", "label_name": "CWE-400", "label": "400"} -{"code": "func (b *Builder) buildControlPlanePathRoute(path string, protected bool) (*envoy_config_route_v3.Route, error) {\n\tr := &envoy_config_route_v3.Route{\n\t\tName: \"pomerium-path-\" + path,\n\t\tMatch: &envoy_config_route_v3.RouteMatch{\n\t\t\tPathSpecifier: &envoy_config_route_v3.RouteMatch_Path{Path: path},\n\t\t},\n\t\tAction: &envoy_config_route_v3.Route_Route{\n\t\t\tRoute: &envoy_config_route_v3.RouteAction{\n\t\t\t\tClusterSpecifier: &envoy_config_route_v3.RouteAction_Cluster{\n\t\t\t\t\tCluster: httpCluster,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tif !protected {\n\t\tr.TypedPerFilterConfig = map[string]*any.Any{\n\t\t\t\"envoy.filters.http.ext_authz\": disableExtAuthz,\n\t\t}\n\t}\n\treturn r, nil\n}", "label_name": "CWE-200", "label": "200"} -{"code": "func (app *Configurable) Encrypt(parameters map[string]string) interfaces.AppFunction {\n\talgorithm, ok := parameters[Algorithm]\n\tif !ok {\n\t\tapp.lc.Errorf(\"Could not find '%s' parameter for Encrypt\", Algorithm)\n\t\treturn nil\n\t}\n\n\tsecretPath := parameters[SecretPath]\n\tsecretName := parameters[SecretName]\n\tencryptionKey := parameters[EncryptionKey]\n\n\t// SecretPath & SecretName are optional if EncryptionKey specified\n\t// EncryptionKey is optional if SecretPath & SecretName are specified\n\n\t// If EncryptionKey not specified, then SecretPath & SecretName must be specified\n\tif len(encryptionKey) == 0 && (len(secretPath) == 0 || len(secretName) == 0) {\n\t\tapp.lc.Errorf(\"Could not find '%s' or '%s' and '%s' in configuration\", EncryptionKey, SecretPath, SecretName)\n\t\treturn nil\n\t}\n\n\t// SecretPath & SecretName both must be specified it one of them is.\n\tif (len(secretPath) != 0 && len(secretName) == 0) || (len(secretPath) == 0 && len(secretName) != 0) {\n\t\tapp.lc.Errorf(\"'%s' and '%s' both must be set in configuration\", SecretPath, SecretName)\n\t\treturn nil\n\t}\n\n\tinitVector, ok := parameters[InitVector]\n\tif !ok {\n\t\tapp.lc.Error(\"Could not find \" + InitVector)\n\t\treturn nil\n\t}\n\n\ttransform := transforms.Encryption{\n\t\tEncryptionKey: encryptionKey,\n\t\tInitializationVector: initVector,\n\t\tSecretPath: secretPath,\n\t\tSecretName: secretName,\n\t}\n\n\tswitch strings.ToLower(algorithm) {\n\tcase EncryptAES:\n\t\treturn transform.EncryptWithAES\n\tdefault:\n\t\tapp.lc.Errorf(\n\t\t\t\"Invalid encryption algorithm '%s'. Must be '%s'\",\n\t\t\talgorithm,\n\t\t\tEncryptAES)\n\t\treturn nil\n\t}\n}", "label_name": "CWE-327", "label": "327"} -{"code": "func (evpool *Pool) removePendingEvidence(evidence types.Evidence) {\n\tkey := keyPending(evidence)\n\tif err := evpool.evidenceStore.Delete(key); err != nil {\n\t\tevpool.logger.Error(\"Unable to delete pending evidence\", \"err\", err)\n\t} else {\n\t\tatomic.AddUint32(&evpool.evidenceSize, ^uint32(0))\n\t\tevpool.logger.Info(\"Deleted pending evidence\", \"evidence\", evidence)\n\t}\n}", "label_name": "CWE-400", "label": "400"} -{"code": "func mountCgroupV1(m *configs.Mount, c *mountConfig) error {\n\tbinds, err := getCgroupMounts(m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar merged []string\n\tfor _, b := range binds {\n\t\tss := filepath.Base(b.Destination)\n\t\tif strings.Contains(ss, \",\") {\n\t\t\tmerged = append(merged, ss)\n\t\t}\n\t}\n\ttmpfs := &configs.Mount{\n\t\tSource: \"tmpfs\",\n\t\tDevice: \"tmpfs\",\n\t\tDestination: m.Destination,\n\t\tFlags: defaultMountFlags,\n\t\tData: \"mode=755\",\n\t\tPropagationFlags: m.PropagationFlags,\n\t}\n\tif err := mountToRootfs(tmpfs, c); err != nil {\n\t\treturn err\n\t}\n\tfor _, b := range binds {\n\t\tif c.cgroupns {\n\t\t\tsubsystemPath := filepath.Join(c.root, b.Destination)\n\t\t\tif err := os.MkdirAll(subsystemPath, 0755); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tflags := defaultMountFlags\n\t\t\tif m.Flags&unix.MS_RDONLY != 0 {\n\t\t\t\tflags = flags | unix.MS_RDONLY\n\t\t\t}\n\t\t\tcgroupmount := &configs.Mount{\n\t\t\t\tSource: \"cgroup\",\n\t\t\t\tDevice: \"cgroup\", // this is actually fstype\n\t\t\t\tDestination: subsystemPath,\n\t\t\t\tFlags: flags,\n\t\t\t\tData: filepath.Base(subsystemPath),\n\t\t\t}\n\t\t\tif err := mountNewCgroup(cgroupmount); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tif err := mountToRootfs(b, c); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\tfor _, mc := range merged {\n\t\tfor _, ss := range strings.Split(mc, \",\") {\n\t\t\t// symlink(2) is very dumb, it will just shove the path into\n\t\t\t// the link and doesn't do any checks or relative path\n\t\t\t// conversion. Also, don't error out if the cgroup already exists.\n\t\t\tif err := os.Symlink(mc, filepath.Join(c.root, m.Destination, ss)); err != nil && !os.IsExist(err) {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "label_name": "CWE-362", "label": "362"} -{"code": "func (svc *Service) ModifyGlobalScheduledQueries(ctx context.Context, id uint, query fleet.ScheduledQueryPayload) (*fleet.ScheduledQuery, error) {\n\tif err := svc.authz.Authorize(ctx, &fleet.Pack{}, fleet.ActionWrite); err != nil {\n\t\treturn nil, err\n\t}\n\n\tgp, err := svc.ds.EnsureGlobalPack(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tquery.PackID = ptr.Uint(gp.ID)\n\n\treturn svc.ModifyScheduledQuery(ctx, id, query)\n}", "label_name": "CWE-863", "label": "863"} -{"code": "func getClaimsFromToken(r *http.Request, token string) (map[string]interface{}, error) {", "label_name": "CWE-285", "label": "285"} -{"code": "func (svc *Service) GlobalScheduleQuery(ctx context.Context, sq *fleet.ScheduledQuery) (*fleet.ScheduledQuery, error) {\n\tif err := svc.authz.Authorize(ctx, &fleet.Pack{}, fleet.ActionRead); err != nil {\n\t\treturn nil, err\n\t}\n\n\tgp, err := svc.ds.EnsureGlobalPack(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsq.PackID = gp.ID\n\n\treturn svc.ScheduleQuery(ctx, sq)\n}", "label_name": "CWE-863", "label": "863"} -{"code": "func TestBuilder_BuildBootstrapStaticResources(t *testing.T) {\n\tt.Run(\"valid\", func(t *testing.T) {\n\t\tb := New(\"localhost:1111\", \"localhost:2222\", filemgr.NewManager(), nil)\n\t\tstaticCfg, err := b.BuildBootstrapStaticResources()\n\t\tassert.NoError(t, err)\n\t\ttestutil.AssertProtoJSONEqual(t, `\n\t\t\t{\n\t\t\t\t\"clusters\": [\n\t\t\t\t\t{\n\t\t\t\t\t\t\"name\": \"pomerium-control-plane-grpc\",\n\t\t\t\t\t\t\"type\": \"STATIC\",\n\t\t\t\t\t\t\"connectTimeout\": \"5s\",\n\t\t\t\t\t\t\"http2ProtocolOptions\": {},\n\t\t\t\t\t\t\"loadAssignment\": {\n\t\t\t\t\t\t\t\"clusterName\": \"pomerium-control-plane-grpc\",\n\t\t\t\t\t\t\t\"endpoints\": [{\n\t\t\t\t\t\t\t\t\"lbEndpoints\": [{\n\t\t\t\t\t\t\t\t\t\"endpoint\": {\n\t\t\t\t\t\t\t\t\t\t\"address\": {\n\t\t\t\t\t\t\t\t\t\t\t\"socketAddress\":{\n\t\t\t\t\t\t\t\t\t\t\t\t\"address\": \"127.0.0.1\",\n\t\t\t\t\t\t\t\t\t\t\t\t\"portValue\": 1111\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}]\n\t\t\t\t\t\t\t}]\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t}\n\t\t`, staticCfg)\n\t})\n\tt.Run(\"bad gRPC address\", func(t *testing.T) {\n\t\tb := New(\"xyz:zyx\", \"localhost:2222\", filemgr.NewManager(), nil)\n\t\t_, err := b.BuildBootstrapStaticResources()\n\t\tassert.Error(t, err)\n\t})\n}", "label_name": "CWE-200", "label": "200"} -{"code": "func NewPool(evidenceDB dbm.DB, stateDB sm.Store, blockStore BlockStore) (*Pool, error) {\n\n\tstate, err := stateDB.Load()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot load state: %w\", err)\n\t}\n\n\tpool := &Pool{\n\t\tstateDB: stateDB,\n\t\tblockStore: blockStore,\n\t\tstate: state,\n\t\tlogger: log.NewNopLogger(),\n\t\tevidenceStore: evidenceDB,\n\t\tevidenceList: clist.New(),\n\t\tconsensusBuffer: make([]types.Evidence, 0),\n\t}\n\n\t// if pending evidence already in db, in event of prior failure, then check for expiration,\n\t// update the size and load it back to the evidenceList\n\tpool.pruningHeight, pool.pruningTime = pool.removeExpiredPendingEvidence()\n\tevList, _, err := pool.listEvidence(baseKeyPending, -1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tatomic.StoreUint32(&pool.evidenceSize, uint32(len(evList)))\n\tfor _, ev := range evList {\n\t\tpool.evidenceList.PushBack(ev)\n\t}\n\n\treturn pool, nil\n}", "label_name": "CWE-400", "label": "400"} -{"code": "func TestListActivities(t *testing.T) {\n\tds := new(mock.Store)\n\tsvc := newTestService(t, ds, nil, nil)\n\n\tds.ListActivitiesFunc = func(ctx context.Context, opts fleet.ListOptions) ([]*fleet.Activity, error) {\n\t\treturn []*fleet.Activity{\n\t\t\t{ID: 1},\n\t\t\t{ID: 2},\n\t\t}, nil\n\t}\n\n\t// admin user\n\tactivities, err := svc.ListActivities(test.UserContext(test.UserAdmin), fleet.ListOptions{})\n\trequire.NoError(t, err)\n\trequire.Len(t, activities, 2)\n\n\t// anyone can read activities\n\tactivities, err = svc.ListActivities(test.UserContext(test.UserNoRoles), fleet.ListOptions{})\n\trequire.NoError(t, err)\n\trequire.Len(t, activities, 2)\n\n\t// no user in context\n\t_, err = svc.ListActivities(context.Background(), fleet.ListOptions{})\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), authz.ForbiddenErrorMessage)\n}", "label_name": "CWE-863", "label": "863"} -{"code": "func Handler(configFns ...func(*Config)) http.HandlerFunc {\n\tvar once sync.Once\n\n\tconfig := &Config{\n\t\tURL: \"doc.json\",\n\t\tDeepLinking: true,\n\t\tDocExpansion: \"list\",\n\t\tDomID: \"#swagger-ui\",\n\t}\n\tfor _, configFn := range configFns {\n\t\tconfigFn(config)\n\t}\n\n\t// create a template with name\n\tt := template.New(\"swagger_index.html\")\n\tindex, _ := t.Parse(indexTempl)\n\n\tvar re = regexp.MustCompile(`^(.*/)([^?].*)?[?|.]*$`)\n\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tmatches := re.FindStringSubmatch(r.RequestURI)\n\t\tpath := matches[2]\n\n\t\th := swaggerFiles.Handler\n\t\tonce.Do(func() {\n\t\t\th.Prefix = matches[1]\n\t\t})\n\n\t\tswitch filepath.Ext(path) {\n\t\tcase \".html\":\n\t\t\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\t\tcase \".css\":\n\t\t\tw.Header().Set(\"Content-Type\", \"text/css; charset=utf-8\")\n\t\tcase \".js\":\n\t\t\tw.Header().Set(\"Content-Type\", \"application/javascript\")\n\t\tcase \".png\":\n\t\t\tw.Header().Set(\"Content-Type\", \"image/png\")\n\t\tcase \".json\":\n\t\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\t\t}\n\n\t\tswitch path {\n\t\tcase \"index.html\":\n\t\t\t_ = index.Execute(w, config)\n\t\tcase \"doc.json\":\n\t\t\tdoc, err := swag.ReadDoc()\n\t\t\tif err != nil {\n\t\t\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\n\t\t\t\treturn\n\t\t\t}\n\t\t\t_, _ = w.Write([]byte(doc))\n\t\tcase \"\":\n\t\t\thttp.Redirect(w, r, h.Prefix+\"index.html\", 301)\n\t\tdefault:\n\t\t\th.ServeHTTP(w, r)\n\t\t}\n\t}\n}", "label_name": "CWE-755", "label": "755"} -{"code": "func NewGrant(a Authorization, expiration time.Time) (Grant, error) {\n\tg := Grant{\n\t\tExpiration: expiration,\n\t}\n\tmsg, ok := a.(proto.Message)\n\tif !ok {\n\t\treturn Grant{}, sdkerrors.Wrapf(sdkerrors.ErrPackAny, \"cannot proto marshal %T\", a)\n\t}\n\n\tany, err := cdctypes.NewAnyWithValue(msg)\n\tif err != nil {\n\t\treturn Grant{}, err\n\t}\n\tg.Authorization = any\n\n\treturn g, nil\n}", "label_name": "CWE-754", "label": "754"} -{"code": "func (EmptyEvidencePool) AddEvidenceFromConsensus(evidence types.Evidence) error {\n\treturn nil\n}", "label_name": "CWE-400", "label": "400"} -{"code": "func Test_bindConfig(t *testing.T) {\n\tctx, clearTimeout := context.WithTimeout(context.Background(), time.Second*10)\n\tdefer clearTimeout()\n\n\tb := New(\"local-grpc\", \"local-http\", filemgr.NewManager(), nil)\n\tt.Run(\"no bind config\", func(t *testing.T) {\n\t\tcluster, err := b.buildPolicyCluster(ctx, &config.Options{}, &config.Policy{\n\t\t\tFrom: \"https://from.example.com\",\n\t\t\tTo: mustParseWeightedURLs(t, \"https://to.example.com\"),\n\t\t})\n\t\tassert.NoError(t, err)\n\t\tassert.Nil(t, cluster.UpstreamBindConfig)\n\t})\n\tt.Run(\"freebind\", func(t *testing.T) {\n\t\tcluster, err := b.buildPolicyCluster(ctx, &config.Options{\n\t\t\tEnvoyBindConfigFreebind: null.BoolFrom(true),\n\t\t}, &config.Policy{\n\t\t\tFrom: \"https://from.example.com\",\n\t\t\tTo: mustParseWeightedURLs(t, \"https://to.example.com\"),\n\t\t})\n\t\tassert.NoError(t, err)\n\t\ttestutil.AssertProtoJSONEqual(t, `\n\t\t\t{\n\t\t\t\t\"freebind\": true,\n\t\t\t\t\"sourceAddress\": {\n\t\t\t\t\t\"address\": \"0.0.0.0\",\n\t\t\t\t\t\"portValue\": 0\n\t\t\t\t}\n\t\t\t}\n\t\t`, cluster.UpstreamBindConfig)\n\t})\n\tt.Run(\"source address\", func(t *testing.T) {\n\t\tcluster, err := b.buildPolicyCluster(ctx, &config.Options{\n\t\t\tEnvoyBindConfigSourceAddress: \"192.168.0.1\",\n\t\t}, &config.Policy{\n\t\t\tFrom: \"https://from.example.com\",\n\t\t\tTo: mustParseWeightedURLs(t, \"https://to.example.com\"),\n\t\t})\n\t\tassert.NoError(t, err)\n\t\ttestutil.AssertProtoJSONEqual(t, `\n\t\t\t{\n\t\t\t\t\"sourceAddress\": {\n\t\t\t\t\t\"address\": \"192.168.0.1\",\n\t\t\t\t\t\"portValue\": 0\n\t\t\t\t}\n\t\t\t}\n\t\t`, cluster.UpstreamBindConfig)\n\t})\n}", "label_name": "CWE-200", "label": "200"} -{"code": "func getGateway(ctx *statsContext) error {\n\tgatewayID := helpers.GetGatewayID(&ctx.gatewayStats)\n\tgw, err := storage.GetAndCacheGateway(ctx.ctx, storage.DB(), gatewayID)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"get gateway error\")\n\t}\n\n\tctx.gateway = gw\n\treturn nil\n}", "label_name": "CWE-20", "label": "20"} -{"code": "func (EmptyEvidencePool) AddEvidence(types.Evidence) error { return nil }", "label_name": "CWE-400", "label": "400"} -{"code": "func (set *IdmapSet) doUidshiftIntoContainer(dir string, testmode bool, how string) error {\n\tconvert := func(path string, fi os.FileInfo, err error) (e error) {\n\t\tuid, gid, err := GetOwner(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvar newuid, newgid int\n\t\tswitch how {\n\t\tcase \"in\":\n\t\t\tnewuid, newgid = set.ShiftIntoNs(uid, gid)\n\t\tcase \"out\":\n\t\t\tnewuid, newgid = set.ShiftFromNs(uid, gid)\n\t\t}\n\t\tif testmode {\n\t\t\tfmt.Printf(\"I would shift %q to %d %d\\n\", path, newuid, newgid)\n\t\t} else {\n\t\t\terr = os.Lchown(path, int(newuid), int(newgid))\n\t\t\tif err == nil {\n\t\t\t\tm := fi.Mode()\n\t\t\t\tif m&os.ModeSymlink == 0 {\n\t\t\t\t\terr = os.Chmod(path, m)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfmt.Printf(\"Error resetting mode on %q, continuing\\n\", path)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\tif !PathExists(dir) {\n\t\treturn fmt.Errorf(\"No such file or directory: %q\", dir)\n\t}\n\treturn filepath.Walk(dir, convert)\n}", "label_name": "CWE-362", "label": "362"} -{"code": "func TestBuilder_BuildBootstrapStatsConfig(t *testing.T) {\n\tb := New(\"local-grpc\", \"local-http\", filemgr.NewManager(), nil)\n\tt.Run(\"valid\", func(t *testing.T) {\n\t\tstatsCfg, err := b.BuildBootstrapStatsConfig(&config.Config{\n\t\t\tOptions: &config.Options{\n\t\t\t\tServices: \"all\",\n\t\t\t},\n\t\t})\n\t\tassert.NoError(t, err)\n\t\ttestutil.AssertProtoJSONEqual(t, `\n\t\t\t{\n\t\t\t\t\"statsTags\": [{\n\t\t\t\t\t\"tagName\": \"service\",\n\t\t\t\t\t\"fixedValue\": \"pomerium\"\n\t\t\t\t}]\n\t\t\t}\n\t\t`, statsCfg)\n\t})\n}", "label_name": "CWE-200", "label": "200"} -{"code": "func (svc Service) ModifyTeamScheduledQueries(ctx context.Context, teamID uint, scheduledQueryID uint, query fleet.ScheduledQueryPayload) (*fleet.ScheduledQuery, error) {\n\tif err := svc.authz.Authorize(ctx, &fleet.Pack{TeamIDs: []uint{teamID}}, fleet.ActionWrite); err != nil {\n\t\treturn nil, err\n\t}\n\n\tgp, err := svc.ds.EnsureTeamPack(ctx, teamID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tquery.PackID = ptr.Uint(gp.ID)\n\n\treturn svc.unauthorizedModifyScheduledQuery(ctx, scheduledQueryID, query)\n}", "label_name": "CWE-863", "label": "863"} -{"code": "func (svc *Service) ListUsers(ctx context.Context, opt fleet.UserListOptions) ([]*fleet.User, error) {\n\tif err := svc.authz.Authorize(ctx, &fleet.User{}, fleet.ActionRead); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn svc.ds.ListUsers(ctx, opt)\n}", "label_name": "CWE-863", "label": "863"} -{"code": "func TestBuilder_BuildBootstrapAdmin(t *testing.T) {\n\tb := New(\"local-grpc\", \"local-http\", filemgr.NewManager(), nil)\n\tt.Run(\"valid\", func(t *testing.T) {\n\t\tadminCfg, err := b.BuildBootstrapAdmin(&config.Config{\n\t\t\tOptions: &config.Options{\n\t\t\t\tEnvoyAdminAddress: \"localhost:9901\",\n\t\t\t},\n\t\t})\n\t\tassert.NoError(t, err)\n\t\ttestutil.AssertProtoJSONEqual(t, `\n\t\t\t{\n\t\t\t\t\"address\": {\n\t\t\t\t\t\"socketAddress\": {\n\t\t\t\t\t\t\"address\": \"127.0.0.1\",\n\t\t\t\t\t\t\"portValue\": 9901\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t`, adminCfg)\n\t})\n\tt.Run(\"bad address\", func(t *testing.T) {\n\t\t_, err := b.BuildBootstrapAdmin(&config.Config{\n\t\t\tOptions: &config.Options{\n\t\t\t\tEnvoyAdminAddress: \"xyz1234:zyx4321\",\n\t\t\t},\n\t\t})\n\t\tassert.Error(t, err)\n\t})\n}", "label_name": "CWE-200", "label": "200"} -{"code": "func (g Grant) ValidateBasic() error {\n\tif g.Expiration.Unix() < time.Now().Unix() {\n\t\treturn sdkerrors.Wrap(ErrInvalidExpirationTime, \"Time can't be in the past\")\n\t}\n\n\tav := g.Authorization.GetCachedValue()\n\ta, ok := av.(Authorization)\n\tif !ok {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrInvalidType, \"expected %T, got %T\", (Authorization)(nil), av)\n\t}\n\treturn a.ValidateBasic()\n}", "label_name": "CWE-754", "label": "754"} -{"code": "func (EmptyEvidencePool) CheckEvidence(evList types.EvidenceList) error { return nil }", "label_name": "CWE-400", "label": "400"} -{"code": "func (AppModule) ConsensusVersion() uint64 { return 1 }", "label_name": "CWE-287", "label": "287"} -{"code": "func (b *Backend) rxPacketHandler(c paho.Client, msg paho.Message) {\n\tb.wg.Add(1)\n\tdefer b.wg.Done()\n\n\tvar uplinkFrame gw.UplinkFrame\n\tt, err := marshaler.UnmarshalUplinkFrame(msg.Payload(), &uplinkFrame)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"data_base64\": base64.StdEncoding.EncodeToString(msg.Payload()),\n\t\t}).WithError(err).Error(\"gateway/mqtt: unmarshal uplink frame error\")\n\t\treturn\n\t}\n\n\tif uplinkFrame.TxInfo == nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"data_base64\": base64.StdEncoding.EncodeToString(msg.Payload()),\n\t\t}).Error(\"gateway/mqtt: tx_info must not be nil\")\n\t\treturn\n\t}\n\n\tif uplinkFrame.RxInfo == nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"data_base64\": base64.StdEncoding.EncodeToString(msg.Payload()),\n\t\t}).Error(\"gateway/mqtt: rx_info must not be nil\")\n\t\treturn\n\t}\n\n\tgatewayID := helpers.GetGatewayID(uplinkFrame.RxInfo)\n\tb.setGatewayMarshaler(gatewayID, t)\n\tuplinkID := helpers.GetUplinkID(uplinkFrame.RxInfo)\n\n\tlog.WithFields(log.Fields{\n\t\t\"uplink_id\": uplinkID,\n\t\t\"gateway_id\": gatewayID,\n\t}).Info(\"gateway/mqtt: uplink frame received\")\n\n\t// Since with MQTT all subscribers will receive the uplink messages sent\n\t// by all the gateways, the first instance receiving the message must lock it,\n\t// so that other instances can ignore the same message (from the same gw).\n\tkey := fmt.Sprintf(\"lora:ns:uplink:lock:%s:%d:%d:%d:%s\", gatewayID, uplinkFrame.TxInfo.Frequency, uplinkFrame.RxInfo.Board, uplinkFrame.RxInfo.Antenna, hex.EncodeToString(uplinkFrame.PhyPayload))\n\tif locked, err := b.isLocked(key); err != nil || locked {\n\t\tif err != nil {\n\t\t\tlog.WithError(err).WithFields(log.Fields{\n\t\t\t\t\"uplink_id\": uplinkID,\n\t\t\t\t\"key\": key,\n\t\t\t}).Error(\"gateway/mqtt: acquire lock error\")\n\t\t}\n\t\treturn\n\t}\n\n\tb.rxPacketChan <- uplinkFrame\n}", "label_name": "CWE-20", "label": "20"} -{"code": "func queryMatches(rp *arrayPathResult, value Result) bool {\n\trpv := rp.query.value\n\tif len(rpv) > 0 && rpv[0] == '~' {\n\t\t// convert to bool\n\t\trpv = rpv[1:]\n\t\tif value.Bool() {\n\t\t\tvalue = Result{Type: True}\n\t\t} else {\n\t\t\tvalue = Result{Type: False}\n\t\t}\n\t}\n\tif !value.Exists() {\n\t\treturn false\n\t}\n\tif rp.query.op == \"\" {\n\t\t// the query is only looking for existence, such as:\n\t\t// friends.#(name)\n\t\t// which makes sure that the array \"friends\" has an element of\n\t\t// \"name\" that exists\n\t\treturn true\n\t}\n\tswitch value.Type {\n\tcase String:\n\t\tswitch rp.query.op {\n\t\tcase \"=\":\n\t\t\treturn value.Str == rpv\n\t\tcase \"!=\":\n\t\t\treturn value.Str != rpv\n\t\tcase \"<\":\n\t\t\treturn value.Str < rpv\n\t\tcase \"<=\":\n\t\t\treturn value.Str <= rpv\n\t\tcase \">\":\n\t\t\treturn value.Str > rpv\n\t\tcase \">=\":\n\t\t\treturn value.Str >= rpv\n\t\tcase \"%\":\n\t\t\treturn match.Match(value.Str, rpv)\n\t\tcase \"!%\":\n\t\t\treturn !match.Match(value.Str, rpv)\n\t\t}\n\tcase Number:\n\t\trpvn, _ := strconv.ParseFloat(rpv, 64)\n\t\tswitch rp.query.op {\n\t\tcase \"=\":\n\t\t\treturn value.Num == rpvn\n\t\tcase \"!=\":\n\t\t\treturn value.Num != rpvn\n\t\tcase \"<\":\n\t\t\treturn value.Num < rpvn\n\t\tcase \"<=\":\n\t\t\treturn value.Num <= rpvn\n\t\tcase \">\":\n\t\t\treturn value.Num > rpvn\n\t\tcase \">=\":\n\t\t\treturn value.Num >= rpvn\n\t\t}\n\tcase True:\n\t\tswitch rp.query.op {\n\t\tcase \"=\":\n\t\t\treturn rpv == \"true\"\n\t\tcase \"!=\":\n\t\t\treturn rpv != \"true\"\n\t\tcase \">\":\n\t\t\treturn rpv == \"false\"\n\t\tcase \">=\":\n\t\t\treturn true\n\t\t}\n\tcase False:\n\t\tswitch rp.query.op {\n\t\tcase \"=\":\n\t\t\treturn rpv == \"false\"\n\t\tcase \"!=\":\n\t\t\treturn rpv != \"false\"\n\t\tcase \"<\":\n\t\t\treturn rpv == \"true\"\n\t\tcase \"<=\":\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "label_name": "CWE-400", "label": "400"} -{"code": "\tctx := log.WithContext(context.TODO(), func(c zerolog.Context) zerolog.Context {\n\t\treturn c.Str(\"config_file_source\", configFile)\n\t})\n\n\toptions, err := newOptionsFromConfig(configFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tports, err := netutil.AllocatePorts(3)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgrpcPort := ports[0]\n\thttpPort := ports[1]\n\toutboundPort := ports[2]\n\n\tcfg := &Config{\n\t\tOptions: options,\n\t\tEnvoyVersion: envoyVersion,\n\n\t\tGRPCPort: grpcPort,\n\t\tHTTPPort: httpPort,\n\t\tOutboundPort: outboundPort,\n\t}\n\tmetrics.SetConfigInfo(ctx, cfg.Options.Services, \"local\", cfg.Checksum(), true)\n\n\tsrc := &FileOrEnvironmentSource{\n\t\tconfigFile: configFile,\n\t\tconfig: cfg,\n\t}\n\toptions.viper.OnConfigChange(src.onConfigChange(ctx))\n\tgo options.viper.WatchConfig()\n\n\treturn src, nil\n}", "label_name": "CWE-200", "label": "200"} -{"code": "func TestService_ListSoftware(t *testing.T) {\n\tds := new(mock.Store)\n\n\tvar calledWithTeamID *uint\n\tvar calledWithOpt fleet.SoftwareListOptions\n\tds.ListSoftwareFunc = func(ctx context.Context, opt fleet.SoftwareListOptions) ([]fleet.Software, error) {\n\t\tcalledWithTeamID = opt.TeamID\n\t\tcalledWithOpt = opt\n\t\treturn []fleet.Software{}, nil\n\t}\n\n\tuser := &fleet.User{ID: 3, Email: \"foo@bar.com\", GlobalRole: ptr.String(fleet.RoleObserver)}\n\n\tsvc := newTestService(t, ds, nil, nil)\n\tctx := context.Background()\n\tctx = viewer.NewContext(ctx, viewer.Viewer{User: user})\n\n\t_, err := svc.ListSoftware(ctx, fleet.SoftwareListOptions{TeamID: ptr.Uint(42), ListOptions: fleet.ListOptions{PerPage: 77, Page: 4}})\n\trequire.NoError(t, err)\n\n\tassert.True(t, ds.ListSoftwareFuncInvoked)\n\tassert.Equal(t, ptr.Uint(42), calledWithTeamID)\n\t// sort order defaults to hosts_count descending, automatically, if not explicitly provided\n\tassert.Equal(t, fleet.ListOptions{PerPage: 77, Page: 4, OrderKey: \"hosts_count\", OrderDirection: fleet.OrderDescending}, calledWithOpt.ListOptions)\n\tassert.True(t, calledWithOpt.WithHostCounts)\n\n\t// call again, this time with an explicit sort\n\tds.ListSoftwareFuncInvoked = false\n\t_, err = svc.ListSoftware(ctx, fleet.SoftwareListOptions{TeamID: nil, ListOptions: fleet.ListOptions{PerPage: 11, Page: 2, OrderKey: \"id\", OrderDirection: fleet.OrderAscending}})\n\trequire.NoError(t, err)\n\n\tassert.True(t, ds.ListSoftwareFuncInvoked)\n\tassert.Nil(t, calledWithTeamID)\n\tassert.Equal(t, fleet.ListOptions{PerPage: 11, Page: 2, OrderKey: \"id\", OrderDirection: fleet.OrderAscending}, calledWithOpt.ListOptions)\n\tassert.True(t, calledWithOpt.WithHostCounts)\n}", "label_name": "CWE-863", "label": "863"} -{"code": "func testExternalNameServiceTLS(namespace string) {\n\tSpecify(\"external name services work over https\", func() {\n\t\tt := f.T()\n\n\t\tf.Certs.CreateSelfSignedCert(namespace, \"backend-server-cert\", \"backend-server-cert\", \"echo\")\n\n\t\tf.Fixtures.EchoSecure.Deploy(namespace, \"echo-tls\")\n\n\t\texternalNameService := &corev1.Service{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: namespace,\n\t\t\t\tName: \"external-name-service-tls\",\n\t\t\t},\n\t\t\tSpec: corev1.ServiceSpec{\n\t\t\t\tType: corev1.ServiceTypeExternalName,\n\t\t\t\tExternalName: \"echo-tls.\" + namespace,\n\t\t\t\tPorts: []corev1.ServicePort{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: \"https\",\n\t\t\t\t\t\tPort: 443,\n\t\t\t\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\trequire.NoError(t, f.Client.Create(context.TODO(), externalNameService))\n\n\t\tp := &contourv1.HTTPProxy{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tNamespace: namespace,\n\t\t\t\tName: \"external-name-proxy-tls\",\n\t\t\t},\n\t\t\tSpec: contourv1.HTTPProxySpec{\n\t\t\t\tVirtualHost: &contourv1.VirtualHost{\n\t\t\t\t\tFqdn: \"tls.externalnameservice.projectcontour.io\",\n\t\t\t\t},\n\t\t\t\tRoutes: []contourv1.Route{\n\t\t\t\t\t{\n\t\t\t\t\t\tServices: []contourv1.Service{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tName: externalNameService.Name,\n\t\t\t\t\t\t\t\tPort: 443,\n\t\t\t\t\t\t\t\tProtocol: stringPtr(\"tls\"),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tRequestHeadersPolicy: &contourv1.HeadersPolicy{\n\t\t\t\t\t\t\tSet: []contourv1.HeaderValue{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tName: \"Host\",\n\t\t\t\t\t\t\t\t\tValue: externalNameService.Spec.ExternalName,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\tf.CreateHTTPProxyAndWaitFor(p, httpProxyValid)\n\n\t\tres, ok := f.HTTP.RequestUntil(&e2e.HTTPRequestOpts{\n\t\t\tHost: p.Spec.VirtualHost.Fqdn,\n\t\t\tCondition: e2e.HasStatusCode(200),\n\t\t})\n\t\trequire.Truef(t, ok, \"expected 200 response code, got %d\", res.StatusCode)\n\t})\n}", "label_name": "CWE-610", "label": "610"} -{"code": "func TestBuilder_BuildBootstrapLayeredRuntime(t *testing.T) {\n\tb := New(\"localhost:1111\", \"localhost:2222\", filemgr.NewManager(), nil)\n\tstaticCfg, err := b.BuildBootstrapLayeredRuntime()\n\tassert.NoError(t, err)\n\ttestutil.AssertProtoJSONEqual(t, `\n\t\t{ \"layers\": [{\n\t\t\t\"name\": \"static_layer_0\",\n\t\t\t\"staticLayer\": {\n\t\t\t\t\"overload\": {\n\t\t\t\t\t\"global_downstream_max_connections\": 50000\n\t\t\t\t}\n\t\t\t}\n\t\t}] }\n\t`, staticCfg)\n}", "label_name": "CWE-200", "label": "200"} -{"code": "func (svc *Service) GetGlobalScheduledQueries(ctx context.Context, opts fleet.ListOptions) ([]*fleet.ScheduledQuery, error) {\n\tif err := svc.authz.Authorize(ctx, &fleet.Pack{}, fleet.ActionRead); err != nil {\n\t\treturn nil, err\n\t}\n\n\tgp, err := svc.ds.EnsureGlobalPack(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn svc.ds.ListScheduledQueriesInPackWithStats(ctx, gp.ID, opts)\n}", "label_name": "CWE-863", "label": "863"} -{"code": "func (k Keeper) AfterEpochEnd(ctx sdk.Context, epochIdentifier string, epochNumber int64) {\n\tparams := k.GetParams(ctx)\n\texpEpochID := k.GetEpochIdentifier(ctx)\n\tif epochIdentifier != expEpochID {\n\t\treturn\n\t}\n\n\t// mint coins, update supply\n\tepochMintProvision, found := k.GetEpochMintProvision(ctx)\n\tif !found {\n\t\tpanic(\"the epochMintProvision was not found\")\n\t}\n\n\tmintedCoin := sdk.NewCoin(params.MintDenom, epochMintProvision.TruncateInt())\n\tif err := k.MintAndAllocateInflation(ctx, mintedCoin); err != nil {\n\t\tpanic(err)\n\t}\n\n\t// check if a period is over. If it's completed, update period, and epochMintProvision\n\tperiod := k.GetPeriod(ctx)\n\tepochsPerPeriod := k.GetEpochsPerPeriod(ctx)\n\n\tnewProvision := epochMintProvision\n\n\t// current epoch number needs to be within range for the period\n\t// Given, epochNumber = 1, period = 0, epochPerPeriod = 365\n\t// 1 - 365 * 0 < 365 --- nothing to do here\n\t// Given, epochNumber = 731, period = 1, epochPerPeriod = 365\n\t// 731 - 1 * 365 > 365 --- a period has passed! we change the epochMintProvision and set a new period\n\tif epochNumber-epochsPerPeriod*int64(period) > epochsPerPeriod {\n\t\tperiod++\n\t\tk.SetPeriod(ctx, period)\n\t\tperiod = k.GetPeriod(ctx)\n\t\tbondedRatio := k.stakingKeeper.BondedRatio(ctx)\n\t\tnewProvision = types.CalculateEpochMintProvision(\n\t\t\tparams,\n\t\t\tperiod,\n\t\t\tepochsPerPeriod,\n\t\t\tbondedRatio,\n\t\t)\n\t\tk.SetEpochMintProvision(ctx, newProvision)\n\t}\n\n\tctx.EventManager().EmitEvent(\n\t\tsdk.NewEvent(\n\t\t\ttypes.EventTypeMint,\n\t\t\tsdk.NewAttribute(types.AttributeEpochNumber, fmt.Sprintf(\"%d\", epochNumber)),\n\t\t\tsdk.NewAttribute(types.AttributeKeyEpochProvisions, newProvision.String()),\n\t\t\tsdk.NewAttribute(sdk.AttributeKeyAmount, mintedCoin.Amount.String()),\n\t\t),\n\t)\n}", "label_name": "CWE-287", "label": "287"} -{"code": "func InstallNps() {\n\tpath := common.GetInstallPath()\n\tif common.FileExists(path) {\n\t\tlog.Fatalf(\"the path %s has exist, does not support install\", path)\n\t}\n\tMkidrDirAll(path, \"conf\", \"web/static\", \"web/views\")\n\t//\u590d\u5236\u6587\u4ef6\u5230\u5bf9\u5e94\u76ee\u5f55\n\tif err := CopyDir(filepath.Join(common.GetAppPath(), \"web\", \"views\"), filepath.Join(path, \"web\", \"views\")); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tif err := CopyDir(filepath.Join(common.GetAppPath(), \"web\", \"static\"), filepath.Join(path, \"web\", \"static\")); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tif err := CopyDir(filepath.Join(common.GetAppPath(), \"conf\"), filepath.Join(path, \"conf\")); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tif !common.IsWindows() {\n\t\tif _, err := copyFile(filepath.Join(common.GetAppPath(), \"nps\"), \"/usr/bin/nps\"); err != nil {\n\t\t\tif _, err := copyFile(filepath.Join(common.GetAppPath(), \"nps\"), \"/usr/local/bin/nps\"); err != nil {\n\t\t\t\tlog.Fatalln(err)\n\t\t\t} else {\n\t\t\t\tos.Chmod(\"/usr/local/bin/nps\", 0777)\n\t\t\t\tlog.Println(\"Executable files have been copied to\", \"/usr/local/bin/nps\")\n\t\t\t}\n\t\t} else {\n\t\t\tos.Chmod(\"/usr/bin/nps\", 0777)\n\t\t\tlog.Println(\"Executable files have been copied to\", \"/usr/bin/nps\")\n\t\t}\n\n\t}\n\tlog.Println(\"install ok!\")\n\tlog.Println(\"Static files and configuration files in the current directory will be useless\")\n\tlog.Println(\"The new configuration file is located in\", path, \"you can edit them\")\n\tif !common.IsWindows() {\n\t\tlog.Println(\"You can start with nps test|start|stop|restart|status anywhere\")\n\t} else {\n\t\tlog.Println(\"You can copy executable files to any directory and start working with nps.exe test|start|stop|restart|status\")\n\t}\n}", "label_name": "CWE-732", "label": "732"} -{"code": "export function exportVariable(name: string, val: any): void {\n const convertedVal = toCommandValue(val)\n process.env[name] = convertedVal\n\n const filePath = process.env['GITHUB_ENV'] || ''\n if (filePath) {\n const delimiter = '_GitHubActionsFileCommandDelimeter_'\n const commandValue = `${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}`\n issueFileCommand('ENV', commandValue)\n } else {\n issueCommand('set-env', {name}, convertedVal)\n }\n}", "label_name": "CWE-74", "label": "74"} -{"code": "export function cloneMirrorTask(repo: string | undefined, directory: string | undefined, customArgs: string[]): StringTask {\n append(customArgs,'--mirror');\n\n return cloneTask(repo, directory, customArgs);\n}", "label_name": "CWE-77", "label": "77"} -{"code": " get lokadIdHex() { return \"534c5000\" }", "label_name": "CWE-20", "label": "20"} -{"code": " 'X-Parse-Session-Token': user1.getSessionToken(),\n },\n },\n });\n\n let foundGraphQLClassReadPreference = false;\n let foundUserClassReadPreference = false;\n databaseAdapter.database.serverConfig.cursor.calls\n .all()\n .forEach((call) => {\n if (\n call.args[0].ns.collection.indexOf('GraphQLClass') >= 0\n ) {\n foundGraphQLClassReadPreference = true;\n expect(call.args[0].options.readPreference.mode).toBe(\n ReadPreference.PRIMARY\n );\n } else if (\n call.args[0].ns.collection.indexOf('_User') >= 0\n ) {\n foundUserClassReadPreference = true;\n expect(call.args[0].options.readPreference.mode).toBe(\n ReadPreference.PRIMARY\n );\n }\n });\n\n expect(foundGraphQLClassReadPreference).toBe(true);\n expect(foundUserClassReadPreference).toBe(true);\n } catch (e) {\n handleError(e);\n }\n });", "label_name": "CWE-863", "label": "863"} -{"code": " private _on_receive_message_chunk(messageChunk: Buffer) {\r\n /* istanbul ignore next */\r\n if (doDebug1) {\r\n const _stream = new BinaryStream(messageChunk);\r\n const messageHeader = readMessageHeader(_stream);\r\n debugLog(\"CLIENT RECEIVED \" + chalk.yellow(JSON.stringify(messageHeader) + \"\"));\r\n debugLog(\"\\n\" + hexDump(messageChunk));\r\n debugLog(messageHeaderToString(messageChunk));\r\n }\r\n this.messageBuilder.feed(messageChunk);\r\n }\r", "label_name": "CWE-400", "label": "400"} -{"code": " buildRawNFT1GenesisTx(config: configBuildRawNFT1GenesisTx, type = 0x01) {\n let config2: configBuildRawGenesisTx = {\n slpGenesisOpReturn: config.slpNFT1GenesisOpReturn,\n mintReceiverAddress: config.mintReceiverAddress,\n mintReceiverSatoshis: config.mintReceiverSatoshis,\n batonReceiverAddress: null,\n bchChangeReceiverAddress: config.bchChangeReceiverAddress,\n input_utxos: config.input_utxos,\n allowed_token_burning: [ config.parentTokenIdHex ]\n }\n\n return this.buildRawGenesisTx(config2);\n }", "label_name": "CWE-20", "label": "20"} -{"code": " Object.keys(req.query as any).length ? validateOrReject(Object.assign(new Validators.Query(), req.query as any), validatorOptions) : null\n ])", "label_name": "CWE-20", "label": "20"} -{"code": " get: ({ params }) => ({ status: 200, body: { id: params.userId, name: 'bbb' } })\n}))", "label_name": "CWE-20", "label": "20"} -{"code": " signBufferFunc: (chunk: Buffer) => makeMessageChunkSignatureWithDerivedKeys(chunk, derivedKeys),\n signatureLength: derivedKeys.signatureLength,\n sequenceHeaderSize: 0,\n };\n\n\n const securityHeader = new SymmetricAlgorithmSecurityHeader({\n tokenId: 10\n });\n\n const msgChunkManager = new SecureMessageChunkManager(\"MSG\", options, securityHeader, sequenceNumberGenerator);\n msgChunkManager.on(\"chunk\", (chunk, final) => callback(null, chunk));\n msgChunkManager.write(buffer, buffer.length);\n msgChunkManager.end();\n}", "label_name": "CWE-400", "label": "400"} -{"code": " on(eventName: \"message\", eventHandler: (message: Buffer) => void): this;", "label_name": "CWE-400", "label": "400"} -{"code": " parseOpReturnToChunks(script: Buffer, allow_op_0=false, allow_op_number=false) {\n // \"\"\"Extract pushed bytes after opreturn. Returns list of bytes() objects,\n // one per push.\n let ops: PushDataOperation[];\n \n // Strict refusal of non-push opcodes; bad scripts throw OpreturnError.\"\"\"\n try {\n ops = this.getScriptOperations(script);\n } catch(e) {\n //console.log(e);\n throw Error('Script error');\n }\n\n if(ops[0].opcode !== this.BITBOX.Script.opcodes.OP_RETURN)\n throw Error('No OP_RETURN');\n let chunks: (Buffer|null)[] = [];\n ops.slice(1).forEach(opitem => {\n if(opitem.opcode > this.BITBOX.Script.opcodes.OP_16)\n throw Error(\"Non-push opcode\");\n if(opitem.opcode > this.BITBOX.Script.opcodes.OP_PUSHDATA4) {\n if(opitem.opcode === 80)\n throw Error('Non-push opcode');\n if(!allow_op_number)\n throw Error('OP_1NEGATE to OP_16 not allowed');\n if(opitem.opcode === this.BITBOX.Script.opcodes.OP_1NEGATE)\n opitem.data = Buffer.from([0x81]);\n else // OP_1 - OP_16\n opitem.data = Buffer.from([opitem.opcode - 80]);\n }\n if(opitem.opcode === this.BITBOX.Script.opcodes.OP_0 && !allow_op_0){\n throw Error('OP_0 not allowed');\n }\n chunks.push(opitem.data)\n });\n //console.log(chunks);\n return chunks\n }", "label_name": "CWE-20", "label": "20"} -{"code": " }validateOrReject(Object.assign(new Validators.${checker.typeToString(v.type)}(), req.${\n v.name\n }), validatorOptions)${v.hasQuestion ? ' : null' : ''}`\n : ''\n )\n .join(',\\n')}\\n ])`", "label_name": "CWE-20", "label": "20"} -{"code": " session: session.fromPartition('about-window'),\n spellcheck: false,\n webviewTag: false,\n },\n width: WINDOW_SIZE.WIDTH,\n });\n aboutWindow.setMenuBarVisibility(false);\n\n // Prevent any kind of navigation\n // will-navigate is broken with sandboxed env, intercepting requests instead\n // see https://github.com/electron/electron/issues/8841\n aboutWindow.webContents.session.webRequest.onBeforeRequest(async ({url}, callback) => {\n // Only allow those URLs to be opened within the window\n if (ABOUT_WINDOW_ALLOWLIST.includes(url)) {\n return callback({cancel: false});\n }\n\n // Open HTTPS links in browser instead\n if (url.startsWith('https://')) {\n await shell.openExternal(url);\n } else {\n logger.info(`Attempt to open URL \"${url}\" in window prevented.`);\n callback({redirectURL: ABOUT_HTML});\n }\n });\n\n // Locales\n ipcMain.on(EVENT_TYPE.ABOUT.LOCALE_VALUES, (event, labels: locale.i18nLanguageIdentifier[]) => {\n if (aboutWindow) {\n const isExpected = event.sender.id === aboutWindow.webContents.id;\n if (isExpected) {\n const resultLabels: Record = {};\n labels.forEach(label => (resultLabels[label] = locale.getText(label)));\n event.sender.send(EVENT_TYPE.ABOUT.LOCALE_RENDER, resultLabels);\n }\n }\n });\n\n // Close window via escape\n aboutWindow.webContents.on('before-input-event', (_event, input) => {\n if (input.type === 'keyDown' && input.key === 'Escape') {\n if (aboutWindow) {\n aboutWindow.close();\n }\n }\n });\n\n aboutWindow.on('closed', () => (aboutWindow = undefined));\n\n await aboutWindow.loadURL(ABOUT_HTML);\n\n if (aboutWindow) {\n aboutWindow.webContents.send(EVENT_TYPE.ABOUT.LOADED, {\n copyright: config.copyright,\n electronVersion: config.version,\n productName: config.name,\n webappVersion,\n });\n }\n }\n\n aboutWindow.show();\n};", "label_name": "CWE-20", "label": "20"} -{"code": " response.responseHeader.serviceResult.should.eql(StatusCodes.BadDiscoveryUrlMissing);\n }\n\n await send_registered_server_request(discoveryServerEndpointUrl, request, check_response);\n });", "label_name": "CWE-400", "label": "400"} -{"code": " privateKey: this.getPrivateKey() || undefined,\r\n securityMode: this.securityMode\r\n });\r\n this._requests = {};\r\n\r\n this.messageBuilder\r\n .on(\"message\", (response: Response, msgType: string, requestId: number) => {\r\n this._on_message_received(response, msgType, requestId);\r\n })\r\n .on(\"start_chunk\", () => {\r\n //\r\n if (doPerfMonitoring) {\r\n this._tick2 = get_clock_tick();\r\n }\r\n })\r\n .on(\"error\", (err, requestId) => {\r\n //\r\n let requestData = this._requests[requestId];\r\n\r\n if (doDebug) {\r\n debugLog(\"request id = \", requestId, err);\r\n debugLog(\" message was \");\r\n debugLog(requestData);\r\n }\r\n\r\n if (!requestData) {\r\n requestData = this._requests[requestId + 1];\r\n if (doTraceClientRequestContent) {\r\n errorLog(\" message was 2:\", requestData ? requestData.request.toString() : \"\");\r\n }\r\n }\r\n });\r\n\r\n this.__in_normal_close_operation = false;\r\n\r\n this._timeout_request_count = 0;\r\n\r\n this._securityTokenTimeoutId = null;\r\n\r\n this.transportTimeout = options.transportTimeout || ClientSecureChannelLayer.defaultTransportTimeout;\r\n\r\n this.channelId = 0;\r\n\r\n this.connectionStrategy = coerceConnectionStrategy(options.connectionStrategy);\r\n }\r", "label_name": "CWE-400", "label": "400"} -{"code": "export function verify_multi_chunk_message(packets: any[]) {\n\n const messageBuilder = new MessageBuilder({});\n messageBuilder.setSecurity(MessageSecurityMode.None, SecurityPolicy.None);\n\n messageBuilder.on(\"full_message_body\", (fullMessageBody: Buffer) => {\n console.log(\"full_message_body received:\");\n analyseExtensionObject(fullMessageBody, 0, 0);\n });\n messageBuilder.on(\"start_chunk\", (info) => {\n console.log(\" starting new chunk \", info.messageHeader);\n });\n\n messageBuilder.on(\"chunk\", (messageChunk) => {\n console.log(messageHeaderToString(messageChunk));\n });\n\n let totalLength = 0;\n packets.forEach((packet) => {\n if (packet instanceof Array) {\n packet = Buffer.from(packet);\n }\n totalLength += packet.length;\n // console.log(sprintf(\" adding packet size : %5d l=%d\", packet.length, totalLength));\n messageBuilder.feed(packet);\n });\n}", "label_name": "CWE-400", "label": "400"} -{"code": " function simulateTransation(request: FindServersRequest, response: FindServersResponse, callback: SimpleCallback) {\n serverSChannel.once(\"message\", (message: Message) => {\n doDebug && console.log(\"server receiving message =\", response.responseHeader.requestHandle);\n response.responseHeader.requestHandle = message.request.requestHeader.requestHandle;\n serverSChannel.send_response(\"MSG\", response, message, () => {\n /** */\n doDebug && console.log(\"server message sent \", response.responseHeader.requestHandle);\n });\n });\n\n doDebug && console.log(\" now sending a request \" + request.constructor.name);\n\n clientChannel.performMessageTransaction(request, (err, response) => {\n doDebug && console.log(\"client received a response \", response?.constructor.name);\n doDebug && console.log(response?.toString());\n callback(err || undefined);\n });\n }", "label_name": "CWE-400", "label": "400"} -{"code": "function setCachedRendererFunction (id: RendererFunctionId, wc: electron.WebContents, frameId: number, value: CallIntoRenderer) {\n // eslint-disable-next-line no-undef\n const wr = new WeakRef(value);\n const mapKey = id[0] + '~' + id[1];\n rendererFunctionCache.set(mapKey, wr);\n finalizationRegistry.register(value, {\n id,\n webContents: wc,\n frameId\n } as FinalizerInfo);\n return value;\n}", "label_name": "CWE-668", "label": "668"} -{"code": " .on(\"message\", (request, msgType, requestId, channelId) => {\n this._on_common_message(request, msgType, requestId, channelId);\n })", "label_name": "CWE-400", "label": "400"} -{"code": " function simulateOpenSecureChannel(callback: SimpleCallback) {\n \n clientChannel.create(\"fake://foobar:123\", (err?: Error) => {\n \n if (param.shouldFailAtClientConnection) {\n if (!err) {\n return callback(new Error(\" Should have failed here !\"));\n }\n callback();\n } else {\n if (err) {\n return callback(err);\n }\n setImmediate(() => callback());\n }\n });\n }", "label_name": "CWE-400", "label": "400"} -{"code": " Object.keys(req.query as any).length ? validateOrReject(Object.assign(new Validators.Query(), req.query as any), validatorOptions) : null\n ])", "label_name": "CWE-20", "label": "20"} -{"code": " from: db.getServerTitle() + \" <\" + db.getReturnAddress() + \">\",\n subject: subject,\n text: text,\n };\n\n sendEmail(sendOptions);\n};", "label_name": "CWE-287", "label": "287"} -{"code": " updateOidcSettings(configuration) {\n checkAdminAuthentication(this)\n ServiceConfiguration.configurations.remove({\n service: 'oidc',\n })\n ServiceConfiguration.configurations.insert(configuration)\n }", "label_name": "CWE-285", "label": "285"} -{"code": "function g_sendError(channel: ServerSecureChannelLayer, message: Message, ResponseClass: any, statusCode: StatusCode): void {\n const response = new ResponseClass({\n responseHeader: { serviceResult: statusCode }\n });\n return channel.send_response(\"MSG\", response, message);\n}", "label_name": "CWE-400", "label": "400"} -{"code": " const uploader = multer({ dest: path.join(__dirname, '.upload'), limits: { fileSize: 1024 ** 3 }, ...options.multer }).any()\n\n app.get(`${basePath}/`, [\n hooks0.onRequest,\n ctrlHooks0.onRequest,\n createValidateHandler(req => [\n Object.keys(req.query).length ? validateOrReject(Object.assign(new Validators.Query(), req.query), validatorOptions) : null\n ]),\n asyncMethodToHandler(controller0.get)\n ])\n\n app.post(`${basePath}/`, [\n hooks0.onRequest,\n ctrlHooks0.onRequest,\n uploader,\n formatMulterData([]),\n createValidateHandler(req => [\n validateOrReject(Object.assign(new Validators.Query(), req.query), validatorOptions),\n validateOrReject(Object.assign(new Validators.Body(), req.body), validatorOptions)\n ]),\n methodToHandler(controller0.post)\n ])\n\n app.get(`${basePath}/empty/noEmpty`, [\n hooks0.onRequest,\n methodToHandler(controller1.get)\n ])\n\n app.post(`${basePath}/multiForm`, [\n hooks0.onRequest,\n uploader,\n formatMulterData([['empty', false], ['vals', false], ['files', false]]),\n createValidateHandler(req => [\n validateOrReject(Object.assign(new Validators.MultiForm(), req.body), validatorOptions)\n ]),\n methodToHandler(controller2.post)\n ])\n\n app.get(`${basePath}/texts`, [\n hooks0.onRequest,\n methodToHandler(controller3.get)\n ])\n\n app.put(`${basePath}/texts`, [\n hooks0.onRequest,\n methodToHandler(controller3.put)\n ])\n\n app.put(`${basePath}/texts/sample`, [\n hooks0.onRequest,\n parseJSONBoby,\n methodToHandler(controller4.put)\n ])\n\n app.get(`${basePath}/users`, [\n hooks0.onRequest,\n hooks1.onRequest,\n ...ctrlHooks1.preHandler,\n asyncMethodToHandler(controller5.get)\n ])\n\n app.post(`${basePath}/users`, [\n hooks0.onRequest,\n hooks1.onRequest,\n parseJSONBoby,\n createValidateHandler(req => [\n validateOrReject(Object.assign(new Validators.UserInfo(), req.body), validatorOptions)\n ]),\n ...ctrlHooks1.preHandler,\n methodToHandler(controller5.post)\n ])\n\n return app\n}", "label_name": "CWE-20", "label": "20"} -{"code": "export function fetchRemoteBranch(remote: string, remoteBranch: string, cwd: string) {\n const results = git([\"fetch\", remote, remoteBranch], { cwd });\n\n if (!results.success) {\n throw gitError(`Cannot fetch remote: ${remote} ${remoteBranch}`);\n }\n}", "label_name": "CWE-77", "label": "77"} -{"code": "export async function getApi(newToken?: string) {\n const token = newToken || (await getToken());\n const apiurl = config.get(\"apiUrl\");\n\n return new GitHub({ apiurl, token });\n}", "label_name": "CWE-863", "label": "863"} -{"code": " constructor(options?: { signatureLength?: number }) {\n super();\n\n this.id = \"\";\n\n this._tick0 = 0;\n this._tick1 = 0;\n this._hasReceivedError = false;\n this.blocks = [];\n this.messageChunks = [];\n this._expectedChannelId = 0;\n\n options = options || {};\n\n this.signatureLength = options.signatureLength || 0;\n\n this.options = options;\n\n this._packetAssembler = new PacketAssembler({\n minimumSizeInBytes: 0,\n readMessageFunc: readRawMessageHeader\n });\n\n this._packetAssembler.on(\"message\", (messageChunk) => this._feed_messageChunk(messageChunk));\n\n this._packetAssembler.on(\"newMessage\", (info, data) => {\n if (doPerfMonitoring) {\n // record tick 0: when the first data is received\n this._tick0 = get_clock_tick();\n }\n /**\n *\n * notify the observers that a new message is being built\n * @event start_chunk\n * @param info\n * @param data\n */\n this.emit(\"start_chunk\", info, data);\n });\n\n this._securityDefeated = false;\n this.totalBodySize = 0;\n this.totalMessageSize = 0;\n this.channelId = 0;\n this.offsetBodyStart = 0;\n this.sequenceHeader = null;\n this._init_new();\n }", "label_name": "CWE-400", "label": "400"} -{"code": " await getManager().transaction(async (manager) => {\n const organizationUser = await manager.findOne(OrganizationUser, { where: { id } });\n const user = await manager.findOne(User, { where: { id: organizationUser.userId } });\n\n await this.usersService.throwErrorIfRemovingLastActiveAdmin(user);\n\n await manager.update(User, user.id, { invitationToken: null });\n await manager.update(OrganizationUser, id, { status: 'archived' });\n });", "label_name": "CWE-74", "label": "74"} -{"code": " async resolve(_source, _args, context, queryInfo) {\n try {\n const { config, info } = context;\n return await getUserFromSessionToken(\n config,\n info,\n queryInfo,\n 'user.',\n false\n );\n } catch (e) {\n parseGraphQLSchema.handleError(e);\n }\n },", "label_name": "CWE-863", "label": "863"} -{"code": " from: globalDb.getServerTitle() + \" <\" + returnAddress + \">\",\n subject: \"Testing your Sandstorm's SMTP setting\",\n text: \"Success! Your outgoing SMTP is working.\",\n smtpConfig: restConfig,\n });\n } catch (e) {\n // Attempt to give more accurate error messages for a variety of known failure modes,\n // and the actual exception data in the event a user hits a new failure mode.\n if (e.syscall === \"getaddrinfo\") {\n if (e.code === \"EIO\" || e.code === \"ENOTFOUND\") {\n throw new Meteor.Error(\"getaddrinfo \" + e.code, \"Couldn't resolve \\\"\" + smtpConfig.hostname + \"\\\" - check for typos or broken DNS.\");\n }\n } else if (e.syscall === \"connect\") {\n if (e.code === \"ECONNREFUSED\") {\n throw new Meteor.Error(\"connect ECONNREFUSED\", \"Server at \" + smtpConfig.hostname + \":\" + smtpConfig.port + \" refused connection. Check your settings, firewall rules, and that your mail server is up.\");\n }\n } else if (e.name === \"AuthError\") {\n throw new Meteor.Error(\"auth error\", \"Authentication failed. Check your credentials. Message from \" +\n smtpConfig.hostname + \": \" + e.data);\n }\n\n throw new Meteor.Error(\"other-email-sending-error\", \"Error while trying to send test email: \" + JSON.stringify(e));\n }\n },", "label_name": "CWE-287", "label": "287"} -{"code": " static buildSendOpReturn(config: configBuildSendOpReturn, type = 0x01) {\n return SlpTokenType1.buildSendOpReturn(\n config.tokenIdHex,\n config.outputQtyArray,\n type\n )\n }", "label_name": "CWE-20", "label": "20"} -{"code": " this._transport.on(\"message\", (messageChunk: Buffer) => {\r\n /**\r\n * notify the observers that ClientSecureChannelLayer has received a message chunk\r\n * @event receive_chunk\r\n * @param message_chunk\r\n */\r\n this.emit(\"receive_chunk\", messageChunk);\r\n this._on_receive_message_chunk(messageChunk);\r\n });\r", "label_name": "CWE-400", "label": "400"} -{"code": "export type ReadMessageFuncType = (data: Buffer) => PacketInfo;", "label_name": "CWE-400", "label": "400"} -{"code": " private onWebSocket(req, socket, websocket) {\n websocket.on(\"error\", onUpgradeError);\n\n if (\n transports[req._query.transport] !== undefined &&\n !transports[req._query.transport].prototype.handlesUpgrades\n ) {\n debug(\"transport doesnt handle upgraded requests\");\n websocket.close();\n return;\n }\n\n // get client id\n const id = req._query.sid;\n\n // keep a reference to the ws.Socket\n req.websocket = websocket;\n\n if (id) {\n const client = this.clients[id];\n if (!client) {\n debug(\"upgrade attempt for closed client\");\n websocket.close();\n } else if (client.upgrading) {\n debug(\"transport has already been trying to upgrade\");\n websocket.close();\n } else if (client.upgraded) {\n debug(\"transport had already been upgraded\");\n websocket.close();\n } else {\n debug(\"upgrading existing transport\");\n\n // transport error handling takes over\n websocket.removeListener(\"error\", onUpgradeError);\n\n const transport = this.createTransport(req._query.transport, req);\n if (req._query && req._query.b64) {\n transport.supportsBinary = false;\n } else {\n transport.supportsBinary = true;\n }\n transport.perMessageDeflate = this.opts.perMessageDeflate;\n client.maybeUpgrade(transport);\n }\n } else {\n // transport error handling takes over\n websocket.removeListener(\"error\", onUpgradeError);\n\n const closeConnection = (errorCode, errorContext) =>\n abortUpgrade(socket, errorCode, errorContext);\n this.handshake(req._query.transport, req, closeConnection);\n }\n\n function onUpgradeError() {\n debug(\"websocket error before upgrade\");\n // websocket.close() not needed\n }\n }", "label_name": "CWE-754", "label": "754"} -{"code": "export function cloneTask(repo: string | undefined, directory: string | undefined, customArgs: string[]): StringTask {\n const commands = ['clone', ...customArgs];\n if (typeof repo === 'string') {\n commands.push(repo);\n }\n if (typeof directory === 'string') {\n commands.push(directory);\n }\n\n return straightThroughStringTask(commands);\n}", "label_name": "CWE-77", "label": "77"} -{"code": " verifyEmail(req) {\n const { token, username } = req.query;\n const appId = req.params.appId;\n const config = Config.get(appId);\n\n if (!config) {\n this.invalidRequest();\n }\n\n if (!config.publicServerURL) {\n return this.missingPublicServerURL();\n }\n\n if (!token || !username) {\n return this.invalidLink(req);\n }\n\n const userController = config.userController;\n return userController.verifyEmail(username, token).then(\n () => {\n const params = qs.stringify({ username });\n return Promise.resolve({\n status: 302,\n location: `${config.verifyEmailSuccessURL}?${params}`,\n });\n },\n () => {\n return this.invalidVerificationLink(req);\n }\n );\n }", "label_name": "CWE-863", "label": "863"} -{"code": " type: new GraphQLNonNull(parseGraphQLSchema.viewerType),\n async resolve(_source, _args, context, queryInfo) {\n try {\n const { config, info } = context;\n return await getUserFromSessionToken(\n config,\n info,\n queryInfo,\n 'user.',\n false\n );\n } catch (e) {\n parseGraphQLSchema.handleError(e);\n }\n },\n },\n true,\n true\n );\n};", "label_name": "CWE-863", "label": "863"} -{"code": "export async function getApi(constructor = Gists) {\n const token = await getToken();\n const apiurl = config.get(\"apiUrl\");\n\n if (!apiurl) {\n const message = \"No API URL is set.\";\n throw new Error(message);\n }\n\n return new constructor({ apiurl, token });\n}", "label_name": "CWE-863", "label": "863"} -{"code": " get: (path) => {\n useCount++;\n expect(path).toEqual('somepath');\n },", "label_name": "CWE-863", "label": "863"} -{"code": " static parseChunkToInt(intBytes: Buffer, minByteLen: number, maxByteLen: number, raise_on_Null = false) {\n // # Parse data as unsigned-big-endian encoded integer.\n // # For empty data different possibilities may occur:\n // # minByteLen <= 0 : return 0\n // # raise_on_Null == False and minByteLen > 0: return None\n // # raise_on_Null == True and minByteLen > 0: raise SlpInvalidOutputMessage\n if(intBytes.length >= minByteLen && intBytes.length <= maxByteLen)\n return intBytes.readUIntBE(0, intBytes.length)\n if(intBytes.length === 0 && !raise_on_Null)\n return null;\n throw Error('Field has wrong length');\n }", "label_name": "CWE-20", "label": "20"} -{"code": " getScriptOperations(script: Buffer) {\n let ops: PushDataOperation[] = [];\n try {\n let n = 0;\n let dlen: number;\n while (n < script.length) {\n let op: PushDataOperation = { opcode: script[n], data: null }\n n += 1;\n if(op.opcode <= this.BITBOX.Script.opcodes.OP_PUSHDATA4) {\n if(op.opcode < this.BITBOX.Script.opcodes.OP_PUSHDATA1)\n dlen = op.opcode;\n else if(op.opcode === this.BITBOX.Script.opcodes.OP_PUSHDATA1) {\n dlen = script[n];\n n += 1;\n }\n else if(op.opcode === this.BITBOX.Script.opcodes.OP_PUSHDATA2) {\n dlen = script.slice(n, n + 2).readUIntLE(0,2);\n n += 2;\n }\n else {\n dlen = script.slice(n, n + 4).readUIntLE(0,4);\n n += 4;\n }\n if((n + dlen) > script.length) {\n throw Error('IndexError');\n }\n if(dlen > 0)\n op.data = script.slice(n, n + dlen);\n n += dlen\n }\n ops.push(op);\n }\n } catch(e) {\n //console.log(e);\n throw Error('truncated script')\n }\n return ops;\n }", "label_name": "CWE-20", "label": "20"} -{"code": " private _readPacketInfo(data: Buffer) {\n return this.readMessageFunc(data);\n }", "label_name": "CWE-400", "label": "400"} -{"code": " const errorHandler = (err: Error) => {\n this._cancel_wait_for_open_secure_channel_request_timeout();\n\n this.messageBuilder.removeListener(\"message\", messageHandler);\n this.close(() => {\n callback(new Error(\"/Expecting OpenSecureChannelRequest to be valid \" + err.message));\n });\n };", "label_name": "CWE-400", "label": "400"} -{"code": "export function get(key: \"apiUrl\"): string;\nexport function get(key: \"images.markdownPasteFormat\"): \"markdown\" | \"html\";", "label_name": "CWE-863", "label": "863"} -{"code": "function applyInlineFootnotes(elem) {\n const footnoteRefs = elem.querySelectorAll(\"sup.footnote-ref\");\n\n footnoteRefs.forEach((footnoteRef) => {\n const expandableFootnote = document.createElement(\"a\");\n expandableFootnote.classList.add(\"expand-footnote\");\n expandableFootnote.innerHTML = iconHTML(\"ellipsis-h\");\n expandableFootnote.href = \"\";\n expandableFootnote.role = \"button\";\n expandableFootnote.dataset.footnoteId = footnoteRef\n .querySelector(\"a\")\n .id.replace(\"footnote-ref-\", \"\");\n\n footnoteRef.after(expandableFootnote);\n });\n\n if (footnoteRefs.length) {\n elem.classList.add(\"inline-footnotes\");\n }\n}", "label_name": "CWE-755", "label": "755"} -{"code": " callParserIfExistsQuery(parseNumberTypeQueryParams([['requiredNum', false, false], ['optionalNum', true, false], ['optionalNumArr', true, true], ['emptyNum', true, false], ['requiredNumArr', false, true]])),\n callParserIfExistsQuery(parseBooleanTypeQueryParams([['bool', false, false], ['optionalBool', true, false], ['boolArray', false, true], ['optionalBoolArray', true, true]])),\n normalizeQuery,\n createValidateHandler(req => [\n Object.keys(req.query as any).length ? validateOrReject(Object.assign(new Validators.Query(), req.query as any), validatorOptions) : null\n ])\n ]\n },\n asyncMethodToHandler(controller0.get)\n )", "label_name": "CWE-20", "label": "20"} -{"code": " use: (path) => {\n useCount++;\n expect(path).toEqual('somepath');\n },", "label_name": "CWE-863", "label": "863"} -{"code": " function check_response(err: Error | null, response: any) {\n should.not.exist(err);\n //xx debugLog(response.toString());\n response.responseHeader.serviceResult.should.eql(StatusCodes.BadInvalidArgument);\n }", "label_name": "CWE-400", "label": "400"} -{"code": " html: html({ url, host, theme }),\n })\n const failed = result.rejected.concat(result.pending).filter(Boolean)\n if (failed.length) {\n throw new Error(`Email(s) (${failed.join(\", \")}) could not be sent`)\n }\n },\n options,\n }\n}", "label_name": "CWE-863", "label": "863"} -{"code": " constructor(bitbox: BITBOX) {\n if(!bitbox)\n throw Error(\"Must provide BITBOX instance to class constructor.\")\n this.BITBOX = bitbox;\n }", "label_name": "CWE-20", "label": "20"} -{"code": "WebContents.prototype.sendToFrame = function (frameId, channel, ...args) {\n if (typeof channel !== 'string') {\n throw new Error('Missing required channel argument');\n } else if (typeof frameId !== 'number') {\n throw new Error('Missing required frameId argument');\n }\n\n return this._sendToFrame(false /* internal */, frameId, channel, args);\n};", "label_name": "CWE-668", "label": "668"} -{"code": "export function fetchRemote(remote: string, cwd: string) {\n const results = git([\"fetch\", remote], { cwd });\n\n if (!results.success) {\n throw gitError(`Cannot fetch remote: ${remote}`);\n }\n}", "label_name": "CWE-77", "label": "77"} -{"code": " async signup(params: any) {\n // Check if the installation allows user signups\n if (process.env.DISABLE_SIGNUPS === 'true') {\n return {};\n }\n\n const { email } = params;\n const existingUser = await this.usersService.findByEmail(email);\n if (existingUser) {\n throw new NotAcceptableException('Email already exists');\n }\n const organization = await this.organizationsService.create('Untitled organization');\n const user = await this.usersService.create({ email }, organization, ['all_users', 'admin']);\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const organizationUser = await this.organizationUsersService.create(user, organization);\n\n await this.emailService.sendWelcomeEmail(user.email, user.firstName, user.invitationToken);\n\n return {};\n }", "label_name": "CWE-74", "label": "74"} -{"code": "module.exports = (env) => {\n const toReplace = Object.keys(env).filter((envVar) => {\n // https://github.com/semantic-release/semantic-release/issues/1558\n if (envVar === 'GOPRIVATE') {\n return false;\n }\n\n return /token|password|credential|secret|private/i.test(envVar) && size(env[envVar].trim()) >= SECRET_MIN_SIZE;\n });\n\n const regexp = new RegExp(toReplace.map((envVar) => escapeRegExp(env[envVar])).join('|'), 'g');\n return (output) =>\n output && isString(output) && toReplace.length > 0 ? output.toString().replace(regexp, SECRET_REPLACEMENT) : output;\n};", "label_name": "CWE-116", "label": "116"} -{"code": " 'X-Parse-Session-Token': user5.getSessionToken(),\n })\n ).data.find.edges.map((object) => object.node.someField)\n ).toEqual(['someValue3']);\n });", "label_name": "CWE-863", "label": "863"} -{"code": " private _buildData(data: Buffer) {\n if (data && this._stack.length === 0) {\n return data;\n }\n if (!data && this._stack.length === 1) {\n data = this._stack[0];\n this._stack.length = 0; // empty stack array\n return data;\n }\n this._stack.push(data);\n data = Buffer.concat(this._stack);\n this._stack.length = 0;\n return data;\n }", "label_name": "CWE-400", "label": "400"} -{"code": " get: ({ params }) => ({ status: 200, body: { id: params.userId, name: 'bbb' } })\n}))", "label_name": "CWE-20", "label": "20"} -{"code": " isValidUser(username, password) {\n const user = users.find(user => user.username === username);\n if (!user) return false;\n return user.password === password;\n }", "label_name": "CWE-400", "label": "400"} -{"code": " ): Promise => {\n event.preventDefault();\n\n if (SingleSignOn.isSingleSignOnLoginWindow(frameName)) {\n return new SingleSignOn(main, event, url, options).init();\n }\n\n this.logger.log('Opening an external window from a webview.');\n return shell.openExternal(url);\n };", "label_name": "CWE-20", "label": "20"} -{"code": " resetPassword(req) {\n const config = req.config;\n\n if (!config) {\n this.invalidRequest();\n }\n\n if (!config.publicServerURL) {\n return this.missingPublicServerURL();\n }\n\n const { username, token, new_password } = req.body;\n\n if ((!username || !token || !new_password) && req.xhr === false) {\n return this.invalidLink(req);\n }\n\n if (!username) {\n throw new Parse.Error(Parse.Error.USERNAME_MISSING, 'Missing username');\n }\n\n if (!token) {\n throw new Parse.Error(Parse.Error.OTHER_CAUSE, 'Missing token');\n }\n\n if (!new_password) {\n throw new Parse.Error(Parse.Error.PASSWORD_MISSING, 'Missing password');\n }\n\n return config.userController\n .updatePassword(username, token, new_password)\n .then(\n () => {\n return Promise.resolve({\n success: true,\n });\n },\n err => {\n return Promise.resolve({\n success: false,\n err,\n });\n }\n )\n .then(result => {\n const params = qs.stringify({\n username: username,\n token: token,\n id: config.applicationId,\n error: result.err,\n app: config.appName,\n });\n\n if (req.xhr) {\n if (result.success) {\n return Promise.resolve({\n status: 200,\n response: 'Password successfully reset',\n });\n }\n if (result.err) {\n throw new Parse.Error(Parse.Error.OTHER_CAUSE, `${result.err}`);\n }\n }\n\n const encodedUsername = encodeURIComponent(username);\n const location = result.success\n ? `${config.passwordResetSuccessURL}?username=${encodedUsername}`\n : `${config.choosePasswordURL}?${params}`;\n\n return Promise.resolve({\n status: 302,\n location,\n });\n });\n }", "label_name": "CWE-863", "label": "863"} -{"code": "function process_request_callback(requestData: RequestData, err?: Error | null, response?: Response) {\r\n assert(typeof requestData.callback === \"function\");\r\n\r\n const request = requestData.request;\r\n\r\n if (!response && !err && requestData.msgType !== \"CLO\") {\r\n // this case happens when CLO is called and when some pending transactions\r\n // remains in the queue...\r\n err = new Error(\" Connection has been closed by client , but this transaction cannot be honored\");\r\n }\r\n\r\n if (response && response instanceof ServiceFault) {\r\n response.responseHeader.stringTable = [...(response.responseHeader.stringTable || [])];\r\n err = new Error(\" serviceResult = \" + response.responseHeader.serviceResult.toString());\r\n // \" returned by server \\n response:\" + response.toString() + \"\\n request: \" + request.toString());\r\n (err as any).response = response;\r\n ((err as any).request = request), (response = undefined);\r\n }\r\n\r\n const theCallbackFunction = requestData.callback;\r\n /* istanbul ignore next */\r\n if (!theCallbackFunction) {\r\n throw new Error(\"Internal error\");\r\n }\r\n assert(requestData.msgType === \"CLO\" || (err && !response) || (!err && response));\r\n\r\n // let set callback to undefined to prevent callback to be called again\r\n requestData.callback = undefined;\r\n\r\n theCallbackFunction(err || null, !err && response !== null ? response : undefined);\r\n}\r", "label_name": "CWE-400", "label": "400"} -{"code": " static buildGenesisOpReturn(config: configBuildGenesisOpReturn, type = 0x01) {\n let hash;\n try { \n hash = config.hash!.toString('hex')\n } catch (_) { hash = null }\n \n return SlpTokenType1.buildGenesisOpReturn(\n config.ticker,\n config.name,\n config.documentUri,\n hash,\n config.decimals,\n config.batonVout,\n config.initialQuantity, \n type\n )\n }", "label_name": "CWE-20", "label": "20"} -{"code": " .catch(error => {\n // There was an error with the session token\n const result = {};\n if (error && error.code === Parse.Error.INVALID_SESSION_TOKEN) {\n // Store a resolved promise with the error for 10 minutes\n result.error = error;\n this.authCache.set(\n sessionToken,\n Promise.resolve(result),\n 60 * 10 * 1000\n );\n } else {", "label_name": "CWE-672", "label": "672"} -{"code": " etsyApiFetch(endpoint, options) {\r\n this._assumeField('endpoint', endpoint);\r\n return new Promise((resolve, reject) => {\r\n const getQueryString = queryString.stringify(this.getOptions(options));\r\n fetch(`${this.apiUrl}${endpoint}?${getQueryString}`)\r\n .then(response => EtsyClient._response(response, resolve, reject))\r\n .catch(reject);\r\n });\r\n }\r", "label_name": "CWE-200", "label": "200"} -{"code": " constructor() {\n super();\n this._aborted = 0;\n this._helloReceived = false;\n this.receiveBufferSize = 0;\n this.sendBufferSize = 0;\n this.maxMessageSize = 0;\n this.maxChunkCount = 0;\n this.protocolVersion = 0;\n }", "label_name": "CWE-400", "label": "400"} -{"code": " userPassword: bcrypt.hashSync(req.body.userPassword, 10),\n isAdmin: isAdmin\n };\n\n // check for existing user\n db.users.findOne({'userEmail': req.body.userEmail}, (err, user) => {\n if(user){\n // user already exists with that email address\n console.error(colors.red('Failed to insert user, possibly already exists: ' + err));\n req.session.message = 'A user with that email address already exists';\n req.session.messageType = 'danger';\n res.redirect('/admin/user/new');\n return;\n }\n // email is ok to be used.\n db.users.insert(doc, (err, doc) => {\n // show the view\n if(err){\n if(doc){\n console.error(colors.red('Failed to insert user: ' + err));\n req.session.message = 'User exists';\n req.session.messageType = 'danger';\n res.redirect('/admin/user/edit/' + doc._id);\n return;\n }\n console.error(colors.red('Failed to insert user: ' + err));\n req.session.message = 'New user creation failed';\n req.session.messageType = 'danger';\n res.redirect('/admin/user/new');\n return;\n }\n req.session.message = 'User account inserted';\n req.session.messageType = 'success';\n\n // if from setup we add user to session and redirect to login.\n // Otherwise we show users screen\n if(urlParts.path === '/admin/setup'){\n req.session.user = req.body.userEmail;\n res.redirect('/admin/login');\n return;\n }\n res.redirect('/admin/users');\n });\n });\n});", "label_name": "CWE-732", "label": "732"} -{"code": " private _renew_security_token() {\r\n doDebug && debugLog(\"ClientSecureChannelLayer#_renew_security_token\");\r\n\r\n // istanbul ignore next\r\n if (!this.isValid()) {\r\n // this may happen if the communication has been closed by the client or the sever\r\n warningLog(\"Invalid socket => Communication has been lost, cannot renew token\");\r\n return;\r\n }\r\n\r\n const isInitial = false;\r\n this._open_secure_channel_request(isInitial, (err?: Error | null) => {\r\n /* istanbul ignore else */\r\n if (!err) {\r\n doDebug && debugLog(\" token renewed\");\r\n /**\r\n * notify the observers that the security has been renewed\r\n * @event security_token_renewed\r\n */\r\n this.emit(\"security_token_renewed\");\r\n } else {\r\n if (doDebug) {\r\n debugLog(\"ClientSecureChannelLayer: Warning: securityToken hasn't been renewed -> err \", err);\r\n }\r\n // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX CHECK ME !!!\r\n this.closeWithError(new Error(\"Restarting because Request has timed out during OpenSecureChannel\"), () => {\r\n /* */\r\n });\r\n }\r\n });\r\n }\r", "label_name": "CWE-400", "label": "400"} -{"code": " constructor() {\n super();\n\n this.name = this.constructor.name + counter;\n counter += 1;\n\n this._timerId = null;\n this._timeout = 30000; // 30 seconds timeout\n this._socket = null;\n this.headerSize = 8;\n this.protocolVersion = 0;\n\n this._disconnecting = false;\n this._pendingBuffer = undefined;\n\n this.bytesWritten = 0;\n this.bytesRead = 0;\n\n this._theCallback = undefined;\n this.chunkWrittenCount = 0;\n this.chunkReadCount = 0;\n\n this._onSocketClosedHasBeenCalled = false;\n this._onSocketEndedHasBeenCalled = false;\n TCP_transport.registry.register(this);\n }", "label_name": "CWE-400", "label": "400"} -{"code": " get: (path) => {\n useCount++;\n expect(path).toEqual('somepath');\n },\n })\n ).not.toThrow();\n expect(useCount).toBeGreaterThan(0);\n });", "label_name": "CWE-863", "label": "863"} -{"code": " link: new ApolloLink((operation, forward) => {\n return forward(operation).map((response) => {\n const context = operation.getContext();\n const {\n response: { headers },\n } = context;\n expect(headers.get('access-control-allow-origin')).toEqual('*');\n checked = true;\n return response;\n });\n }).concat(\n createHttpLink({\n uri: 'http://localhost:13377/graphql',\n fetch,\n headers: {\n ...headers,\n Origin: 'http://someorigin.com',\n },\n })\n ),\n cache: new InMemoryCache(),\n });", "label_name": "CWE-863", "label": "863"} -{"code": " }\n\n actionItems() {\n let composing = new PrivateComposing(this.user);\n\n const items = new ItemList();\n\n if (app.session.user && app.forum.attribute('canStartPrivateDiscussion')) {\n items.add('start_private', composing.component());\n }\n", "label_name": "CWE-269", "label": "269"} -{"code": " this.transport.init(socket, (err?: Error) => {\n if (err) {\n callback(err);\n } else {\n this._rememberClientAddressAndPort();\n\n this.messageChunker.maxMessageSize = this.transport.maxMessageSize;\n\n // bind low level TCP transport to messageBuilder\n this.transport.on(\"message\", (messageChunk: Buffer) => {\n assert(this.messageBuilder);\n this.messageBuilder.feed(messageChunk);\n });\n debugLog(\"ServerSecureChannelLayer : Transport layer has been initialized\");\n debugLog(\"... now waiting for OpenSecureChannelRequest...\");\n\n ServerSecureChannelLayer.registry.register(this);\n\n this._wait_for_open_secure_channel_request(callback, this.timeout);\n }\n });", "label_name": "CWE-400", "label": "400"} -{"code": " constructor(options: PacketAssemblerOptions) {\n super();\n this._stack = [];\n this.expectedLength = 0;\n this.currentLength = 0;\n this.readMessageFunc = options.readMessageFunc;\n this.minimumSizeInBytes = options.minimumSizeInBytes || 8;\n assert(typeof this.readMessageFunc === \"function\", \"packet assembler requires a readMessageFunc\");\n }", "label_name": "CWE-400", "label": "400"} -{"code": " use: (path) => {\n useCount++;\n expect(path).toEqual('somepath');\n },\n })\n ).not.toThrow();\n expect(useCount).toBeGreaterThan(0);\n });", "label_name": "CWE-863", "label": "863"} -{"code": " let getNftParentId = async (tokenIdHex: string) => {\n let txnhex = (await asyncSlpValidator.getRawTransactions([tokenIdHex]))[0];\n let tx = Primatives.Transaction.parseFromBuffer(Buffer.from(txnhex, 'hex'));\n let nftBurnTxnHex = (await asyncSlpValidator.getRawTransactions([tx.inputs[0].previousTxHash]))[0];\n let nftBurnTxn = Primatives.Transaction.parseFromBuffer(Buffer.from(nftBurnTxnHex, 'hex'));\n let slp = new Slp(this.BITBOX);\n let nftBurnSlp = slp.parseSlpOutputScript(Buffer.from(nftBurnTxn.outputs[0].scriptPubKey));\n if (nftBurnSlp.transactionType === SlpTransactionType.GENESIS) {\n return tx.inputs[0].previousTxHash;\n }\n else {\n return nftBurnSlp.tokenIdHex;\n }\n }", "label_name": "CWE-20", "label": "20"} -{"code": " @action gotoUrl = (_url) => {\n transaction(() => {\n let url = (_url || this.nextUrl).trim().replace(/\\/+$/, '');\n\n if (!hasProtocol.test(url)) {\n url = `https://${url}`;\n }\n\n this.setNextUrl(url);\n this.setCurrentUrl(this.nextUrl);\n });\n }", "label_name": "CWE-346", "label": "346"} -{"code": " throw new Error(`Email(s) (${failed.join(\", \")}) could not be sent`)\n }\n },", "label_name": "CWE-863", "label": "863"} -{"code": "WebContents.prototype._sendToFrameInternal = function (frameId, channel, ...args) {\n if (typeof channel !== 'string') {\n throw new Error('Missing required channel argument');\n } else if (typeof frameId !== 'number') {\n throw new Error('Missing required frameId argument');\n }\n\n return this._sendToFrame(true /* internal */, frameId, channel, args);\n};", "label_name": "CWE-668", "label": "668"} -{"code": "async function validateSPLTokenTransfer(\n message: Message,\n meta: ConfirmedTransactionMeta,\n recipient: Recipient,\n splToken: SPLToken\n): Promise<[BigNumber, BigNumber]> {\n const recipientATA = await getAssociatedTokenAddress(splToken, recipient);\n const accountIndex = message.accountKeys.findIndex((pubkey) => pubkey.equals(recipientATA));\n if (accountIndex === -1) throw new ValidateTransferError('recipient not found');\n\n const preBalance = meta.preTokenBalances?.find((x) => x.accountIndex === accountIndex);\n const postBalance = meta.postTokenBalances?.find((x) => x.accountIndex === accountIndex);\n\n return [\n new BigNumber(preBalance?.uiTokenAmount.uiAmountString || 0),\n new BigNumber(postBalance?.uiTokenAmount.uiAmountString || 0),\n ];\n}", "label_name": "CWE-670", "label": "670"} -{"code": "async function validateSystemTransfer(\n message: Message,\n meta: ConfirmedTransactionMeta,\n recipient: Recipient\n): Promise<[BigNumber, BigNumber]> {\n const accountIndex = message.accountKeys.findIndex((pubkey) => pubkey.equals(recipient));\n if (accountIndex === -1) throw new ValidateTransferError('recipient not found');\n\n return [\n new BigNumber(meta.preBalances[accountIndex] || 0).div(LAMPORTS_PER_SOL),\n new BigNumber(meta.postBalances[accountIndex] || 0).div(LAMPORTS_PER_SOL),\n ];\n}", "label_name": "CWE-670", "label": "670"} -{"code": " link: new ApolloLink((operation, forward) => {\n return forward(operation).map((response) => {\n const context = operation.getContext();\n const {\n response: { headers },\n } = context;\n expect(headers.get('access-control-allow-origin')).toEqual('*');\n checked = true;\n return response;\n });\n }).concat(", "label_name": "CWE-863", "label": "863"} -{"code": " calculateGenesisCost(genesisOpReturnLength: number, inputUtxoSize: number, batonAddress: string|null, bchChangeAddress?: string, feeRate = 1) {\n return this.calculateMintOrGenesisCost(genesisOpReturnLength, inputUtxoSize, batonAddress, bchChangeAddress, feeRate);\n }", "label_name": "CWE-20", "label": "20"} -{"code": " event.reply = (...args: any[]) => {\n event.sender.sendToFrame(event.frameId, ...args);\n };", "label_name": "CWE-668", "label": "668"} -{"code": "export function get(key: \"treeIcons\"): boolean;\nexport function get(key: \"apiUrl\"): string;", "label_name": "CWE-863", "label": "863"} -{"code": " stitchSchemas({ subschemas: [autoSchema] }),\n });\n\n parseGraphQLServer.applyGraphQL(expressApp);\n await new Promise((resolve) =>\n httpServer.listen({ port: 13377 }, resolve)\n );\n const httpLink = createUploadLink({\n uri: 'http://localhost:13377/graphql',\n fetch,\n headers,\n });\n apolloClient = new ApolloClient({\n link: httpLink,\n cache: new InMemoryCache(),\n defaultOptions: {\n query: {\n fetchPolicy: 'no-cache',\n },\n },\n });\n });\n\n afterAll(async () => {\n await httpServer.close();\n });\n\n it('can resolve a query', async () => {\n const result = await apolloClient.query({\n query: gql`\n query Health {\n health\n }\n `,\n });\n expect(result.data.health).toEqual(true);\n });\n });", "label_name": "CWE-863", "label": "863"} -{"code": "const addReplyToEvent = (event: any) => {\n event.reply = (...args: any[]) => {\n event.sender.sendToFrame(event.frameId, ...args);\n };\n};", "label_name": "CWE-668", "label": "668"} -{"code": " componentDidMount () {\n this.store.gotoUrl(this.props.params.url);\n return this.store.generateToken();\n }", "label_name": "CWE-346", "label": "346"} -{"code": " await manager.update(User, organizationUser.userId, { invitationToken: uuid.v4(), password: uuid.v4() });\n });", "label_name": "CWE-74", "label": "74"} -{"code": "async function decodeMessage(buffer: Buffer): Promise {\n /*\n const offset = 16 * 3 + 6;\n buffer = buffer.slice(offset);\n */\n const messageBuilder = new MessageBuilder({});\n messageBuilder.setSecurity(MessageSecurityMode.None, SecurityPolicy.None);\n let objMessage: any = null;\n messageBuilder.once(\"full_message_body\", (fullMessageBody: Buffer) => {\n const stream = new BinaryStream(fullMessageBody);\n const id = decodeExpandedNodeId(stream);\n objMessage = constructObject(id);\n objMessage.decode(stream);\n });\n messageBuilder.feed(buffer);\n\n return objMessage;\n}", "label_name": "CWE-400", "label": "400"} -{"code": " redirect: `${url}/error?${new URLSearchParams({\n error: error as string,\n })}`,\n }\n }\n\n try {\n const redirect = await emailSignin(email, options)\n return { redirect }\n } catch (error) {\n logger.error(\"SIGNIN_EMAIL_ERROR\", {\n error: error as Error,\n providerId: provider.id,\n })\n return { redirect: `${url}/error?error=EmailSignin` }\n }\n }\n return { redirect: `${url}/signin` }\n}", "label_name": "CWE-863", "label": "863"} -{"code": " calculateMintCost(mintOpReturnLength: number, inputUtxoSize: number, batonAddress: string|null, bchChangeAddress?: string, feeRate = 1) {\n return this.calculateMintOrGenesisCost(mintOpReturnLength, inputUtxoSize, batonAddress, bchChangeAddress, feeRate);\n }", "label_name": "CWE-20", "label": "20"} -{"code": "module.exports = (yargs) => {\n yargs.command('exec [commands...]', 'Execute command in docker container', () => {}, async (argv) => {\n const containers = docker.getContainers();\n const services = Object.keys(containers);\n\n if (services.includes(argv.containername) || services.some((service) => service.includes(argv.containername))) {\n const container = containers[argv.containername]\n ? containers[argv.containername]\n : Object.entries(containers).find(([key]) => key.includes(argv.containername))[1];\n\n if (argv.commands.length === 0) {\n // if we have default connect command then use it\n if (container.connectCommand) {\n // eslint-disable-next-line no-param-reassign\n argv.commands = container.connectCommand;\n } else {\n // otherwise fall back to bash (if it exists inside container)\n argv.commands.push('bash');\n }\n }\n await executeInContainer({\n containerName: container.name,\n commands: argv.commands\n });\n\n return;\n }\n\n logger.error(`No container found \"${argv.containername}\"`);\n });\n};", "label_name": "CWE-670", "label": "670"} +{"code": " protected function fixupImportedAttributes($modelName, X2Model &$model) {\n if ($modelName === 'Contacts' || $modelName === 'X2Leads')\n $this->fixupImportedContactName ($model);\n\n if ($modelName === 'Actions' && isset($model->associationType))\n $this->reconstructImportedActionAssoc($model);\n\n if ($model->hasAttribute('visibility')) {\n // Nobody every remembers to set visibility... set it for them\n if(empty($model->visibility) && ($model->visibility !== 0 && $model->visibility !== \"0\")\n || $model->visibility == 'Public') {\n $model->visibility = 1;\n } elseif($model->visibility == 'Private')\n $model->visibility = 0;\n }\n // If date fields were provided, do not create new values for them\n if (!empty($model->createDate) || !empty($model->lastUpdated) ||\n !empty($model->lastActivity)) {\n $now = time();\n if (empty($model->createDate))\n $model->createDate = $now;\n if (empty($model->lastUpdated))\n $model->lastUpdated = $now;\n if ($model->hasAttribute('lastActivity') && empty($model->lastActivity))\n $model->lastActivity = $now;\n }\n if($_SESSION['leadRouting'] == 1){\n $assignee = $this->getNextAssignee();\n if($assignee == \"Anyone\")\n $assignee = \"\";\n $model->assignedTo = $assignee;\n }\n // Loop through our override and set the manual data\n foreach($_SESSION['override'] as $attr => $val){\n $model->$attr = $val;\n }\n }", "label_name": "CWE-20", "label": 0} +{"code": " function import() {\r\n $pullable_modules = expModules::listInstalledControllers($this->baseclassname);\r\n $modules = new expPaginator(array(\r\n 'records' => $pullable_modules,\r\n 'controller' => $this->loc->mod,\r\n 'action' => $this->params['action'],\r\n 'order' => isset($this->params['order']) ? $this->params['order'] : 'section',\r\n 'dir' => isset($this->params['dir']) ? $this->params['dir'] : '',\r\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\r\n 'columns' => array(\r\n gt('Title') => 'title',\r\n gt('Page') => 'section'\r\n ),\r\n ));\r\n\r\n assign_to_template(array(\r\n 'modules' => $modules,\r\n ));\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public static function returnChildrenAsJSON() {\r\n global $db;\r\n\r\n //$nav = section::levelTemplate(intval($_REQUEST['id'], 0));\r\n $id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;\r\n $nav = $db->selectObjects('section', 'parent=' . $id, 'rank');\r\n //FIXME $manage_all is moot w/ cascading perms now?\r\n $manage_all = false;\r\n if (expPermissions::check('manage', expCore::makeLocation('navigation', '', $id))) {\r\n $manage_all = true;\r\n }\r\n //FIXME recode to use foreach $key=>$value\r\n $navcount = count($nav);\r\n for ($i = 0; $i < $navcount; $i++) {\r\n if ($manage_all || expPermissions::check('manage', expCore::makeLocation('navigation', '', $nav[$i]->id))) {\r\n $nav[$i]->manage = 1;\r\n $view = true;\r\n } else {\r\n $nav[$i]->manage = 0;\r\n $view = $nav[$i]->public ? true : expPermissions::check('view', expCore::makeLocation('navigation', '', $nav[$i]->id));\r\n }\r\n $nav[$i]->link = expCore::makeLink(array('section' => $nav[$i]->id), '', $nav[$i]->sef_name);\r\n if (!$view) unset($nav[$i]);\r\n }\r\n $nav= array_values($nav);\r\n// $nav[$navcount - 1]->last = true;\r\n if (count($nav)) $nav[count($nav) - 1]->last = true;\r\n// echo expJavascript::ajaxReply(201, '', $nav);\r\n $ar = new expAjaxReply(201, '', $nav);\r\n $ar->send();\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": "function XMLRPCtest($string) {\n\t$string = processInputData($string, ARG_STRING);\n\treturn array('status' => 'success',\n\t 'message' => 'RPC call worked successfully',\n\t 'string' => $string);\n}", "label_name": "CWE-20", "label": 0} +{"code": " static function description() { return gt(\"Places navigation links/menus on the page.\"); }\r", "label_name": "CWE-74", "label": 1} +{"code": " static function author() {\r\n return \"Dave Leffler\";\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic function formatItem( Article $article, $pageText = null ) {\n\t\t$item = '';\n\n\t\tif ( $pageText !== null ) {\n\t\t\t//Include parsed/processed wiki markup content after each item before the closing tag.\n\t\t\t$item .= $pageText;\n\t\t}\n\n\t\t$item = $this->getItemStart() . $item . $this->getItemEnd();\n\n\t\t$item = $this->replaceTagParameters( $item, $article );\n\n\t\treturn $item;\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " public static function getHelpVersion($version_id) {\n global $db;\n\n return $db->selectValue('help_version', 'version', 'id=\"'.$version_id.'\"');\n }", "label_name": "CWE-74", "label": 1} +{"code": "\tfunction lockTable($table,$lockType=\"WRITE\") {\n $sql = \"LOCK TABLES `\" . $this->prefix . \"$table` $lockType\";\n \n $res = mysqli_query($this->connection, $sql); \n return $res;\n }", "label_name": "CWE-74", "label": 1} +{"code": " $module_views[$key]['name'] = gt($value['name']);\n }\n\n // look for a config form for this module's current view \n// $controller->loc->mod = expModules::getControllerClassName($controller->loc->mod);\n //check to see if hcview was passed along, indicating a hard-coded module\n// if (!empty($controller->params['hcview'])) {\n// $viewname = $controller->params['hcview'];\n// } else {\n// $viewname = $db->selectValue('container', 'view', \"internal='\".serialize($controller->loc).\"'\");\n// }\n// $viewconfig = $viewname.'.config';\n// foreach ($modpaths as $path) {\n// if (file_exists($path.'/'.$viewconfig)) {\n// $fileparts = explode('_', $viewname);\n// if ($fileparts[0]=='show'||$fileparts[0]=='showall') array_shift($fileparts);\n// $module_views[$viewname]['name'] = ucwords(implode(' ', $fileparts)).' '.gt('View Configuration');\n// $module_views[$viewname]['file'] =$path.'/'.$viewconfig;\n// }\n// }\n \n // sort the views highest to lowest by filename\n // we are reverse sorting now so our array merge\n // will overwrite property..we will run array_reverse\n // when we're finished to get them back in the right order\n krsort($common_views);\n krsort($module_views);\n\n if (!empty($moduleconfig)) $common_views = array_merge($common_views, $moduleconfig);\n $views = array_merge($common_views, $module_views);\n $views = array_reverse($views);\n\n return $views;\n}", "label_name": "CWE-74", "label": 1} +{"code": "\t\t\t$result = $search->getSearchResults($item->query, false, true);\n\t\t\tif(empty($result) && !in_array($item->query, $badSearchArr)) {\n\t\t\t\t$badSearchArr[] = $item->query;\n\t\t\t\t$badSearch[$ctr2]['query'] = $item->query;\n\t\t\t\t$badSearch[$ctr2]['count'] = $db->countObjects(\"search_queries\", \"query='{$item->query}'\");\n\t\t\t\t$ctr2++;\n\t\t\t}\n\t\t\t\n\t\t}\n\t\n\t\t//Check if the user choose from the dropdown\n\t\tif(!empty($user_default)) {\n\t\t\tif($user_default == $anonymous) {\n\t\t\t\t$u_id = 0;\n\t\t\t} else {\n\t\t\t\t$u_id = $user_default;\n\t\t\t}\n\t\t\t$where .= \"user_id = {$u_id}\";\n\t\t}\n\t\n\t\t//Get all the search query records\n\t\t$records = $db->selectObjects('search_queries', $where);\n for ($i = 0, $iMax = count($records); $i < $iMax; $i++) {\n\t\t\tif(!empty($records[$i]->user_id)) {\n\t\t\t\t$u = user::getUserById($records[$i]->user_id);\n\t\t\t\t$records[$i]->user = $u->firstname . ' ' . $u->lastname;\n\t\t\t}\n\t\t}\n\t\t\n $page = new expPaginator(array(\n 'records' => $records,\n 'where'=>1,\n 'model'=>'search_queries',\n 'limit'=>(isset($this->config['limit']) && $this->config['limit'] != '') ? 10 : $this->config['limit'],\n 'order'=>empty($this->config['order']) ? 'timestamp' : $this->config['order'],\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->baseclassname,\n 'action'=>$this->params['action'],\n 'columns'=>array(\n 'ID'=>'id',\n gt('Query')=>'query',\n gt('Timestamp')=>'timestamp',\n gt('User')=>'user_id',\n ),\n ));\n\n $uname['id'] = implode($uname['id'],',');\n $uname['name'] = implode($uname['name'],',');\n assign_to_template(array(\n 'page'=>$page,\n 'users'=>$uname,\n 'user_default' => $user_default,\n 'badSearch' => $badSearch\n ));\n\t\t\n\t}", "label_name": "CWE-74", "label": 1} +{"code": "\tstatic function validUTF($string) {\n\t\tif(!mb_check_encoding($string, 'UTF-8') OR !($string === mb_convert_encoding(mb_convert_encoding($string, 'UTF-32', 'UTF-8' ), 'UTF-8', 'UTF-32'))) {\n\t\t\treturn false;\n\t\t}\t\t\n\t\treturn true;\n\t}", "label_name": "CWE-74", "label": 1} +{"code": " public function testEncrypt($string, $key, $expected) {\n $this->string(\\Toolbox::encrypt($string, $key))->isIdenticalTo($expected);\n }", "label_name": "CWE-327", "label": 3} +{"code": " public function onKernelResponse(ResponseEvent $event)\n {\n if (!$event->isMainRequest()) {\n return;\n }\n\n $request = $event->getRequest();\n\n if (!$request->hasSession() || !$request->attributes->get('_security_firewall_run', false)) {\n return;\n }\n\n if ($this->dispatcher) {\n $this->dispatcher->removeListener(KernelEvents::RESPONSE, [$this, 'onKernelResponse']);\n }\n $this->registered = false;\n $session = $request->getSession();\n $sessionId = $session->getId();\n $usageIndexValue = $session instanceof Session ? $usageIndexReference = &$session->getUsageIndex() : null;\n $token = $this->tokenStorage->getToken();\n\n if (null === $token || $this->trustResolver->isAnonymous($token)) {\n if ($request->hasPreviousSession()) {\n $session->remove($this->sessionKey);\n }\n } else {\n $session->set($this->sessionKey, serialize($token));\n\n if (null !== $this->logger) {\n $this->logger->debug('Stored the security token in the session.', ['key' => $this->sessionKey]);\n }\n }\n\n if ($this->sessionTrackerEnabler && $session->getId() === $sessionId) {\n $usageIndexReference = $usageIndexValue;\n }\n }", "label_name": "CWE-287", "label": 4} +{"code": "\tprivate function _categoriesminmax( $option ) {\n\t\tif ( is_numeric( $option[0] ) ) {\n\t\t\t$this->addWhere( intval( $option[0] ) . ' <= (SELECT count(*) FROM ' . $this->tableNames['categorylinks'] . ' WHERE ' . $this->tableNames['categorylinks'] . '.cl_from=page_id)' );\n\t\t}\n\t\tif ( is_numeric( $option[1] ) ) {\n\t\t\t$this->addWhere( intval( $option[1] ) . ' >= (SELECT count(*) FROM ' . $this->tableNames['categorylinks'] . ' WHERE ' . $this->tableNames['categorylinks'] . '.cl_from=page_id)' );\n\t\t}\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " public static function parseAndTrimImport($str, $isHTML = false) { //\ufffdDeath from above\ufffd? \ufffd\n //echo \"1
\"; eDebug($str);\n// global $db;\n\n $str = str_replace(\"\ufffd\", \"’\", $str);\n $str = str_replace(\"\ufffd\", \"‘\", $str);\n $str = str_replace(\"\ufffd\", \"®\", $str);\n $str = str_replace(\"\ufffd\", \"-\", $str);\n $str = str_replace(\"\ufffd\", \"—\", $str);\n $str = str_replace(\"\ufffd\", \"”\", $str);\n $str = str_replace(\"\ufffd\", \"“\", $str);\n $str = str_replace(\"\\r\\n\", \" \", $str);\n $str = str_replace(\"\\,\", \",\", $str);\n $str = str_replace('\"\"', '\"', $str); //do this no matter what...in case someone added a quote in a non HTML field\n if (!$isHTML) {\n //if HTML, then leave the single quotes alone, otheriwse replace w/ special Char \n $str = str_replace('\"', \""\", $str);\n }\n $str = str_replace(\"\ufffd\", \"¼\", $str);\n $str = str_replace(\"\ufffd\", \"½\", $str);\n $str = str_replace(\"\ufffd\", \"¾\", $str);\n //$str = htmlspecialchars($str);\n //$str = utf8_encode($str);\n// if (DB_ENGINE=='mysqli') {\n//\t $str = @mysqli_real_escape_string($db->connection,trim(str_replace(\"\ufffd\", \"™\", $str)));\n// } elseif(DB_ENGINE=='mysql') {\n// $str = @mysql_real_escape_string(trim(str_replace(\"\ufffd\", \"™\", $str)),$db->connection);\n// } else {\n//\t $str = trim(str_replace(\"\ufffd\", \"™\", $str));\n// }\n $str = @expString::escape(trim(str_replace(\"\ufffd\", \"™\", $str)));\n //echo \"2
\"; eDebug($str,die);\n return $str;\n }", "label_name": "CWE-74", "label": 1} +{"code": " public function testUserCredentials($email, $password, $server, $port, $security) {\n require_once(realpath(Yii::app()->basePath.'/components/phpMailer/class.phpmailer.php'));\n require_once(realpath(Yii::app()->basePath.'/components/phpMailer/class.smtp.php'));\n $phpMail = new PHPMailer(true);\n\n $phpMail->isSMTP();\n $phpMail->SMTPAuth = true;\n $phpMail->Username = $email;\n $phpMail->Password = $password;\n $phpMail->Host = $server;\n $phpMail->Port = $port;\n $phpMail->SMTPSecure = $security;\n\n try {\n $validCredentials = $phpMail->SmtpConnect();\n } catch(phpmailerException $error) {\n $validCredentials = false;\n }\n return $validCredentials;\n }", "label_name": "CWE-20", "label": 0} +{"code": " protected function markCompleted($endStatus, ServiceResponse $serviceResponse, $gatewayMessage)\n {\n parent::markCompleted($endStatus, $serviceResponse, $gatewayMessage);\n $this->createMessage(Message\\VoidedResponse::class, $gatewayMessage);\n\n ErrorHandling::safeExtend($this->payment, 'onVoid', $serviceResponse);\n }", "label_name": "CWE-436", "label": 5} +{"code": "\tpublic function delete_version() {\n\t if (empty($this->params['id'])) {\n\t flash('error', gt('The version you are trying to delete could not be found'));\n\t }\n\t \n\t // get the version\n\t $version = new help_version($this->params['id']);\n\t if (empty($version->id)) {\n\t flash('error', gt('The version you are trying to delete could not be found'));\n\t }\n\t \n\t // if we have errors than lets get outta here!\n\t if (!expQueue::isQueueEmpty('error')) expHistory::back();\n\t \n\t // delete the version\n\t $version->delete();\n\t \n\t expSession::un_set('help-version');\n\n\t flash('message', gt('Deleted version').' '.$version->version.' '.gt('and all documents in that version.'));\n\t expHistory::back();\t \n\t}", "label_name": "CWE-74", "label": 1} +{"code": " private function __pullEvent($eventId, &$successes, &$fails, $eventModel, $server, $user, $jobId)\n {\n $event = $eventModel->downloadEventFromServer(\n $eventId,\n $server\n );\n if (!empty($event)) {\n if ($this->__checkIfEventIsBlockedBeforePull($event)) {\n return false;\n }\n $event = $this->__updatePulledEventBeforeInsert($event, $server, $user);\n if (!$this->__checkIfEventSaveAble($event)) {\n $fails[$eventId] = __('Empty event detected.');\n } else {\n $this->__checkIfPulledEventExistsAndAddOrUpdate($event, $eventId, $successes, $fails, $eventModel, $server, $user, $jobId);\n }\n } else {\n // error\n $fails[$eventId] = __('failed downloading the event') . ': ' . json_encode($event);\n }\n return true;\n }", "label_name": "CWE-269", "label": 6} +{"code": " function showByModel() {\n global $order, $template, $db;\n\n expHistory::set('viewable', $this->params);\n $product = new product();\n $model = $product->find(\"first\", 'model=\"' . $this->params['model'] . '\"');\n //eDebug($model);\n $product_type = new $model->product_type($model->id);\n //eDebug($product_type);\n $tpl = $product_type->getForm('show');\n if (!empty($tpl)) $template = new controllertemplate($this, $tpl);\n //eDebug($template);\n $this->grabConfig(); // grab the global config\n assign_to_template(array(\n 'config' => $this->config,\n 'product' => $product_type,\n 'last_category' => $order->lastcat\n ));\n }", "label_name": "CWE-20", "label": 0} +{"code": " function edit_externalalias() {\r\n $section = isset($this->params['id']) ? $this->section->find($this->params['id']) : new section($this->params);\r\n if ($section->parent == -1) {\r\n notfoundController::handle_not_found();\r\n exit;\r\n } // doesn't work for standalone pages\r\n if (empty($section->id)) {\r\n $section->public = 1;\r\n if (!isset($section->parent)) {\r\n // This is another precaution. The parent attribute\r\n // should ALWAYS be set by the caller.\r\n //FJD - if that's the case, then we should die.\r\n notfoundController::handle_not_authorized();\r\n exit;\r\n //$section->parent = 0;\r\n }\r\n }\r\n assign_to_template(array(\r\n 'section' => $section,\r\n 'glyphs' => self::get_glyphs(),\r\n ));\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " private function checkResponse ($string) {\n if (substr($string, 0, 3) !== '+OK') {\n $this->error = array(\n 'error' => \"Server reported an error: $string\",\n 'errno' => 0,\n 'errstr' => ''\n );\n\n if ($this->do_debug >= 1) {\n $this->displayErrors();\n }\n\n return false;\n } else {\n return true;\n }\n\n }", "label_name": "CWE-20", "label": 0} +{"code": "\tpublic function approve_toggle() {\n\t if (empty($this->params['id'])) return;\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n// $require_login = empty($this->params['require_login']) ? COMMENTS_REQUIRE_LOGIN : $this->params['require_login'];\n// $require_approval = empty($this->params['require_approval']) ? COMMENTS_REQUIRE_APPROVAL : $this->params['require_approval'];\n// $require_notification = empty($this->params['require_notification']) ? COMMENTS_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n// $notification_email = empty($this->params['notification_email']) ? COMMENTS_NOTIFICATION_EMAIL : $this->params['notification_email'];\n\n\t $comment = new expComment($this->params['id']);\n\t $comment->approved = $comment->approved == 1 ? 0 : 1;\n\t if ($comment->approved) {\n\t\t $this->sendApprovalNotification($comment,$this->params);\n\t }\n\t $comment->save();\n\t expHistory::back();\n\t}", "label_name": "CWE-74", "label": 1} +{"code": " $section = new section(intval($page));\r\n if ($section) {\r\n// self::deleteLevel($section->id);\r\n $section->delete();\r\n }\r\n }\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": "\tprivate function _minrevisions( $option ) {\n\t\t$this->addWhere( \"((SELECT count(rev_aux2.revactor_page) FROM {$this->tableNames['revision_actor_temp']} AS rev_aux2 WHERE rev_aux2.revactor_page = {$this->tableNames['page']}.page_id) >= {$option})\" );\n\t}", "label_name": "CWE-400", "label": 2} +{"code": "\tprivate function getFullOutput( $totalResults = false, $skipHeaderFooter = true ) {\n\t\tif ( !$skipHeaderFooter ) {\n\t\t\t$header = '';\n\t\t\t$footer = '';\n\t\t\t//Only override header and footers if specified.\n\t\t\t$_headerType = $this->getHeaderFooterType( 'header', $totalResults );\n\t\t\tif ( $_headerType !== false ) {\n\t\t\t\t$header = $this->parameters->getParameter( $_headerType );\n\t\t\t}\n\t\t\t$_footerType = $this->getHeaderFooterType( 'footer', $totalResults );\n\t\t\tif ( $_footerType !== false ) {\n\t\t\t\t$footer = $this->parameters->getParameter( $_footerType );\n\t\t\t}\n\n\t\t\t$this->setHeader( $header );\n\t\t\t$this->setFooter( $footer );\n\t\t}\n\n\t\tif ( !$totalResults && !strlen( $this->getHeader() ) && !strlen( $this->getFooter() ) ) {\n\t\t\t$this->logger->addMessage( \\DynamicPageListHooks::WARN_NORESULTS );\n\t\t}\n\t\t$messages = $this->logger->getMessages( false );\n\n\t\treturn ( count( $messages ) ? implode( \"
\\n\", $messages ) : null ) . $this->getHeader() . $this->getOutput() . $this->getFooter();\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " $ds = self::connectToServer($replicate[\"host\"], $replicate[\"port\"],\n $ldap_method['rootdn'],\n Toolbox::decrypt($ldap_method['rootdn_passwd'], GLPIKEY),\n $ldap_method['use_tls'], $ldap_method['deref_option']);\n\n // Test with login and password of the user\n if (!$ds\n && !empty($login)) {\n $ds = self::connectToServer($replicate[\"host\"], $replicate[\"port\"], $login,\n $password, $ldap_method['use_tls'],\n $ldap_method['deref_option']);\n }\n if ($ds) {\n return $ds;\n }\n }\n }", "label_name": "CWE-327", "label": 3} +{"code": "function invalidTestController($port) {\n $host = php_uname('n');\n\n $filename = __DIR__.'/request-doesnotexist.dat';\n $file = fopen($filename, 'rb');\n $req_dat = fread($file, filesize($filename));\n fclose($file);\n\n // Repeat the data three times, to make it invalid. This particular bytestream\n // (and ones like it -- repeat 3 times!) in particular used to tickle a\n // use-after-free in the FastCGI support.\n $req_dat = $req_dat . $req_dat . $req_dat;\n\n $sock = fsockopen($host, $port);\n fwrite($sock, $req_dat);\n fclose($sock);\n\n // Should still be able to recover and respond to a request over the port on a\n // new TCP connection.\n echo request($host, $port, 'hello.php');\n echo \"\\n\";\n}", "label_name": "CWE-668", "label": 7} +{"code": " public static function getTemplateHierarchyFlat($parent, $depth = 1) {\r\n global $db;\r\n\r\n $arr = array();\r\n $kids = $db->selectObjects('section_template', 'parent=' . $parent, 'rank');\r\n//\t\t$kids = expSorter::sort(array('array'=>$kids,'sortby'=>'rank', 'order'=>'ASC'));\r\n for ($i = 0, $iMax = count($kids); $i < $iMax; $i++) {\r\n $page = $kids[$i];\r\n $page->depth = $depth;\r\n $page->first = ($i == 0 ? 1 : 0);\r\n $page->last = ($i == count($kids) - 1 ? 1 : 0);\r\n $arr[] = $page;\r\n $arr = array_merge($arr, self::getTemplateHierarchyFlat($page->id, $depth + 1));\r\n }\r\n return $arr;\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": "function format_install_param( $value )\n{\n\t$value = str_replace( array( \"'\", \"\\$\" ), array( \"\\'\", \"\\\\$\" ), $value );\n\treturn preg_replace( \"#([\\\\\\\\]*)(\\\\\\\\\\\\\\')#\", \"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'\", $value );\n}", "label_name": "CWE-20", "label": 0} +{"code": " public function admin_delete($id = null)\n {\n if (!$this->request->is('post') && !$this->request->is('delete')) {\n throw new MethodNotAllowedException(__('Action not allowed, post or delete request expected.'));\n }\n if (!$this->_isAdmin()) {\n throw new Exception('Administrators only.');\n }\n $this->User->id = $id;\n $conditions = array('User.id' => $id);\n if (!$this->_isSiteAdmin()) {\n $conditions['org_id'] = $this->Auth->user('org_id');\n }\n $user = $this->User->find('first', array(\n 'conditions' => $conditions,\n 'recursive' => -1\n ));\n if (empty($user)) {\n throw new NotFoundException(__('Invalid user'));\n }\n $fieldsDescrStr = 'User (' . $id . '): ' . $user['User']['email'];\n if ($this->User->delete($id)) {\n $this->__extralog(\"delete\", $fieldsDescrStr, '');\n if ($this->_isRest()) {\n return $this->RestResponse->saveSuccessResponse('User', 'admin_delete', $id, $this->response->type(), 'User deleted.');\n } else {\n $this->Flash->success(__('User deleted'));\n $this->redirect(array('action' => 'index'));\n }\n }\n $this->Flash->error(__('User was not deleted'));\n $this->redirect(array('action' => 'index'));\n }", "label_name": "CWE-269", "label": 6} +{"code": " public function buildControl() {\r\n $control = new colorcontrol();\r\n if (!empty($this->params['value'])) $control->value = $this->params['value'];\r\n if ($this->params['value'][0] != '#') $this->params['value'] = '#' . $this->params['value'];\r\n $control->default = $this->params['value'];\r\n if (!empty($this->params['hide'])) $control->hide = $this->params['hide'];\r\n if (isset($this->params['flip'])) $control->flip = $this->params['flip'];\r\n $this->params['name'] = !empty($this->params['name']) ? $this->params['name'] : '';\r\n $control->name = $this->params['name'];\r\n $this->params['id'] = !empty($this->params['id']) ? $this->params['id'] : '';\r\n $control->id = isset($this->params['id']) && $this->params['id'] != \"\" ? $this->params['id'] : \"\";\r\n //echo $control->id;\r\n if (empty($control->id)) $control->id = $this->params['name'];\r\n if (empty($control->name)) $control->name = $this->params['id'];\r\n\r\n // attempt to translate the label\r\n if (!empty($this->params['label'])) {\r\n $this->params['label'] = gt($this->params['label']);\r\n } else {\r\n $this->params['label'] = null;\r\n }\r\n echo $control->toHTML($this->params['label'], $this->params['name']);\r\n// $ar = new expAjaxReply(200, gt('The control was created'), json_encode(array('data'=>$code)));\r\n// $ar->send();\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic function manage_versions() {\n\t expHistory::set('manageable', $this->params);\n\t \n\t $hv = new help_version();\n\t $current_version = $hv->find('first', 'is_current=1');\n\t \n\t $sql = 'SELECT hv.*, COUNT(h.title) AS num_docs FROM '.DB_TABLE_PREFIX.'_help h ';\n\t $sql .= 'RIGHT JOIN '.DB_TABLE_PREFIX.'_help_version hv ON h.help_version_id=hv.id GROUP BY hv.version';\n\n\t $page = new expPaginator(array(\n 'sql'=>$sql,\n 'limit'=>30,\n 'order' => (isset($this->params['order']) ? $this->params['order'] : 'version'),\n 'dir' => (isset($this->params['dir']) ? $this->params['dir'] : 'DESC'),\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->baseclassname,\n 'action'=>$this->params['action'],\n 'src'=>$this->loc->src,\n 'columns'=>array(\n gt('Version')=>'version',\n gt('Title')=>'title',\n gt('Current')=>'is_current',\n gt('# of Docs')=>'num_docs'\n ),\n ));\n\t \n\t assign_to_template(array(\n 'current_version'=>$current_version,\n 'page'=>$page\n ));\n\t}", "label_name": "CWE-74", "label": 1} +{"code": "function twig_array_filter(Environment $env, $array, $arrow)\n{\n if (!twig_test_iterable($array)) {\n throw new RuntimeError(sprintf('The \"filter\" filter expects an array or \"Traversable\", got \"%s\".', \\is_object($array) ? \\get_class($array) : \\gettype($array)));\n }\n\n if (!$arrow instanceof Closure && $env->hasExtension('\\Twig\\Extension\\SandboxExtension') && $env->getExtension('\\Twig\\Extension\\SandboxExtension')->isSandboxed()) {\n throw new RuntimeError('The callable passed to \"filter\" filter must be a Closure in sandbox mode.');\n }\n\n if (\\is_array($array)) {\n return array_filter($array, $arrow, \\ARRAY_FILTER_USE_BOTH);\n }\n\n // the IteratorIterator wrapping is needed as some internal PHP classes are \\Traversable but do not implement \\Iterator\n return new \\CallbackFilterIterator(new \\IteratorIterator($array), $arrow);\n}", "label_name": "CWE-74", "label": 1} +{"code": "\tprivate function _lastrevisionbefore( $option ) {\n\t\t$this->addTable( 'revision_actor_temp', 'rev' );\n\t\t$this->addSelect( [ 'rev.revactor_rev', 'rev.revactor_timestamp' ] );\n\t\t// tell the query optimizer not to look at rows that the following subquery will filter out anyway\n\t\t$this->addWhere(\n\t\t\t[\n\t\t\t\t$this->tableNames['page'] . '.page_id = rev.revactor_page',\n\t\t\t\t'rev.revactor_timestamp < ' . $this->convertTimestamp( $option )\n\t\t\t]\n\t\t);\n\t\t$this->addWhere(\n\t\t\t[\n\t\t\t\t$this->tableNames['page'] . '.page_id = rev.revactor_page',\n\t\t\t\t'rev.revactor_timestamp = (SELECT MAX(rev_aux_bef.revactor_timestamp) FROM ' . $this->tableNames['revision_actor_temp'] . ' AS rev_aux_bef WHERE rev_aux_bef.revactor_page=rev.revactor_page AND rev_aux_bef.revactor_timestamp < ' . $this->convertTimestamp( $option ) . ')'\n\t\t\t]\n\t\t);\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " public function store(CreateAppointmentCalendarRequest $request)\n {\n \n $client_id = null;\n $user = User::where('external_id', $request->user)->first();\n\n if ($request->client_external_id) {\n $client_id = Client::where('external_id', $request->client_external_id)->first()->id;\n if (!$client_id) {\n return response(__(\"Client not found\"), 422);\n }\n }\n\n $request_type = null;\n $request_id = null;\n if ($request->source_type && $request->source_external_id) {\n $request_type = $request->source_type;\n\n $entry = $request_type::whereExternalId($request->source_external_id);\n $request_id = $entry->id;\n }\n\n if (!$user) {\n return response(__(\"User not found\"), 422);\n }\n\n $startTime = str_replace([\"am\", \"pm\", ' '], \"\", $request->start_time) . ':00';\n $endTime = str_replace([\"am\", \"pm\", ' '], \"\", $request->end_time) . ':00';\n\n \n\n $appointment = Appointment::create([\n 'external_id' => Uuid::uuid4()->toString(),\n 'source_type' => $request_type,\n 'source_id' => $request_id,\n 'client_id' => $client_id,\n 'title' => $request->title,\n 'start_at' => Carbon::parse($request->start_date . \" \" . $startTime),\n 'end_at' => Carbon::parse($request->end_date . \" \" . $endTime),\n 'user_id' => $user->id,\n 'color' => $request->color\n ]);\n $appointment->user_external_id = $user->external_id;\n $appointment->start_at = $appointment->start_at;\n\n return response($appointment);\n }", "label_name": "CWE-862", "label": 8} +{"code": "\tstatic function convertXMLFeedSafeChar($str) {\n\t\t$str = str_replace(\"
\",\"\",$str);\n $str = str_replace(\"
\",\"\",$str);\n $str = str_replace(\"
\",\"\",$str);\n $str = str_replace(\"
\",\"\",$str);\n $str = str_replace(\""\",'\"',$str);\n $str = str_replace(\"'\",\"'\",$str);\n $str = str_replace(\"’\",\"'\",$str);\n $str = str_replace(\"‘\",\"'\",$str); \n $str = str_replace(\"®\",\"\",$str);\n $str = str_replace(\"\ufffd\",\"-\", $str);\n $str = str_replace(\"\ufffd\",\"-\", $str); \n $str = str_replace(\"\ufffd\", '\"', $str);\n $str = str_replace(\"”\",'\"', $str);\n $str = str_replace(\"\ufffd\", '\"', $str);\n $str = str_replace(\"“\",'\"', $str);\n $str = str_replace(\"\\r\\n\",\" \",$str); \n $str = str_replace(\"\ufffd\",\" 1/4\",$str);\n $str = str_replace(\"¼\",\" 1/4\", $str);\n $str = str_replace(\"\ufffd\",\" 1/2\",$str);\n $str = str_replace(\"½\",\" 1/2\",$str);\n $str = str_replace(\"\ufffd\",\" 3/4\",$str);\n $str = str_replace(\"¾\",\" 3/4\",$str);\n $str = str_replace(\"\ufffd\", \"(TM)\", $str);\n $str = str_replace(\"™\",\"(TM)\", $str);\n $str = str_replace(\"®\",\"(R)\", $str);\n $str = str_replace(\"\ufffd\",\"(R)\",$str); \n $str = str_replace(\"&\",\"&\",$str); \n\t\t$str = str_replace(\">\",\">\",$str); \t\t\n return trim($str);\n\t}", "label_name": "CWE-74", "label": 1} +{"code": " private static function _aesEncrypt($data, $secret)\n {\n if (!is_string($data)) {\n throw new \\InvalidArgumentException('Input parameter \"$data\" must be a string.');\n }\n\n if (!function_exists(\"openssl_encrypt\")) {\n throw new \\SimpleSAML_Error_Exception('The openssl PHP module is not loaded.');\n }\n\n $raw = defined('OPENSSL_RAW_DATA') ? OPENSSL_RAW_DATA : true;\n $key = openssl_digest($secret, 'sha256');\n $method = 'AES-256-CBC';\n $ivSize = 16;\n $iv = substr($key, 0, $ivSize);\n\n return $iv.openssl_encrypt($data, $method, $key, $raw, $iv);\n }", "label_name": "CWE-326", "label": 9} +{"code": " public function disable()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $swimlane_id = $this->request->getIntegerParam('swimlane_id');\n\n if ($this->swimlaneModel->disable($project['id'], $swimlane_id)) {\n $this->flash->success(t('Swimlane updated successfully.'));\n } else {\n $this->flash->failure(t('Unable to update this swimlane.'));\n }\n\n $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-200", "label": 10} +{"code": " public function logout()\n {\n if ($this->Session->check('Auth.User')) {\n $this->__extralog(\"logout\");\n }\n $this->Flash->info(__('Good-Bye'));\n $user = $this->User->find('first', array(\n 'conditions' => array(\n 'User.id' => $this->Auth->user('id')\n ),\n 'recursive' => -1\n ));\n unset($user['User']['password']);\n $user['User']['action'] = 'logout';\n $this->User->save($user['User'], true, array('id'));\n $this->redirect($this->Auth->logout());\n }", "label_name": "CWE-269", "label": 6} +{"code": " function remove() {\r\n global $db;\r\n\r\n $section = $db->selectObject('section', 'id=' . $this->params['id']);\r\n if ($section) {\r\n section::removeLevel($section->id);\r\n $db->decrement('section', 'rank', 1, 'rank > ' . $section->rank . ' AND parent=' . $section->parent);\r\n $section->parent = -1;\r\n $db->updateObject($section, 'section');\r\n expSession::clearAllUsersSessionCache('navigation');\r\n expHistory::back();\r\n } else {\r\n notfoundController::handle_not_authorized();\r\n }\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public function downloadfile() {\n if (empty($this->params['fileid'])) {\n flash('error', gt('There was an error while trying to download your file. No File Specified.'));\n expHistory::back();\n }\n \n $fd = new filedownload($this->params['fileid']); \n if (empty($this->params['filenum'])) $this->params['filenum'] = 0;\n\n if (empty($fd->expFile['downloadable'][$this->params['filenum']]->id)) {\n flash('error', gt('There was an error while trying to download your file. The file you were looking for could not be found.'));\n expHistory::back();\n } \n \n $fd->downloads++;\n $fd->save();\n \n // this will set the id to the id of the actual file..makes the download go right.\n $this->params['id'] = $fd->expFile['downloadable'][$this->params['filenum']]->id;\n parent::downloadfile(); \n }", "label_name": "CWE-74", "label": 1} +{"code": " $db->updateObject($value, 'section');\r\n }\r\n $db->updateObject($moveSec, 'section');\r\n //handle re-ranking of previous parent\r\n $oldSiblings = $db->selectObjects(\"section\", \"parent=\" . $oldParent . \" AND rank>\" . $oldRank . \" ORDER BY rank\");\r\n $rerank = 1;\r\n foreach ($oldSiblings as $value) {\r\n if ($value->id != $moveSec->id) {\r\n $value->rank = $rerank;\r\n $db->updateObject($value, 'section');\r\n $rerank++;\r\n }\r\n }\r\n if ($oldParent != $moveSec->parent) {\r\n //we need to re-rank the children of the parent that the moving section has just left\r\n $childOfLastMove = $db->selectObjects(\"section\", \"parent=\" . $oldParent . \" ORDER BY rank\");\r\n for ($i = 0, $iMax = count($childOfLastMove); $i < $iMax; $i++) {\r\n $childOfLastMove[$i]->rank = $i;\r\n $db->updateObject($childOfLastMove[$i], 'section');\r\n }\r\n }\r\n }\r\n }\r\n self::checkForSectionalAdmins($move);\r\n expSession::clearAllUsersSessionCache('navigation');\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public static function canView($section) {\r\n global $db;\r\n\r\n if ($section == null) {\r\n return false;\r\n }\r\n if ($section->public == 0) {\r\n // Not a public section. Check permissions.\r\n return expPermissions::check('view', expCore::makeLocation('navigation', '', $section->id));\r\n } else { // Is public. check parents.\r\n if ($section->parent <= 0) {\r\n // Out of parents, and since we are still checking, we haven't hit a private section.\r\n return true;\r\n } else {\r\n $s = $db->selectObject('section', 'id=' . $section->parent);\r\n return self::canView($s);\r\n }\r\n }\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " function captureAuthorization() {\n //eDebug($this->params,true);\n $order = new order($this->params['id']);\n /*eDebug($this->params); \n //eDebug($order,true);*/\n //eDebug($order,true);\n //$billing = new billing();\n\n //eDebug($billing, true);\n //$billing->calculator = new $calcname($order->billingmethod[0]->billingcalculator_id);\n $calc = $order->billingmethod[0]->billingcalculator->calculator;\n $calc->config = $order->billingmethod[0]->billingcalculator->config;\n\n //$calc = new $calc-\n //eDebug($calc,true);\n if (!method_exists($calc, 'delayed_capture')) {\n flash('error', gt('The Billing Calculator does not support delayed capture'));\n expHistory::back();\n }\n\n $result = $calc->delayed_capture($order->billingmethod[0], $this->params['capture_amt'], $order);\n\n if (empty($result->errorCode)) {\n flash('message', gt('The authorized payment was successfully captured'));\n expHistory::back();\n\n } else {\n flash('error', gt('An error was encountered while capturing the authorized payment.') . '

' . $result->message);\n expHistory::back();\n }\n }", "label_name": "CWE-74", "label": 1} +{"code": " public function bind($dn = null, $password = null)\n {\n /* Fetch current bind credentials. */\n if (empty($dn)) {\n $dn = $this->_config['binddn'];\n }\n if (empty($password)) {\n $password = $this->_config['bindpw'];\n }\n\n /* Connect first, if we haven't so far. This will also bind\n * us to the server. */\n if (!$this->_link) {\n /* Store old credentials so we can revert them later, then\n * overwrite config with new bind credentials. */\n $olddn = $this->_config['binddn'];\n $oldpw = $this->_config['bindpw'];\n\n /* Overwrite bind credentials in config so\n * _connect() knows about them. */\n $this->_config['binddn'] = $dn;\n $this->_config['bindpw'] = $password;\n\n /* Try to connect with provided credentials. */\n $msg = $this->_connect();\n\n /* Reset to previous config. */\n $this->_config['binddn'] = $olddn;\n $this->_config['bindpw'] = $oldpw;\n return;\n }\n\n /* Do the requested bind as we are asked to bind manually. */\n if (empty($dn)) {\n /* Anonymous bind. */\n $msg = @ldap_bind($this->_link);\n } else {\n /* Privileged bind. */\n $msg = @ldap_bind($this->_link, $dn, $password);\n }\n if (!$msg) {\n throw new Horde_Ldap_Exception('Bind failed: ' . @ldap_error($this->_link),\n @ldap_errno($this->_link));\n }\n }", "label_name": "CWE-287", "label": 4} +{"code": " $emails[$u->email] = trim(user::getUserAttribution($u->id));\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " private function runCallback() {\n foreach ($this->records as &$record) {\n if (isset($record->ref_type)) {\n $refType = $record->ref_type;\n if (class_exists($record->ref_type)) {\n $type = new $refType();\n $classinfo = new ReflectionClass($type);\n if ($classinfo->hasMethod('paginationCallback')) {\n $item = new $type($record->original_id);\n $item->paginationCallback($record);\n }\n }\n }\n } \n }", "label_name": "CWE-74", "label": 1} +{"code": "function BadAuthDigestTestController($serverPort) {\n $args = array('Authorization' => 'Digest \"username=\"admin\", ' .\n 'realm=\"Restricted area\", nonce=\"564a12f5c065e\", ' .\n 'uri=\"/test_auth_digest.php\", cnonce=\"MjIyMTg2\", nc=00000001, ' .\n 'qop=\"auth\", response=\"6dfbea52fbf13016476c1879e6436004\", ' .\n 'opaque=\"cdce8a5c95a1427d74df7acbf41c9ce0\"');\n var_dump(request(php_uname('n'), $serverPort, \"test_auth_digest.php\",\n [], [], $args));\n}", "label_name": "CWE-668", "label": 7} +{"code": " function update_option_master() { \n global $db;\n\n $id = empty($this->params['id']) ? null : $this->params['id'];\n $opt = new option_master($id);\n $oldtitle = $opt->title;\n \n $opt->update($this->params);\n \n // if the title of the master changed we should update the option groups that are already using it.\n if ($oldtitle != $opt->title) {\n \n }$db->sql('UPDATE '.$db->prefix.'option SET title=\"'.$opt->title.'\" WHERE option_master_id='.$opt->id);\n \n expHistory::back();\n }", "label_name": "CWE-74", "label": 1} +{"code": " public function settings_save() {\n AuthUser::load();\n if (!AuthUser::isLoggedIn()) {\n redirect(get_url('login'));\n } else if (!AuthUser::hasPermission('admin_edit')) {\n Flash::set('error', __('You do not have permission to access the requested page!'));\n redirect(get_url());\n }\n \n if (!isset($_POST['settings'])) {\n Flash::set('error', 'File Manager - ' . __('form was not posted.'));\n redirect(get_url('plugin/file_manager/settings'));\n } else {\n $settings = $_POST['settings'];\n\n if ($settings['umask'] == 0)\n $settings['umask'] = 0;\n elseif (!preg_match('/^0?[0-7]{3}$/', $settings['umask']))\n $settings['umask'] = 0;\n if (strlen($settings['umask']) === 3)\n $settings['umask'] = '0' . $settings['umask'];\n elseif (strlen($settings['umask']) !== 4 && $settings['umask'] != 0)\n $settings['umask'] = 0;\n\n if (!preg_match('/^0?[0-7]{3}$/', $settings['dirmode']))\n $settings['dirmode'] = '0755';\n if (strlen($settings['dirmode']) === 3)\n $settings['dirmode'] = '0' . $settings['dirmode'];\n\n if (!preg_match('/^0?[0-7]{3}$/', $settings['filemode']))\n $settings['filemode'] = '0755';\n if (strlen($settings['filemode']) === 3)\n $settings['filemode'] = '0' . $settings['filemode'];\n }\n\n if (Plugin::setAllSettings($settings, 'file_manager'))\n Flash::setNow('success', 'File Manager - ' . __('plugin settings saved.'));\n else\n Flash::setNow('error', 'File Manager - ' . __('plugin settings not saved!'));\n\n $this->display('file_manager/views/settings', array('settings' => $settings));\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function save($check_notify = false)\n {\n if (isset($_POST['email_recipients']) && is_array($_POST['email_recipients'])) {\n $this->email_recipients = base64_encode(serialize($_POST['email_recipients']));\n }\n\n return parent::save($check_notify);\n }", "label_name": "CWE-863", "label": 11} +{"code": " function searchByModelForm() {\n // get the search terms\n $terms = $this->params['search_string'];\n\n $sql = \"model like '%\" . $terms . \"%'\";\n\n $limit = !empty($this->config['limit']) ? $this->config['limit'] : 10;\n $page = new expPaginator(array(\n 'model' => 'product',\n 'where' => $sql,\n 'limit' => !empty($this->config['pagination_default']) ? $this->config['pagination_default'] : $limit,\n 'order' => 'title',\n 'dir' => 'DESC',\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller' => $this->params['controller'],\n 'action' => $this->params['action'],\n 'columns' => array(\n gt('Model #') => 'model',\n gt('Product Name') => 'title',\n gt('Price') => 'base_price'\n ),\n ));\n\n assign_to_template(array(\n 'page' => $page,\n 'terms' => $terms\n ));\n }", "label_name": "CWE-20", "label": 0} +{"code": " protected function renderImageByImagick($code)\n {\n $backColor = $this->transparent ? new \\ImagickPixel('transparent') : new \\ImagickPixel('#' . str_pad(dechex($this->backColor), 6, 0, STR_PAD_LEFT));\n $foreColor = new \\ImagickPixel('#' . str_pad(dechex($this->foreColor), 6, 0, STR_PAD_LEFT));\n\n $image = new \\Imagick();\n $image->newImage($this->width, $this->height, $backColor);\n\n $draw = new \\ImagickDraw();\n $draw->setFont($this->fontFile);\n $draw->setFontSize(30);\n $fontMetrics = $image->queryFontMetrics($draw, $code);\n\n $length = strlen($code);\n $w = (int) $fontMetrics['textWidth'] - 8 + $this->offset * ($length - 1);\n $h = (int) $fontMetrics['textHeight'] - 8;\n $scale = min(($this->width - $this->padding * 2) / $w, ($this->height - $this->padding * 2) / $h);\n $x = 10;\n $y = round($this->height * 27 / 40);\n for ($i = 0; $i < $length; ++$i) {\n $draw = new \\ImagickDraw();\n $draw->setFont($this->fontFile);\n $draw->setFontSize((int) (mt_rand(26, 32) * $scale * 0.8));\n $draw->setFillColor($foreColor);\n $image->annotateImage($draw, $x, $y, mt_rand(-10, 10), $code[$i]);\n $fontMetrics = $image->queryFontMetrics($draw, $code[$i]);\n $x += (int) $fontMetrics['textWidth'] + $this->offset;\n }\n\n $image->setImageFormat('png');\n return $image->getImageBlob();\n }", "label_name": "CWE-330", "label": 12} +{"code": "\tpublic function Update() {\n\n\t\t// Update \"main\" ticket\n\t\t$upd_stmt = Database::prepare('\n\t\t\tUPDATE `' . TABLE_PANEL_TICKETS . '` SET\n `priority` = :priority,\n `lastchange` = :lastchange,\n `status` = :status,\n `lastreplier` = :lastreplier\n WHERE `id` = :tid'\n\t\t);\n\t\t$upd_data = array(\n\t\t\t'priority' => $this->Get('priority'),\n\t\t\t'lastchange' => $this->Get('lastchange'),\n\t\t\t'status' => $this->Get('status'),\n\t\t\t'lastreplier' => $this->Get('lastreplier'),\n\t\t\t'tid' => $this->tid\n\t\t);\n\t\tDatabase::pexecute($upd_stmt, $upd_data);\n\t\treturn true;\n\t}", "label_name": "CWE-732", "label": 13} +{"code": "\tpublic function __construct( \\DPL\\Parameters $parameters, \\Parser $parser ) {\n\t\tparent::__construct( $parameters, $parser );\n\t\t$this->textSeparator = $parameters->getParameter( 'inlinetext' );\n\t\t$listSeparators = $parameters->getParameter( 'listseparators' );\n\t\tif ( isset( $listSeparators[0] ) ) {\n\t\t\t$this->listStart = $listSeparators[0];\n\t\t}\n\t\tif ( isset( $listSeparators[1] ) ) {\n\t\t\t$this->itemStart = $listSeparators[1];\n\t\t}\n\t\tif ( isset( $listSeparators[2] ) ) {\n\t\t\t$this->itemEnd = $listSeparators[2];\n\t\t}\n\t\tif ( isset( $listSeparators[3] ) ) {\n\t\t\t$this->listEnd = $listSeparators[3];\n\t\t}\n\t}", "label_name": "CWE-400", "label": 2} +{"code": "\tpublic function validate($value, $isUserFormat = false)\n\t{\n\t\tif (empty($value)) {\n\t\t\treturn;\n\t\t}\n\t\tif (\\is_string($value)) {\n\t\t\t$value = \\App\\Json::decode($value);\n\t\t}\n\t\tif (!\\is_array($value)) {\n\t\t\tthrow new \\App\\Exceptions\\Security('ERR_ILLEGAL_FIELD_VALUE||' . $this->getFieldModel()->getFieldName() . '||' . $this->getFieldModel()->getModuleName() . '||' . $value, 406);\n\t\t}\n\t\t$currencies = \\App\\Fields\\Currency::getAll(true);\n\t\tforeach ($value['currencies'] ?? [] as $id => $currency) {\n\t\t\tif (!isset($currencies[$id])) {\n\t\t\t\tthrow new \\App\\Exceptions\\Security('ERR_ILLEGAL_FIELD_VALUE||' . $this->getFieldModel()->getFieldName() . '||' . $this->getFieldModel()->getModuleName() . '||' . $id, 406);\n\t\t\t}\n\t\t\t$price = $currency['price'];\n\t\t\tif ($isUserFormat) {\n\t\t\t\t$price = App\\Fields\\Double::formatToDb($price);\n\t\t\t}\n\t\t\tif (!is_numeric($price)) {\n\t\t\t\tthrow new \\App\\Exceptions\\Security('ERR_ILLEGAL_FIELD_VALUE||' . $this->getFieldModel()->getFieldName() . '||' . $this->getFieldModel()->getModuleName() . '||' . $price, 406);\n\t\t\t}\n\t\t}\n\t}", "label_name": "CWE-20", "label": 0} +{"code": " private function resolveTrustedProxy()\n {\n if (!$trustedProxies = Request::getTrustedProxies()) {\n return '127.0.0.1';\n }\n\n $firstTrustedProxy = reset($trustedProxies);\n\n return false !== ($i = strpos($firstTrustedProxy, '/')) ? substr($firstTrustedProxy, 0, $i) : $firstTrustedProxy;\n }", "label_name": "CWE-20", "label": 0} +{"code": "\t\t\t\t$this->run('rm', $item, '-r');\n\t\t\t}\n\n\t\t\treturn $this;\n\t\t}", "label_name": "CWE-77", "label": 14} +{"code": "\t\t\tforeach ( $option as $_option ) {\n\t\t\t\t//Parameter functions return true or false. The full parameter data will be passed into the Query object later.\n\t\t\t\tif ( $this->parameters->$parameter( $_option ) === false ) {\n\t\t\t\t\t//Do not build this into the output just yet. It will be collected at the end.\n\t\t\t\t\t$this->logger->addMessage( \\DynamicPageListHooks::WARN_WRONGPARAM, $parameter, $_option );\n\t\t\t\t}\n\t\t\t}", "label_name": "CWE-400", "label": 2} +{"code": " public function save() {\n $data = $_POST['file'];\n\n // security (remove all ..)\n $data['name'] = str_replace('..', '', $data['name']);\n $file = FILES_DIR . DS . $data['name'];\n \n // CSRF checks\n if (isset($_POST['csrf_token'])) {\n $csrf_token = $_POST['csrf_token'];\n if (!SecureToken::validateToken($csrf_token, BASE_URL.'plugin/file_manager/save/'.$data['name'])) {\n Flash::set('error', __('Invalid CSRF token found!'));\n redirect(get_url('plugin/file_manager/view/'.$data['name']));\n }\n }\n else {\n Flash::set('error', __('No CSRF token found!'));\n redirect(get_url('plugin/file_manager/view/'.$data['name']));\n }\n \n if (file_exists($file)) {\n if (file_put_contents($file, $data['content']) !== false) {\n Flash::set('success', __('File has been saved with success!'));\n } else {\n Flash::set('error', __('File is not writable! File has not been saved!'));\n }\n } else {\n if (file_put_contents($file, $data['content'])) {\n Flash::set('success', __('File :name has been created with success!', array(':name' => $data['name'])));\n } else {\n Flash::set('error', __('Directory is not writable! File has not been saved!'));\n }\n }\n\n // save and quit or save and continue editing ?\n if (isset($_POST['commit'])) {\n redirect(get_url('plugin/file_manager/browse/' . substr($data['name'], 0, strrpos($data['name'], '/'))));\n } else {\n redirect(get_url('plugin/file_manager/view/' . $data['name'] . (endsWith($data['name'], URL_SUFFIX) ? '?has_url_suffix=1' : '')));\n }", "label_name": "CWE-20", "label": 0} +{"code": "\tpublic function newModel() {\n\t\treturn new APIModel('testuser','5f4dcc3b5aa765d61d8327deb882cf99',rtrim(TEST_BASE_URL,'/'));\n\t}", "label_name": "CWE-20", "label": 0} +{"code": "\tfunction manage() {\n\t global $db;\n\t \n\t expHistory::set('manageable', $this->params);\n//\t $classes = array();\n $dir = BASE.\"framework/modules/ecommerce/billingcalculators\";\n if (is_readable($dir)) {\n $dh = opendir($dir);\n while (($file = readdir($dh)) !== false) {\n if (is_file(\"$dir/$file\") && substr(\"$dir/$file\", -4) == \".php\") {\n include_once(\"$dir/$file\");\n $classname = substr($file, 0, -4);\n $id = $db->selectValue('billingcalculator', 'id', 'calculator_name=\"'.$classname.'\"');\n if (empty($id)) {\n// $calobj = null;\n $calcobj = new $classname();\n if ($calcobj->isSelectable() == true) {\n $obj = new billingcalculator(array(\n 'title'=>$calcobj->name(),\n// 'user_title'=>$calcobj->title,\n 'body'=>$calcobj->description(), \n 'calculator_name'=>$classname,\n 'enabled'=>false));\n $obj->save();\n }\n }\n }\n }\n }\n \n $bcalc = new billingcalculator();\n $calculators = $bcalc->find('all');\n assign_to_template(array(\n 'calculators'=>$calculators\n ));\n\t}", "label_name": "CWE-74", "label": 1} +{"code": " public function view() {\n $params = func_get_args();\n $content = '';\n\n $filename = urldecode(join('/', $params));\n\n // Sanitize filename for securtiy\n // We don't allow backlinks\n if (strpos($filename, '..') !== false) {\n /*\n if (Plugin::isEnabled('statistics_api')) {\n $user = null;\n if (AuthUser::isLoggedIn())\n $user = AuthUser::getUserName();\n $ip = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : ($_SERVER['REMOTE_ADDR']);\n $event = array('event_type' => 'hack_attempt', // simple event type identifier\n 'description' => __('A possible hack attempt was detected.'), // translatable description\n 'ipaddress' => $ip,\n 'username' => $user);\n Observer::notify('stats_file_manager_hack_attempt', $event);\n }\n */\n }\n $filename = str_replace('..', '', $filename);\n\n // Clean up nicely\n $filename = str_replace('//', '', $filename);\n\n // We don't allow leading slashes\n $filename = preg_replace('/^\\//', '', $filename);\n \n // Check if file had URL_SUFFIX - if so, append it to filename\n $filename .= (isset($_GET['has_url_suffix']) && $_GET['has_url_suffix']==='1') ? URL_SUFFIX : '';\n \n $file = FILES_DIR . '/' . $filename;\n if (!$this->_isImage($file) && file_exists($file)) {\n $content = file_get_contents($file);\n }\n \n $this->display('file_manager/views/view', array(\n 'csrf_token' => SecureToken::generateToken(BASE_URL.'plugin/file_manager/save/'.$filename),\n 'is_image' => $this->_isImage($file),\n 'filename' => $filename,\n 'content' => $content\n ));\n }", "label_name": "CWE-20", "label": 0} +{"code": " $value = str_replace($originalName, $cleanedName, $value);\n }\n unset($value);\n }\n $result = hash_equals(GeneralUtility::hmac(serialize($fieldChangeFunctions)), $this->parameters['fieldChangeFuncHash']);\n }\n return $result;\n }", "label_name": "CWE-327", "label": 3} +{"code": " $this->subtaskTimeTrackingModel->logEndTime($subtaskId, $this->userSession->getId());\n $this->subtaskTimeTrackingModel->updateTaskTimeTracking($task['id']);\n }", "label_name": "CWE-200", "label": 10} +{"code": "\tprotected function sort(&$rowsKey, $sortColumn) {\n\t\t$sortMethod = $this->getTableSortMethod();\n\t\n\t\tif ($sortColumn < 0) {\n\t\t\tswitch ($sortMethod) {\n\t\t\t\tcase 'natural':\n\t\t\t\t\t// Reverse natsort()\n uasort($rowsKey, function($first, $second) {\n \treturn strnatcmp($second, $first);\n\t\t\t\t\t});\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'standard':\n\t\t\t\tdefault:\n\t\t\t\t\tarsort($rowsKey);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t} else {\n\t\t\tswitch ($sortMethod) {\n\t\t\t\tcase 'natural':\n\t\t\t\tnatsort($rowsKey);\n\t\t\t\tbreak;\n\t\t\tcase 'standard':\n\t\t\tdefault:\n\t\t\t\tasort($rowsKey);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}", "label_name": "CWE-400", "label": 2} +{"code": "\t\t\t\t$this->run('mv', $from, $to);\n\t\t\t}\n\n\t\t\treturn $this;\n\t\t}", "label_name": "CWE-77", "label": 14} +{"code": "\tpublic function __construct() {\n\t\tglobal $wgRequest;\n\n\t\t$this->DB\t\t\t= wfGetDB( DB_REPLICA, 'dpl' );\n\t\t$this->parameters\t= new Parameters();\n\t\t$this->logger\t\t= new Logger( $this->parameters->getData( 'debug' )['default'] );\n\t\t$this->tableNames\t= Query::getTableNames();\n\t\t$this->wgRequest\t= $wgRequest;\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " public function downloadfile() {\n if (empty($this->params['fileid'])) {\n flash('error', gt('There was an error while trying to download your file. No File Specified.'));\n expHistory::back();\n }\n \n $fd = new filedownload($this->params['fileid']); \n if (empty($this->params['filenum'])) $this->params['filenum'] = 0;\n\n if (empty($fd->expFile['downloadable'][$this->params['filenum']]->id)) {\n flash('error', gt('There was an error while trying to download your file. The file you were looking for could not be found.'));\n expHistory::back();\n } \n \n $fd->downloads++;\n $fd->save();\n \n // this will set the id to the id of the actual file..makes the download go right.\n $this->params['id'] = $fd->expFile['downloadable'][$this->params['filenum']]->id;\n parent::downloadfile(); \n }", "label_name": "CWE-74", "label": 1} +{"code": " public function browse() {\n $params = func_get_args();\n\n $this->path = join('/', $params);\n // make sure there's a / at the end\n if (substr($this->path, -1, 1) != '/')\n $this->path .= '/';\n\n //security\n // we dont allow back link\n if (strpos($this->path, '..') !== false) {\n /*\n if (Plugin::isEnabled('statistics_api')) {\n $user = null;\n if (AuthUser::isLoggedIn())\n $user = AuthUser::getUserName();\n $ip = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : ($_SERVER['REMOTE_ADDR']);\n $event = array('event_type' => 'hack_attempt', // simple event type identifier\n 'description' => __('A possible hack attempt was detected.'), // translatable description\n 'ipaddress' => $ip,\n 'username' => $user);\n Observer::notify('stats_file_manager_hack_attempt', $event);\n }\n */\n }\n $this->path = str_replace('..', '', $this->path);\n\n // clean up nicely\n $this->path = str_replace('//', '', $this->path);\n\n // we dont allow leading slashes\n $this->path = preg_replace('/^\\//', '', $this->path);\n\n $this->fullpath = FILES_DIR . '/' . $this->path;\n\n // clean up nicely\n $this->fullpath = preg_replace('/\\/\\//', '/', $this->fullpath);\n\n $this->display('file_manager/views/index', array(\n 'dir' => $this->path,\n //'files' => $this->_getListFiles()\n 'files' => $this->_listFiles()\n ));\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function actionGetItems(){\n $sql = 'SELECT id, name as value FROM x2_products WHERE name LIKE :qterm ORDER BY name ASC';\n $command = Yii::app()->db->createCommand($sql);\n $qterm = $_GET['term'].'%';\n $command->bindParam(\":qterm\", $qterm, PDO::PARAM_STR);\n $result = $command->queryAll();\n echo CJSON::encode($result); exit;\n }", "label_name": "CWE-20", "label": 0} +{"code": "\tfunction update_vendor() {\n\t\t$vendor = new vendor();\n\t\t\n\t\t$vendor->update($this->params['vendor']);\n expHistory::back();\n }", "label_name": "CWE-74", "label": 1} +{"code": " public function renderAttribute ($name) {\n switch ($name) {\n case 'name':\n echo $this->relatedModel->getLink (/*array (\n 'class' => 'quick-read-link',\n 'data-id' => $this->relatedModel->id,\n 'data-class' => get_class ($this->relatedModel),\n 'data-name' => CHtml::encode ($this->relatedModel->name),\n )*/);\n break;\n case 'relatedModelName':\n echo $this->getRelatedModelName ();\n break;\n case 'assignedTo':\n echo $this->relatedModel->renderAttribute ('assignedTo');\n break;\n case 'label':\n echo $this->getLabel ();\n break;\n case 'createDate':\n echo X2Html::dynamicDate ($this->relatedModel->createDate);\n break;\n }\n }", "label_name": "CWE-20", "label": 0} +{"code": " print_r($single_error);\n }\n\n echo '';\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function show()\n {\n $task = $this->getTask();\n $subtask = $this->getSubtask();\n\n $this->response->html($this->template->render('subtask_restriction/show', array(\n 'status_list' => array(\n SubtaskModel::STATUS_TODO => t('Todo'),\n SubtaskModel::STATUS_DONE => t('Done'),\n ),\n 'subtask_inprogress' => $this->subtaskStatusModel->getSubtaskInProgress($this->userSession->getId()),\n 'subtask' => $subtask,\n 'task' => $task,\n )));\n }", "label_name": "CWE-200", "label": 10} +{"code": " public function Connect($host, $port = 0, $tval = 30) {\n // set the error val to null so there is no confusion\n $this->error = null;\n\n // make sure we are __not__ connected\n if($this->connected()) {\n // already connected, generate error\n $this->error = array(\"error\" => \"Already connected to a server\");\n return false;\n }\n\n if(empty($port)) {\n $port = $this->SMTP_PORT;\n }\n\n // connect to the smtp server\n $this->smtp_conn = @fsockopen($host, // the host of the server\n $port, // the port to use\n $errno, // error number if any\n $errstr, // error message if any\n $tval); // give up after ? secs\n // verify we connected properly\n if(empty($this->smtp_conn)) {\n $this->error = array(\"error\" => \"Failed to connect to server\",\n \"errno\" => $errno,\n \"errstr\" => $errstr);\n if($this->do_debug >= 1) {\n $this->edebug(\"SMTP -> ERROR: \" . $this->error[\"error\"] . \": $errstr ($errno)\" . $this->CRLF . '
');\n }\n return false;\n }\n\n // SMTP server can take longer to respond, give longer timeout for first read\n // Windows does not have support for this timeout function\n if(substr(PHP_OS, 0, 3) != \"WIN\") {\n $max = ini_get('max_execution_time');\n if ($max != 0 && $tval > $max) { // don't bother if unlimited\n @set_time_limit($tval);\n }\n stream_set_timeout($this->smtp_conn, $tval, 0);\n }\n\n // get any announcement\n $announce = $this->get_lines();\n\n if($this->do_debug >= 2) {\n $this->edebug(\"SMTP -> FROM SERVER:\" . $announce . $this->CRLF . '
');\n }\n\n return true;\n }", "label_name": "CWE-20", "label": 0} +{"code": " function edit_freeform() {\r\n $section = isset($this->params['id']) ? $this->section->find($this->params['id']) : new section($this->params);\r\n if ($section->parent == -1) {\r\n notfoundController::handle_not_found();\r\n exit;\r\n } // doesn't work for standalone pages\r\n if (empty($section->id)) {\r\n $section->public = 1;\r\n if (!isset($section->parent)) {\r\n // This is another precaution. The parent attribute\r\n // should ALWAYS be set by the caller.\r\n //FJD - if that's the case, then we should die.\r\n notfoundController::handle_not_authorized();\r\n exit;\r\n //$section->parent = 0;\r\n }\r\n }\r\n assign_to_template(array(\r\n 'section' => $section,\r\n 'glyphs' => self::get_glyphs(),\r\n ));\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public function confirm()\n {\n $task = $this->getTask();\n $subtask = $this->getSubtask();\n\n $this->response->html($this->template->render('subtask/remove', array(\n 'subtask' => $subtask,\n 'task' => $task,\n )));\n }", "label_name": "CWE-200", "label": 10} +{"code": " function addDiscountToCart() {\n// global $user, $order;\n global $order;\n //lookup discount to see if it's real and valid, and not already in our cart\n //this will change once we allow more than one coupon code\n\n $discount = new discounts();\n $discount = $discount->getCouponByName($this->params['coupon_code']);\n\n if (empty($discount)) {\n flash('error', gt(\"This discount code you entered does not exist.\"));\n //redirect_to(array('controller'=>'cart', 'action'=>'checkout')); \n expHistory::back();\n }\n\n //check to see if it's in our cart already\n if ($this->isDiscountInCart($discount->id)) {\n flash('error', gt(\"This discount code is already in your cart.\"));\n //redirect_to(array('controller'=>'cart', 'action'=>'checkout'));\n expHistory::back();\n }\n\n //this should really be reworked, as it shoudn't redirect directly and not return\n $validateDiscountMessage = $discount->validateDiscount();\n if ($validateDiscountMessage == \"\") {\n //if all good, add to cart, otherwise it will have redirected\n $od = new order_discounts();\n $od->orders_id = $order->id;\n $od->discounts_id = $discount->id;\n $od->coupon_code = $discount->coupon_code;\n $od->title = $discount->title;\n $od->body = $discount->body;\n $od->save();\n // set this to just the discount applied via this coupon?? if so, when though? $od->discount_total = ??;\n flash('message', gt(\"The discount code has been applied to your cart.\"));\n } else {\n flash('error', $validateDiscountMessage);\n }\n //redirect_to(array('controller'=>'cart', 'action'=>'checkout')); \n expHistory::back();\n }", "label_name": "CWE-20", "label": 0} +{"code": "\tfunction edit_vendor() {\n\t\t$vendor = new vendor();\n\t\t\n\t\tif(isset($this->params['id'])) {\n\t\t\t$vendor = $vendor->find('first', 'id =' .$this->params['id']);\n\t\t\tassign_to_template(array(\n 'vendor'=>$vendor\n ));\n\t\t}\n\t}", "label_name": "CWE-74", "label": 1} +{"code": "function getTypes($subtype=\"both\") {\n\t$types = array(\"users\" => array(),\n\t \"resources\" => array());\n\tif($subtype == \"users\" || $subtype == \"both\") {\n\t\t$query = \"SELECT id, name FROM userprivtype\";\n\t\t$qh = doQuery($query, 365);\n\t\twhile($row = mysql_fetch_assoc($qh)) {\n\t\t\tif($row[\"name\"] == \"block\" || $row[\"name\"] == \"cascade\")\n\t\t\t\tcontinue;\n\t\t\t$types[\"users\"][$row[\"id\"]] = $row[\"name\"];\n\t\t}\n\t}\n\tif($subtype == \"resources\" || $subtype == \"both\") {\n\t\t$query = \"SELECT id, name FROM resourcetype\";\n\t\t$qh = doQuery($query, 366);\n\t\twhile($row = mysql_fetch_assoc($qh)) {\n\t\t\tif($row[\"name\"] == \"block\" || $row[\"name\"] == \"cascade\")\n\t\t\t\tcontinue;\n\t\t\t$types[\"resources\"][$row[\"id\"]] = $row[\"name\"];\n\t\t}\n\t}\n\treturn $types;\n}", "label_name": "CWE-20", "label": 0} +{"code": " public function delete() {\n global $db, $history;\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n $require_login = empty($this->params['require_login']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];\n $require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];\n $require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n $notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];\n \n if (empty($this->params['id'])) {\n flash('error', gt('Missing id for the comment you would like to delete'));\n $lastUrl = expHistory::getLast('editable');\n }\n \n // delete the note\n $simplenote = new expSimpleNote($this->params['id']);\n $rows = $simplenote->delete();\n \n // delete the assocication too\n $db->delete($simplenote->attachable_table, 'expsimplenote_id='.$this->params['id']); \n \n // send the user back where they came from.\n $lastUrl = expHistory::getLast('editable');\n if (!empty($this->params['tab']))\n {\n $lastUrl .= \"#\".$this->params['tab'];\n }\n redirect_to($lastUrl);\n }", "label_name": "CWE-74", "label": 1} +{"code": " $payment->write();\n $i++;\n }\n\n // Ugly hack to set the money amount\n $this->payment->Status = 'Created';\n $this->payment->setAmount($total);\n\n // If not everything was refunded, the payment should still have the \"Captured\" status\n if ($total > 0) {\n $endStatus = 'Captured';\n }\n }\n\n parent::markCompleted($endStatus, $serviceResponse, $gatewayMessage);\n if ($endStatus === 'Captured') {\n $this->createMessage(Message\\PartiallyRefundedResponse::class, $gatewayMessage);\n } else {\n $this->createMessage(Message\\RefundedResponse::class, $gatewayMessage);\n }\n\n ErrorHandling::safeExtend($this->payment, 'onRefunded', $serviceResponse);\n }", "label_name": "CWE-436", "label": 5} +{"code": " public function urlProvider()\n {\n return array(\n array('http://till:test@svn.example.org/', $this->getCmd(\" --username 'till' --password 'test' \")),\n array('http://svn.apache.org/', ''),\n array('svn://johndoe@example.org', $this->getCmd(\" --username 'johndoe' --password '' \")),\n );\n }", "label_name": "CWE-77", "label": 14} +{"code": " public function __construct() {\n $this->pop_conn = 0;\n $this->connected = false;\n $this->error = null;\n }", "label_name": "CWE-20", "label": 0} +{"code": " protected function getSubtask()\n {\n $subtask = $this->subtaskModel->getById($this->request->getIntegerParam('subtask_id'));\n\n if (empty($subtask)) {\n throw new PageNotFoundException();\n }\n\n return $subtask;\n }", "label_name": "CWE-200", "label": 10} +{"code": "\tprivate function _hiddencategories( $option ) {\n\t\t//@TODO: Unfinished functionality! Never implemented by original author.\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " foreach($image->expTag as $tag) {\n if (isset($used_tags[$tag->id])) {\n $used_tags[$tag->id]->count++;\n } else {\n $exptag = new expTag($tag->id);\n $used_tags[$tag->id] = $exptag;\n $used_tags[$tag->id]->count = 1;\n }\n \n }", "label_name": "CWE-74", "label": 1} +{"code": " function update_option_master() { \n global $db;\n\n $id = empty($this->params['id']) ? null : $this->params['id'];\n $opt = new option_master($id);\n $oldtitle = $opt->title;\n \n $opt->update($this->params);\n \n // if the title of the master changed we should update the option groups that are already using it.\n if ($oldtitle != $opt->title) {\n \n }$db->sql('UPDATE '.$db->prefix.'option SET title=\"'.$opt->title.'\" WHERE option_master_id='.$opt->id);\n \n expHistory::back();\n }", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic function formatItem( Article $article, $pageText = null ) {\n\t\t$item = $article->mTitle;\n\n\t\tif ( $pageText !== null ) {\n\t\t\t//Include parsed/processed wiki markup content after each item before the closing tag.\n\t\t\t$item .= $pageText;\n\t\t}\n\n\t\t$item = $this->getItemStart() . $item . $this->itemEnd;\n\n\t\t$item = $this->replaceTagParameters( $item, $article );\n\n\t\treturn $item;\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " public function update() {\n\n //populate the alt tag field if the user didn't\n if (empty($this->params['alt'])) $this->params['alt'] = $this->params['title'];\n \n // call expController update to save the image\n parent::update();\n }", "label_name": "CWE-74", "label": 1} +{"code": " public function showall() {\n expHistory::set('viewable', $this->params);\n $limit = (isset($this->config['limit']) && $this->config['limit'] != '') ? $this->config['limit'] : 10;\n if (!empty($this->params['view']) && ($this->params['view'] == 'showall_accordion' || $this->params['view'] == 'showall_tabbed')) {\n $limit = '0';\n }\n $order = isset($this->config['order']) ? $this->config['order'] : \"rank\";\n $page = new expPaginator(array(\n 'model'=>'photo',\n 'where'=>$this->aggregateWhereClause(),\n 'limit'=>$limit,\n 'order'=>$order,\n 'categorize'=>empty($this->config['usecategories']) ? false : $this->config['usecategories'],\n 'uncat'=>!empty($this->config['uncat']) ? $this->config['uncat'] : gt('Not Categorized'),\n 'groups'=>!isset($this->params['gallery']) ? array() : array($this->params['gallery']),\n 'grouplimit'=>!empty($this->params['view']) && $this->params['view'] == 'showall_galleries' ? 1 : null,\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->baseclassname,\n 'action'=>$this->params['action'],\n 'src'=>$this->loc->src,\n 'columns'=>array(\n gt('Title')=>'title'\n ),\n ));\n \n assign_to_template(array(\n 'page'=>$page,\n 'params'=>$this->params,\n ));\n }", "label_name": "CWE-74", "label": 1} +{"code": " public function event()\n {\n $project = $this->getProject();\n $values = $this->request->getValues();\n\n if (empty($values['action_name']) || empty($values['project_id'])) {\n return $this->create();\n }\n\n return $this->response->html($this->template->render('action_creation/event', array(\n 'values' => $values,\n 'project' => $project,\n 'available_actions' => $this->actionManager->getAvailableActions(),\n 'events' => $this->actionManager->getCompatibleEvents($values['action_name']),\n )));\n }", "label_name": "CWE-200", "label": 10} +{"code": "\tpublic function addMessage( $errorId ) {\n\t\t$args = func_get_args();\n\t\t$args = array_map( 'htmlspecialchars', $args );\n\t\treturn call_user_func_array( [ $this, 'msg' ], $args );\n\t}", "label_name": "CWE-400", "label": 2} +{"code": "\t\t\treturn $wgLang->timeanddate( $article->mDate, true );\n\t\t}\n\t\treturn null;\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " public function confirm()\n {\n $project = $this->getProject();\n $tag_id = $this->request->getIntegerParam('tag_id');\n $tag = $this->tagModel->getById($tag_id);\n\n $this->response->html($this->template->render('project_tag/remove', array(\n 'tag' => $tag,\n 'project' => $project,\n )));\n }", "label_name": "CWE-200", "label": 10} +{"code": "function getUserGroupID($name, $affilid=DEFAULT_AFFILID) {\n\t$query = \"SELECT id \"\n\t . \"FROM usergroup \"\n\t . \"WHERE name = '$name' AND \"\n\t . \"affiliationid = $affilid\";\n\t$qh = doQuery($query, 300);\n\tif($row = mysql_fetch_row($qh)) {\n\t\treturn $row[0];\n\t}\n\t$query = \"INSERT INTO usergroup \"\n\t . \"(name, \"\n\t . \"affiliationid, \"\n\t . \"custom, \"\n\t . \"courseroll) \"\n\t . \"VALUES \"\n\t . \"('$name', \"\n\t . \"$affilid, \"\n\t . \"0, \"\n\t . \"0)\";\n\tdoQuery($query, 301);\n\t$qh = doQuery(\"SELECT LAST_INSERT_ID() FROM usergroup\", 302);\n\tif(! $row = mysql_fetch_row($qh)) {\n\t\tabort(303);\n\t}\n\treturn $row[0];\n}", "label_name": "CWE-20", "label": 0} +{"code": " foreach ($allgroups as $gid) {\r\n $g = group::getGroupById($gid);\r\n expPermissions::grantGroup($g, 'manage', $sloc);\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public function Connected() {\n if(!empty($this->smtp_conn)) {\n $sock_status = socket_get_status($this->smtp_conn);\n if($sock_status[\"eof\"]) {\n // the socket is valid but we are not connected\n if($this->do_debug >= 1) {\n $this->edebug(\"SMTP -> NOTICE:\" . $this->CRLF . \"EOF caught while checking if connected\");\n }\n $this->Close();\n return false;\n }\n return true; // everything looks good\n }\n return false;\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function manage() {\n expHistory::set('manageable', $this->params);\n \n // build out a SQL query that gets all the data we need and is sortable.\n $sql = 'SELECT b.*, c.title as companyname, f.expfiles_id as file_id ';\n $sql .= 'FROM '.DB_TABLE_PREFIX.'_banner b, '.DB_TABLE_PREFIX.'_companies c , '.DB_TABLE_PREFIX.'_content_expFiles f ';\n $sql .= 'WHERE b.companies_id = c.id AND (b.id = f.content_id AND f.content_type=\"banner\")';\n\t\t\n\t\t$page = new expPaginator(array(\n\t\t\t'model'=>'banner',\n\t\t\t'sql'=>$sql,\n\t\t\t'order'=>'title',\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->params['controller'],\n 'action'=>$this->params['action'],\n 'src'=>$this->loc->src,\n\t\t\t'columns'=>array(\n gt('Title')=>'title',\n gt('Company')=>'companyname',\n gt('Impressions')=>'impressions',\n gt('Clicks')=>'clicks'\n )\n ));\n\n\t\tassign_to_template(array(\n 'page'=>$page\n ));\n }", "label_name": "CWE-74", "label": 1} +{"code": " function move_standalone() {\r\n expSession::clearAllUsersSessionCache('navigation');\r\n assign_to_template(array(\r\n 'parent' => $this->params['parent'],\r\n ));\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " function categoryBreadcrumb() {\n// global $db, $router;\n\n //eDebug($this->category);\n\n /*if(isset($router->params['action']))\n {\n $ancestors = $this->category->pathToNode(); \n }else if(isset($router->params['section']))\n {\n $current = $db->selectObject('section',' id= '.$router->params['section']);\n $ancestors[] = $current;\n if( $current->parent != -1 || $current->parent != 0 )\n { \n while ($db->selectObject('section',' id= '.$router->params['section']);)\n if ($section->id == $id) {\n $current = $section;\n break;\n }\n }\n }\n eDebug($sections);\n $ancestors = $this->category->pathToNode(); \n }*/\n\n $ancestors = $this->category->pathToNode();\n // eDebug($ancestors);\n assign_to_template(array(\n 'ancestors' => $ancestors\n ));\n }", "label_name": "CWE-74", "label": 1} +{"code": " public static function getIconName($module)\n {\n return isset(static::$iconNames[$module])\n ? static::$iconNames[$module]\n : strtolower(str_replace('_', '-', $module));\n }", "label_name": "CWE-863", "label": 11} +{"code": " public function AddAddress($address, $name = '') {\n return $this->AddAnAddress('to', $address, $name);\n }", "label_name": "CWE-20", "label": 0} +{"code": " protected function loginRequired()\n {\n Yii::$app->user->logout();\n Yii::$app->user->loginRequired();\n\n return false;\n }", "label_name": "CWE-863", "label": 11} +{"code": " public function uploadCustomLogoAction(Request $request)\n {\n $fileExt = File::getFileExtension($_FILES['Filedata']['name']);\n if (!in_array($fileExt, ['svg', 'png', 'jpg'])) {\n throw new \\Exception('Unsupported file format');\n }\n\n if ($fileExt === 'svg' && stripos(file_get_contents($_FILES['Filedata']['tmp_name']), 'writeStream(self::CUSTOM_LOGO_PATH, fopen($_FILES['Filedata']['tmp_name'], 'rb'));\n\n // set content-type to text/html, otherwise (when application/json is sent) chrome will complain in\n // Ext.form.Action.Submit and mark the submission as failed\n\n $response = $this->adminJson(['success' => true]);\n $response->headers->set('Content-Type', 'text/html');\n\n return $response;\n }", "label_name": "CWE-200", "label": 10} +{"code": " public function getBackendRequest()\n {\n return $this->backendRequest;\n }", "label_name": "CWE-20", "label": 0} +{"code": " function delete_selected() {\r\n $item = $this->event->find('first', 'id=' . $this->params['id']);\r\n if ($item && $item->is_recurring == 1) {\r\n $event_remaining = false;\r\n $eventdates = $item->eventdate[0]->find('all', 'event_id=' . $item->id);\r\n foreach ($eventdates as $ed) {\r\n if (array_key_exists($ed->id, $this->params['dates'])) {\r\n $ed->delete();\r\n } else {\r\n $event_remaining = true;\r\n }\r\n }\r\n if (!$event_remaining) {\r\n $item->delete(); // model will also ensure we delete all event dates\r\n }\r\n expHistory::back();\r\n } else {\r\n notfoundController::handle_not_found();\r\n }\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public function afterSave($event) {\n // look up current tags\n $oldTags = $this->getTags();\n $newTags = array();\n\n foreach ($this->scanForTags() as $tag) {\n if (!in_array($tag, $oldTags)) { // don't add duplicates if there are already tags\n $tagModel = new Tags;\n $tagModel->tag = $tag; // includes the #\n $tagModel->type = get_class($this->getOwner());\n $tagModel->itemId = $this->getOwner()->id;\n $tagModel->itemName = $this->getOwner()->name;\n $tagModel->taggedBy = Yii::app()->getSuName();\n $tagModel->timestamp = time();\n if ($tagModel->save())\n $newTags[] = $tag;\n }\n }\n $this->_tags = $newTags + $oldTags; // update tag cache\n\n if (!empty($newTags) && $this->flowTriggersEnabled) {\n X2Flow::trigger('RecordTagAddTrigger', array(\n 'model' => $this->getOwner(),\n 'tags' => $newTags,\n ));\n }\n }", "label_name": "CWE-20", "label": 0} +{"code": " public static function parseAndTrimExport($str, $isHTML = false) { //\ufffdDeath from above\ufffd? \ufffd\n //echo \"1
\"; eDebug($str); \n\n $str = str_replace(\"\ufffd\", \"’\", $str);\n $str = str_replace(\"\ufffd\", \"‘\", $str);\n $str = str_replace(\"\ufffd\", \"®\", $str);\n $str = str_replace(\"\ufffd\", \"-\", $str);\n $str = str_replace(\"\ufffd\", \"—\", $str);\n $str = str_replace(\"\ufffd\", \"”\", $str);\n $str = str_replace(\"\ufffd\", \"“\", $str);\n $str = str_replace(\"\\r\\n\", \" \", $str);\n $str = str_replace(\"\\t\", \" \", $str);\n $str = str_replace(\",\", \"\\,\", $str);\n $str = str_replace(\"\ufffd\", \"¼\", $str);\n $str = str_replace(\"\ufffd\", \"½\", $str);\n $str = str_replace(\"\ufffd\", \"¾\", $str);\n\n if (!$isHTML) {\n $str = str_replace('\\\"', \""\", $str);\n $str = str_replace('\"', \""\", $str);\n } else {\n $str = str_replace('\"', '\"\"', $str);\n }\n\n //$str = htmlspecialchars($str);\n //$str = utf8_encode($str);\n $str = trim(str_replace(\"\ufffd\", \"™\", $str));\n //echo \"2
\"; eDebug($str,die);\n return $str;\n }", "label_name": "CWE-74", "label": 1} +{"code": " public static function getModelTypes($assoc = false) {\n $modelTypes = Yii::app()->db->createCommand()\n ->selectDistinct('modelName')\n ->from('x2_fields')\n ->where('modelName!=\"Calendar\"')\n ->order('modelName ASC')\n ->queryColumn();\n\n if ($assoc === true) {\n return array_combine($modelTypes, array_map(function($term) {\n return Yii::t('app', X2Model::getModelTitle($term));\n }, $modelTypes));\n }\n $modelTypes = array_map(function($term) {\n return Yii::t('app', $term);\n }, $modelTypes);\n return $modelTypes;\n }", "label_name": "CWE-20", "label": 0} +{"code": " protected function renderImageByGD($code)\n {\n $image = imagecreatetruecolor($this->width, $this->height);\n\n $backColor = imagecolorallocate(\n $image,\n (int) ($this->backColor % 0x1000000 / 0x10000),\n (int) ($this->backColor % 0x10000 / 0x100),\n $this->backColor % 0x100\n );\n imagefilledrectangle($image, 0, 0, $this->width - 1, $this->height - 1, $backColor);\n imagecolordeallocate($image, $backColor);\n\n if ($this->transparent) {\n imagecolortransparent($image, $backColor);\n }\n\n $foreColor = imagecolorallocate(\n $image,\n (int) ($this->foreColor % 0x1000000 / 0x10000),\n (int) ($this->foreColor % 0x10000 / 0x100),\n $this->foreColor % 0x100\n );\n\n $length = strlen($code);\n $box = imagettfbbox(30, 0, $this->fontFile, $code);\n $w = $box[4] - $box[0] + $this->offset * ($length - 1);\n $h = $box[1] - $box[5];\n $scale = min(($this->width - $this->padding * 2) / $w, ($this->height - $this->padding * 2) / $h);\n $x = 10;\n $y = round($this->height * 27 / 40);\n for ($i = 0; $i < $length; ++$i) {\n $fontSize = (int) (mt_rand(26, 32) * $scale * 0.8);\n $angle = mt_rand(-10, 10);\n $letter = $code[$i];\n $box = imagettftext($image, $fontSize, $angle, $x, $y, $foreColor, $this->fontFile, $letter);\n $x = $box[2] + $this->offset;\n }\n\n imagecolordeallocate($image, $foreColor);\n\n ob_start();\n imagepng($image);\n imagedestroy($image);\n\n return ob_get_clean();\n }", "label_name": "CWE-330", "label": 12} +{"code": " function manage() {\r\n global $db, $router, $user;\r\n\r\n expHistory::set('manageable', $router->params);\r\n assign_to_template(array(\r\n 'canManageStandalones' => self::canManageStandalones(),\r\n 'sasections' => $db->selectObjects('section', 'parent=-1'),\r\n 'user' => $user,\r\n// 'canManagePagesets' => $user->isAdmin(),\r\n// 'templates' => $db->selectObjects('section_template', 'parent=0'),\r\n ));\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic static function newFromStyle( $style, \\DPL\\Parameters $parameters ) {\n\t\t$style = strtolower( $style );\n\t\tswitch ( $style ) {\n\t\t\tcase 'definition':\n\t\t\t\t$class = 'DefinitionHeading';\n\t\t\t\tbreak;\n\t\t\tcase 'h1':\n\t\t\tcase 'h2':\n\t\t\tcase 'h3':\n\t\t\tcase 'h4':\n\t\t\tcase 'h5':\n\t\t\tcase 'h6':\n\t\t\tcase 'header':\n\t\t\t\t$class = 'TieredHeading';\n\t\t\t\tbreak;\n\t\t\tcase 'ordered':\n\t\t\t\t$class = 'OrderedHeading';\n\t\t\t\tbreak;\n\t\t\tcase 'unordered':\n\t\t\t\t$class = 'UnorderedHeading';\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn null;\n\t\t\t\tbreak;\n\t\t}\n\t\t$class = '\\DPL\\Heading\\\\' . $class;\n\n\t\treturn new $class( $parameters );\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " public static function parentPlaceholder($section = '')\n {\n if (! isset(static::$parentPlaceholder[$section])) {\n static::$parentPlaceholder[$section] = '##parent-placeholder-'.sha1($section).'##';\n }\n\n return static::$parentPlaceholder[$section];\n }", "label_name": "CWE-327", "label": 3} +{"code": " $fileName = ltrim(dirname($fileName) . '/' . basename($fileName, '.js'), '/.');\n if (empty($fileName)) {\n continue;\n }\n $templateBase = $inflector->filter(array(\n 'module' => $moduleName,\n 'controller' => $controllerName,\n 'file' => $fileName)\n );\n\n $templateExtend = $inflector->filter(array(\n 'module' => $moduleName,\n 'controller' => $this->Request()->getControllerName(),\n 'file' => $fileName)\n );\n if ($this->View()->templateExists($templateBase)) {\n $template .= '{include file=\"' . $templateBase. '\"}' . \"\\n\";\n }\n if ($this->View()->templateExists($templateExtend)) {\n $template .= '{include file=\"' . $templateExtend. '\"}' . \"\\n\";\n }\n }", "label_name": "CWE-20", "label": 0} +{"code": " static function searchUser(AuthLDAP $authldap) {\n\n if (self::connectToServer($authldap->getField('host'), $authldap->getField('port'),\n $authldap->getField('rootdn'),\n Toolbox::decrypt($authldap->getField('rootdn_passwd'), GLPIKEY),\n $authldap->getField('use_tls'),\n $authldap->getField('deref_option'))) {\n self::showLdapUsers();\n\n } else {\n echo \"
\".__('Unable to connect to the LDAP directory');\n }\n }", "label_name": "CWE-327", "label": 3} +{"code": " public function approve() {\n expHistory::set('editable', $this->params);\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n $require_login = empty($this->params['require_login']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];\n $require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];\n $require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n $notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];\n \n if (empty($this->params['id'])) {\n flash('error', gt('No ID supplied for note to approve'));\n $lastUrl = expHistory::getLast('editable');\n }\n \n $simplenote = new expSimpleNote($this->params['id']);\n assign_to_template(array(\n 'simplenote'=>$simplenote,\n 'require_login'=>$require_login,\n 'require_approval'=>$require_approval,\n 'require_notification'=>$require_notification,\n 'notification_email'=>$notification_email,\n 'tab'=>$this->params['tab']\n ));\n }", "label_name": "CWE-74", "label": 1} +{"code": "\t\t\t$return[$index] = strip_tags($value);\n\t\t\tif($return[$index] == 'zero')\n\t\t\t\t$return[$index] = '0';\n\t\t}\n\t}\n\telseif($type == ARG_MULTISTRING) {\n\t\tforeach($return as $index => $value) {\n\t\t\t$return[$index] = strip_tags($value);\n\t\t}\n\t}\n\telse\n\t\t$return = strip_tags($return);\n\n\tif(! empty($return) && $type == ARG_NUMERIC) {\n\t\tif(! is_numeric($return)) {\n\t\t\treturn preg_replace('([^\\d])', '', $return);\n\t\t}\n\t}\n\telseif(! empty($return) && $type == ARG_STRING) {\n\t\tif(! is_string($return))\n\t\t\t$return = $defaultvalue;\n\t}\n\telseif(! empty($return) && $type == ARG_MULTINUMERIC) {\n\t\tforeach($return as $index => $value) {\n\t\t\tif(! is_numeric($value)) {\n\t\t\t\t$return[$index] = preg_replace('([^\\d])', '', $value);\n\t\t\t}\n\t\t}\n\t\treturn $return;\n\t}\n\telseif(! empty($return) && $type == ARG_MULTISTRING) {\n\t\tforeach($return as $index => $value) {\n\t\t\tif(! is_string($value))\n\t\t\t\t$return[$index] = $defaultvalue;\n\t\t\telseif($addslashes)\n\t\t\t\t$return[$index] = addslashes($value);\n\t\t}\n\t\treturn $return;\n\t}\n\n\tif(is_string($return)) {\n\t\tif(strlen($return) == 0)\n\t\t\t$return = $defaultvalue;\n\t\telseif($addslashes)\n\t\t\t$return = addslashes($return);\n\t}\n\n\treturn $return;\n}", "label_name": "CWE-20", "label": 0} +{"code": " public function searchNew() {\n global $db, $user;\n //$this->params['query'] = str_ireplace('-','\\-',$this->params['query']);\n $sql = \"select DISTINCT(p.id) as id, p.title, model, sef_url, f.id as fileid, \";\n $sql .= \"match (p.title,p.model,p.body) against ('\" . $this->params['query'] . \"*' IN BOOLEAN MODE) as relevance, \";\n $sql .= \"CASE when p.model like '\" . $this->params['query'] . \"%' then 1 else 0 END as modelmatch, \";\n $sql .= \"CASE when p.title like '%\" . $this->params['query'] . \"%' then 1 else 0 END as titlematch \";\n $sql .= \"from \" . $db->prefix . \"product as p INNER JOIN \" .\n $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 .\n \"expFiles as f ON cef.expFiles_id = f.id WHERE \";\n if (!$user->isAdmin()) $sql .= '(p.active_type=0 OR p.active_type=1) AND ';\n $sql .= \" match (p.title,p.model,p.body) against ('\" . $this->params['query'] . \"*' IN BOOLEAN MODE) AND p.parent_id=0 \";\n $sql .= \" HAVING relevance > 0 \";\n //$sql .= \"GROUP BY p.id \"; \n $sql .= \"order by modelmatch,titlematch,relevance desc LIMIT 10\";\n\n eDebug($sql);\n $res = $db->selectObjectsBySql($sql);\n eDebug($res, true);\n $ar = new expAjaxReply(200, gt('Here\\'s the items you wanted'), $res);\n $ar->send();\n }", "label_name": "CWE-74", "label": 1} +{"code": " public function generateMessageFileName()\n {\n $time = microtime(true);\n\n return date('Ymd-His-', $time) . sprintf('%04d', (int) (($time - (int) $time) * 10000)) . '-' . sprintf('%04d', mt_rand(0, 10000)) . '.eml';\n }", "label_name": "CWE-330", "label": 12} +{"code": " function searchName() { return gt('Webpage'); }\r", "label_name": "CWE-74", "label": 1} +{"code": " foreach ($day as $extevent) {\r\n $event_cache = new stdClass();\r\n $event_cache->feed = $extgcalurl;\r\n $event_cache->event_id = $extevent->event_id;\r\n $event_cache->title = $extevent->title;\r\n $event_cache->body = $extevent->body;\r\n $event_cache->eventdate = $extevent->eventdate->date;\r\n if (isset($extevent->dateFinished) && $extevent->dateFinished != -68400)\r\n $event_cache->dateFinished = $extevent->dateFinished;\r\n if (isset($extevent->eventstart))\r\n $event_cache->eventstart = $extevent->eventstart;\r\n if (isset($extevent->eventend))\r\n $event_cache->eventend = $extevent->eventend;\r\n if (isset($extevent->is_allday))\r\n $event_cache->is_allday = $extevent->is_allday;\r\n $found = false;\r\n if ($extevent->eventdate->date < $start) // prevent duplicating events crossing month boundaries\r\n $found = $db->selectObject('event_cache','feed=\"'.$extgcalurl.'\" AND event_id=\"'.$event_cache->event_id.'\" AND eventdate='.$event_cache->eventdate);\r\n if (!$found)\r\n $db->insertObject($event_cache,'event_cache');\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " foreach ($matches[1] as $index => $body) {\n $parts = explode('_', $body);\n $fileID = $parts[0];\n $hash = $parts[1];\n try {\n $file = erLhcoreClassModelChatFile::fetch($fileID);\n if (is_object($file) && $hash == $file->security_hash) {\n\n $url = (erLhcoreClassSystem::$httpsMode == true ? 'https:' : 'http:') . '//' . $_SERVER['HTTP_HOST'] . erLhcoreClassDesign::baseurldirect('file/downloadfile') . \"/{$file->id}/{$hash}\";\n\n $media[] = array(\n 'id' => $file->id,\n 'size' => $file->size,\n 'upload_name' => $file->upload_name,\n 'type' => $file->type,\n 'extension' => $file->extension,\n 'hash' => $hash,\n 'url' => $url,\n );\n\n $msg_text_cleaned = str_replace($matches[0][$index],'',$msg_text_cleaned);\n }\n\n } catch (Exception $e) {\n\n }\n }", "label_name": "CWE-116", "label": 15} +{"code": " foreach ($events as $event) {\r\n $extevents[$date][] = $event;\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " foreach ($week as $dayNum => $day) {\r\n if ($dayNum == $now['mday']) {\r\n $currentweek = $weekNum;\r\n }\r\n if ($dayNum <= $endofmonth) {\r\n// $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;\r\n $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;\r\n }\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic function test_valid_comment_allow_empty_content() {\n\t\tadd_filter( 'allow_empty_comment', '__return_true' );\n\t\t$result = $this->myxmlrpcserver->wp_newComment(\n\t\t\tarray(\n\t\t\t\t1,\n\t\t\t\t'administrator',\n\t\t\t\t'administrator',\n\t\t\t\tself::$post->ID,\n\t\t\t\tarray(\n\t\t\t\t\t'content' => ' ',\n\t\t\t\t),\n\t\t\t)\n\t\t);\n\n\t\t$this->assertNotIXRError( $result );\n\t}", "label_name": "CWE-862", "label": 8} +{"code": " public function showall() {\n expHistory::set('viewable', $this->params);\n $limit = (isset($this->config['limit']) && $this->config['limit'] != '') ? $this->config['limit'] : 10;\n if (!empty($this->params['view']) && ($this->params['view'] == 'showall_accordion' || $this->params['view'] == 'showall_tabbed')) {\n $limit = '0';\n }\n $order = isset($this->config['order']) ? $this->config['order'] : \"rank\";\n $page = new expPaginator(array(\n 'model'=>'photo',\n 'where'=>$this->aggregateWhereClause(),\n 'limit'=>$limit,\n 'order'=>$order,\n 'categorize'=>empty($this->config['usecategories']) ? false : $this->config['usecategories'],\n 'uncat'=>!empty($this->config['uncat']) ? $this->config['uncat'] : gt('Not Categorized'),\n 'groups'=>!isset($this->params['gallery']) ? array() : array($this->params['gallery']),\n 'grouplimit'=>!empty($this->params['view']) && $this->params['view'] == 'showall_galleries' ? 1 : null,\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->baseclassname,\n 'action'=>$this->params['action'],\n 'src'=>$this->loc->src,\n 'columns'=>array(\n gt('Title')=>'title'\n ),\n ));\n \n assign_to_template(array(\n 'page'=>$page,\n 'params'=>$this->params,\n ));\n }", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic function getPurchaseOrderByJSON() {\n\t\t\n\t\tif(!empty($this->params['vendor'])) {\n\t\t\t$purchase_orders = $this->purchase_order->find('all', 'vendor_id=' . $this->params['vendor']);\n\t\t} else {\n\t\t\t$purchase_orders = $this->purchase_order->find('all');\n\t\t}\n\t\t\n\t\techo json_encode($purchase_orders);\n\t}", "label_name": "CWE-74", "label": 1} +{"code": "\tfunction unlockTables() {\n $sql = \"UNLOCK TABLES\";\n \n $res = mysqli_query($this->connection, $sql);\n return $res;\n }", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic function update() {\n global $user;\n\n if (expSession::get('customer-signup')) expSession::set('customer-signup', false);\n if (isset($this->params['address_country_id'])) {\n $this->params['country'] = $this->params['address_country_id'];\n unset($this->params['address_country_id']);\n }\n if (isset($this->params['address_region_id'])) {\n $this->params['state'] = $this->params['address_region_id'];\n unset($this->params['address_region_id']);\n }\n\t\tif ($user->isLoggedIn()) {\n\t\t\t// check to see how many other addresses this user has already.\n\t\t\t$count = $this->address->find('count', 'user_id='.$user->id);\n\t\t\t// if this is first address save for this user we'll make this the default\n\t\t\tif ($count == 0) \n {\n $this->params['is_default'] = 1;\n $this->params['is_billing'] = 1;\n $this->params['is_shipping'] = 1;\n }\n\t\t\t// associate this address with the current user.\n\t\t\t$this->params['user_id'] = $user->id;\n\t\t\t// save the object\n\t\t\t$this->address->update($this->params);\n\t\t}\n else { //if (ecomconfig::getConfig('allow_anonymous_checkout')){\n //user is not logged in, but allow anonymous checkout is enabled so we'll check \n //a few things that we don't check in the parent 'stuff and create a user account.\n $this->params['is_default'] = 1;\n $this->params['is_billing'] = 1;\n $this->params['is_shipping'] = 1; \n $this->address->update($this->params);\n }\n\t\texpHistory::back(); \n\t}", "label_name": "CWE-74", "label": 1} +{"code": " self::assertSame($shouldBePresent, $request->hasHeader('Authorization'));\n self::assertSame($shouldBePresent, $request->hasHeader('Cookie'));\n\n return new Response(200);\n }\n ]);", "label_name": "CWE-200", "label": 10} +{"code": " $loc = expCore::makeLocation('navigation', '', $standalone->id);\r\n if (expPermissions::check('manage', $loc)) return true;\r\n }\r\n return false;\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": "\tprivate function _modifiedby( $option ) {\n\t\t$this->addTable( 'revision_actor_temp', 'change_rev' );\n\t\t$user = new \\User;\n\n\t\t$this->addWhere( $this->DB->addQuotes( $user->newFromName( $option )->getActorId() ) . ' = change_rev.revactor_actor AND change_rev.revactor_page = page_id' );\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " $newret = recyclebin::restoreFromRecycleBin($iLoc, $page_id);\r\n if (!empty($newret)) $ret .= $newret . '
';\r\n if ($iLoc->mod == 'container') {\r\n $ret .= scan_container($container->internal, $page_id);\r\n }\r\n }\r\n return $ret;\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " $query->whereExists(function ($permissionQuery) use (&$tableDetails, $morphClass) {\n /** @var Builder $permissionQuery */\n $permissionQuery->select('id')->from('joint_permissions')\n ->whereColumn('joint_permissions.entity_id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])\n ->where('entity_type', '=', $morphClass)\n ->where('action', '=', 'view')\n ->whereIn('role_id', $this->getCurrentUserRoles())\n ->where(function (QueryBuilder $query) {\n $this->addJointHasPermissionCheck($query, $this->currentUser()->id);\n });\n });", "label_name": "CWE-863", "label": 11} +{"code": " public function handle($stanza, $parent = false)\n {\n $message = $stanza->forwarded->message;\n\n $jid = explode('/',(string)$message->attributes()->from);\n $to = current(explode('/',(string)$message->attributes()->to));\n\n if($message->composing)\n $this->event('composing', array($jid[0], $to));\n if($message->paused)\n $this->event('paused', array($jid[0], $to));\n if($message->gone)\n $this->event('gone', array($jid[0], $to));\n\n if($message->body || $message->subject) {\n $m = new \\Modl\\Message;\n $m->set($message, $stanza->forwarded);\n\n if(!preg_match('#^\\?OTR#', $m->body)) {\n $md = new \\Modl\\MessageDAO;\n $md->set($m);\n\n $this->pack($m);\n $this->deliver();\n }\n }\n }", "label_name": "CWE-346", "label": 16} +{"code": " function process_subsections($parent_section, $subtpl) {\r\n global $db, $router;\r\n\r\n $section = new stdClass();\r\n $section->parent = $parent_section->id;\r\n $section->name = $subtpl->name;\r\n $section->sef_name = $router->encode($section->name);\r\n $section->subtheme = $subtpl->subtheme;\r\n $section->active = $subtpl->active;\r\n $section->public = $subtpl->public;\r\n $section->rank = $subtpl->rank;\r\n $section->page_title = $subtpl->page_title;\r\n $section->keywords = $subtpl->keywords;\r\n $section->description = $subtpl->description;\r\n $section->id = $db->insertObject($section, 'section');\r\n self::process_section($section, $subtpl);\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": "\t\t\treturn \\DPL\\Variables::setVarDefault( $args );\n\t\t}\n\t\treturn \\DPL\\Variables::getVar( $cmd );\n\t}", "label_name": "CWE-400", "label": 2} +{"code": "\tfunction selectBillingOptions() {\n\t\t\n\t}", "label_name": "CWE-74", "label": 1} +{"code": " $layout[$position] = array($elem => $initLayout[$position][$elem]) + $layout[$position]; // unshift key-value pair\n $changed = true;\n }\n\n // remove obsolete widgets\n $arrayDiff =\n array_diff(array_keys($layoutWidgets), array_keys($initLayoutWidgets));\n foreach($arrayDiff as $elem){\n if(in_array ($elem, array_keys ($layout[$position]))) {\n unset($layout[$position][$elem]);\n $changed = true;\n } else if($position === 'center' && in_array ($elem, array_keys ($layout['hidden']))) {\n unset($layout['hidden'][$elem]);\n $changed = true;\n }\n }\n\n\n // ensure that widget properties are the same as those in the default layout\n foreach($layout[$position] as $name=>$arr){\n if (in_array ($name, array_keys ($initLayout[$position])) &&\n $initLayout[$position][$name]['title'] !== $arr['title']) {\n\n $layout[$position][$name]['title'] = $initLayout[$position][$name]['title'];\n $changed = true;\n }\n }\n if ($position === 'center') {\n foreach($layout['hidden'] as $name=>$arr){\n if (in_array ($name, array_keys ($initLayout[$position])) &&\n $initLayout[$position][$name]['title'] !== $arr['title']) {\n\n $layout['hidden'][$name]['title'] = $initLayout[$position][$name]['title'];\n $changed = true;\n }\n }\n }\n\n if($changed){\n $this->layout = json_encode($layout);\n $this->update(array('layout'));\n }\n }", "label_name": "CWE-20", "label": 0} +{"code": "\t\tforeach($row as $key => $value) {\n\t\t\t$type = gettype($value);\n\t\t\t$sqltype=NULL;\n\t\t\tswitch($type) {\n\t\t\t\tcase \"integer\":\n\t\t\t\t\t$sqltype = SQLITE3_INTEGER;\n\t\t\t\tbreak;\n\t\t\t\tcase \"string\":\n\t\t\t\t\t$sqltype = SQLITE3_TEXT;\n\t\t\t\tbreak;\n\t\t\t\tcase \"NULL\":\n\t\t\t\t\t$sqltype = SQLITE3_NULL;\n\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\t$sqltype = \"UNK\";\n\t\t\t}\n\t\t\t$stmt->bindValue(\":\".$key, $value, $sqltype);\n\t\t}", "label_name": "CWE-862", "label": 8} +{"code": " private function sendString ($string) {\n $bytes_sent = fwrite($this->pop_conn, $string, strlen($string));\n\n return $bytes_sent;\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function getBranches()\n {\n if (null === $this->branches) {\n $branches = array();\n\n $this->process->execute('git branch --no-color --no-abbrev -v', $output, $this->repoDir);\n foreach ($this->process->splitLines($output) as $branch) {\n if ($branch && !Preg::isMatch('{^ *[^/]+/HEAD }', $branch)) {\n if (Preg::isMatch('{^(?:\\* )? *(\\S+) *([a-f0-9]+)(?: .*)?$}', $branch, $match)) {\n $branches[$match[1]] = $match[2];\n }\n }\n }\n\n $this->branches = $branches;\n }\n\n return $this->branches;\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function params()\n {\n $project = $this->getProject();\n $values = $this->request->getValues();\n\n if (empty($values['action_name']) || empty($values['project_id']) || empty($values['event_name'])) {\n $this->create();\n return;\n }\n\n $action = $this->actionManager->getAction($values['action_name']);\n $action_params = $action->getActionRequiredParameters();\n\n if (empty($action_params)) {\n $this->doCreation($project, $values + array('params' => array()));\n }\n\n $projects_list = $this->projectUserRoleModel->getActiveProjectsByUser($this->userSession->getId());\n unset($projects_list[$project['id']]);\n\n $this->response->html($this->template->render('action_creation/params', array(\n 'values' => $values,\n 'action_params' => $action_params,\n 'columns_list' => $this->columnModel->getList($project['id']),\n 'users_list' => $this->projectUserRoleModel->getAssignableUsersList($project['id']),\n 'projects_list' => $projects_list,\n 'colors_list' => $this->colorModel->getList(),\n 'categories_list' => $this->categoryModel->getList($project['id']),\n 'links_list' => $this->linkModel->getList(0, false),\n 'priorities_list' => $this->projectTaskPriorityModel->getPriorities($project),\n 'project' => $project,\n 'available_actions' => $this->actionManager->getAvailableActions(),\n 'swimlane_list' => $this->swimlaneModel->getList($project['id']),\n 'events' => $this->actionManager->getCompatibleEvents($values['action_name']),\n )));\n }", "label_name": "CWE-200", "label": 10} +{"code": " public function beforeSave () {\n $valid = parent::beforeSave ();\n if ($valid) {\n $table = Yii::app()->db->schema->tables[$this->myTableName];\n $existing = array_key_exists($this->fieldName, $table->columns) && \n $table->columns[$this->fieldName] instanceof CDbColumnSchema;\n if($existing){ \n $valid = $this->modifyColumn();\n }\n }\n return $valid;\n }", "label_name": "CWE-20", "label": 0} +{"code": " $date->delete(); // event automatically deleted if all assoc eventdates are deleted\r\n }\r\n expHistory::back();\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public function testPOSTForRegularUser()\n {\n $post_resource = json_encode([\n 'label' => 'Test Request 9747 regular user',\n 'shortname' => 'test9747-regular-user',\n 'description' => 'Test of Request 9747 for REST API Project Creation',\n 'is_public' => true,\n 'template_id' => 100,\n ]);\n\n $response = $this->getResponseByName(\n REST_TestDataBuilder::TEST_USER_2_NAME,\n $this->request_factory->createRequest(\n 'POST',\n 'projects'\n )->withBody(\n $this->stream_factory->createStream($post_resource)\n )\n );\n\n self::assertEquals(201, $response->getStatusCode());\n\n $create_project_id = json_decode($response->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR)['id'];\n\n $this->removeAdminFromProjectMembers(\n $create_project_id,\n REST_TestDataBuilder::TEST_USER_2_NAME,\n );\n }", "label_name": "CWE-863", "label": 11} +{"code": " private function __checkIfPulledEventExistsAndAddOrUpdate($event, $eventId, &$successes, &$fails, $eventModel, $server, $user, $jobId)\n {\n // check if the event already exist (using the uuid)\n $existingEvent = $eventModel->find('first', array('conditions' => array('Event.uuid' => $event['Event']['uuid'])));\n $passAlong = $server['Server']['id'];\n if (!$existingEvent) {\n // add data for newly imported events\n $result = $eventModel->_add($event, true, $user, $server['Server']['org_id'], $passAlong, true, $jobId);\n if ($result === true) {\n $successes[] = $eventId;\n } else {\n $fails[$eventId] = __('Failed (partially?) because of errors: ') . $result;\n }\n } else {\n if (!$existingEvent['Event']['locked'] && !$server['Server']['internal']) {\n $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.');\n } else {\n $result = $eventModel->_edit($event, $user, $existingEvent['Event']['id'], $jobId, $passAlong);\n if ($result === true) {\n $successes[] = $eventId;\n } elseif (isset($result['error'])) {\n $fails[$eventId] = $result['error'];\n } else {\n $fails[$eventId] = json_encode($result);\n }\n }\n }\n }", "label_name": "CWE-269", "label": 6} +{"code": " $object->size = convert_size($cur->getSize());\n $object->mtime = date('D, j M, Y', $cur->getMTime());\n list($object->perms, $object->chmod) = $this->_getPermissions($cur->getPerms());\n \n // Find the file type\n $object->type = $this->_getFileType($cur);\n\n // make the link depending on if it's a file or a dir\n if ($cur->isDir()) {\n $object->link = 'path . $object->name) . '\">' . $object->name . '';\n } else {\n $object->link = 'path . $object->name . (endsWith($object->name, URL_SUFFIX) ? '?has_url_suffix=1' : '')) . '\">' . $object->name . '';\n }\n\n $files[$object->name] = $object;\n }", "label_name": "CWE-20", "label": 0} +{"code": " $masteroption->delete();\n }\n \n // delete the mastergroup\n $db->delete('optiongroup', 'optiongroup_master_id='.$mastergroup->id);\n $mastergroup->delete();\n \n expHistory::back();\n }", "label_name": "CWE-74", "label": 1} +{"code": " public function view() {\n $params = func_get_args();\n $content = '';\n\n $filename = urldecode(join('/', $params));\n\n // Sanitize filename for securtiy\n // We don't allow backlinks\n if (strpos($filename, '..') !== false) {\n /*\n if (Plugin::isEnabled('statistics_api')) {\n $user = null;\n if (AuthUser::isLoggedIn())\n $user = AuthUser::getUserName();\n $ip = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : ($_SERVER['REMOTE_ADDR']);\n $event = array('event_type' => 'hack_attempt', // simple event type identifier\n 'description' => __('A possible hack attempt was detected.'), // translatable description\n 'ipaddress' => $ip,\n 'username' => $user);\n Observer::notify('stats_file_manager_hack_attempt', $event);\n }\n */\n }\n $filename = str_replace('..', '', $filename);\n\n // Clean up nicely\n $filename = str_replace('//', '', $filename);\n\n // We don't allow leading slashes\n $filename = preg_replace('/^\\//', '', $filename);\n \n // Check if file had URL_SUFFIX - if so, append it to filename\n $filename .= (isset($_GET['has_url_suffix']) && $_GET['has_url_suffix']==='1') ? URL_SUFFIX : '';\n \n $file = FILES_DIR . '/' . $filename;\n if (!$this->_isImage($file) && file_exists($file)) {\n $content = file_get_contents($file);\n }\n \n $this->display('file_manager/views/view', array(\n 'csrf_token' => SecureToken::generateToken(BASE_URL.'plugin/file_manager/save/'.$filename),\n 'is_image' => $this->_isImage($file),\n 'filename' => $filename,\n 'content' => $content\n ));\n }", "label_name": "CWE-20", "label": 0} +{"code": " protected function renderImageByImagick($code)\n {\n $backColor = $this->transparent ? new \\ImagickPixel('transparent') : new \\ImagickPixel('#' . str_pad(dechex($this->backColor), 6, 0, STR_PAD_LEFT));\n $foreColor = new \\ImagickPixel('#' . str_pad(dechex($this->foreColor), 6, 0, STR_PAD_LEFT));\n\n $image = new \\Imagick();\n $image->newImage($this->width, $this->height, $backColor);\n\n $draw = new \\ImagickDraw();\n $draw->setFont($this->fontFile);\n $draw->setFontSize(30);\n $fontMetrics = $image->queryFontMetrics($draw, $code);\n\n $length = strlen($code);\n $w = (int) $fontMetrics['textWidth'] - 8 + $this->offset * ($length - 1);\n $h = (int) $fontMetrics['textHeight'] - 8;\n $scale = min(($this->width - $this->padding * 2) / $w, ($this->height - $this->padding * 2) / $h);\n $x = 10;\n $y = round($this->height * 27 / 40);\n for ($i = 0; $i < $length; ++$i) {\n $draw = new \\ImagickDraw();\n $draw->setFont($this->fontFile);\n $draw->setFontSize((int) (mt_rand(26, 32) * $scale * 0.8));\n $draw->setFillColor($foreColor);\n $image->annotateImage($draw, $x, $y, mt_rand(-10, 10), $code[$i]);\n $fontMetrics = $image->queryFontMetrics($draw, $code[$i]);\n $x += (int) $fontMetrics['textWidth'] + $this->offset;\n }\n\n $image->setImageFormat('png');\n return $image->getImageBlob();\n }", "label_name": "CWE-330", "label": 12} +{"code": "function current_user_get_bug_filter( $p_project_id = null ) {\n\t$f_filter_string = gpc_get_string( 'filter', '' );\n\t$t_filter = '';\n\n\tif( !is_blank( $f_filter_string ) ) {\n\t\tif( is_numeric( $f_filter_string ) ) {\n\t\t\t$t_token = token_get_value( TOKEN_FILTER );\n\t\t\tif( null != $t_token ) {\n\t\t\t\t$t_filter = json_decode( $t_token, true );\n\t\t\t}\n\t\t} else {\n\t\t\t$t_filter = json_decode( $f_filter_string, true );\n\t\t}\n\t\t$t_filter = filter_ensure_valid_filter( $t_filter );\n\t} else if( !filter_is_cookie_valid() ) {\n\t\t$t_filter = filter_get_default();\n\t} else {\n\t\t$t_user_id = auth_get_current_user_id();\n\t\t$t_filter = user_get_bug_filter( $t_user_id, $p_project_id );\n\t}\n\n\treturn $t_filter;\n}", "label_name": "CWE-200", "label": 10} +{"code": "\tfunction test_username_avoids_anon_flow() {\n\t\tadd_filter( 'xmlrpc_allow_anonymous_comments', '__return_true' );\n\n\t\t$comment_args = array(\n\t\t\t1,\n\t\t\t'administrator',\n\t\t\t'administrator',\n\t\t\tself::$post->ID,\n\t\t\tarray(\n\t\t\t\t'author' => 'WordPress',\n\t\t\t\t'author_email' => 'noreply at wordpress.org',\n\t\t\t\t'content' => 'Test Anon Comments',\n\t\t\t),\n\t\t);\n\n\t\t$result = $this->myxmlrpcserver->wp_newComment( $comment_args );\n\t\t$comment = get_comment( $result );\n\t\t$user_id = get_user_by( 'login', 'administrator' )->ID;\n\n\t\t$this->assertSame( $user_id, (int) $comment->user_id );\n\t}", "label_name": "CWE-862", "label": 8} +{"code": " function prepareInputForUpdate($input) {\n\n if (isset($input[\"rootdn_passwd\"])) {\n if (empty($input[\"rootdn_passwd\"])) {\n unset($input[\"rootdn_passwd\"]);\n } else {\n $input[\"rootdn_passwd\"] = Toolbox::encrypt(stripslashes($input[\"rootdn_passwd\"]),\n GLPIKEY);\n }\n }\n\n if (isset($input[\"_blank_passwd\"]) && $input[\"_blank_passwd\"]) {\n $input['rootdn_passwd'] = '';\n }\n\n // Set attributes in lower case\n if (count($input)) {\n foreach ($input as $key => $val) {\n if (preg_match('/_field$/', $key)) {\n $input[$key] = Toolbox::strtolower($val);\n }\n }\n }\n\n //do not permit to override sync_field\n if ($this->isSyncFieldEnabled()\n && isset($input['sync_field'])\n && $this->isSyncFieldUsed()\n ) {\n if ($input['sync_field'] == $this->fields['sync_field']) {\n unset($input['sync_field']);\n } else {\n Session::addMessageAfterRedirect(\n __('Synchronization field cannot be changed once in use.'),\n false,\n ERROR\n );\n return false;\n };\n }\n return $input;\n }", "label_name": "CWE-327", "label": 3} +{"code": " function edit_internalalias() {\r\n $section = isset($this->params['id']) ? $this->section->find($this->params['id']) : new section($this->params);\r\n if ($section->parent == -1) {\r\n notfoundController::handle_not_found();\r\n exit;\r\n } // doesn't work for standalone pages\r\n if (empty($section->id)) {\r\n $section->public = 1;\r\n if (!isset($section->parent)) {\r\n // This is another precaution. The parent attribute\r\n // should ALWAYS be set by the caller.\r\n //FJD - if that's the case, then we should die.\r\n notfoundController::handle_not_authorized();\r\n exit;\r\n //$section->parent = 0;\r\n }\r\n }\r\n assign_to_template(array(\r\n 'section' => $section,\r\n 'glyphs' => self::get_glyphs(),\r\n ));\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " function configure() {\n expHistory::set('editable', $this->params);\n // little bit of trickery so that that categories can have their own configs\n \n $this->loc->src = \"@globalstoresettings\";\n $config = new expConfig($this->loc);\n $this->config = $config->config;\n $pullable_modules = expModules::listInstalledControllers($this->baseclassname, $this->loc);\n $views = expTemplate::get_config_templates($this, $this->loc);\n \n $gc = new geoCountry(); \n $countries = $gc->find('all');\n \n $gr = new geoRegion(); \n $regions = $gr->find('all');\n \n assign_to_template(array(\n 'config'=>$this->config,\n 'pullable_modules'=>$pullable_modules,\n 'views'=>$views,\n 'countries'=>$countries,\n 'regions'=>$regions,\n 'title'=>static::displayname()\n ));\n } ", "label_name": "CWE-74", "label": 1} +{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $category = $this->getCategory();\n\n if ($this->categoryModel->remove($category['id'])) {\n $this->flash->success(t('Category removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this category.'));\n }\n\n $this->response->redirect($this->helper->url->to('CategoryController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-200", "label": 10} +{"code": " public static function isPublic($s) {\r\n if ($s == null) {\r\n return false;\r\n }\r\n while ($s->public && $s->parent > 0) {\r\n $s = new section($s->parent);\r\n }\r\n $lineage = (($s->public) ? 1 : 0);\r\n return $lineage;\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " foreach ($days as $event) {\r\n if (empty($event->eventdate->date) || ($viewrange == 'upcoming' && $event->eventdate->date < time()))\r\n break;\r\n if (empty($event->eventstart))\r\n $event->eventstart = $event->eventdate->date;\r\n $extitem[] = $event;\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " private function getCategory()\n {\n $category = $this->categoryModel->getById($this->request->getIntegerParam('category_id'));\n\n if (empty($category)) {\n throw new PageNotFoundException();\n }\n\n return $category;\n }", "label_name": "CWE-200", "label": 10} +{"code": "\tpublic function delete() {\n\t global $db;\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n// $require_login = empty($this->params['require_login']) ? COMMENTS_REQUIRE_LOGIN : $this->params['require_login'];\n// $require_approval = empty($this->params['require_approval']) ? COMMENTS_REQUIRE_APPROVAL : $this->params['require_approval'];\n// $require_notification = empty($this->params['require_notification']) ? COMMENTS_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n// $notification_email = empty($this->params['notification_email']) ? COMMENTS_NOTIFICATION_EMAIL : $this->params['notification_email'];\n\t \n\t if (empty($this->params['id'])) {\n\t flash('error', gt('Missing id for the comment you would like to delete'));\n\t expHistory::back();\n\t }\n\t \n\t // delete the comment\n $comment = new expComment($this->params['id']);\n $comment->delete();\n \n // delete the association too\n $db->delete($comment->attachable_table, 'expcomments_id='.$this->params['id']); \n \n // send the user back where they came from.\n expHistory::back();\n\t}", "label_name": "CWE-74", "label": 1} +{"code": " private function getSwimlane()\n {\n $swimlane = $this->swimlaneModel->getById($this->request->getIntegerParam('swimlane_id'));\n\n if (empty($swimlane)) {\n throw new PageNotFoundException();\n }\n\n return $swimlane;\n }", "label_name": "CWE-200", "label": 10} +{"code": "\t\t\t$temp_result_value = str_replace( $search, $v, $subject );\n\t\t\t$rendered_values[] = $temp_result_value;\n\t\t}\n\t\treturn [\n\t\t\timplode( $delimiter, $rendered_values ),\n\t\t\t'noparse'\t=> false,\n\t\t\t'isHTML'\t=> false\n\t\t];\n\t}", "label_name": "CWE-400", "label": 2} +{"code": "\tfunction test_allowed_anon_comments() {\n\t\tadd_filter( 'xmlrpc_allow_anonymous_comments', '__return_true' );\n\n\t\t$comment_args = array(\n\t\t\t1,\n\t\t\t'',\n\t\t\t'',\n\t\t\tself::$post->ID,\n\t\t\tarray(\n\t\t\t\t'author' => 'WordPress',\n\t\t\t\t'author_email' => 'noreply@wordpress.org',\n\t\t\t\t'content' => 'Test Anon Comments',\n\t\t\t),\n\t\t);\n\n\t\t$result = $this->myxmlrpcserver->wp_newComment( $comment_args );\n\t\t$this->assertNotIXRError( $result );\n\t\t$this->assertInternalType( 'int', $result );\n\t}", "label_name": "CWE-862", "label": 8} +{"code": " public function testAuthCheckAuthFails()\n {\n $GLOBALS['cfg']['Server']['auth_swekey_config'] = 'testConfigSwekey';\n $GLOBALS['server'] = 1;\n $_REQUEST['old_usr'] = '';\n $_REQUEST['pma_username'] = '';\n $_COOKIE['pmaServer-1'] = 'pmaServ1';\n $_COOKIE['pmaUser-1'] = 'pmaUser1';\n $_COOKIE['pma_iv-1'] = base64_encode('testiv09testiv09');\n $GLOBALS['cfg']['blowfish_secret'] = 'secret';\n $_SESSION['last_access_time'] = 1;\n $_SESSION['last_valid_captcha'] = true;\n $GLOBALS['cfg']['LoginCookieValidity'] = 0;\n $_SESSION['last_access_time'] = -1;\n // mock for blowfish function\n $this->object = $this->getMockBuilder('AuthenticationCookie')\n ->disableOriginalConstructor()\n ->setMethods(array('authFails'))\n ->getMock();\n\n $this->object->expects($this->once())\n ->method('authFails');\n\n $this->assertFalse(\n $this->object->authCheck()\n );\n\n $this->assertTrue(\n $GLOBALS['no_activity']\n );\n }", "label_name": "CWE-200", "label": 10} +{"code": " public static function referenceFixtures() {\n return array(\n 'campaign' => array ('Campaign', '.CampaignMailingBehaviorTest'),\n 'lists' => 'X2List',\n 'credentials' => 'Credentials',\n 'users' => 'User',\n 'profile' => array('Profile','.marketing')\n );\n }", "label_name": "CWE-20", "label": 0} +{"code": " public static function _date2timestamp( $datetime, $wtz=null ) {\r\n if( !isset( $datetime['hour'] )) $datetime['hour'] = 0;\r\n if( !isset( $datetime['min'] )) $datetime['min'] = 0;\r\n if( !isset( $datetime['sec'] )) $datetime['sec'] = 0;\r\n if( empty( $wtz ) && ( !isset( $datetime['tz'] ) || empty( $datetime['tz'] )))\r\n return mktime( $datetime['hour'], $datetime['min'], $datetime['sec'], $datetime['month'], $datetime['day'], $datetime['year'] );\r\n $output = $offset = 0;\r\n if( empty( $wtz )) {\r\n if( iCalUtilityFunctions::_isOffset( $datetime['tz'] )) {\r\n $offset = iCalUtilityFunctions::_tz2offset( $datetime['tz'] ) * -1;\r\n $wtz = 'UTC';\r\n }\r\n else\r\n $wtz = $datetime['tz'];\r\n }\r\n if(( 'Z' == $wtz ) || ( 'GMT' == strtoupper( $wtz )))\r\n $wtz = 'UTC';\r\n try {\r\n $strdate = sprintf( '%04d-%02d-%02d %02d:%02d:%02d', $datetime['year'], $datetime['month'], $datetime['day'], $datetime['hour'], $datetime['min'], $datetime['sec'] );\r\n $d = new DateTime( $strdate, new DateTimeZone( $wtz ));\r\n if( 0 != $offset ) // adjust for offset\r\n $d->modify( $offset.' seconds' );\r\n $output = $d->format( 'U' );\r\n unset( $d );\r\n }\r\n catch( Exception $e ) {\r\n $output = mktime( $datetime['hour'], $datetime['min'], $datetime['sec'], $datetime['month'], $datetime['day'], $datetime['year'] );\r\n }\r\n return $output;\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic function register()\n\t{\n\t\tJSession::checkToken('post') or jexit(JText::_('JINVALID_TOKEN'));\n\n\t\t// Get the application\n\t\t$app = JFactory::getApplication();\n\n\t\t// Get the form data.\n\t\t$data = $this->input->post->get('user', array(), 'array');\n\n\t\t// Get the model and validate the data.\n\t\t$model = $this->getModel('Registration', 'UsersModel');\n\n\t\t$form = $model->getForm();\n\n\t\tif (!$form)\n\t\t{\n\t\t\tJError::raiseError(500, $model->getError());\n\n\t\t\treturn false;\n\t\t}\n\n\t\t$return = $model->validate($form, $data);\n\n\t\t// Check for errors.\n\t\tif ($return === false)\n\t\t{\n\t\t\t// Get the validation messages.\n\t\t\t$errors = $model->getErrors();\n\n\t\t\t// Push up to three validation messages out to the user.\n\t\t\tfor ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++)\n\t\t\t{\n\t\t\t\tif ($errors[$i] instanceof Exception)\n\t\t\t\t{\n\t\t\t\t\t$app->enqueueMessage($errors[$i]->getMessage(), 'notice');\n\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t$app->enqueueMessage($errors[$i], 'notice');\n\t\t\t}\n\n\t\t\t// Save the data in the session.\n\t\t\t$app->setUserState('users.registration.form.data', $data);\n\n\t\t\t// Redirect back to the registration form.\n\t\t\t$this->setRedirect('index.php?option=com_users&view=registration');\n\n\t\t\treturn false;\n\t\t}\n\n\t\t// Finish the registration.\n\t\t$return = $model->register($data);\n\n\t\t// Check for errors.\n\t\tif ($return === false)\n\t\t{\n\t\t\t// Save the data in the session.\n\t\t\t$app->setUserState('users.registration.form.data', $data);\n\n\t\t\t// Redirect back to the registration form.\n\t\t\t$message = JText::sprintf('COM_USERS_REGISTRATION_SAVE_FAILED', $model->getError());\n\t\t\t$this->setRedirect('index.php?option=com_users&view=registration', $message, 'error');\n\n\t\t\treturn false;\n\t\t}\n\n\t\t// Flush the data from the session.\n\t\t$app->setUserState('users.registration.form.data', null);\n\n\t\treturn true;\n\t}", "label_name": "CWE-20", "label": 0} +{"code": " public function toolbar() {\n// global $user;\n\n $menu = array();\n\t\t$dirs = array(\n\t\t\tBASE.'framework/modules/administration/menus',\n\t\t\tBASE.'themes/'.DISPLAY_THEME.'/modules/administration/menus'\n\t\t);\n\n\t\tforeach ($dirs as $dir) {\n\t\t if (is_readable($dir)) {\n\t\t\t $dh = opendir($dir);\n\t\t\t while (($file = readdir($dh)) !== false) {\n\t\t\t\t if (substr($file,-4,4) == '.php' && is_readable($dir.'/'.$file) && is_file($dir.'/'.$file)) {\n\t\t\t\t\t $menu[substr($file,0,-4)] = include($dir.'/'.$file);\n if (empty($menu[substr($file,0,-4)])) unset($menu[substr($file,0,-4)]);\n\t\t\t\t }\n\t\t\t }\n\t\t }\n\t\t}\n\n // sort the top level menus alphabetically by filename\n\t\tksort($menu);\t\t\n\t\t$sorted = array();\n\t\tforeach($menu as $m) $sorted[] = $m;\n \n // slingbar position\n if (isset($_COOKIE['slingbar-top'])){\n $top = $_COOKIE['slingbar-top'];\n } else {\n $top = SLINGBAR_TOP;\n }\n \n\t\tassign_to_template(array(\n 'menu'=>(bs3()) ? $sorted : json_encode($sorted),\n \"top\"=>$top\n ));\n }", "label_name": "CWE-74", "label": 1} +{"code": "\t\tpublic static function upload_user_avatar() {\n\t\t\t$file = $_FILES['lp-upload-avatar'];\n\t\t\t$upload_dir = learn_press_user_profile_picture_upload_dir();\n\n\t\t\tadd_filter( 'upload_dir', array( __CLASS__, '_user_avatar_upload_dir' ), 10000 );\n\n\t\t\t$result = wp_handle_upload(\n\t\t\t\t$file,\n\t\t\t\tarray(\n\t\t\t\t\t'test_form' => false,\n\t\t\t\t)\n\t\t\t);\n\n\t\t\tremove_filter( 'upload_dir', array( __CLASS__, '_user_avatar_upload_dir' ), 10000 );\n\n\t\t\tif ( is_array( $result ) ) {\n\t\t\t\t$result['name'] = $upload_dir['subdir'] . '/' . basename( $result['file'] );\n\t\t\t\tunset( $result['file'] );\n\t\t\t} else {\n\t\t\t\t$result = array(\n\t\t\t\t\t'error' => __( 'Profile picture upload failed', 'learnpress' ),\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlearn_press_send_json( $result );\n\t\t}", "label_name": "CWE-610", "label": 17} +{"code": " public function fromData($data, $filename)\n {\n if ($data === null) {\n return;\n }\n\n $tempPath = temp_path(basename($filename));\n FileHelper::put($tempPath, $data);\n\n $file = $this->fromFile($tempPath);\n FileHelper::delete($tempPath);\n\n return $file;\n }", "label_name": "CWE-362", "label": 18} +{"code": " public static function parseAndTrimExport($str, $isHTML = false) { //\ufffdDeath from above\ufffd? \ufffd\n //echo \"1
\"; eDebug($str); \n\n $str = str_replace(\"\ufffd\", \"’\", $str);\n $str = str_replace(\"\ufffd\", \"‘\", $str);\n $str = str_replace(\"\ufffd\", \"®\", $str);\n $str = str_replace(\"\ufffd\", \"-\", $str);\n $str = str_replace(\"\ufffd\", \"—\", $str);\n $str = str_replace(\"\ufffd\", \"”\", $str);\n $str = str_replace(\"\ufffd\", \"“\", $str);\n $str = str_replace(\"\\r\\n\", \" \", $str);\n $str = str_replace(\"\\t\", \" \", $str);\n $str = str_replace(\",\", \"\\,\", $str);\n $str = str_replace(\"\ufffd\", \"¼\", $str);\n $str = str_replace(\"\ufffd\", \"½\", $str);\n $str = str_replace(\"\ufffd\", \"¾\", $str);\n\n if (!$isHTML) {\n $str = str_replace('\\\"', \""\", $str);\n $str = str_replace('\"', \""\", $str);\n } else {\n $str = str_replace('\"', '\"\"', $str);\n }\n\n //$str = htmlspecialchars($str);\n //$str = utf8_encode($str);\n $str = trim(str_replace(\"\ufffd\", \"™\", $str));\n //echo \"2
\"; eDebug($str,die);\n return $str;\n }", "label_name": "CWE-74", "label": 1} +{"code": " public function scopeSearch(Builder $query, array $search = [])\n {\n if (empty($search)) {\n return $query;\n }\n\n if (!array_intersect(array_keys($search), $this->searchable)) {\n return $query;\n }\n\n return $query->where($search);\n }", "label_name": "CWE-287", "label": 4} +{"code": " function updateObject($object, $table, $where=null, $identifier='id', $is_revisioned=false) {\n\n if ($is_revisioned) {\n $object->revision_id++;\n //if ($table==\"text\") eDebug($object);\n $res = $this->insertObject($object, $table);\n //if ($table==\"text\") eDebug($object,true); \n $this->trim_revisions($table, $object->$identifier, WORKFLOW_REVISION_LIMIT);\n return $res;\n }\n $sql = \"UPDATE \" . $this->prefix . \"$table SET \";\n foreach (get_object_vars($object) as $var => $val) {\n //We do not want to save any fields that start with an '_'\n //if($is_revisioned && $var=='revision_id') $val++;\n if ($var{0} != '_') {\n if (is_array($val) || is_object($val)) {\n $val = serialize($val); \n $sql .= \"`$var`='\".$val.\"',\";\n } else {\n $sql .= \"`$var`='\" . $this->escapeString($val) . \"',\";\n }\n }\n }\n $sql = substr($sql, 0, -1) . \" WHERE \";\n if ($where != null)\n $sql .= $this->injectProof($where);\n else\n $sql .= \"`\" . $identifier . \"`=\" . $object->$identifier;\n //if ($table == 'text') eDebug($sql,true); \n $res = (@mysqli_query($this->connection, $sql) != false);\n return $res;\n }", "label_name": "CWE-74", "label": 1} +{"code": " function edit() {\n global $user;\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n $require_login = empty($this->params['require_login']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];\n $require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];\n $require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n $notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];\n \n if (empty($this->params['formtitle'])) \n {\n if (empty($this->params['id']))\n {\n $formtitle = gt(\"Add New Note\");\n }\n else\n {\n $formtitle = gt(\"Edit Note\");\n }\n }\n else\n {\n $formtitle = $this->params['formtitle'];\n }\n \n $id = empty($this->params['id']) ? null : $this->params['id'];\n $simpleNote = new expSimpleNote($id);\n //FIXME here is where we might sanitize the note before displaying/editing it\n\n assign_to_template(array(\n 'simplenote'=>$simpleNote,\n 'user'=>$user,\n 'require_login'=>$require_login,\n 'require_approval'=>$require_approval,\n 'require_notification'=>$require_notification,\n 'notification_email'=>$notification_email,\n 'formtitle'=>$formtitle,\n 'content_type'=>$this->params['content_type'],\n 'content_id'=>$this->params['content_id'],\n 'tab'=>empty($this->params['tab'])?0:$this->params['tab']\n ));\n } ", "label_name": "CWE-74", "label": 1} +{"code": " static function description() { return gt(\"Places navigation links/menus on the page.\"); }\r", "label_name": "CWE-74", "label": 1} +{"code": " public static function DragnDropReRank2() {\r\n global $router, $db;\r\n\r\n $id = $router->params['id'];\r\n $page = new section($id);\r\n $old_rank = $page->rank;\r\n $old_parent = $page->parent;\r\n $new_rank = $router->params['position'] + 1; // rank\r\n $new_parent = intval($router->params['parent']);\r\n\r\n $db->decrement($page->tablename, 'rank', 1, 'rank>' . $old_rank . ' AND parent=' . $old_parent); // close in hole\r\n $db->increment($page->tablename, 'rank', 1, 'rank>=' . $new_rank . ' AND parent=' . $new_parent); // make room\r\n\r\n $params = array();\r\n $params['parent'] = $new_parent;\r\n $params['rank'] = $new_rank;\r\n $page->update($params);\r\n\r\n self::checkForSectionalAdmins($id);\r\n expSession::clearAllUsersSessionCache('navigation');\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " function productFeed() {\n// global $db;\n //check query password to avoid DDOS\n /*\n * condition = new\n * description \n * id - SKU \n * link \n * price \n * title \n * brand - manufacturer \n * image link - fullsized image, up to 10, comma seperated \n * product type - category - \"Electronics > Audio > Audio Accessories MP3 Player Accessories\",\"Health & Beauty > Healthcare > Biometric Monitors > Pedometers\" \n */\n $out = '\"id\",\"condition\",\"description\",\"like\",\"price\",\"title\",\"brand\",\"image link\",\"product type\"' . chr(13) . chr(10);\n\n $p = new product();\n $prods = $p->find('all', 'parent_id=0 AND ');\n //$prods = $db->selectObjects('product','parent_id=0 AND');\n }", "label_name": "CWE-74", "label": 1} +{"code": " $text = preg_replace($exp, '', $text);\n }\n\n // Primary expression to filter out tags\n $exp = '/(?:^|\\s|\\.)(#\\w+[-\\w]+\\w+|#\\w+)(?:$|[^\\'\"])/u';\n\n $matches = array();\n preg_match_all($exp, $text, $matches);\n\n return $matches;\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function validate() {\n global $db;\n // check for an sef url field. If it exists make sure it's valid and not a duplicate\n //this needs to check for SEF URLS being turned on also: TODO\n\n if (property_exists($this, 'sef_url') && !(in_array('sef_url', $this->do_not_validate))) {\n if (empty($this->sef_url)) $this->makeSefUrl();\n if (!isset($this->validates['is_valid_sef_name']['sef_url'])) $this->validates['is_valid_sef_name']['sef_url'] = array();\n if (!isset($this->validates['uniqueness_of']['sef_url'])) $this->validates['uniqueness_of']['sef_url'] = array();\n }\n\n // safeguard again loc data not being pass via forms...sometimes this happens when you're in a router\n // mapped view and src hasn't been passed in via link to the form \n if (isset($this->id) && empty($this->location_data)) {\n $loc = $db->selectValue($this->tablename, 'location_data', 'id=' . $this->id);\n if (!empty($loc)) $this->location_data = $loc;\n }\n\n // run the validation as defined in the models\n if (!isset($this->validates)) return true;\n $messages = array();\n $post = empty($_POST) ? array() : expString::sanitize($_POST);\n foreach ($this->validates as $validation=> $field) {\n foreach ($field as $key=> $value) {\n $fieldname = is_numeric($key) ? $value : $key;\n $opts = is_numeric($key) ? array() : $value;\n $ret = expValidator::$validation($fieldname, $this, $opts);\n if (!is_bool($ret)) {\n $messages[] = $ret;\n expValidator::setErrorField($fieldname);\n unset($post[$fieldname]);\n }\n }\n }\n\n if (count($messages) >= 1) expValidator::failAndReturnToForm($messages, $post);\n }", "label_name": "CWE-74", "label": 1} +{"code": " recyclebin::sendToRecycleBin($loc, $parent);\r\n //FIXME if we delete the module & sectionref the module completely disappears\r\n// if (class_exists($secref->module)) {\r\n// $modclass = $secref->module;\r\n// //FIXME: more module/controller glue code\r\n// if (expModules::controllerExists($modclass)) {\r\n// $modclass = expModules::getControllerClassName($modclass);\r\n// $mod = new $modclass($loc->src);\r\n// $mod->delete_instance();\r\n// } else {\r\n// $mod = new $modclass();\r\n// $mod->deleteIn($loc);\r\n// }\r\n// }\r\n }\r\n// $db->delete('sectionref', 'section=' . $parent);\r\n $db->delete('section', 'parent=' . $parent);\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " $this->markTestSkipped('Function openssl_random_pseudo_bytes need LibreSSL version >=2.1.5 or Windows system on server');\n }\n }\n\n static::$functions = $functions;\n\n // test various string lengths\n for ($length = 1; $length < 64; $length++) {\n $key1 = $this->security->generateRandomKey($length);\n $this->assertInternalType('string', $key1);\n $this->assertEquals($length, strlen($key1));\n $key2 = $this->security->generateRandomKey($length);\n $this->assertInternalType('string', $key2);\n $this->assertEquals($length, strlen($key2));\n if ($length >= 7) { // avoid random test failure, short strings are likely to collide\n $this->assertNotEquals($key1, $key2);\n }\n }\n\n // test for /dev/urandom, reading larger data to see if loop works properly\n $length = 1024 * 1024;\n $key1 = $this->security->generateRandomKey($length);\n $this->assertInternalType('string', $key1);\n $this->assertEquals($length, strlen($key1));\n $key2 = $this->security->generateRandomKey($length);\n $this->assertInternalType('string', $key2);\n $this->assertEquals($length, strlen($key2));\n $this->assertNotEquals($key1, $key2);\n\n // force /dev/urandom reading loop to deal with chunked data\n // the above test may have read everything in one run.\n // not sure if this can happen in real life but if it does\n // we should be prepared\n static::$fopen = fopen('php://memory', 'rwb');\n $length = 1024 * 1024;\n $key1 = $this->security->generateRandomKey($length);\n $this->assertInternalType('string', $key1);\n $this->assertEquals($length, strlen($key1));\n }", "label_name": "CWE-330", "label": 12} +{"code": " public function testLogout()\n {\n $GLOBALS['cfg']['Server']['auth_swekey_config'] = '';\n $GLOBALS['cfg']['CaptchaLoginPrivateKey'] = '';\n $GLOBALS['cfg']['CaptchaLoginPublicKey'] = '';\n $_REQUEST['old_usr'] = 'pmaolduser';\n $GLOBALS['cfg']['LoginCookieDeleteAll'] = false;\n $GLOBALS['cfg']['Servers'] = array(1);\n $GLOBALS['server'] = 1;\n\n $_COOKIE['pmaPass-1'] = 'test';\n\n $this->object->authCheck();\n\n $this->assertFalse(\n isset($_COOKIE['pmaPass-1'])\n );\n }", "label_name": "CWE-200", "label": 10} +{"code": " private function isWindows()\n {\n return DIRECTORY_SEPARATOR !== '/';\n }", "label_name": "CWE-330", "label": 12} +{"code": " $escapedArgument .= '^%\"'.substr($part, 1, -1).'\"^%';\n } else {\n // escape trailing backslash\n if ('\\\\' === substr($part, -1)) {\n $part .= '\\\\';\n }\n $quote = true;\n $escapedArgument .= $part;\n }\n }\n if ($quote) {\n $escapedArgument = '\"'.$escapedArgument.'\"';\n }\n\n return $escapedArgument;\n }", "label_name": "CWE-77", "label": 14} +{"code": " } elseif (!empty($this->params['src'])) {\r\n if ($this->params['src'] == $loc->src) {\r\n $this->config = $config->config;\r\n break;\r\n }\r\n }\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " private function userCanSeeUserGroups($project_id)\n {\n $project = $this->project_manager->getProject($project_id);\n $user = $this->user_manager->getCurrentUser();\n ProjectAuthorization::userCanAccessProject($user, $project, new URLVerification());\n\n return true;\n }", "label_name": "CWE-863", "label": 11} +{"code": " private static function verifySignature($signature, $input, $key, $algo = 'HS256')\n {\n switch ($algo) {\n case'HS256':\n case'HS384':\n case'HS512':\n return JWT::sign($input, $key, $algo) === $signature;\n\n case 'RS256':\n return (boolean) openssl_verify($input, $signature, $key, OPENSSL_ALGO_SHA256);\n\n case 'RS384':\n return (boolean) openssl_verify($input, $signature, $key, OPENSSL_ALGO_SHA384);\n\n case 'RS512':\n return (boolean) openssl_verify($input, $signature, $key, OPENSSL_ALGO_SHA512);\n\n default:\n throw new Exception(\"Unsupported or invalid signing algorithm.\");\n }\n }", "label_name": "CWE-20", "label": 0} +{"code": " $link = str_replace(URL_FULL, '', makeLink(array('section' => $section->id)));\r", "label_name": "CWE-74", "label": 1} +{"code": " public function actionGetItems(){\n $sql = 'SELECT id, name as value FROM x2_opportunities WHERE name LIKE :qterm ORDER BY name ASC';\n $command = Yii::app()->db->createCommand($sql);\n $qterm = $_GET['term'].'%';\n $command->bindParam(\":qterm\", $qterm, PDO::PARAM_STR);\n $result = $command->queryAll();\n echo CJSON::encode($result);\n Yii::app()->end();\n }", "label_name": "CWE-20", "label": 0} +{"code": " $query->whereExists(function ($permissionQuery) use (&$tableDetails, $action) {\n /** @var Builder $permissionQuery */\n $permissionQuery->select(['role_id'])->from('joint_permissions')\n ->whereColumn('joint_permissions.entity_id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])\n ->whereColumn('joint_permissions.entity_type', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])\n ->where('action', '=', $action)\n ->whereIn('role_id', $this->getCurrentUserRoles())\n ->where(function (QueryBuilder $query) {\n $this->addJointHasPermissionCheck($query, $this->currentUser()->id);\n });\n });\n });", "label_name": "CWE-863", "label": 11} +{"code": "function XMLRPCaddImageGroupToComputerGroup($imageGroup, $computerGroup){\n $imageid = getResourceGroupID(\"image/$imageGroup\");\n $compid = getResourceGroupID(\"computer/$computerGroup\");\n if($imageid && $compid){\n $tmp = getUserResources(array(\"imageAdmin\"),\n array(\"manageMapping\"), 1);\n $imagegroups = $tmp['image'];\n $tmp = getUserResources(array(\"computerAdmin\"),\n array(\"manageMapping\"), 1);\n $computergroups = $tmp['computer'];\n\n if(array_key_exists($compid, $computergroups) &&\n array_key_exists($imageid, $imagegroups)){\n $mapping = getResourceMapping(\"image\", \"computer\",\n $imageid,\n $compid);\n if(!array_key_exists($imageid, $mapping) ||\n !array_key_exists($compid, $mapping[$imageid])){\n $query = \"INSERT INTO resourcemap \"\n . \"(resourcegroupid1, \"\n\t\t\t . \"resourcetypeid1, \"\n\t\t\t . \"resourcegroupid2, \"\n\t\t\t . \"resourcetypeid2) \"\n\t\t\t . \"VALUES ($imageid, \"\n\t\t\t . \"13, \"\n\t\t\t . \"$compid, \"\n\t\t\t . \"12)\";\n doQuery($query, 101);\n }\n return array('status' => 'success');\n } else {\n return array('status' => 'error',\n 'errorcode' => 84,\n 'errormsg' => 'cannot access computer and/or image group');\n }\n } else {\n return array('status' => 'error',\n 'errorcode' => 83,\n 'errormsg' => 'invalid resource group name');\n }\n}", "label_name": "CWE-20", "label": 0} +{"code": " function _setupMcrypt()\n {\n $this->_clearBuffers();\n $this->enchanged = $this->dechanged = true;\n\n if (!isset($this->enmcrypt)) {\n static $mcrypt_modes = array(\n self::MODE_CTR => 'ctr',\n self::MODE_ECB => MCRYPT_MODE_ECB,\n self::MODE_CBC => MCRYPT_MODE_CBC,\n self::MODE_CFB => 'ncfb',\n self::MODE_OFB => MCRYPT_MODE_NOFB,\n self::MODE_STREAM => MCRYPT_MODE_STREAM,\n );\n\n $this->demcrypt = mcrypt_module_open($this->cipher_name_mcrypt, '', $mcrypt_modes[$this->mode], '');\n $this->enmcrypt = mcrypt_module_open($this->cipher_name_mcrypt, '', $mcrypt_modes[$this->mode], '');\n\n // we need the $ecb mcrypt resource (only) in MODE_CFB with enableContinuousBuffer()\n // to workaround mcrypt's broken ncfb implementation in buffered mode\n // see: {@link http://phpseclib.sourceforge.net/cfb-demo.phps}\n if ($this->mode == self::MODE_CFB) {\n $this->ecb = mcrypt_module_open($this->cipher_name_mcrypt, '', MCRYPT_MODE_ECB, '');\n }\n\n } // else should mcrypt_generic_deinit be called?\n\n if ($this->mode == self::MODE_CFB) {\n mcrypt_generic_init($this->ecb, $this->key, str_repeat(\"\\0\", $this->block_size));\n }\n }", "label_name": "CWE-200", "label": 10} +{"code": " $backup = ['sys' => $GLOBALS['TYPO3_CONF_VARS']['SYS'], 'server' => $_SERVER];", "label_name": "CWE-20", "label": 0} +{"code": " public function search_external() {\n// global $db, $user;\n global $db;\n\n $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 \";\n $sql .= \"from \" . $db->prefix . \"external_addresses as a \"; //R JOIN \" . \n //$db->prefix . \"billingmethods as bm ON bm.addresses_id=a.id \";\n $sql .= \" WHERE match (a.firstname,a.lastname,a.email,a.organization) against ('\" . $this->params['query'] .\n \"*' IN BOOLEAN MODE) \";\n $sql .= \"order by match (a.firstname,a.lastname,a.email,a.organization) against ('\" . $this->params['query'] . \"*' IN BOOLEAN MODE) ASC LIMIT 12\";\n $res = $db->selectObjectsBySql($sql);\n foreach ($res as $key=>$record) {\n $res[$key]->title = $record->firstname . ' ' . $record->lastname;\n }\n //eDebug($sql);\n $ar = new expAjaxReply(200, gt('Here\\'s the items you wanted'), $res);\n $ar->send();\n }", "label_name": "CWE-74", "label": 1} +{"code": " public function editAlt() {\n global $user; \n $file = new expFile($this->params['id']);\n if ($user->id==$file->poster || $user->isAdmin()) {\n $file->alt = $this->params['newValue'];\n $file->save();\n $ar = new expAjaxReply(200, gt('Your alt was updated successfully'), $file);\n } else {\n $ar = new expAjaxReply(300, gt(\"You didn't create this file, so you can't edit it.\"));\n }\n $ar->send();\n echo json_encode($file); //FIXME we exit before hitting this\n } ", "label_name": "CWE-74", "label": 1} +{"code": "\t\t$stmt->bindValue(\":$field\", $domain, SQLITE3_TEXT);\n\t\tif($bindcomment) {\n\t\t\t$stmt->bindValue(\":comment\", $comment, SQLITE3_TEXT);\n\t\t}\n\n\t\tif($stmt->execute() && $stmt->reset())\n\t\t\t$num++;\n\t\telse\n\t\t{\n\t\t\t$stmt->close();\n\t\t\tif($returnnum)\n\t\t\t\treturn $num;\n\t\t\telse\n\t\t\t{\n\t\t\t\tif($num === 1)\n\t\t\t\t\t$plural = \"\";\n\t\t\t\telse\n\t\t\t\t\t$plural = \"s\";\n\t\t\t\treturn \"Error: \".$db->lastErrorMsg().\", added \".$num.\" domain\".$plural;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Close prepared statement and return number of processed rows\n\t$stmt->close();\n\t$db->exec(\"COMMIT;\");\n\n\tif($returnnum)\n\t\treturn $num;\n\telse\n\t{\n\t\t$finalcount = intval($db->querySingle($countquery));\n\t\t$modified = $finalcount - $initialcount;\n\n\t\t// If we add less domains than the user specified, then they wanted to add duplicates\n\t\tif($modified !== $num)\n\t\t{\n\t\t\t$delta = $num - $modified;\n\t\t\t$extra = \" (skipped \".$delta.\" duplicates)\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$extra = \"\";\n\t\t}\n\n\t\tif($num === 1)\n\t\t\t$plural = \"\";\n\t\telse\n\t\t\t$plural = \"s\";\n\t\treturn \"Success, added \".$modified.\" of \".$num.\" domain\".$plural.$extra;\n\t}\n}", "label_name": "CWE-862", "label": 8} +{"code": " public function enable()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $swimlane_id = $this->request->getIntegerParam('swimlane_id');\n\n if ($this->swimlaneModel->enable($project['id'], $swimlane_id)) {\n $this->flash->success(t('Swimlane updated successfully.'));\n } else {\n $this->flash->failure(t('Unable to update this swimlane.'));\n }\n\n $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-200", "label": 10} +{"code": "\tpublic function editspeed() {\n global $db;\n\n if (empty($this->params['id'])) return false;\n $calcname = $db->selectValue('shippingcalculator', 'calculator_name', 'id='.$this->params['id']);\n $calc = new $calcname($this->params['id']);\n assign_to_template(array(\n 'calculator'=>$calc\n ));\n\t\t\n }", "label_name": "CWE-74", "label": 1} +{"code": "\t\t} elseif ( $rowSize > 0 ) {\n\t\t\t// repeat row header after n lines of output\n\t\t\t$nstart = 0;\n\t\t\t$nsize = $rowSize;\n\t\t\t$count = count( $articles );\n\t\t\t$output .= '{|' . $rowColFormat . \"\\n|\\n\";\n\t\t\tdo {\n\t\t\t\tif ( $nstart + $nsize > $count ) {\n\t\t\t\t\t$nsize = $count - $nstart;\n\t\t\t\t}\n\t\t\t\t$output .= $lister->formatList( $articles, $nstart, $nsize );\n\t\t\t\t$output .= \"\\n|-\\n|\\n\";\n\t\t\t\t$nstart = $nstart + $nsize;\n\t\t\t\tif ( $nstart >= $count ) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} while ( true );\n\t\t\t$output .= \"\\n|}\\n\";\n\t\t} else {", "label_name": "CWE-400", "label": 2} +{"code": " $module_views[$key]['name'] = gt($value['name']);\n }\n\n // look for a config form for this module's current view \n// $controller->loc->mod = expModules::getControllerClassName($controller->loc->mod);\n //check to see if hcview was passed along, indicating a hard-coded module\n// if (!empty($controller->params['hcview'])) {\n// $viewname = $controller->params['hcview'];\n// } else {\n// $viewname = $db->selectValue('container', 'view', \"internal='\".serialize($controller->loc).\"'\");\n// }\n// $viewconfig = $viewname.'.config';\n// foreach ($modpaths as $path) {\n// if (file_exists($path.'/'.$viewconfig)) {\n// $fileparts = explode('_', $viewname);\n// if ($fileparts[0]=='show'||$fileparts[0]=='showall') array_shift($fileparts);\n// $module_views[$viewname]['name'] = ucwords(implode(' ', $fileparts)).' '.gt('View Configuration');\n// $module_views[$viewname]['file'] =$path.'/'.$viewconfig;\n// }\n// }\n \n // sort the views highest to lowest by filename\n // we are reverse sorting now so our array merge\n // will overwrite property..we will run array_reverse\n // when we're finished to get them back in the right order\n krsort($common_views);\n krsort($module_views);\n\n if (!empty($moduleconfig)) $common_views = array_merge($common_views, $moduleconfig);\n $views = array_merge($common_views, $module_views);\n $views = array_reverse($views);\n\n return $views;\n}", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic function actionGetItems(){\n\t\t$sql = 'SELECT id, name as value FROM x2_docs WHERE name LIKE :qterm ORDER BY name ASC';\n\t\t$command = Yii::app()->db->createCommand($sql);\n\t\t$qterm = '%'.$_GET['term'].'%';\n\t\t$command->bindParam(\":qterm\", $qterm, PDO::PARAM_STR);\n\t\t$result = $command->queryAll();\n\t\techo CJSON::encode($result); exit;\n\t}", "label_name": "CWE-20", "label": 0} +{"code": "\tstatic public function deleteCategory($_id = 0) {\n\n\t\tif ($_id != 0) {\n\n\t\t\t$result_stmt = Database::prepare(\"\n\t\t\t\tSELECT COUNT(`id`) as `numtickets` FROM `\" . TABLE_PANEL_TICKETS . \"`\n\t\t\t\tWHERE `category` = :cat\"\n\t\t\t);\n\t\t\t$result = Database::pexecute_first($result_stmt, array('cat' => $_id));\n\n\t\t\tif ($result['numtickets'] == \"0\") {\n\t\t\t\t$del_stmt = Database::prepare(\"\n\t\t\t\t\tDELETE FROM `\" . TABLE_PANEL_TICKET_CATS . \"` WHERE `id` = :id\"\n\t\t\t\t);\n\t\t\t\tDatabase::pexecute($del_stmt, array('id' => $_id));\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}", "label_name": "CWE-732", "label": 13} +{"code": "\tpublic function approve() {\n\t expHistory::set('editable', $this->params);\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n// $require_login = empty($this->params['require_login']) ? COMMENTS_REQUIRE_LOGIN : $this->params['require_login'];\n// $require_approval = empty($this->params['require_approval']) ? COMMENTS_REQUIRE_APPROVAL : $this->params['require_approval'];\n// $require_notification = empty($this->params['require_notification']) ? COMMENTS_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n// $notification_email = empty($this->params['notification_email']) ? COMMENTS_NOTIFICATION_EMAIL : $this->params['notification_email'];\n\t \n\t if (empty($this->params['id'])) {\n\t flash('error', gt('No ID supplied for comment to approve'));\n\t expHistory::back();\n\t }\n\t \n\t $comment = new expComment($this->params['id']);\n\t assign_to_template(array(\n 'comment'=>$comment\n ));\n\t}", "label_name": "CWE-74", "label": 1} +{"code": " public function save_change_password() {\n global $user;\n\n $isuser = ($this->params['uid'] == $user->id) ? 1 : 0;\n\n if (!$user->isAdmin() && !$isuser) {\n flash('error', gt('You do not have permissions to change this users password.'));\n expHistory::back();\n }\n\n if (($isuser && empty($this->params['password'])) || (!empty($this->params['password']) && $user->password != user::encryptPassword($this->params['password']))) {\n flash('error', gt('The current password you entered is not correct.'));\n expHistory::returnTo('editable');\n }\n //eDebug($user);\n $u = new user($this->params['uid']);\n\n $ret = $u->setPassword($this->params['new_password1'], $this->params['new_password2']);\n //eDebug($u, true);\n if (is_string($ret)) {\n flash('error', $ret);\n expHistory::returnTo('editable');\n } else {\n $params = array();\n $params['is_admin'] = !empty($u->is_admin);\n $params['is_acting_admin'] = !empty($u->is_acting_admin);\n $u->update($params);\n }\n\n if (!$isuser) {\n flash('message', gt('The password for') . ' ' . $u->username . ' ' . gt('has been changed.'));\n } else {\n $user->password = $u->password;\n flash('message', gt('Your password has been changed.'));\n }\n expHistory::back();\n }", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic function delete() {\n\t global $db;\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n// $require_login = empty($this->params['require_login']) ? COMMENTS_REQUIRE_LOGIN : $this->params['require_login'];\n// $require_approval = empty($this->params['require_approval']) ? COMMENTS_REQUIRE_APPROVAL : $this->params['require_approval'];\n// $require_notification = empty($this->params['require_notification']) ? COMMENTS_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n// $notification_email = empty($this->params['notification_email']) ? COMMENTS_NOTIFICATION_EMAIL : $this->params['notification_email'];\n\t \n\t if (empty($this->params['id'])) {\n\t flash('error', gt('Missing id for the comment you would like to delete'));\n\t expHistory::back();\n\t }\n\t \n\t // delete the comment\n $comment = new expComment($this->params['id']);\n $comment->delete();\n \n // delete the association too\n $db->delete($comment->attachable_table, 'expcomments_id='.$this->params['id']); \n \n // send the user back where they came from.\n expHistory::back();\n\t}", "label_name": "CWE-74", "label": 1} +{"code": " function edit() {\n global $user;\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n $require_login = empty($this->params['require_login']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];\n $require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];\n $require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n $notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];\n \n if (empty($this->params['formtitle'])) \n {\n if (empty($this->params['id']))\n {\n $formtitle = gt(\"Add New Note\");\n }\n else\n {\n $formtitle = gt(\"Edit Note\");\n }\n }\n else\n {\n $formtitle = $this->params['formtitle'];\n }\n \n $id = empty($this->params['id']) ? null : $this->params['id'];\n $simpleNote = new expSimpleNote($id);\n //FIXME here is where we might sanitize the note before displaying/editing it\n\n assign_to_template(array(\n 'simplenote'=>$simpleNote,\n 'user'=>$user,\n 'require_login'=>$require_login,\n 'require_approval'=>$require_approval,\n 'require_notification'=>$require_notification,\n 'notification_email'=>$notification_email,\n 'formtitle'=>$formtitle,\n 'content_type'=>$this->params['content_type'],\n 'content_id'=>$this->params['content_id'],\n 'tab'=>empty($this->params['tab'])?0:$this->params['tab']\n ));\n } ", "label_name": "CWE-74", "label": 1} +{"code": "function XMLRPCremoveImageGroupFromComputerGroup($imageGroup, $computerGroup){\n $imageid = getResourceGroupID(\"image/$imageGroup\");\n $compid = getResourceGroupID(\"computer/$computerGroup\");\n if($imageid && $compid){\n $tmp = getUserResources(array(\"imageAdmin\"),\n array(\"manageMapping\"), 1);\n $imagegroups = $tmp['image'];\n $tmp = getUserResources(array(\"computerAdmin\"),\n array(\"manageMapping\"), 1);\n $computergroups = $tmp['computer'];\n\n if(array_key_exists($compid, $computergroups) &&\n array_key_exists($imageid, $imagegroups)){\n $mapping = getResourceMapping(\"image\", \"computer\",\n $imageid,\n $compid);\n if(array_key_exists($imageid, $mapping) &&\n array_key_exists($compid, $mapping[$imageid])){\n $query = \"DELETE FROM resourcemap \"\n\t\t\t\t\t . \"WHERE resourcegroupid1 = $imageid AND \"\n\t\t\t\t\t . \"resourcetypeid1 = 13 AND \"\n\t\t\t\t\t . \"resourcegroupid2 = $compid AND \"\n\t\t\t\t\t . \"resourcetypeid2 = 12\";\n\t\t\t doQuery($query, 101);\n }\n return array('status' => 'success');\n } else {\n return array('status' => 'error',\n 'errorcode' => 84,\n 'errormsg' => 'cannot access computer and/or image group');\n }\n } else {\n return array('status' => 'error',\n 'errorcode' => 83,\n 'errormsg' => 'invalid resource group name');\n }\n}", "label_name": "CWE-20", "label": 0} +{"code": " function send_feedback() {\r\n $success = false;\r\n if (isset($this->params['id'])) {\r\n $ed = new eventdate($this->params['id']);\r\n// $email_addrs = array();\r\n if ($ed->event->feedback_email != '') {\r\n $msgtemplate = expTemplate::get_template_for_action($this, 'email/_' . $this->params['formname'], $this->loc);\r\n $msgtemplate->assign('params', $this->params);\r\n $msgtemplate->assign('event', $ed);\r\n $email_addrs = explode(',', $ed->event->feedback_email);\r\n //This is an easy way to remove duplicates\r\n $email_addrs = array_flip(array_flip($email_addrs));\r\n $email_addrs = array_map('trim', $email_addrs);\r\n $mail = new expMail();\r\n $success += $mail->quickSend(array(\r\n \"text_message\" => $msgtemplate->render(),\r\n 'to' => $email_addrs,\r\n 'from' => !empty($this->params['email']) ? $this->params['email'] : trim(SMTP_FROMADDRESS),\r\n 'subject' => $this->params['subject'],\r\n ));\r\n }\r\n }\r\n\r\n if ($success) {\r\n flashAndFlow('message', gt('Your feedback was successfully sent.'));\r\n } else {\r\n flashAndFlow('error', gt('We could not send your feedback. Please contact your administrator.'));\r\n }\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public function theme_switch() {\n if (!expUtil::isReallyWritable(BASE.'framework/conf/config.php')) { // we can't write to the config.php file\n flash('error',gt('The file /framework/conf/config.php is NOT Writeable. You will be unable to change the theme.'));\n }\n \texpSettings::change('DISPLAY_THEME_REAL', $this->params['theme']);\n\t expSession::set('display_theme',$this->params['theme']);\n\t $sv = isset($this->params['sv'])?$this->params['sv']:'';\n\t if (strtolower($sv)=='default') {\n\t $sv = '';\n\t }\n\t expSettings::change('THEME_STYLE_REAL',$sv);\n\t expSession::set('theme_style',$sv);\n\t expDatabase::install_dbtables(); // update tables to include any custom definitions in the new theme\n\n // $message = (MINIFY != 1) ? \"Exponent is now minifying Javascript and CSS\" : \"Exponent is no longer minifying Javascript and CSS\" ;\n // flash('message',$message);\n\t $message = gt(\"You have selected the\").\" '\".$this->params['theme'].\"' \".gt(\"theme\");\n\t if ($sv != '') {\n\t\t $message .= ' '.gt('with').' '.$this->params['sv'].' '.gt('style variation');\n\t }\n\t flash('message',$message);\n// expSession::un_set('framework');\n expSession::set('force_less_compile', 1);\n// expTheme::removeSmartyCache();\n expSession::clearAllUsersSessionCache();\n \texpHistory::returnTo('manageable');\n }\t", "label_name": "CWE-74", "label": 1} +{"code": "\t\t\tVariables::setVar( [ '', '', $argName, $argValue ] );\n\t\t\tif ( defined( 'ExtVariables::VERSION' ) ) {\n\t\t\t\t\\ExtVariables::get( $this->parser )->setVarValue( $argName, $argValue );\n\t\t\t}\n\t\t}\n\t}", "label_name": "CWE-400", "label": 2} +{"code": "\tpublic function approve() {\n\t expHistory::set('editable', $this->params);\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n// $require_login = empty($this->params['require_login']) ? COMMENTS_REQUIRE_LOGIN : $this->params['require_login'];\n// $require_approval = empty($this->params['require_approval']) ? COMMENTS_REQUIRE_APPROVAL : $this->params['require_approval'];\n// $require_notification = empty($this->params['require_notification']) ? COMMENTS_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n// $notification_email = empty($this->params['notification_email']) ? COMMENTS_NOTIFICATION_EMAIL : $this->params['notification_email'];\n\t \n\t if (empty($this->params['id'])) {\n\t flash('error', gt('No ID supplied for comment to approve'));\n\t expHistory::back();\n\t }\n\t \n\t $comment = new expComment($this->params['id']);\n\t assign_to_template(array(\n 'comment'=>$comment\n ));\n\t}", "label_name": "CWE-74", "label": 1} +{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $filter = $this->customFilterModel->getById($this->request->getIntegerParam('filter_id'));\n\n $this->checkPermission($project, $filter);\n\n if ($this->customFilterModel->remove($filter['id'])) {\n $this->flash->success(t('Custom filter removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this custom filter.'));\n }\n\n $this->response->redirect($this->helper->url->to('CustomFilterController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-200", "label": 10} +{"code": " public static function getHelpVersionId($version) {\n global $db;\n\n return $db->selectValue('help_version', 'id', 'version=\"'.$version.'\"');\n }", "label_name": "CWE-74", "label": 1} +{"code": " protected function tearDown()\n {\n static::$functions = [];\n static::$fopen = null;\n static::$fread = null;\n parent::tearDown();\n }", "label_name": "CWE-330", "label": 12} +{"code": " public function Hello($host = '') {\n $this->error = null; // so no confusion is caused\n\n if(!$this->connected()) {\n $this->error = array(\n \"error\" => \"Called Hello() without being connected\");\n return false;\n }\n\n // if hostname for HELO was not specified send default\n if(empty($host)) {\n // determine appropriate default to send to server\n $host = \"localhost\";\n }\n\n // Send extended hello first (RFC 2821)\n if(!$this->SendHello(\"EHLO\", $host)) {\n if(!$this->SendHello(\"HELO\", $host)) {\n return false;\n }\n }\n\n return true;\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function execute(&$params){\n $model = new Actions;\n $model->type = 'note';\n $model->complete = 'Yes';\n $model->associationId = $params['model']->id;\n $model->associationType = $params['model']->module;\n $model->actionDescription = $this->parseOption('comment', $params);\n $model->assignedTo = $this->parseOption('assignedTo', $params);\n $model->completedBy = $this->parseOption('assignedTo', $params);\n\n if(empty($model->assignedTo) && $params['model']->hasAttribute('assignedTo')){\n $model->assignedTo = $params['model']->assignedTo;\n $model->completedBy = $params['model']->assignedTo;\n }\n\n if($params['model']->hasAttribute('visibility'))\n $model->visibility = $params['model']->visibility;\n $model->createDate = time();\n $model->completeDate = time();\n\n if($model->save()){\n return array(\n true,\n Yii::t('studio', 'View created action: ').$model->getLink());\n }else{\n return array(false, array_shift($model->getErrors()));\n }\n }", "label_name": "CWE-20", "label": 0} +{"code": "\t\t\t\t\t\t\t\t\t\tunset($sql, $parameters, $row);\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t//download compressed file\n\t\t\t\t\t\t\t\tif (@sizeof($email_files) != 0) {\n\n\t\t\t\t\t\t\t\t\t//define compressed file name\n\t\t\t\t\t\t\t\t\t\t$compressed_filename = 'emails_'.date('Ymd_His').'.zip';\n\n\t\t\t\t\t\t\t\t\t//compress email files\n\t\t\t\t\t\t\t\t\t\t$command = 'zip -mj '.$_SESSION['server']['temp']['dir'].'/'.$compressed_filename.' '.implode(' ', $email_files).' 2>&1';\n\t\t\t\t\t\t\t\t\t\texec($command, $response, $restore_errlevel);\n\t\t\t\t\t\t\t\t\t\tunset($command);\n\n\t\t\t\t\t\t\t\t\t//push download\n\t\t\t\t\t\t\t\t\t\tif (file_exists($_SESSION['server']['temp']['dir'].'/'.$compressed_filename)) {\n\n\t\t\t\t\t\t\t\t\t\t\t//open file\n\t\t\t\t\t\t\t\t\t\t\t\tsession_cache_limiter('public');\n\t\t\t\t\t\t\t\t\t\t\t\t$fd = fopen($_SESSION['server']['temp']['dir'].'/'.$compressed_filename, 'rb');\n\n\t\t\t\t\t\t\t\t\t\t\t//set headers\n\t\t\t\t\t\t\t\t\t\t\t\theader(\"Content-Type: application/zip\");\n\t\t\t\t\t\t\t\t\t\t\t\theader('Content-Disposition: attachment; filename=\"'.$compressed_filename.'\"');\n\t\t\t\t\t\t\t\t\t\t\t\theader(\"Cache-Control: no-cache, must-revalidate\"); // HTTP/1.1\n\t\t\t\t\t\t\t\t\t\t\t\theader(\"Expires: Sat, 26 Jul 1997 05:00:00 GMT\"); // Date in the past\n\t\t\t\t\t\t\t\t\t\t\t\theader(\"Content-Length: \".filesize($_SESSION['server']['temp']['dir'].'/'.$compressed_filename));\n\n\t\t\t\t\t\t\t\t\t\t\t//output file content\n\t\t\t\t\t\t\t\t\t\t\t\tob_clean();\n\t\t\t\t\t\t\t\t\t\t\t\tfpassthru($fd);\n\t\t\t\t\t\t\t\t\t\t\t\tfclose($fd);\n\n\t\t\t\t\t\t\t\t\t\t\t//remove compressed file\n\t\t\t\t\t\t\t\t\t\t\t\t@unlink($_SESSION['server']['temp']['dir'].'/'.$compressed_filename);\n\t\t\t\t\t\t\t\t\t\t\t\texit;\n\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t}\n\n\t\t} //method", "label_name": "CWE-77", "label": 14} +{"code": " public function getAcl($node) {\n if (is_string($node)) {\n $node = $this->server->tree->getNodeForPath($node);\n }\n\n $acl = parent::getAcl($node);\n\n // Authenticated user have read access to all nodes, as node list only contains elements\n // that user can read.\n $acl[] = [\n 'principal' => '{DAV:}authenticated',\n 'privilege' => '{DAV:}read',\n 'protected' => true,\n ];\n\n if ($node instanceof Calendar && \\Session::haveRight(\\PlanningExternalEvent::$rightname, UPDATE)) {\n // If user can update external events, then he is able to write on calendar to create new events.\n $acl[] = [\n 'principal' => '{DAV:}authenticated',\n 'privilege' => '{DAV:}write',\n 'protected' => true,\n ];\n } else if ($node instanceof CalendarObject) {\n $item = $this->getCalendarItemForPath($node->getName());\n if ($item instanceof \\CommonDBTM && $item->can($item->fields['id'], UPDATE)) {\n $acl[] = [\n 'principal' => '{DAV:}authenticated',\n 'privilege' => '{DAV:}write',\n 'protected' => true,\n ];\n }\n }\n\n return $acl;\n }", "label_name": "CWE-862", "label": 8} +{"code": " public function setModelAttributes(&$model,&$attributeList,&$params) {\n $data = array ();\n foreach($attributeList as &$attr) {\n if(!isset($attr['name'],$attr['value']))\n continue;\n\n if(null !== $field = $model->getField($attr['name'])) {\n // first do variable/expression evaluation, // then process with X2Fields::parseValue()\n $type = $field->type;\n $value = $attr['value'];\n if(is_string($value)){\n if(strpos($value, '=') === 0){\n $evald = X2FlowFormatter::parseFormula($value, $params);\n if(!$evald[0])\n return false;\n $value = $evald[1];\n } elseif($params !== null){\n\n if(is_string($value) && isset($params['model'])){\n $value = X2FlowFormatter::replaceVariables(\n $value, $params['model'], $type);\n }\n }\n }\n\n $data[$attr['name']] = $value;\n }\n }\n if (!isset ($model->scenario)) \n $model->setScenario ('X2Flow');\n $model->setX2Fields ($data);\n\n if ($model instanceof Actions && isset($data['complete'])) {\n switch($data['complete']) {\n case 'Yes':\n $model->complete();\n break;\n case 'No':\n $model->uncomplete();\n break;\n }\n }\n\n return true;\n }", "label_name": "CWE-20", "label": 0} +{"code": " $rst[$key] = self::parseAndTrim($st, $unescape);\n }\n return $rst;\n }\n\n $str = str_replace(\"
\",\" \",$str);\n $str = str_replace(\"
\",\" \",$str);\n $str = str_replace(\"
\",\" \",$str);\n $str = str_replace(\"
\",\" \",$str);\n $str = str_replace(\"\\r\\n\",\" \",$str);\n $str = str_replace('\"',\""\",$str);\n $str = str_replace(\"'\",\"'\",$str);\n $str = str_replace(\"\u2019\",\"’\",$str);\n $str = str_replace(\"\u2018\",\"‘\",$str);\n $str = str_replace(\"\u00ae\",\"®\",$str);\n $str = str_replace(\"\u2013\",\"-\", $str);\n $str = str_replace(\"\u2014\",\"—\", $str);\n $str = str_replace(\"\u201d\",\"”\", $str);\n $str = str_replace(\"\u201c\",\"“\", $str);\n $str = str_replace(\"\u00bc\",\"¼\",$str);\n $str = str_replace(\"\u00bd\",\"½\",$str);\n $str = str_replace(\"\u00be\",\"¾\",$str);\n\t\t$str = str_replace(\"\u2122\",\"™\", $str);\n\t\t$str = trim($str);\n\t\t\n if ($unescape) {\n\t\t\t$str = stripcslashes($str); \n\t\t} else {\n\t $str = addslashes($str);\n }\n\n return $str;\n }", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic function update_groupdiscounts() {\n\t global $db;\n\t \n\t if (empty($this->params['id'])) {\n\t // look for existing discounts for the same group\n\t $existing_id = $db->selectValue('groupdiscounts', 'id', 'group_id='.$this->params['group_id']);\n\t if (!empty($existing_id)) flashAndFlow('error',gt('There is already a discount for that group.'));\n\t }\n\n $gd = new groupdiscounts();\n\t $gd->update($this->params);\n\t expHistory::back();\n\t}", "label_name": "CWE-74", "label": 1} +{"code": " protected function tearDown()\n {\n static::$functions = [];\n static::$fopen = null;\n static::$fread = null;\n parent::tearDown();\n }", "label_name": "CWE-330", "label": 12} +{"code": "\tprotected function doDBUpdates() {\n\t\t$title = Title::newFromText( 'Template:Extension DPL' );\n\n\t\t// Make sure template does not already exist\n\t\tif ( !$title->exists() ) {\n\t\t\t$wikipage = WikiPage::factory( $title );\n\t\t\t$updater = $wikipage->newPageUpdater( User::newSystemUser( 'DynamicPageList3 extension' ) );\n\t\t\t$content = $wikipage->getContentHandler()->makeContent( 'This page was automatically created. It serves as an anchor page for all \\'\\'\\'[[Special:WhatLinksHere/Template:Extension_DPL|invocations]]\\'\\'\\' of [https://www.mediawiki.org/wiki/Special:MyLanguage/Extension:DynamicPageList3 Extension:DynamicPageList3].', $title );\n\t\t\t$updater->setContent( SlotRecord::MAIN, $content );\n\t\t\t$comment = CommentStoreComment::newUnsavedComment( 'Autogenerated DPL\\'s necessary template for content inclusion' );\n\t\t\t$updater->saveRevision(\n\t\t\t\t$comment,\n\t\t\t\tEDIT_NEW | EDIT_FORCE_BOT\n\t\t\t);\n\t\t}\n\n\t\treturn true;\n\t}", "label_name": "CWE-400", "label": 2} +{"code": "\tpublic function setListAttributes( $attributes ) {\n\t\t$this->listAttributes = \\Sanitizer::fixTagAttributes( $attributes, 'ul' );\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " $banner->increaseImpressions();\n }\n }\n \n // assign banner to the template and show it!\n assign_to_template(array(\n 'banners'=>$banners\n ));\n }", "label_name": "CWE-74", "label": 1} +{"code": " $count += $db->dropTable($basename);\n }\n \n flash('message', gt('Deleted').' '.$count.' '.gt('unused tables').'.');\n expHistory::back();\n }", "label_name": "CWE-74", "label": 1} +{"code": " public function saveconfig() {\n global $db;\n\n if (empty($this->params['id'])) return false;\n $calcname = $db->selectValue('shippingcalculator', 'calculator_name', 'id='.$this->params['id']);\n $calc = new $calcname($this->params['id']);\n $conf = serialize($calc->parseConfig($this->params)); \n $calc->update(array('config'=>$conf));\n expHistory::back();\n }", "label_name": "CWE-74", "label": 1} +{"code": " public function testAuthCheckDecryptUser()\n {\n $GLOBALS['cfg']['Server']['auth_swekey_config'] = 'testConfigSwekey';\n $GLOBALS['server'] = 1;\n $_REQUEST['old_usr'] = '';\n $_REQUEST['pma_username'] = '';\n $_COOKIE['pmaServer-1'] = 'pmaServ1';\n $_COOKIE['pmaUser-1'] = 'pmaUser1';\n $_COOKIE['pma_iv-1'] = base64_encode('testiv09testiv09');\n $GLOBALS['cfg']['blowfish_secret'] = 'secret';\n $_SESSION['last_access_time'] = '';\n $_SESSION['last_valid_captcha'] = true;\n\n // mock for blowfish function\n $this->object = $this->getMockBuilder('AuthenticationCookie')\n ->disableOriginalConstructor()\n ->setMethods(array('cookieDecrypt'))\n ->getMock();\n\n $this->object->expects($this->once())\n ->method('cookieDecrypt')\n ->will($this->returnValue('testBF'));\n\n $this->assertFalse(\n $this->object->authCheck()\n );\n\n $this->assertEquals(\n 'testBF',\n $GLOBALS['PHP_AUTH_USER']\n );\n }", "label_name": "CWE-200", "label": 10} +{"code": " public function confirm()\n {\n $project = $this->getProject();\n\n $this->response->html($this->helper->layout->project('action/remove', array(\n 'action' => $this->actionModel->getById($this->request->getIntegerParam('action_id')),\n 'available_events' => $this->eventManager->getAll(),\n 'available_actions' => $this->actionManager->getAvailableActions(),\n 'project' => $project,\n 'title' => t('Remove an action')\n )));\n }", "label_name": "CWE-200", "label": 10} +{"code": " public function gc($force = false)\n {\n if ($force || mt_rand(0, 1000000) < $this->gcProbability) {\n $this->db->createCommand()\n ->delete($this->cacheTable, '[[expire]] > 0 AND [[expire]] < ' . time())\n ->execute();\n }\n }", "label_name": "CWE-330", "label": 12} +{"code": "\tpublic function attributeLabels() {\n\t\treturn array(\n\t\t\t'actionId' => Yii::t('actions','Action ID'),\n\t\t\t'text' => Yii::t('actions','Action Text'),\n\t\t);\n\t}", "label_name": "CWE-20", "label": 0} +{"code": " function build_daterange_sql($timestamp, $endtimestamp=null, $field='date', $multiday=false) {\r\n if (empty($endtimestamp)) {\r\n $date_sql = \"((\".$field.\" >= \" . expDateTime::startOfDayTimestamp($timestamp) . \" AND \".$field.\" <= \" . expDateTime::endOfDayTimestamp($timestamp) . \")\";\r\n } else {\r\n $date_sql = \"((\".$field.\" >= \" . expDateTime::startOfDayTimestamp($timestamp) . \" AND \".$field.\" <= \" . expDateTime::endOfDayTimestamp($endtimestamp) . \")\";\r\n }\r\n if ($multiday)\r\n $date_sql .= \" OR (\" . expDateTime::startOfDayTimestamp($timestamp) . \" BETWEEN \".$field.\" AND dateFinished)\";\r\n $date_sql .= \")\";\r\n return $date_sql;\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " static function encrypt($string, $key) {\n\n $result = '';\n for ($i=0; $iconnected == false) {\n $this->error = 'Not connected to POP3 server';\n\n if ($this->do_debug >= 1) {\n $this->displayErrors();\n }\n }\n\n if (empty($username)) {\n $username = $this->username;\n }\n\n if (empty($password)) {\n $password = $this->password;\n }\n\n $pop_username = \"USER $username\" . $this->CRLF;\n $pop_password = \"PASS $password\" . $this->CRLF;\n\n // Send the Username\n $this->sendString($pop_username);\n $pop3_response = $this->getResponse();\n\n if ($this->checkResponse($pop3_response)) {\n // Send the Password\n $this->sendString($pop_password);\n $pop3_response = $this->getResponse();\n\n if ($this->checkResponse($pop3_response)) {\n return true;\n }\n }\n return false;\n }", "label_name": "CWE-20", "label": 0} +{"code": " function reparent_standalone() {\r\n $standalone = $this->section->find($this->params['page']);\r\n if ($standalone) {\r\n $standalone->parent = $this->params['parent'];\r\n $standalone->update();\r\n expSession::clearAllUsersSessionCache('navigation');\r\n expHistory::back();\r\n } else {\r\n notfoundController::handle_not_found();\r\n }\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " function showallSubcategories() {\n// global $db;\n\n expHistory::set('viewable', $this->params);\n// $parent = isset($this->params['cat']) ? $this->params['cat'] : expSession::get('catid');\n $catid = expSession::get('catid');\n $parent = !empty($catid) ? $catid : (!empty($this->params['cat']) ? $this->params['cat'] : 0);\n $category = new storeCategory($parent);\n $categories = $category->getEcomSubcategories();\n $ancestors = $category->pathToNode();\n assign_to_template(array(\n 'categories' => $categories,\n 'ancestors' => $ancestors,\n 'category' => $category\n ));\n }", "label_name": "CWE-20", "label": 0} +{"code": "\tpublic function test_empty_content_multiple_spaces() {\n\t\t$result = $this->myxmlrpcserver->wp_newComment(\n\t\t\tarray(\n\t\t\t\t1,\n\t\t\t\t'administrator',\n\t\t\t\t'administrator',\n\t\t\t\tself::$post->ID,\n\t\t\t\tarray(\n\t\t\t\t\t'content' => ' ',\n\t\t\t\t),\n\t\t\t)\n\t\t);\n\n\t\t$this->assertIXRError( $result );\n\t\t$this->assertSame( 403, $result->code );\n\t}", "label_name": "CWE-862", "label": 8} +{"code": " public function show()\n {\n $task = $this->getTask();\n $subtask = $this->getSubtask();\n\n $this->response->html($this->template->render('subtask_converter/show', array(\n 'subtask' => $subtask,\n 'task' => $task,\n )));\n }", "label_name": "CWE-200", "label": 10} +{"code": "function XMLRPCremoveNode($nodeID){\n require_once(\".ht-inc/privileges.php\");\n global $user;\n if(!in_array(\"nodeAdmin\", $user['privileges'])){\n return array(\n 'status' => 'error',\n 'errorcode' => 56,\n 'errormsg' => 'User cannot administer nodes');\n }\n if(!checkUserHasPriv(\"nodeAdmin\", $user['id'], $nodeID)){\n return array(\n 'status' => 'error',\n 'errorcode' => 57,\n 'errormsg' => 'User cannot edit this node');\n }\n $nodes = recurseGetChildren($nodeID);\n array_push($nodes, $nodeID);\n $deleteNodes = implode(',', $nodes);\n $query = \"DELETE FROM privnode \"\n . \"WHERE id IN ($deleteNodes)\";\n doQuery($query, 345);\n return array(\n 'status' => 'success');\n}", "label_name": "CWE-20", "label": 0} +{"code": " public function checkRedirect(RequestInterface $request, array $options, ResponseInterface $response)\n {\n if (\\strpos((string) $response->getStatusCode(), '3') !== 0\n || !$response->hasHeader('Location')\n ) {\n return $response;\n }\n\n $this->guardMax($request, $response, $options);\n $nextRequest = $this->modifyRequest($request, $options, $response);\n\n // If authorization is handled by curl, unset it if host is different.\n if ($request->getUri()->getHost() !== $nextRequest->getUri()->getHost()\n && defined('\\CURLOPT_HTTPAUTH')\n ) {\n unset(\n $options['curl'][\\CURLOPT_HTTPAUTH],\n $options['curl'][\\CURLOPT_USERPWD]\n );\n }\n\n if (isset($options['allow_redirects']['on_redirect'])) {\n ($options['allow_redirects']['on_redirect'])(\n $request,\n $response,\n $nextRequest->getUri()\n );\n }\n\n $promise = $this($nextRequest, $options);\n\n // Add headers to be able to track history of redirects.\n if (!empty($options['allow_redirects']['track_redirects'])) {\n return $this->withTracking(\n $promise,\n (string) $nextRequest->getUri(),\n $response->getStatusCode()\n );\n }\n\n return $promise;\n }", "label_name": "CWE-200", "label": 10} +{"code": " public static function canImportData() {\r\n return true;\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public function configure() {\n $this->config['defaultbanner'] = array();\n if (!empty($this->config['defaultbanner_id'])) {\n $this->config['defaultbanner'][] = new expFile($this->config['defaultbanner_id']);\n } \n\t parent::configure();\n\t $banners = $this->banner->find('all', null, 'companies_id');\n\t assign_to_template(array(\n 'banners'=>$banners,\n 'title'=>static::displayname()\n ));\n\t}", "label_name": "CWE-74", "label": 1} +{"code": " protected function generateVerifyCode()\n {\n if ($this->minLength > $this->maxLength) {\n $this->maxLength = $this->minLength;\n }\n if ($this->minLength < 3) {\n $this->minLength = 3;\n }\n if ($this->maxLength > 20) {\n $this->maxLength = 20;\n }\n $length = mt_rand($this->minLength, $this->maxLength);\n\n $letters = 'bcdfghjklmnpqrstvwxyz';\n $vowels = 'aeiou';\n $code = '';\n for ($i = 0; $i < $length; ++$i) {\n if ($i % 2 && mt_rand(0, 10) > 2 || !($i % 2) && mt_rand(0, 10) > 9) {\n $code .= $vowels[mt_rand(0, 4)];\n } else {\n $code .= $letters[mt_rand(0, 20)];\n }\n }\n\n return $code;\n }", "label_name": "CWE-330", "label": 12} +{"code": " public function testCompilePathIsProperlyCreated()\n {\n $compiler = new BladeCompiler($this->getFiles(), __DIR__);\n $this->assertEquals(__DIR__.'/'.sha1('foo').'.php', $compiler->getCompiledPath('foo'));\n }", "label_name": "CWE-327", "label": 3} +{"code": " public function getDisplayName ($plural=true) {\n return Yii::t('marketing', 'Web Form');\n }", "label_name": "CWE-20", "label": 0} +{"code": "\tfunction __construct() {\n\t\t$this->mDb = GlobalNewFilesHooks::getGlobalDB( DB_REPLICA, 'gnf_files' );\n\n\t\tif ( $this->getRequest()->getText( 'sort', 'files_date' ) == 'files_date' ) {\n\t\t\t$this->mDefaultDirection = IndexPager::DIR_DESCENDING;\n\t\t} else {\n\t\t\t$this->mDefaultDirection = IndexPager::DIR_ASCENDING;\n\t\t}\n\n\t\tparent::__construct( $this->getContext() );\n\t}", "label_name": "CWE-20", "label": 0} +{"code": " foreach ($flatArray as $key => $value) {\n $pattern = '/' . $key . '([^.]|$)/';\n if (preg_match($pattern, $expression, $matches)) {\n\n switch (gettype($flatArray[$key])) {\n case 'boolean':\n $expression = str_replace($key, $flatArray[$key] ? 'true' : 'false', $expression);\n break;\n case 'NULL':\n $expression = str_replace($key, 'false', $expression);\n break;\n case 'string':\n $expression = str_replace($key, '\"' . $flatArray[$key] . '\"', $expression);\n break;\n case 'object':\n $expression = self::executeClosure($expression, $key, $flatArray[$key], $flatArray);\n break;\n default:\n $expression = str_replace($key, $flatArray[$key], $expression);\n break;\n }\n $bool = eval(\"return $expression;\");\n }\n }", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic static function endReset( &$parser, $text ) {\n\t\tif ( !self::$createdLinks['resetdone'] ) {\n\t\t\tself::$createdLinks['resetdone'] = true;\n\t\t\tforeach ( $parser->getOutput()->mCategories as $key => $val ) {\n\t\t\t\tif ( array_key_exists( $key, self::$fixedCategories ) ) {\n\t\t\t\t\tself::$fixedCategories[$key] = $val;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// $text .= self::dumpParsedRefs($parser,\"before final reset\");\n\t\t\tif ( self::$createdLinks['resetLinks'] ) {\n\t\t\t\t$parser->getOutput()->mLinks = [];\n\t\t\t}\n\t\t\tif ( self::$createdLinks['resetCategories'] ) {\n\t\t\t\t$parser->getOutput()->mCategories = self::$fixedCategories;\n\t\t\t}\n\t\t\tif ( self::$createdLinks['resetTemplates'] ) {\n\t\t\t\t$parser->getOutput()->mTemplates = [];\n\t\t\t}\n\t\t\tif ( self::$createdLinks['resetImages'] ) {\n\t\t\t\t$parser->getOutput()->mImages = [];\n\t\t\t}\n\t\t\t// $text .= self::dumpParsedRefs( $parser, 'after final reset' );\n\t\t\tself::$fixedCategories = [];\n\t\t}\n\t\treturn true;\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " private function _getMetaTags()\n {\n $retval = '';\n $retval .= '';\n $retval .= '';\n $retval .= '';\n if (! $GLOBALS['cfg']['AllowThirdPartyFraming']) {\n $retval .= '';\n }\n return $retval;\n }", "label_name": "CWE-200", "label": 10} +{"code": "\t\t\t\t\t$parser->getOutput()->mTemplates[$nsp] = array_diff_assoc( $parser->getOutput()->mTemplates[$nsp], self::$createdLinks[1][$nsp] );\n\t\t\t\t\t// echo (\"
 elim: parser  Tpls [$nsp] nachher = \". count($parser->getOutput()->mTemplates[$nsp])\t .\"
\\n\");\n\t\t\t\t\tif ( count( $parser->getOutput()->mTemplates[$nsp] ) == 0 ) {\n\t\t\t\t\t\tunset( $parser->getOutput()->mTemplates[$nsp] );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}", "label_name": "CWE-400", "label": 2} +{"code": "function XMLRPCgetResourceGroupPrivs($name, $type, $nodeid){\n require_once(\".ht-inc/privileges.php\");\n global $user;\n\n if(! checkUserHasPriv(\"resourceGrant\", $user['id'], $nodeid)){\n return array('status' => 'error',\n 'errorcode' => 53,\n 'errormsg' => 'Unable to add resource group to this node');\n }\n\n if($typeid = getResourceTypeID($type)){\n if(!checkForGroupName($name, 'resource', '', $typeid)){\n return array('status' => 'error',\n 'errorcode' => 28,\n 'errormsg' => 'resource group does not exist');\n }\n $nodePrivileges = getNodePrivileges($nodeid, 'resources');\n $nodePrivileges = getNodeCascadePrivileges($nodeid, 'resources', $nodePrivileges); \n foreach($nodePrivileges['resources'] as $resource => $privs){\n if(strstr($resource, \"$type/$name\")){\n return array(\n 'status' => 'success',\n 'privileges' => $privs);\n }\n }\n return array(\n 'status' => 'error',\n 'errorcode' => 29,\n 'errormsg' => 'could not find resource name in privilege list');\n } else {\n return array('status' => 'error',\n 'errorcode' => 56,\n 'errormsg' => 'Invalid resource type');\n }\n}", "label_name": "CWE-20", "label": 0} +{"code": " public function upload() {\n if (!AuthUser::hasPermission('file_manager_upload')) {\n Flash::set('error', __('You do not have sufficient permissions to upload a file.'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n \n // CSRF checks\n if (isset($_POST['csrf_token'])) {\n $csrf_token = $_POST['csrf_token'];\n if (!SecureToken::validateToken($csrf_token, BASE_URL.'plugin/file_manager/upload')) {\n Flash::set('error', __('Invalid CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n }\n else {\n Flash::set('error', __('No CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n \n $mask = Plugin::getSetting('umask', 'file_manager');\n umask(octdec($mask));\n\n $data = $_POST['upload'];\n $path = str_replace('..', '', $data['path']);\n $overwrite = isset($data['overwrite']) ? true : false;\n\n // Clean filenames\n $filename = preg_replace('/ /', '_', $_FILES['upload_file']['name']);\n $filename = preg_replace('/[^a-z0-9_\\-\\.]/i', '', $filename);\n\n if (isset($_FILES)) {\n $file = $this->_upload_file($filename, FILES_DIR . '/' . $path . '/', $_FILES['upload_file']['tmp_name'], $overwrite);\n\n if ($file === false)\n Flash::set('error', __('File has not been uploaded!'));\n }\n redirect(get_url('plugin/file_manager/browse/' . $path));\n }", "label_name": "CWE-20", "label": 0} +{"code": " public static function validateNumber(\n $path,\n $values,\n $allow_neg,\n $allow_zero,\n $max_value,\n $error_string\n ) {\n if ($values[$path] === '') {\n return '';\n }\n\n if (intval($values[$path]) != $values[$path]\n || (! $allow_neg && $values[$path] < 0)\n || (! $allow_zero && $values[$path] == 0)\n || $values[$path] > $max_value\n ) {\n return $error_string;\n }\n\n return '';\n }", "label_name": "CWE-200", "label": 10} +{"code": "\tstatic public function getHighestOrderNumber($_uid = 0) {\n\n\t\t$where = '';\n\t\t$sel_data = array();\n\t\tif ($_uid > 0) {\n\t\t\t$where = \" WHERE `adminid` = :adminid\";\n\t\t\t$sel_data['adminid'] = $_uid;\n\t\t}\n\t\t$sql = \"SELECT MAX(`logicalorder`) as `highestorder` FROM `\" . TABLE_PANEL_TICKET_CATS . \"`\".$where.\";\";\n\t\t$result_stmt = Database::prepare($sql);\n\t\t$result = Database::pexecute_first($result_stmt, $sel_data);\n\t\treturn (isset($result['highestorder']) ? (int)$result['highestorder'] : 0);\n\t}", "label_name": "CWE-732", "label": 13} +{"code": "\tpublic function addGroupBy( $groupBy ) {\n\t\tif ( empty( $groupBy ) ) {\n\t\t\tthrow new \\MWException( __METHOD__ . ': An empty group by clause was passed.' );\n\t\t}\n\t\t$this->groupBy[] = $groupBy;\n\t\treturn true;\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " public function generateMessageFileName()\n {\n $time = microtime(true);\n\n return date('Ymd-His-', $time) . sprintf('%04d', (int) (($time - (int) $time) * 10000)) . '-' . sprintf('%04d', mt_rand(0, 10000)) . '.eml';\n }", "label_name": "CWE-330", "label": 12} +{"code": " foreach ($allusers as $uid) {\r\n $u = user::getUserById($uid);\r\n expPermissions::grant($u, 'manage', $sloc);\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic static function init( $settings = false ) {\n\t\tif ( $settings === false ) {\n\t\t\tglobal $wgDplSettings;\n\n\t\t\t$settings = $wgDplSettings;\n\t\t}\n\n\t\tif ( !is_array( $settings ) ) {\n\t\t\tthrow new MWException( __METHOD__ . \": Invalid settings passed.\" );\n\t\t}\n\n\t\tself::$settings = array_merge( self::$settings, $settings );\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " self::removeLevel($kid->id);\r\n }\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " static function testLDAPConnection($auths_id, $replicate_id = -1) {\n\n $config_ldap = new self();\n $res = $config_ldap->getFromDB($auths_id);\n\n // we prevent some delay...\n if (!$res) {\n return false;\n }\n\n //Test connection to a replicate\n if ($replicate_id != -1) {\n $replicate = new AuthLdapReplicate();\n $replicate->getFromDB($replicate_id);\n $host = $replicate->fields[\"host\"];\n $port = $replicate->fields[\"port\"];\n\n } else {\n //Test connection to a master ldap server\n $host = $config_ldap->fields['host'];\n $port = $config_ldap->fields['port'];\n }\n $ds = self::connectToServer($host, $port, $config_ldap->fields['rootdn'],\n Toolbox::decrypt($config_ldap->fields['rootdn_passwd'], GLPIKEY),\n $config_ldap->fields['use_tls'],\n $config_ldap->fields['deref_option']);\n if ($ds) {\n return true;\n }\n return false;\n }", "label_name": "CWE-327", "label": 3} +{"code": "\t\t\t\t$curVal[$key] = $tp->post_toForm($val);\n\t\t\t}\n\t\t}\n\n\t\t$target = e107::getUrl()->create('user/myprofile/edit',array('id'=>USERID));\n\n\t\t$text = '
';\n\n\t\t//$text = (is_numeric($_uid) ? $rs->form_open(\"post\", e_SELF.\"?\".e_QUERY, \"dataform\", \"\", \" class='form-horizontal' role='form' enctype='multipart/form-data'\") : $rs->form_open(\"post\", e_SELF, \"dataform\", \"\", \" class='form-horizontal' role='form' enctype='multipart/form-data'\"));\n\n\t\tif (e_QUERY == \"update\")\n\t\t{\n\t\t\t$text .= \"

\".str_replace(\"*\", \"*\", LAN_USET_9).\"
\".LAN_USET_10.\"

\";\n\t\t}\n\n\t\t// e107::scStyle($sc_style);\n\t\te107::getScBatch('usersettings')->setVars($curVal)->reset();\n\n\t\t$USERSETTINGS_EDIT = $this->getTemplate('edit');\n\t\t$USERSETTINGS_EDIT_CAPTION = $this->getTemplate('edit_caption');\n\n\t\t$text .= $tp->parseTemplate($USERSETTINGS_EDIT, true, $this->sc); //ParseSC must be set to true so that custom plugin -shortcodes can be utilized.\n\n\n\t\t$text .= \"
\n\t\t
\n\t\t\";\n\n\t\t$caption = (isset($USERSETTINGS_EDIT_CAPTION)) ? $USERSETTINGS_EDIT_CAPTION : LAN_USET_39; // 'Update User Settings'\n\n\t\t$ns->tablerender($caption, $text);\n\n\n\n\n\n\t}", "label_name": "CWE-326", "label": 9} +{"code": " $tags = array_merge($matches[1], $tags);\n }\n $tags = array_unique($tags);\n return $tags;\n }", "label_name": "CWE-20", "label": 0} +{"code": "\tpublic function fixsessions() {\n\t global $db;\n\n//\t\t$test = $db->sql('CHECK TABLE '.$db->prefix.'sessionticket');\n\t\t$fix = $db->sql('REPAIR TABLE '.$db->prefix.'sessionticket');\n\t\tflash('message', gt('Sessions Table was Repaired'));\n\t\texpHistory::back();\n\t}", "label_name": "CWE-74", "label": 1} +{"code": " $link = str_replace(URL_FULL, '', makeLink(array('section' => $section->id)));\r", "label_name": "CWE-74", "label": 1} +{"code": " function update_optiongroup_master() {\n global $db;\n\n $id = empty($this->params['id']) ? null : $this->params['id'];\n $og = new optiongroup_master($id);\n $oldtitle = $og->title;\n $og->update($this->params);\n \n // if the title of the master changed we should update the option groups that are already using it.\n if ($oldtitle != $og->title) {\n $db->sql('UPDATE '.$db->prefix.'optiongroup SET title=\"'.$og->title.'\" WHERE title=\"'.$oldtitle.'\"');\n }\n \n expHistory::back();\n }", "label_name": "CWE-74", "label": 1} +{"code": "\tprivate function _createdby( $option ) {\n\t\t$this->addTable( 'revision', 'creation_rev' );\n\t\t$this->addTable( 'revision_actor_temp', 'creation_rev_actor' );\n\t\t$this->_adduser( null, 'creation_rev_actor' );\n\t\t$user = new \\User;\n\n\t\t$this->addWhere(\n\t\t\t[\n\t\t\t\t$this->DB->addQuotes( $user->newFromName( $option )->getActorId() ) . ' = creation_rev_actor.revactor_actor',\n\t\t\t\t'creation_rev_actor.revactor_page = page_id',\n\t\t\t\t'creation_rev.rev_parent_id = 0'\n\t\t\t]\n\t\t);\n\t}", "label_name": "CWE-400", "label": 2} +{"code": "\t\t\t$dplArg = $this->wgRequest->getVal( $arg, '' );\n\t\t\tif ( $dplArg == '' ) {\n\t\t\t\t$input = preg_replace( '/\\{%' . $arg . ':(.*)%\\}/U', '\\1', $input );\n\t\t\t\t$input = str_replace( '{%' . $arg . '%}', '', $input );\n\t\t\t} else {\n\t\t\t\t$input = preg_replace( '/\\{%' . $arg . ':.*%\\}/U ', $dplArg, $input );\n\t\t\t\t$input = str_replace( '{%' . $arg . '%}', $dplArg, $input );\n\t\t\t}\n\t\t}\n\t\treturn $input;\n\t}", "label_name": "CWE-400", "label": 2} +{"code": "\t\t\t$this->where = array_merge( $this->where, $where );\n\t\t} else {\n\t\t\tthrow new \\MWException( __METHOD__ . ': An invalid where clause was passed.' );\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}", "label_name": "CWE-400", "label": 2} +{"code": "\tpublic function assets_path($file = NULL, $path = NULL, $module = NULL, $absolute = NULL)\n\t{\n\t\t$cache = '';\n\t\tif (!isset($absolute)) $absolute = $this->assets_absolute_path;\n\t\t\n\t\t$CI = $this->_get_assets_config();\n\t\tif ($this->asset_append_cache_timestamp AND in_array($path, $this->asset_append_cache_timestamp) AND !empty($file))\n\t\t{\n\t\t\t$q_str = (strpos($file, '?') === FALSE) ? '?' : '&';\n\t\t\t$cache = $q_str.'c='.strtotime($this->assets_last_updated);\n\t\t}\n\t\n\t\t// if it is an absolute path already provided, then we just return it without any caching\n\t\tif (!$this->_is_local_path($file))\n\t\t{\n\t\t\treturn $file.$cache;\n\t\t}\n\t\t\n\t\t$assets_folders = $this->assets_folders;\n\n\t\t$asset_type = (!empty($assets_folders[$path])) ? $assets_folders[$path] : $CI->config->item($path);\n\n\t\t// if absolute path, then we just return that\n\t\tif (!$this->_is_local_path($this->assets_path))\n\t\t{\n\t\t\treturn $this->assets_path.$asset_type.$file.$cache;\n\t\t}\n\n\t\t$assets_path = $this->_get_assets_path($module);\n\t\t\n\t\t$path = WEB_PATH.$assets_path.$asset_type.$file.$cache;\n\n\t\tif ($absolute)\n\t\t{\n\t\t\t$protocol = ($_SERVER[\"SERVER_PORT\"] == 443) ? \"https://\" : \"http://\";\n\t\t\t$path = $protocol.$_SERVER['HTTP_HOST'].$path;\n\t\t}\n\t\treturn $path;\n\t}", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic function behaviors() {\n\t\treturn array_merge(parent::behaviors(),array(\n\t\t\t'X2LinkableBehavior'=>array(\n\t\t\t\t'class'=>'X2LinkableBehavior',\n\t\t\t\t'module'=>'marketing'\n\t\t\t),\n\t\t\t'ERememberFiltersBehavior' => array(\n\t\t\t\t'class'=>'application.components.ERememberFiltersBehavior',\n\t\t\t\t'defaults'=>array(),\n\t\t\t\t'defaultStickOnClear'=>false\n\t\t\t)\n\t\t));\n\t}", "label_name": "CWE-20", "label": 0} +{"code": "\tstatic public function customerHasTickets($_cid = 0) {\n\n\t\tif ($_cid != 0) {\n\t\t\t$result_stmt = Database::prepare(\"\n\t\t\t\tSELECT `id` FROM `\" . TABLE_PANEL_TICKETS . \"` WHERE `customerid` = :cid\"\n\t\t\t);\n\t\t\tDatabase::pexecute($result_stmt, array('cid' => $_cid));\n\n\t\t\t$tickets = array();\n\t\t\twhile ($row = $result_stmt->fetch(PDO::FETCH_ASSOC)) {\n\t\t\t\t$tickets[] = $row['id'];\n\t\t\t}\n\n\t\t\treturn $tickets;\n\t\t}\n\n\t\treturn false;\n\t}", "label_name": "CWE-732", "label": 13} +{"code": " function manage() {\n expHistory::set('viewable', $this->params);\n // $category = new storeCategory();\n // $categories = $category->getFullTree();\n // \n // // foreach($categories as $i=>$val){\n // // if (!empty($this->values) && in_array($val->id,$this->values)) {\n // // $this->tags[$i]->value = true;\n // // } else {\n // // $this->tags[$i]->value = false;\n // // }\n // // $this->tags[$i]->draggable = $this->draggable; \n // // $this->tags[$i]->checkable = $this->checkable; \n // // }\n //\n // $obj = json_encode($categories); \n }", "label_name": "CWE-74", "label": 1} +{"code": " public function isLocal() {\n $localhosts = array('::1', '127.0.0.1', '0.0.0.0');\n return (\n in_array(server::get('SERVER_ADDR'), $localhosts) ||\n server::get('SERVER_NAME') == 'localhost' ||\n str::endsWith(server::get('SERVER_NAME'), '.localhost') ||\n str::endsWith(server::get('SERVER_NAME'), '.test')\n );\n }", "label_name": "CWE-346", "label": 16} +{"code": " function searchName() { return gt('Webpage'); }\r", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic function getListStart() {\n\t\t// increase start value of ordered lists at multi-column output\n\t\t//The offset that comes from the URL parameter is zero based, but has to be +1'ed for display.\n\t\t$offset = $this->getParameters()->getParameter( 'offset' ) + 1;\n\n\t\tif ( $offset != 0 ) {\n\t\t\t//@TODO: So this adds the total count of articles to the offset. I have not found a case where this does not mess up the displayed count. I am commenting this out for now.\n\t\t\t//$offset += $this->offsetCount;\n\t\t}\n\n\t\treturn sprintf( $this->listStart, $this->listAttributes . ' start=\"' . $offset . '\"' );\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " function update() {\r\n parent::update();\r\n expSession::clearAllUsersSessionCache('navigation');\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " static function displayname() {\n return gt(\"e-Commerce Category Manager\");\n }", "label_name": "CWE-74", "label": 1} +{"code": " $connecttext = preg_replace(\"/#connectport#/\", $connectport, $connecttext); \n $connectMethods[$key][\"connecttext\"] = $connecttext;\n }\n\t\treturn array('status' => 'ready',\n\t\t 'serverIP' => $serverIP,\n\t\t 'user' => $thisuser,\n 'password' => $passwd,\n 'connectport' => $connectport,\n 'connectMethods' => $connectMethods);\n\t}\n\treturn array('status' => 'notready');\n}", "label_name": "CWE-20", "label": 0} +{"code": "\tfunction getTextColumns($table) {\n\t\t$sql = \"SHOW COLUMNS FROM \" . $this->prefix.$table . \" WHERE type = 'text' OR type like 'varchar%'\";\n\t\t$res = @mysqli_query($this->connection, $sql);\n\t\tif ($res == null)\n return array();\n\t\t$records = array();\n\t\twhile($row = mysqli_fetch_object($res)) {\n\t\t\t$records[] = $row->Field;\n\t\t}\n\t\t\n\t\treturn $records;\n\t}", "label_name": "CWE-74", "label": 1} +{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $swimlane_id = $this->request->getIntegerParam('swimlane_id');\n\n if ($this->swimlaneModel->remove($project['id'], $swimlane_id)) {\n $this->flash->success(t('Swimlane removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this swimlane.'));\n }\n\n $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-200", "label": 10} +{"code": " private function get_lines() {\n $data = \"\";\n $endtime = 0;\n /* If for some reason the fp is bad, don't inf loop */\n if (!is_resource($this->smtp_conn)) {\n return $data;\n }\n stream_set_timeout($this->smtp_conn, $this->Timeout);\n if ($this->Timelimit > 0) {\n $endtime = time() + $this->Timelimit;\n }\n while(is_resource($this->smtp_conn) && !feof($this->smtp_conn)) {\n $str = @fgets($this->smtp_conn,515);\n if($this->do_debug >= 4) {\n $this->edebug(\"SMTP -> get_lines(): \\$data was \\\"$data\\\"\" . $this->CRLF . '
');\n $this->edebug(\"SMTP -> get_lines(): \\$str is \\\"$str\\\"\" . $this->CRLF . '
');\n }\n $data .= $str;\n if($this->do_debug >= 4) {\n $this->edebug(\"SMTP -> get_lines(): \\$data is \\\"$data\\\"\" . $this->CRLF . '
');\n }\n // if 4th character is a space, we are done reading, break the loop\n if(substr($str,3,1) == \" \") { break; }\n // Timed-out? Log and break\n $info = stream_get_meta_data($this->smtp_conn);\n if ($info['timed_out']) {\n if($this->do_debug >= 4) {\n $this->edebug(\"SMTP -> get_lines(): timed-out (\" . $this->Timeout . \" seconds)
\");\n }\n break;\n }\n // Now check if reads took too long\n if ($endtime) {\n if (time() > $endtime) {\n if($this->do_debug >= 4) {\n $this->edebug(\"SMTP -> get_lines(): timelimit reached (\" . $this->Timelimit . \" seconds)
\");\n }\n break;\n }\n }\n }\n return $data;\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function testAuth()\n {\n if (! defined('PMA_TEST_HEADERS')) {\n $this->markTestSkipped(\n 'Cannot redefine constant/function - missing runkit extension'\n );\n }\n\n // case 1\n\n $GLOBALS['cfg']['Server']['SignonURL'] = '';\n\n ob_start();\n $this->object->auth();\n $result = ob_get_clean();\n\n $this->assertContains(\n 'You must set SignonURL!',\n $result\n );\n\n // case 2\n\n $GLOBALS['cfg']['Server']['SignonURL'] = 'http://phpmyadmin.net/SignonURL';\n $_REQUEST['old_usr'] = 'oldUser';\n $GLOBALS['cfg']['Server']['LogoutURL'] = 'http://phpmyadmin.net/logoutURL';\n\n $this->object->auth();\n\n $this->assertContains(\n 'Location: http://phpmyadmin.net/logoutURL?PHPSESSID=',\n $GLOBALS['header'][0]\n );\n\n // case 3\n\n $GLOBALS['header'] = array();\n $GLOBALS['cfg']['Server']['SignonURL'] = 'http://phpmyadmin.net/SignonURL';\n $_REQUEST['old_usr'] = '';\n $GLOBALS['cfg']['Server']['LogoutURL'] = '';\n\n $this->object->auth();\n\n $this->assertContains(\n 'Location: http://phpmyadmin.net/SignonURL?PHPSESSID=',\n $GLOBALS['header'][0]\n );\n }", "label_name": "CWE-200", "label": 10} +{"code": "\tfunction execute( $par ) {\n\t\t$this->setHeaders();\n\t\t$this->outputHeader();\n\n\t\t$pager = new GlobalNewFilesPager();\n\t\t\n\t\t$this->getOutput()->addParserOutputContent( $pager->getFullOutput() );\n\t}", "label_name": "CWE-20", "label": 0} +{"code": "\tprivate function _notmodifiedby( $option ) {\n\t\t$user = new \\User;\n\t\t$this->addWhere( 'NOT EXISTS (SELECT 1 FROM ' . $this->tableNames['revision_actor_temp'] . ' WHERE ' . $this->tableNames['revision_actor_temp'] . '.revactor_page=page_id AND ' . $this->tableNames['revision_actor_temp'] . '.revactor_actor = ' . $this->DB->addQuotes( $user->newFromName( $option )->getActorId() ) . ' LIMIT 1)' );\n\t}", "label_name": "CWE-400", "label": 2} +{"code": "\tstatic public function addCategory($_category = null, $_admin = 1, $_order = 1) {\n\n\t\tif ($_category != null\n\t\t\t&& $_category != ''\n\t\t) {\n\t\t\tif ($_order < 1) {\n\t\t\t\t$_order = 1;\n\t\t\t}\n\n\t\t\t$ins_stmt = Database::prepare(\"\n\t\t\t\tINSERT INTO `\" . TABLE_PANEL_TICKET_CATS . \"` SET\n\t\t\t\t\t`name` = :name,\n\t\t\t\t\t`adminid` = :adminid,\n\t\t\t\t\t`logicalorder` = :lo\"\n\t\t\t);\n\t\t\t$ins_data = array(\n\t\t\t\t'name' => $_category,\n\t\t\t\t'adminid' => $_admin,\n\t\t\t\t'lo' => $_order\n\t\t\t);\n\t\t\tDatabase::pexecute($ins_stmt, $ins_data);\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}", "label_name": "CWE-732", "label": 13} +{"code": "\t\t\t$iloc = expUnserialize($container->internal);\n\t\t\tif ($db->selectObject('sectionref',\"module='\".$iloc->mod.\"' AND source='\".$iloc->src.\"'\") == null) {\n\t\t\t// There is no sectionref for this container. Populate sectionref\n if ($container->external != \"N;\") {\n $newSecRef = new stdClass();\n $newSecRef->module = $iloc->mod;\n $newSecRef->source = $iloc->src;\n $newSecRef->internal = '';\n $newSecRef->refcount = 1;\n// $newSecRef->is_original = 1;\n\t\t\t\t\t$eloc = expUnserialize($container->external);\n//\t\t\t\t\t$section = $db->selectObject('sectionref',\"module='containermodule' AND source='\".$eloc->src.\"'\");\n $section = $db->selectObject('sectionref',\"module='container' AND source='\".$eloc->src.\"'\");\n\t\t\t\t\tif (!empty($section)) {\n\t\t\t\t\t\t$newSecRef->section = $section->id;\n\t\t\t\t\t\t$db->insertObject($newSecRef,\"sectionref\");\n\t\t\t\t\t\t$missing_sectionrefs[] = gt(\"Missing sectionref for container replaced\").\": \".$iloc->mod.\" - \".$iloc->src.\" - PageID #\".$section->id;\n\t\t\t\t\t} else {\n $db->delete('container','id=\"'.$container->id.'\"');\n $missing_sectionrefs[] = gt(\"Cant' find the container page for container\").\": \".$iloc->mod.\" - \".$iloc->src.' - '.gt('deleted');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n assign_to_template(array(\n 'missing_sectionrefs'=>$missing_sectionrefs,\n ));\n\t}", "label_name": "CWE-74", "label": 1} +{"code": " public static function fixName($name) {\n $name = preg_replace('/[^A-Za-z0-9\\.]/','_',$name);\n if ($name[0] == '.')\n $name[0] = '_';\n return $name;\n// return preg_replace('/[^A-Za-z0-9\\.]/', '-', $name);\n }", "label_name": "CWE-74", "label": 1} +{"code": "\tprivate function _notlinksto( $option ) {\n\t\tif ( $this->parameters->getParameter( 'distinct' ) == 'strict' ) {\n\t\t\t$this->addGroupBy( 'page_title' );\n\t\t}\n\t\tif ( count( $option ) ) {\n\t\t\t$where = $this->tableNames['page'] . '.page_id NOT IN (SELECT ' . $this->tableNames['pagelinks'] . '.pl_from FROM ' . $this->tableNames['pagelinks'] . ' WHERE ';\n\t\t\t$ors = [];\n\t\t\tforeach ( $option as $linkGroup ) {\n\t\t\t\tforeach ( $linkGroup as $link ) {\n\t\t\t\t\t$_or = '(' . $this->tableNames['pagelinks'] . '.pl_namespace=' . intval( $link->getNamespace() );\n\t\t\t\t\tif ( strpos( $link->getDbKey(), '%' ) >= 0 ) {\n\t\t\t\t\t\t$operator = 'LIKE';\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$operator = '=';\n\t\t\t\t\t}\n\t\t\t\t\tif ( $this->parameters->getParameter( 'ignorecase' ) ) {\n\t\t\t\t\t\t$_or .= ' AND LOWER(CAST(' . $this->tableNames['pagelinks'] . '.pl_title AS char)) ' . $operator . ' LOWER(' . $this->DB->addQuotes( $link->getDbKey() ) . '))';\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$_or .= ' AND ' . $this->tableNames['pagelinks'] . '.pl_title ' . $operator . ' ' . $this->DB->addQuotes( $link->getDbKey() ) . ')';\n\t\t\t\t\t}\n\t\t\t\t\t$ors[] = $_or;\n\t\t\t\t}\n\t\t\t}\n\t\t\t$where .= '(' . implode( ' OR ', $ors ) . '))';\n\t\t}\n\t\t$this->addWhere( $where );\n\t}", "label_name": "CWE-400", "label": 2} +{"code": "\tpublic static function setArray( $arg ) {\n\t\t$numargs = count( $arg );\n\t\tif ( $numargs < 5 ) {\n\t\t\treturn '';\n\t\t}\n\t\t$var = trim( $arg[2] );\n\t\t$value = $arg[3];\n\t\t$delimiter = $arg[4];\n\t\tif ( $var == '' ) {\n\t\t\treturn '';\n\t\t}\n\t\tif ( $value == '' ) {\n\t\t\tself::$memoryArray[$var] = [];\n\t\t\treturn;\n\t\t}\n\t\tif ( $delimiter == '' ) {\n\t\t\tself::$memoryArray[$var] = [\n\t\t\t\t$value\n\t\t\t];\n\t\t\treturn;\n\t\t}\n\t\tif ( 0 !== strpos( $delimiter, '/' ) || ( strlen( $delimiter ) - 1 ) !== strrpos( $delimiter, '/' ) ) {\n\t\t\t$delimiter = '/\\s*' . $delimiter . '\\s*/';\n\t\t}\n\t\tself::$memoryArray[$var] = preg_split( $delimiter, $value );\n\t\treturn \"value={$value}, delimiter={$delimiter},\" . count( self::$memoryArray[$var] );\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " $rndString = function ($len = 10) {\n $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n $randomString = '';\n for ($i = 0; $i < $len; $i++) {\n $randomString .= $characters[rand(0, strlen($characters) - 1)];\n }\n\n return $randomString;\n };", "label_name": "CWE-330", "label": 12} +{"code": " public function actionDeleteDropdown() {\n $dropdowns = Dropdowns::model()->findAll();\n\n if (isset($_POST['dropdown'])) {\n if ($_POST['dropdown'] != Actions::COLORS_DROPDOWN_ID) {\n $model = Dropdowns::model()->findByPk($_POST['dropdown']);\n $model->delete();\n $this->redirect('manageDropDowns');\n }\n }\n\n $this->render('deleteDropdowns', array(\n 'dropdowns' => $dropdowns,\n ));\n }", "label_name": "CWE-20", "label": 0} +{"code": "\tpublic function setPageTextMatchRegex( array $pageTextMatchRegex = [] ) {\n\t\t$this->pageTextMatchRegex = (array)$pageTextMatchRegex;\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " function delete_recurring() {\r\n $item = $this->event->find('first', 'id=' . $this->params['id']);\r\n if ($item->is_recurring == 1) { // need to give user options\r\n expHistory::set('editable', $this->params);\r\n assign_to_template(array(\r\n 'checked_date' => $this->params['date_id'],\r\n 'event' => $item,\r\n ));\r\n } else { // Process a regular delete\r\n $item->delete();\r\n }\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " protected function markCompleted($endStatus, ServiceResponse $serviceResponse, $gatewayMessage)\n {\n parent::markCompleted($endStatus, $serviceResponse, $gatewayMessage);\n $this->createMessage(Message\\PurchasedResponse::class, $gatewayMessage);\n ErrorHandling::safeExtend($this->payment, 'onCaptured', $serviceResponse);\n }", "label_name": "CWE-436", "label": 5} +{"code": " public function AddReplyTo($address, $name = '') {\n return $this->AddAnAddress('Reply-To', $address, $name);\n }", "label_name": "CWE-20", "label": 0} +{"code": " function searchByModelForm() {\n // get the search terms\n $terms = $this->params['search_string'];\n\n $sql = \"model like '%\" . $terms . \"%'\";\n\n $limit = !empty($this->config['limit']) ? $this->config['limit'] : 10;\n $page = new expPaginator(array(\n 'model' => 'product',\n 'where' => $sql,\n 'limit' => !empty($this->config['pagination_default']) ? $this->config['pagination_default'] : $limit,\n 'order' => 'title',\n 'dir' => 'DESC',\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller' => $this->params['controller'],\n 'action' => $this->params['action'],\n 'columns' => array(\n gt('Model #') => 'model',\n gt('Product Name') => 'title',\n gt('Price') => 'base_price'\n ),\n ));\n\n assign_to_template(array(\n 'page' => $page,\n 'terms' => $terms\n ));\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function save($check_notify = false)\n {\n if (isset($_POST['email_recipients']) && is_array($_POST['email_recipients'])) {\n $this->email_recipients = base64_encode(serialize($_POST['email_recipients']));\n }\n\n return parent::save($check_notify);\n }", "label_name": "CWE-287", "label": 4} +{"code": " function selectArraysBySql($sql) { \n $res = @mysqli_query($this->connection, $this->injectProof($sql));\n if ($res == null)\n return array();\n $arrays = array();\n for ($i = 0, $iMax = mysqli_num_rows($res); $i < $iMax; $i++)\n $arrays[] = mysqli_fetch_assoc($res);\n return $arrays;\n }", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic function addTable( $table, $alias ) {\n\t\tif ( empty( $table ) ) {\n\t\t\tthrow new \\MWException( __METHOD__ . ': An empty table name was passed.' );\n\t\t}\n\t\tif ( empty( $alias ) || is_numeric( $alias ) ) {\n\t\t\tthrow new \\MWException( __METHOD__ . ': An empty or numeric table alias was passed.' );\n\t\t}\n\t\tif ( !isset( $this->tables[$alias] ) ) {\n\t\t\t$this->tables[$alias] = $this->DB->tableName( $table );\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " $navs[$i]->link = expCore::makeLink(array('section' => $navs[$i]->id), '', $navs[$i]->sef_name);\r\n if (!$view) {\r\n// unset($navs[$i]); //FIXME this breaks jstree if we remove a parent and not the child\r\n $attr = new stdClass();\r\n $attr->class = 'hidden'; // bs3 class to hide elements\r\n $navs[$i]->li_attr = $attr;\r\n }\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public function shouldRun(DateTime $date)\n {\n global $timedate;\n\n $runDate = clone $date;\n $this->handleTimeZone($runDate);\n\n $cron = Cron\\CronExpression::factory($this->schedule);\n if (empty($this->last_run) && $cron->isDue($runDate)) {\n return true;\n }\n\n $lastRun = $this->last_run ? $timedate->fromDb($this->last_run) : $timedate->fromDb($this->date_entered);\n \n $this->handleTimeZone($lastRun);\n $next = $cron->getNextRunDate($lastRun);\n\n return $next <= $runDate;\n }", "label_name": "CWE-287", "label": 4} +{"code": "\t\t\t$rest = $count - ( floor( $nsize ) * floor( $iGroup ) );\n\t\t\tif ( $rest > 0 ) {\n\t\t\t\t$nsize += 1;\n\t\t\t}\n\t\t\t$output .= \"{|\" . $rowColFormat . \"\\n|\\n\";\n\t\t\tfor ( $g = 0; $g < $iGroup; $g++ ) {\n\t\t\t\t$output .= $lister->formatList( $articles, $nstart, $nsize );\n\t\t\t\tif ( $columns != 1 ) {\n\t\t\t\t\t$output .= \"\\n|valign=top|\\n\";\n\t\t\t\t} else {\n\t\t\t\t\t$output .= \"\\n|-\\n|\\n\";\n\t\t\t\t}\n\t\t\t\t$nstart = $nstart + $nsize;\n\t\t\t\t// if ($rest != 0 && $g+1==$rest) $nsize -= 1;\n\t\t\t\tif ( $nstart + $nsize > $count ) {\n\t\t\t\t\t$nsize = $count - $nstart;\n\t\t\t\t}\n\t\t\t}\n\t\t\t$output .= \"\\n|}\\n\";\n\t\t} elseif ( $rowSize > 0 ) {", "label_name": "CWE-400", "label": 2} +{"code": " public function manage()\n {\n expHistory::set('manageable',$this->params);\n $gc = new geoCountry();\n $countries = $gc->find('all');\n \n $gr = new geoRegion(); \n $regions = $gr->find('all',null,'rank asc,name asc');\n \n assign_to_template(array(\n 'countries'=>$countries,\n 'regions'=>$regions\n ));\n }", "label_name": "CWE-74", "label": 1} +{"code": " public static function getIconName($module)\n {\n return isset(static::$iconNames[$module])\n ? static::$iconNames[$module]\n : strtolower(str_replace('_', '-', $module));\n }", "label_name": "CWE-287", "label": 4} +{"code": "\tpublic static function onRegistration() {\n\t\tif ( !defined( 'DPL_VERSION' ) ) {\n\t\t\tdefine( 'DPL_VERSION', '3.3.5' );\n\t\t}\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " public function testOnKernelResponseWithoutSession()\n {\n $tokenStorage = new TokenStorage();\n $tokenStorage->setToken(new UsernamePasswordToken('test1', 'pass1', 'phpunit'));\n $request = new Request();\n $request->attributes->set('_security_firewall_run', true);\n $session = new Session(new MockArraySessionStorage());\n $request->setSession($session);\n\n $event = new ResponseEvent(\n $this->createMock(HttpKernelInterface::class),\n $request,\n HttpKernelInterface::MAIN_REQUEST,\n new Response()\n );\n\n $listener = new ContextListener($tokenStorage, [], 'session', null, new EventDispatcher());\n $listener->onKernelResponse($event);\n\n $this->assertTrue($session->isStarted());\n }", "label_name": "CWE-287", "label": 4} +{"code": " public function AddBCC($address, $name = '') {\n return $this->AddAnAddress('bcc', $address, $name);\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function testNotRemoveAuthorizationHeaderOnRedirect()\n {\n $mock = new MockHandler([\n new Response(302, ['Location' => 'http://example.com/2']),\n static function (RequestInterface $request) {\n self::assertTrue($request->hasHeader('Authorization'));\n return new Response(200);\n }\n ]);\n $handler = HandlerStack::create($mock);\n $client = new Client(['handler' => $handler]);\n $client->get('http://example.com?a=b', ['auth' => ['testuser', 'testpass']]);\n }", "label_name": "CWE-200", "label": 10} +{"code": " public function testRemoveCurlAuthorizationOptionsOnRedirect($auth)\n {\n if (!defined('\\CURLOPT_HTTPAUTH')) {\n self::markTestSkipped('ext-curl is required for this test');\n }\n\n $mock = new MockHandler([\n new Response(302, ['Location' => 'http://test.com']),\n static function (RequestInterface $request, $options) {\n self::assertFalse(\n isset($options['curl'][\\CURLOPT_HTTPAUTH]),\n 'curl options still contain CURLOPT_HTTPAUTH entry'\n );\n self::assertFalse(\n isset($options['curl'][\\CURLOPT_USERPWD]),\n 'curl options still contain CURLOPT_USERPWD entry'\n );\n return new Response(200);\n }\n ]);\n $handler = HandlerStack::create($mock);\n $client = new Client(['handler' => $handler]);\n $client->get('http://example.com?a=b', ['auth' => ['testuser', 'testpass', $auth]]);\n }", "label_name": "CWE-200", "label": 10} +{"code": "\tstatic function convertXMLFeedSafeChar($str) {\n\t\t$str = str_replace(\"
\",\"\",$str);\n $str = str_replace(\"
\",\"\",$str);\n $str = str_replace(\"
\",\"\",$str);\n $str = str_replace(\"
\",\"\",$str);\n $str = str_replace(\""\",'\"',$str);\n $str = str_replace(\"'\",\"'\",$str);\n $str = str_replace(\"’\",\"'\",$str);\n $str = str_replace(\"‘\",\"'\",$str); \n $str = str_replace(\"®\",\"\",$str);\n $str = str_replace(\"\ufffd\",\"-\", $str);\n $str = str_replace(\"\ufffd\",\"-\", $str); \n $str = str_replace(\"\ufffd\", '\"', $str);\n $str = str_replace(\"”\",'\"', $str);\n $str = str_replace(\"\ufffd\", '\"', $str);\n $str = str_replace(\"“\",'\"', $str);\n $str = str_replace(\"\\r\\n\",\" \",$str); \n $str = str_replace(\"\ufffd\",\" 1/4\",$str);\n $str = str_replace(\"¼\",\" 1/4\", $str);\n $str = str_replace(\"\ufffd\",\" 1/2\",$str);\n $str = str_replace(\"½\",\" 1/2\",$str);\n $str = str_replace(\"\ufffd\",\" 3/4\",$str);\n $str = str_replace(\"¾\",\" 3/4\",$str);\n $str = str_replace(\"\ufffd\", \"(TM)\", $str);\n $str = str_replace(\"™\",\"(TM)\", $str);\n $str = str_replace(\"®\",\"(R)\", $str);\n $str = str_replace(\"\ufffd\",\"(R)\",$str); \n $str = str_replace(\"&\",\"&\",$str); \n\t\t$str = str_replace(\">\",\">\",$str); \t\t\n return trim($str);\n\t}", "label_name": "CWE-74", "label": 1} +{"code": " protected function getBodyTagAttributes()\n {\n $formEngineParameters = [];\n $parameters = parent::getBodyTagAttributes();\n\n $formEngineParameters['fieldChangeFunc'] = $this->parameters['fieldChangeFunc'];\n $formEngineParameters['fieldChangeFuncHash'] = GeneralUtility::hmac(serialize($this->parameters['fieldChangeFunc']));\n\n $parameters['data-add-on-params'] .= HttpUtility::buildQueryString(['P' => $formEngineParameters], '&');\n\n return $parameters;\n }", "label_name": "CWE-327", "label": 3} +{"code": " public function showall() {\r\n global $user, $sectionObj, $sections;\r\n\r\n expHistory::set('viewable', $this->params);\r\n $id = $sectionObj->id;\r\n $current = null;\r\n // all we need to do is determine the current section\r\n $navsections = $sections;\r\n if ($sectionObj->parent == -1) {\r\n $current = $sectionObj;\r\n } else {\r\n foreach ($navsections as $section) {\r\n if ($section->id == $id) {\r\n $current = $section;\r\n break;\r\n }\r\n }\r\n }\r\n assign_to_template(array(\r\n 'sections' => $navsections,\r\n 'current' => $current,\r\n 'canManage' => ((isset($user->is_acting_admin) && $user->is_acting_admin == 1) ? 1 : 0),\r\n ));\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public function __get($var) {\n\n switch ($var) {\n case 'configuration_array':\n $this->configuration_array = array();\n if ($this->configuration != ''){\n $jsonData = json_decode($this->configuration,true);\n if ($jsonData !== null) {\n $this->configuration_array = $jsonData;\n } else {\n $this->configuration_array = array();\n }\n }\n return $this->configuration_array;\n break;\n\n case 'name_support':\n return $this->name_support = $this->nick;\n break;\n\n case 'has_photo':\n return $this->filename != '';\n break;\n\n case 'photo_path':\n $this->photo_path = ($this->filepath != '' ? '//' . $_SERVER['HTTP_HOST'] . erLhcoreClassSystem::instance()->wwwDir() : erLhcoreClassSystem::instance()->wwwImagesDir() ) .'/'. $this->filepath . $this->filename;\n return $this->photo_path;\n break;\n\n case 'file_path_server':\n return $this->filepath . $this->filename;\n break;\n\n default:\n break;\n }\n }", "label_name": "CWE-116", "label": 15} +{"code": " private function checkAuthenticationTag() {\n if ($this->authentication_tag === $this->calculateAuthenticationTag()) {\n return true;\n } else {\n throw new JOSE_Exception_UnexpectedAlgorithm('Invalid authentication tag');\n }\n }", "label_name": "CWE-200", "label": 10} +{"code": "\tprivate static function thumb($source_path, $thumb_path){\n\t\tini_set('memory_limit', '128M');\n\n\t\t$source_details = getimagesize($source_path);\n\t\t$source_w = $source_details[0];\n\t\t$source_h = $source_details[1];\n\n\t\tif($source_w > $source_h){\n\t\t\t$new_w = self::THUMB_W;\n\t\t\t$new_h = intval($source_h * $new_w / $source_w);\n\t\t} else {\n\t\t\t$new_h = self::THUMB_H;\n\t\t\t$new_w = intval($source_w * $new_h / $source_h);\n\t\t}\n\n\t\tswitch($source_details[2]){\n\t\t\tcase IMAGETYPE_GIF:\n\t\t\t\t$imgt = \"imagegif\";\n\t\t\t\t$imgcreatefrom = \"imagecreatefromgif\";\n\t\t\t\tbreak;\n\n\t\t\tcase IMAGETYPE_JPEG:\n\t\t\t\t$imgt = \"imagejpeg\";\n\t\t\t\t$imgcreatefrom = \"imagecreatefromjpeg\";\n\t\t\t\tbreak;\n\n\t\t\tcase IMAGETYPE_PNG:\n\t\t\t\t$imgt = \"imagepng\";\n\t\t\t\t$imgcreatefrom = \"imagecreatefrompng\";\n\t\t\t\tbreak;\n\n\t\t\tcase IMAGETYPE_WEBP:\n\t\t\t\t$imgt = \"imagewebp\";\n\t\t\t\t$imgcreatefrom = \"imagecreatefromwebp\";\n\t\t\t\tbreak;\n\n\t\t\tcase IMAGETYPE_WBMP:\n\t\t\t\t$imgt = \"imagewbmp\";\n\t\t\t\t$imgcreatefrom = \"imagecreatefromwbmp\";\n\t\t\t\tbreak;\n\n\t\t\tcase IMAGETYPE_BMP:\n\t\t\t\t$imgt = \"imagebmp\";\n\t\t\t\t$imgcreatefrom = \"imagecreatefrombmp\";\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\treturn false;\n\t\t}\n\n\t\t$old_image = $imgcreatefrom($source_path);\n\t\t$new_image = imagecreatetruecolor($new_w, $new_h);\n\t\timagecopyresampled($new_image, $old_image, 0, 0, 0, 0, $new_w, $new_h, $source_w, $source_h);\n\n\t\t$new_image = self::fix_orientation($source_path, $new_image);\n\t\t$old_image = self::fix_orientation($source_path, $old_image);\n\n\t\t$imgt($new_image, $thumb_path);\n\t\t$imgt($old_image, $source_path);\n\t\treturn true;\n\t}", "label_name": "CWE-20", "label": 0} +{"code": " function manage() {\n expHistory::set('viewable', $this->params);\n // $category = new storeCategory();\n // $categories = $category->getFullTree();\n // \n // // foreach($categories as $i=>$val){\n // // if (!empty($this->values) && in_array($val->id,$this->values)) {\n // // $this->tags[$i]->value = true;\n // // } else {\n // // $this->tags[$i]->value = false;\n // // }\n // // $this->tags[$i]->draggable = $this->draggable; \n // // $this->tags[$i]->checkable = $this->checkable; \n // // }\n //\n // $obj = json_encode($categories); \n }", "label_name": "CWE-74", "label": 1} +{"code": " function edit_internalalias() {\r\n $section = isset($this->params['id']) ? $this->section->find($this->params['id']) : new section($this->params);\r\n if ($section->parent == -1) {\r\n notfoundController::handle_not_found();\r\n exit;\r\n } // doesn't work for standalone pages\r\n if (empty($section->id)) {\r\n $section->public = 1;\r\n if (!isset($section->parent)) {\r\n // This is another precaution. The parent attribute\r\n // should ALWAYS be set by the caller.\r\n //FJD - if that's the case, then we should die.\r\n notfoundController::handle_not_authorized();\r\n exit;\r\n //$section->parent = 0;\r\n }\r\n }\r\n assign_to_template(array(\r\n 'section' => $section,\r\n 'glyphs' => self::get_glyphs(),\r\n ));\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public function getDisplayName ($plural=true) {\n return Yii::t('workflow', '{process}', array(\n '{process}' => Modules::displayName($plural, 'Process'),\n ));\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function execute(&$params){\n $options = &$this->config['options'];\n $notif = new Notification;\n $notif->user = $this->parseOption('user', $params);\n $notif->createdBy = 'API';\n $notif->createDate = time();\n // file_put_contents('triggerLog.txt',\"\\n\".$notif->user,FILE_APPEND);\n // if($this->parseOption('type',$params) == 'auto') {\n // if(!isset($params['model']))\n // return false;\n // $notif->modelType = get_class($params['model']);\n // $notif->modelId = $params['model']->id;\n // $notif->type = $this->getNotifType();\n // } else {\n $notif->type = 'custom';\n $notif->text = $this->parseOption('text', $params);\n // }\n\n if ($notif->save()) {\n return array (true, \"\");\n } else {\n return array(false, array_shift($notif->getErrors()));\n }\n\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function clearTags() {\n $this->_tags = array(); // clear tag cache\n\n return (bool) CActiveRecord::model('Tags')->deleteAllByAttributes(array(\n 'type' => get_class($this->getOwner()),\n 'itemId' => $this->getOwner()->id)\n );\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function actionAppendTag() {\n if (isset($_POST['Type'], $_POST['Id'], $_POST['Tag']) &&\n preg_match('/^[\\w\\d_-]+$/', $_POST['Type'])) {\n\n if (!class_exists($_POST['Type'])) {\n echo 'false';\n return;\n }\n $model = X2Model::model($_POST['Type'])->findByPk($_POST['Id']);\n echo $model->addTags($_POST['Tag']);\n exit;\n if ($model !== null && $model->addTags($_POST['Tag'])) {\n echo 'true';\n return;\n }\n }\n echo 'false';\n }", "label_name": "CWE-20", "label": 0} +{"code": "\tpublic function delete() {\n\t global $user;\n\n $count = $this->address->find('count', 'user_id=' . $user->id);\n if($count > 1)\n { \n $address = new address($this->params['id']);\n\t if ($user->isAdmin() || ($user->id == $address->user_id)) {\n if ($address->is_billing)\n {\n $billAddress = $this->address->find('first', 'user_id=' . $user->id . \" AND id != \" . $address->id);\n $billAddress->is_billing = true;\n $billAddress->save();\n }\n if ($address->is_shipping) \n {\n $shipAddress = $this->address->find('first', 'user_id=' . $user->id . \" AND id != \" . $address->id);\n $shipAddress->is_shipping = true;\n $shipAddress->save();\n }\n\t parent::delete();\n\t }\n }\n else\n {\n flash(\"error\", gt(\"You must have at least one address.\"));\n }\n\t expHistory::back();\n\t}", "label_name": "CWE-74", "label": 1} +{"code": " $input = ['name' => 'ldap', 'rootdn_passwd' => $password];", "label_name": "CWE-327", "label": 3} +{"code": " public function autocomplete() {\n return;\n global $db;\n\n $model = $this->params['model'];\n $mod = new $model();\n $srchcol = explode(\",\",$this->params['searchoncol']);\n /*for ($i=0; $i=1) $sql .= \" OR \";\n $sql .= $srchcol[$i].' LIKE \\'%'.$this->params['query'].'%\\'';\n }*/\n // $sql .= ' AND parent_id=0';\n //eDebug($sql);\n \n //$res = $mod->find('all',$sql,'id',25);\n $sql = \"select DISTINCT(p.id), p.title, model, sef_url, f.id as fileid from \".$db->prefix.\"product as p INNER JOIN \".$db->prefix.\"content_expfiles as cef ON p.id=cef.content_id INNER JOIN \".$db->prefix.\"expfiles as f ON cef.expfiles_id = f.id where match (p.title,p.model,p.body) against ('\" . $this->params['query'] . \"') AND p.parent_id=0 order by match (p.title,p.model,p.body) against ('\" . $this->params['query'] . \"') desc LIMIT 25\";\n //$res = $db->selectObjectsBySql($sql);\n //$res = $db->selectObjectBySql('SELECT * FROM `exponent_product`');\n \n $ar = new expAjaxReply(200, gt('Here\\'s the items you wanted'), $res);\n $ar->send();\n }", "label_name": "CWE-74", "label": 1} +{"code": " function columnUpdate($table, $col, $val, $where=1) { \n $res = @mysqli_query($this->connection, \"UPDATE `\" . $this->prefix . \"$table` SET `$col`='\" . $val . \"' WHERE $where\");\n /*if ($res == null)\n return array();\n $objects = array();\n for ($i = 0; $i < mysqli_num_rows($res); $i++)\n $objects[] = mysqli_fetch_object($res);*/\n //return $objects;\n }", "label_name": "CWE-74", "label": 1} +{"code": " static function isSearchable() { return true; }\r", "label_name": "CWE-74", "label": 1} +{"code": " public function getDisplayName ($plural=true) {\n return Yii::t('calendar', 'Calendar');\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function searchAdmin(){\n $criteria = new CDbCriteria;\n return $this->searchBase($criteria);\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function rename() {\n if (!AuthUser::hasPermission('file_manager_rename')) {\n Flash::set('error', __('You do not have sufficient permissions to rename this file or directory.'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n \n // CSRF checks\n if (isset($_POST['csrf_token'])) {\n $csrf_token = $_POST['csrf_token'];\n if (!SecureToken::validateToken($csrf_token, BASE_URL.'plugin/file_manager/rename')) {\n Flash::set('error', __('Invalid CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n }\n else {\n Flash::set('error', __('No CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n\n $data = $_POST['file'];\n\n $data['current_name'] = str_replace('..', '', $data['current_name']);\n $data['new_name'] = str_replace('..', '', $data['new_name']);\n\n // Clean filenames\n $data['new_name'] = preg_replace('/ /', '_', $data['new_name']);\n $data['new_name'] = preg_replace('/[^a-z0-9_\\-\\.]/i', '', $data['new_name']);\n\n $path = substr($data['current_name'], 0, strrpos($data['current_name'], '/'));\n $file = FILES_DIR . '/' . $data['current_name'];\n\n // Check another file doesn't already exist with same name\n if (file_exists(FILES_DIR . '/' . $path . '/' . $data['new_name'])) {\n Flash::set('error', __('A file or directory with that name already exists!'));\n redirect(get_url('plugin/file_manager/browse/' . $path));\n }\n\n if (file_exists($file)) {\n if (!rename($file, FILES_DIR . '/' . $path . '/' . $data['new_name']))\n Flash::set('error', __('Permission denied!'));\n }\n else {\n Flash::set('error', __('File or directory not found!' . $file));\n }\n\n redirect(get_url('plugin/file_manager/browse/' . $path));\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function save_change_password() {\n global $user;\n\n $isuser = ($this->params['uid'] == $user->id) ? 1 : 0;\n\n if (!$user->isAdmin() && !$isuser) {\n flash('error', gt('You do not have permissions to change this users password.'));\n expHistory::back();\n }\n\n if (($isuser && empty($this->params['password'])) || (!empty($this->params['password']) && $user->password != user::encryptPassword($this->params['password']))) {\n flash('error', gt('The current password you entered is not correct.'));\n expHistory::returnTo('editable');\n }\n //eDebug($user);\n $u = new user($this->params['uid']);\n\n $ret = $u->setPassword($this->params['new_password1'], $this->params['new_password2']);\n //eDebug($u, true);\n if (is_string($ret)) {\n flash('error', $ret);\n expHistory::returnTo('editable');\n } else {\n $params = array();\n $params['is_admin'] = !empty($u->is_admin);\n $params['is_acting_admin'] = !empty($u->is_acting_admin);\n $u->update($params);\n }\n\n if (!$isuser) {\n flash('message', gt('The password for') . ' ' . $u->username . ' ' . gt('has been changed.'));\n } else {\n $user->password = $u->password;\n flash('message', gt('Your password has been changed.'));\n }\n expHistory::back();\n }", "label_name": "CWE-74", "label": 1} +{"code": " public function create_file() {\n if (!AuthUser::hasPermission('file_manager_mkfile')) {\n Flash::set('error', __('You do not have sufficient permissions to create a file.'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n \n // CSRF checks\n if (isset($_POST['csrf_token'])) {\n $csrf_token = $_POST['csrf_token'];\n if (!SecureToken::validateToken($csrf_token, BASE_URL.'plugin/file_manager/create_file')) {\n Flash::set('error', __('Invalid CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n }\n else {\n Flash::set('error', __('No CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n\n $data = $_POST['file'];\n\n $path = str_replace('..', '', $data['path']);\n $filename = str_replace('..', '', $data['name']);\n $file = FILES_DIR . DS . $path . DS . $filename;\n\n if (file_put_contents($file, '') !== false) {\n $mode = Plugin::getSetting('filemode', 'file_manager');\n chmod($file, octdec($mode));\n } else {\n Flash::set('error', __('File :name has not been created!', array(':name' => $filename)));\n }\n redirect(get_url('plugin/file_manager/browse/' . $path));\n }", "label_name": "CWE-20", "label": 0} +{"code": "\tfunction formatValue( $name, $value ) {\n\t\t$row = $this->mCurrentRow;\n\n\t\t$wiki = $row->files_dbname;\n\n\t\tswitch ( $name ) {\n\t\t\tcase 'files_timestamp':\n\t\t\t\t$formatted = htmlspecialchars( $this->getLanguage()->userTimeAndDate( $row->files_timestamp, $this->getUser() ) );\n\t\t\t\tbreak;\n\t\t\tcase 'files_dbname':\n\t\t\t\t$formatted = $row->files_dbname;\n\t\t\t\tbreak;\n\t\t\tcase 'files_url':\n\t\t\t\t$formatted = \"files_url}\\\" style=\\\"width:135px;height:135px;\\\">\";\n\t\t\t\tbreak;\n\t\t\tcase 'files_name':\n\t\t\t\t$formatted = \"files_page}\\\">{$row->files_name}\";\n\t\t\t\tbreak;\n\t\t\tcase 'files_user':\n\t\t\t\t$formatted = \"files_user}\\\">{$row->files_user}\";\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\t$formatted = \"Unable to format $name\";\n\t\t\t\tbreak;\n\t\t}\n\n\t\treturn $formatted;\n\t}", "label_name": "CWE-20", "label": 0} +{"code": " public function approve_toggle() {\n global $history;\n \n if (empty($this->params['id'])) return;\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n $require_login = empty($this->params['require_login']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];\n $require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];\n $require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n $notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];\n \n \n $simplenote = new expSimpleNote($this->params['id']);\n $simplenote->approved = $simplenote->approved == 1 ? 0 : 1;\n $simplenote->save();\n \n $lastUrl = makelink($history->history[$history->history['lasts']['type']][count($history->history[$history->history['lasts']['type']])-1]['params']);\n if (!empty($this->params['tab']))\n {\n $lastUrl .= \"#\".$this->params['tab'];\n }\n redirect_to($lastUrl);\n }", "label_name": "CWE-74", "label": 1} +{"code": "\tprivate function _notuses( $option ) {\n\t\tif ( count( $option ) > 0 ) {\n\t\t\t$where = $this->tableNames['page'] . '.page_id NOT IN (SELECT ' . $this->tableNames['templatelinks'] . '.tl_from FROM ' . $this->tableNames['templatelinks'] . ' WHERE (';\n\t\t\t$ors = [];\n\t\t\tforeach ( $option as $linkGroup ) {\n\t\t\t\tforeach ( $linkGroup as $link ) {\n\t\t\t\t\t$_or = '(' . $this->tableNames['templatelinks'] . '.tl_namespace=' . intval( $link->getNamespace() );\n\t\t\t\t\tif ( $this->parameters->getParameter( 'ignorecase' ) ) {\n\t\t\t\t\t\t$_or .= ' AND LOWER(CAST(' . $this->tableNames['templatelinks'] . '.tl_title AS char))=LOWER(' . $this->DB->addQuotes( $link->getDbKey() ) . '))';\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$_or .= ' AND ' . $this->tableNames['templatelinks'] . '.tl_title=' . $this->DB->addQuotes( $link->getDbKey() ) . ')';\n\t\t\t\t\t}\n\t\t\t\t\t$ors[] = $_or;\n\t\t\t\t}\n\t\t\t}\n\t\t\t$where .= implode( ' OR ', $ors ) . '))';\n\t\t}\n\t\t$this->addWhere( $where );\n\t}", "label_name": "CWE-400", "label": 2} +{"code": "function adodb_addslashes($s)\n{\n\t$len = strlen($s);\n\tif ($len == 0) return \"''\";\n\tif (strncmp($s,\"'\",1) === 0 && substr($s,$len-1) == \"'\") return $s; // already quoted\n\n\treturn \"'\".addslashes($s).\"'\";\n}", "label_name": "CWE-287", "label": 4} +{"code": " static function description() {\n return gt(\"This module is for managing categories in your store.\");\n }", "label_name": "CWE-74", "label": 1} +{"code": " public function addTags($tags) {\n $result = false;\n $addedTags = array();\n\n foreach ((array) $tags as $tagName) {\n if (empty($tagName))\n continue;\n if (!in_array($tagName, $this->getTags())) { // check for duplicate tag\n $tag = new Tags;\n $tag->tag = '#' . ltrim($tagName, '#');\n $tag->itemId = $this->getOwner()->id;\n $tag->type = get_class($this->getOwner());\n $tag->taggedBy = Yii::app()->getSuName();\n $tag->timestamp = time();\n $tag->itemName = $this->getOwner()->name;\n\n if ($tag->save()) {\n $this->_tags[] = $tag->tag; // update tag cache\n $addedTags[] = $tagName;\n $result = true;\n } else {\n throw new CHttpException(422, 'Failed saving tag due to errors: ' . json_encode($tag->errors));\n }\n }\n }\n if ($this->flowTriggersEnabled)\n X2Flow::trigger('RecordTagAddTrigger', array(\n 'model' => $this->getOwner(),\n 'tags' => $addedTags,\n ));\n\n return $result;\n }", "label_name": "CWE-20", "label": 0} +{"code": " foreach ($page as $pageperm) {\r\n if (!empty($pageperm['manage'])) return true;\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic function setTableSortMethod($method = null) {\n\t\t$this->tableSortMethod = $method === null ? 'standard' : $method;\n\t}", "label_name": "CWE-400", "label": 2} +{"code": "\t\timagepng( $im_crop, $output );\n\t}\n\n\t$new_avatar = false;\n\n\tif ( file_exists( $output ) ) {\n\n\t\t$old_avatar = get_user_meta( $user_id, '_lp_profile_picture', true );\n\n\t\tif ( file_exists( $upload_dir['basedir'] . '/' . $old_avatar ) ) {\n\t\t\t@unlink( $upload_dir['basedir'] . '/' . $old_avatar );\n\t\t}\n\n\t\t$new_avatar = preg_replace( '!^/!', '', $upload_dir['subdir'] ) . '/' . $newname;\n\t\tupdate_user_meta( $user_id, '_lp_profile_picture', $new_avatar );\n\t\tupdate_user_meta( $user_id, '_lp_profile_picture_changed', 'yes' );\n\n\t\t$new_avatar = $upload_dir['baseurl'] . '/' . $new_avatar;\n\t}\n\n\t@unlink( $path );\n\n\treturn $new_avatar;\n}", "label_name": "CWE-610", "label": 17} +{"code": " $db->insertObject($obj, 'expeAlerts_subscribers');\n }\n \n $count = count($this->params['ealerts']);\n \n if ($count > 0) {\n flash('message', gt(\"Your subscriptions have been updated. You are now subscriber to\").\" \".$count.' '.gt('E-Alerts.'));\n } else {\n flash('error', gt(\"You have been unsubscribed from all E-Alerts.\"));\n }\n \n expHistory::back();\n }", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic function check(&$params){\n $tags = $this->config['options']['tags']['value'];\n $tags = is_array($tags) ? $tags : Tags::parseTags($tags, true);\n if(!empty($tags) && isset($params['tags'])){ // Check passed params to be sure they're set\n if(!is_array($params['tags'])){\n $params['tags'] = explode(',', $params['tags']);\n }\n $params['tags'] = array_map(function($item){ \n return preg_replace('/^#/','', $item); \n }, $params['tags']);\n\n // must have at least 1 tag in the list:\n if(count(array_intersect($params['tags'], $tags)) > 0){\n return $this->checkConditions($params);\n }else{\n return array(false, Yii::t('studio','No tags on the record matched those in the tag trigger criteria.'));\n }\n }else{ // config is invalid or record has no tags (tags are not optional)\n return array(false, empty($tags) ? Yii::t('studio','No tags in the trigger criteria!') : Yii::t('studio','Tags parameter missing!'));\n }\n }", "label_name": "CWE-20", "label": 0} +{"code": "\tpublic static function onLoadExtensionSchemaUpdates( DatabaseUpdater $updater ) {\n\t\t$config = MediaWikiServices::getInstance()->getConfigFactory()->makeConfig( 'globalnewfiles' );\n\n\t\tif ( $config->get( 'CreateWikiDatabase' ) === $config->get( 'DBname' ) ) {\n\t\t\t$updater->addExtensionTable(\n\t\t\t\t'gnf_files',\n\t\t\t\t__DIR__ . '/../sql/gnf_files.sql'\n\t\t\t);\n\n\t\t\t$updater->modifyExtensionField(\n\t\t\t\t'gnf_files',\n\t\t\t\t'files_timestamp',\n\t\t\t\t__DIR__ . '/../sql/patches/patch-gnf_files-binary.sql' \n\t\t\t);\n\n\t\t\t$updater->modifyTable(\n \t\t\t\t'gnf_files',\n \t\t\t\t__DIR__ . '/../sql/patches/patch-gnf_files-add-indexes.sql',\n\t\t\t\ttrue\n \t\t\t);\n\t\t}\n\n\t\treturn true;\n\t}", "label_name": "CWE-20", "label": 0} +{"code": " $newret = recyclebin::restoreFromRecycleBin($iLoc, $page_id);\r\n if (!empty($newret)) $ret .= $newret . '
';\r\n if ($iLoc->mod == 'container') {\r\n $ret .= scan_container($container->internal, $page_id);\r\n }\r\n }\r\n return $ret;\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public static function validateServer($path, $values)\n {\n $result = array(\n 'Server' => '',\n 'Servers/1/user' => '',\n 'Servers/1/SignonSession' => '',\n 'Servers/1/SignonURL' => ''\n );\n $error = false;\n if ($values['Servers/1/auth_type'] == 'config'\n && empty($values['Servers/1/user'])\n ) {\n $result['Servers/1/user'] = __(\n 'Empty username while using [kbd]config[/kbd] authentication method!'\n );\n $error = true;\n }\n if ($values['Servers/1/auth_type'] == 'signon'\n && empty($values['Servers/1/SignonSession'])\n ) {\n $result['Servers/1/SignonSession'] = __(\n 'Empty signon session name '\n . 'while using [kbd]signon[/kbd] authentication method!'\n );\n $error = true;\n }\n if ($values['Servers/1/auth_type'] == 'signon'\n && empty($values['Servers/1/SignonURL'])\n ) {\n $result['Servers/1/SignonURL'] = __(\n 'Empty signon URL while using [kbd]signon[/kbd] authentication '\n . 'method!'\n );\n $error = true;\n }\n\n if (! $error && $values['Servers/1/auth_type'] == 'config') {\n $password = $values['Servers/1/nopassword'] ? null\n : $values['Servers/1/password'];\n $test = static::testDBConnection(\n $values['Servers/1/connect_type'],\n $values['Servers/1/host'],\n $values['Servers/1/port'],\n $values['Servers/1/socket'],\n $values['Servers/1/user'],\n $password,\n 'Server'\n );\n if ($test !== true) {\n $result = array_merge($result, $test);\n }\n }\n return $result;\n }", "label_name": "CWE-200", "label": 10} +{"code": "\tfunction token($str) {\n\t\t$fw=$this->fw;\n\t\t$str=trim(preg_replace('/\\{\\{(.+?)\\}\\}/s',trim('\\1'),\n\t\t\t$fw->compile($str)));\n\t\tif (preg_match('/^(.+)(?split(trim($parts[2],\"\\xC2\\xA0\")) as $func)\n\t\t\t\t$str=((empty($this->filter[$cmd=$func]) &&\n\t\t\t\t\tfunction_exists($cmd)) ||\n\t\t\t\t\tis_string($cmd=$this->filter($func)))?\n\t\t\t\t\t$cmd.'('.$str.')':\n\t\t\t\t\t'Base::instance()->'.\n\t\t\t\t\t\t'call($this->filter(\\''.$func.'\\'),['.$str.'])';\n\t\t}\n\t\treturn $str;\n\t}", "label_name": "CWE-20", "label": 0} +{"code": " public function testLogoutDelete()\n {\n $GLOBALS['cfg']['Server']['auth_swekey_config'] = '';\n $GLOBALS['cfg']['CaptchaLoginPrivateKey'] = '';\n $GLOBALS['cfg']['CaptchaLoginPublicKey'] = '';\n $_REQUEST['old_usr'] = 'pmaolduser';\n $GLOBALS['cfg']['LoginCookieDeleteAll'] = true;\n $GLOBALS['cfg']['Servers'] = array(1);\n\n $_COOKIE['pmaPass-0'] = 'test';\n\n $this->object->authCheck();\n\n $this->assertFalse(\n isset($_COOKIE['pmaPass-0'])\n );\n }", "label_name": "CWE-200", "label": 10} +{"code": "\tprotected function parseImageUrlWithPath( $article ) {\n\t\t$imageUrl = '';\n\t\tif ( $article instanceof \\DPL\\Article ) {\n\t\t\tif ( $article->mNamespace == NS_FILE ) {\n\t\t\t\t// calculate URL for existing images\n\t\t\t\t// $img = Image::newFromName($article->mTitle->getText());\n\t\t\t\t$img = wfFindFile( \\Title::makeTitle( NS_FILE, $article->mTitle->getText() ) );\n\t\t\t\tif ( $img && $img->exists() ) {\n\t\t\t\t\t$imageUrl = $img->getURL();\n\t\t\t\t} else {\n\t\t\t\t\t$fileTitle = \\Title::makeTitleSafe( NS_FILE, $article->mTitle->getDBKey() );\n\t\t\t\t\t$imageUrl = \\RepoGroup::singleton()->getLocalRepo()->newFile( $fileTitle )->getPath();\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t$title = \\Title::newfromText( 'File:' . $article );\n\t\t\tif ( $title !== null ) {\n\t\t\t\t$fileTitle = \\Title::makeTitleSafe( 6, $title->getDBKey() );\n\t\t\t\t$imageUrl = \\RepoGroup::singleton()->getLocalRepo()->newFile( $fileTitle )->getPath();\n\t\t\t}\n\t\t}\n\n\t\t//@TODO: Check this preg_replace. Probably only works for stock file repositories. --Alexia\n\t\t$imageUrl = preg_replace( '~^.*images/(.*)~', '\\1', $imageUrl );\n\n\t\treturn $imageUrl;\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " public function actionGetItems(){\n $sql = 'SELECT id, name as value, subject FROM x2_bug_reports WHERE name LIKE :qterm ORDER BY name ASC';\n $command = Yii::app()->db->createCommand($sql);\n $qterm = $_GET['term'].'%';\n $command->bindParam(\":qterm\", $qterm, PDO::PARAM_STR);\n $result = $command->queryAll();\n echo CJSON::encode($result); exit;\n }", "label_name": "CWE-20", "label": 0} +{"code": "\tpublic function getPurchaseOrderByJSON() {\n\n\t\tif(!empty($this->params['vendor'])) {\n\t\t\t$purchase_orders = $this->purchase_order->find('all', 'vendor_id=' . $this->params['vendor']);\n\t\t} else {\n\t\t\t$purchase_orders = $this->purchase_order->find('all');\n\t\t}\n\n\t\techo json_encode($purchase_orders);\n\t}", "label_name": "CWE-20", "label": 0} +{"code": "\tprivate function _allrevisionssince( $option ) {\n\t\t$this->addTable( 'revision_actor_temp', 'rev' );\n\t\t$this->addSelect(\n\t\t\t[\n\t\t\t\t'rev.revactor_rev',\n\t\t\t\t'rev.revactor_timestamp'\n\t\t\t]\n\t\t);\n\t\t$this->addOrderBy( 'rev.revactor_rev' );\n\t\t$this->setOrderDir( 'DESC' );\n\t\t$this->addWhere(\n\t\t\t[\n\t\t\t\t$this->tableNames['page'] . '.page_id = rev.revactor_page',\n\t\t\t\t'rev.revactor_timestamp >= ' . $this->convertTimestamp( $option )\n\t\t\t]\n\t\t);\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " function searchByModelForm() {\n // get the search terms\n $terms = $this->params['search_string'];\n\n $sql = \"model like '%\" . $terms . \"%'\";\n\n $limit = !empty($this->config['limit']) ? $this->config['limit'] : 10;\n $page = new expPaginator(array(\n 'model' => 'product',\n 'where' => $sql,\n 'limit' => !empty($this->config['pagination_default']) ? $this->config['pagination_default'] : $limit,\n 'order' => 'title',\n 'dir' => 'DESC',\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller' => $this->params['controller'],\n 'action' => $this->params['action'],\n 'columns' => array(\n gt('Model #') => 'model',\n gt('Product Name') => 'title',\n gt('Price') => 'base_price'\n ),\n ));\n\n assign_to_template(array(\n 'page' => $page,\n 'terms' => $terms\n ));\n }", "label_name": "CWE-20", "label": 0} +{"code": " public static function checkPermissions($permission,$location) {\r\n global $exponent_permissions_r, $router;\r\n\r\n // only applies to the 'manage' method\r\n if (empty($location->src) && empty($location->int) && (!empty($router->params['action']) && $router->params['action'] == 'manage') || strpos($router->current_url, 'action=manage') !== false) {\r\n if (!empty($exponent_permissions_r['navigation'])) foreach ($exponent_permissions_r['navigation'] as $page) {\r\n foreach ($page as $pageperm) {\r\n if (!empty($pageperm['manage'])) return true;\r\n }\r\n }\r\n }\r\n return false;\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public function Quit($close_on_error = true) {\n $this->error = null; // so there is no confusion\n\n if(!$this->connected()) {\n $this->error = array(\n \"error\" => \"Called Quit() without being connected\");\n return false;\n }\n\n // send the quit command to the server\n fputs($this->smtp_conn,\"quit\" . $this->CRLF);\n\n // get any good-bye messages\n $byemsg = $this->get_lines();\n\n if($this->do_debug >= 2) {\n $this->edebug(\"SMTP -> FROM SERVER:\" . $byemsg . $this->CRLF . '
');\n }\n\n $rval = true;\n $e = null;\n\n $code = substr($byemsg,0,3);\n if($code != 221) {\n // use e as a tmp var cause Close will overwrite $this->error\n $e = array(\"error\" => \"SMTP server rejected quit command\",\n \"smtp_code\" => $code,\n \"smtp_rply\" => substr($byemsg,4));\n $rval = false;\n if($this->do_debug >= 1) {\n $this->edebug(\"SMTP -> ERROR: \" . $e[\"error\"] . \": \" . $byemsg . $this->CRLF . '
');\n }\n }\n\n if(empty($e) || $close_on_error) {\n $this->Close();\n }\n\n return $rval;\n }", "label_name": "CWE-20", "label": 0} +{"code": "\tfunction manage() {\n\t global $db;\n\t \n\t expHistory::set('manageable', $this->params);\n//\t $classes = array();\n $dir = BASE.\"framework/modules/ecommerce/billingcalculators\";\n if (is_readable($dir)) {\n $dh = opendir($dir);\n while (($file = readdir($dh)) !== false) {\n if (is_file(\"$dir/$file\") && substr(\"$dir/$file\", -4) == \".php\") {\n include_once(\"$dir/$file\");\n $classname = substr($file, 0, -4);\n $id = $db->selectValue('billingcalculator', 'id', 'calculator_name=\"'.$classname.'\"');\n if (empty($id)) {\n// $calobj = null;\n $calcobj = new $classname();\n if ($calcobj->isSelectable() == true) {\n $obj = new billingcalculator(array(\n 'title'=>$calcobj->name(),\n// 'user_title'=>$calcobj->title,\n 'body'=>$calcobj->description(), \n 'calculator_name'=>$classname,\n 'enabled'=>false));\n $obj->save();\n }\n }\n }\n }\n }\n \n $bcalc = new billingcalculator();\n $calculators = $bcalc->find('all');\n assign_to_template(array(\n 'calculators'=>$calculators\n ));\n\t}", "label_name": "CWE-74", "label": 1} +{"code": " public function IsHTML($ishtml = true) {\n if ($ishtml) {\n $this->ContentType = 'text/html';\n } else {\n $this->ContentType = 'text/plain';\n }\n }", "label_name": "CWE-20", "label": 0} +{"code": " static function description() {\r\n return \"Manage events and schedules, and optionally publish them.\";\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public function testAuthCheckToken()\n {\n $GLOBALS['cfg']['Server']['SignonURL'] = 'http://phpmyadmin.net/SignonURL';\n $GLOBALS['cfg']['Server']['SignonSession'] = 'session123';\n $GLOBALS['cfg']['Server']['host'] = 'localhost';\n $GLOBALS['cfg']['Server']['port'] = '80';\n $GLOBALS['cfg']['Server']['user'] = 'user';\n $GLOBALS['cfg']['Server']['SignonScript'] = '';\n $_COOKIE['session123'] = true;\n $_REQUEST['old_usr'] = 'oldUser';\n $_SESSION['PMA_single_signon_user'] = 'user123';\n $_SESSION['PMA_single_signon_password'] = 'pass123';\n $_SESSION['PMA_single_signon_host'] = 'local';\n $_SESSION['PMA_single_signon_port'] = '12';\n $_SESSION['PMA_single_signon_cfgupdate'] = array('foo' => 'bar');\n $_SESSION['PMA_single_signon_token'] = 'pmaToken';\n $sessionName = session_name();\n $sessionID = session_id();\n\n $this->assertFalse(\n $this->object->authCheck()\n );\n\n $this->assertEquals(\n array(\n 'SignonURL' => 'http://phpmyadmin.net/SignonURL',\n 'SignonScript' => '',\n 'SignonSession' => 'session123',\n 'host' => 'local',\n 'port' => '12',\n 'user' => 'user',\n 'foo' => 'bar'\n ),\n $GLOBALS['cfg']['Server']\n );\n\n $this->assertEquals(\n 'pmaToken',\n $_SESSION[' PMA_token ']\n );\n\n $this->assertEquals(\n $sessionName,\n session_name()\n );\n\n $this->assertEquals(\n $sessionID,\n session_id()\n );\n\n $this->assertFalse(\n isset($_SESSION['LAST_SIGNON_URL'])\n );\n }", "label_name": "CWE-200", "label": 10} +{"code": " protected function assertNoPHPErrors () {\n\t\t$this->assertElementNotPresent('css=.xdebug-error');\n\t\t$this->assertElementNotPresent('css=#x2-php-error');\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function confirm()\n {\n $project = $this->getProject();\n $category = $this->getCategory();\n\n $this->response->html($this->helper->layout->project('category/remove', array(\n 'project' => $project,\n 'category' => $category,\n )));\n }", "label_name": "CWE-200", "label": 10} +{"code": " public function testRenderWithTrustedHeaderDisabled()\n {\n Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, '');\n\n $strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest(Request::create('/')));\n $this->assertSame('foo', $strategy->render('/', Request::create('/'))->getContent());\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function confirm()\n {\n $project = $this->getProject();\n\n $this->response->html($this->helper->layout->project('column/remove', array(\n 'column' => $this->columnModel->getById($this->request->getIntegerParam('column_id')),\n 'project' => $project,\n )));\n }", "label_name": "CWE-200", "label": 10} +{"code": "\tpublic function test_valid_comment_0_content() {\n\t\t$result = $this->myxmlrpcserver->wp_newComment(\n\t\t\tarray(\n\t\t\t\t1,\n\t\t\t\t'administrator',\n\t\t\t\t'administrator',\n\t\t\t\tself::$post->ID,\n\t\t\t\tarray(\n\t\t\t\t\t'content' => '0',\n\t\t\t\t),\n\t\t\t)\n\t\t);\n\n\t\t$this->assertNotIXRError( $result );\n\t}", "label_name": "CWE-862", "label": 8} +{"code": " public function confirm()\n {\n $task = $this->getTask();\n $link_id = $this->request->getIntegerParam('link_id');\n $link = $this->taskExternalLinkModel->getById($link_id);\n\n if (empty($link)) {\n throw new PageNotFoundException();\n }\n\n $this->response->html($this->template->render('task_external_link/remove', array(\n 'link' => $link,\n 'task' => $task,\n )));\n }", "label_name": "CWE-200", "label": 10} +{"code": " function checkPassword($username, $password)\n {\n $doUser = OA_Dal::factoryDO('users');\n $doUser->username = strtolower($username);\n $doUser->password = md5($password);\n $doUser->find();\n\n if ($doUser->fetch()) {\n return $doUser;\n } else {\n return false;\n }\n }", "label_name": "CWE-287", "label": 4} +{"code": " $sloc = expCore::makeLocation('navigation', null, $section->id);\r\n // remove any manage permissions for this page and it's children\r\n // $db->delete('userpermission', \"module='navigationController' AND internal=\".$section->id);\r\n // $db->delete('grouppermission', \"module='navigationController' AND internal=\".$section->id);\r\n foreach ($allusers as $uid) {\r\n $u = user::getUserById($uid);\r\n expPermissions::grant($u, 'manage', $sloc);\r\n }\r\n foreach ($allgroups as $gid) {\r\n $g = group::getGroupById($gid);\r\n expPermissions::grantGroup($g, 'manage', $sloc);\r\n }\r\n }\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public function delete() {\n if (!AuthUser::hasPermission('file_manager_delete')) {\n Flash::set('error', __('You do not have sufficient permissions to delete a file or directory.'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n\n $paths = func_get_args();\n\n $file = urldecode(join('/', $paths));\n \n // CSRF checks\n if (isset($_GET['csrf_token'])) {\n $csrf_token = $_GET['csrf_token'];\n if (!SecureToken::validateToken($csrf_token, BASE_URL.'plugin/file_manager/delete/'.$file)) {\n Flash::set('error', __('Invalid CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n }\n else {\n Flash::set('error', __('No CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n\n $file = FILES_DIR . '/' . str_replace('..', '', $file);\n $filename = array_pop($paths);\n $paths = join('/', $paths);\n\n if (is_file($file)) {\n if (!unlink($file))\n Flash::set('error', __('Permission denied!'));\n }\n else {\n if (!$this->_rrmdir($file))\n Flash::set('error', __('Permission denied!'));\n }\n\n redirect(get_url('plugin/file_manager/browse/' . $paths));\n }", "label_name": "CWE-20", "label": 0} +{"code": "\tpublic function __construct( \\DPL\\Parameters $parameters, \\Parser $parser ) {\n\t\t$this->setHeadListAttributes( $parameters->getParameter( 'hlistattr' ) );\n\t\t$this->setHeadItemAttributes( $parameters->getParameter( 'hitemattr' ) );\n\t\t$this->setListAttributes( $parameters->getParameter( 'listattr' ) );\n\t\t$this->setItemAttributes( $parameters->getParameter( 'itemattr' ) );\n\t\t$this->setDominantSectionCount( $parameters->getParameter( 'dominantsection' ) );\n\t\t$this->setTemplateSuffix( $parameters->getParameter( 'defaulttemplatesuffix' ) );\n\t\t$this->setTrimIncluded( $parameters->getParameter( 'includetrim' ) );\n\t\t$this->setTableSortColumn( $parameters->getParameter( 'tablesortcol' ) );\n\t\t$this->setTableSortMethod($parameters->getParameter('tablesortmethod'));\n\t\t$this->setTitleMaxLength( $parameters->getParameter( 'titlemaxlen' ) );\n\t\t$this->setEscapeLinks( $parameters->getParameter( 'escapelinks' ) );\n\t\t$this->setSectionSeparators( $parameters->getParameter( 'secseparators' ) );\n\t\t$this->setMultiSectionSeparators( $parameters->getParameter( 'multisecseparators' ) );\n\t\t$this->setIncludePageText( $parameters->getParameter( 'incpage' ) );\n\t\t$this->setIncludePageMaxLength( $parameters->getParameter( 'includemaxlen' ) );\n\t\t$this->setPageTextMatch( (array)$parameters->getParameter( 'seclabels' ) );\n\t\t$this->setPageTextMatchRegex( (array)$parameters->getParameter( 'seclabelsmatch' ) );\n\t\t$this->setPageTextMatchNotRegex( (array)$parameters->getParameter( 'seclabelsnotmatch' ) );\n\t\t$this->setIncludePageParsed( $parameters->getParameter( 'incparsed' ) );\n\t\t$this->parameters = $parameters;\n\t\t$this->parser = clone $parser;\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " $files[$key]->save();\n }\n \n// eDebug($files,true);\n }", "label_name": "CWE-74", "label": 1} +{"code": " public function getLayout(){\n $layout = $this->getAttribute('layout');\n\n $initLayout = $this->initLayout();\n\n if(!$layout){ // layout hasn't been initialized?\n $layout = $initLayout;\n $this->layout = json_encode($layout);\n $this->update(array('layout'));\n }else{\n $layout = json_decode($layout, true); // json to associative array\n $this->addRemoveLayoutElements('center', $layout, $initLayout);\n $this->addRemoveLayoutElements('left', $layout, $initLayout);\n $this->addRemoveLayoutElements('right', $layout, $initLayout);\n }\n\n return $layout;\n }", "label_name": "CWE-20", "label": 0} +{"code": " public static function navtojson() {\r\n return json_encode(self::navhierarchy());\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": "\t\t\t$iloc = expUnserialize($container->internal);\n\t\t\tif ($db->selectObject('sectionref',\"module='\".$iloc->mod.\"' AND source='\".$iloc->src.\"'\") == null) {\n\t\t\t// There is no sectionref for this container. Populate sectionref\n if ($container->external != \"N;\") {\n $newSecRef = new stdClass();\n $newSecRef->module = $iloc->mod;\n $newSecRef->source = $iloc->src;\n $newSecRef->internal = '';\n $newSecRef->refcount = 1;\n// $newSecRef->is_original = 1;\n\t\t\t\t\t$eloc = expUnserialize($container->external);\n//\t\t\t\t\t$section = $db->selectObject('sectionref',\"module='containermodule' AND source='\".$eloc->src.\"'\");\n $section = $db->selectObject('sectionref',\"module='container' AND source='\".$eloc->src.\"'\");\n\t\t\t\t\tif (!empty($section)) {\n\t\t\t\t\t\t$newSecRef->section = $section->id;\n\t\t\t\t\t\t$db->insertObject($newSecRef,\"sectionref\");\n\t\t\t\t\t\t$missing_sectionrefs[] = gt(\"Missing sectionref for container replaced\").\": \".$iloc->mod.\" - \".$iloc->src.\" - PageID #\".$section->id;\n\t\t\t\t\t} else {\n $db->delete('container','id=\"'.$container->id.'\"');\n $missing_sectionrefs[] = gt(\"Cant' find the container page for container\").\": \".$iloc->mod.\" - \".$iloc->src.' - '.gt('deleted');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n assign_to_template(array(\n 'missing_sectionrefs'=>$missing_sectionrefs,\n ));\n\t}", "label_name": "CWE-74", "label": 1} +{"code": "\tprivate function _maxrevisions( $option ) {\n\t\t$this->addWhere( \"((SELECT count(rev_aux3.revactor_page) FROM {$this->tableNames['revision_actor_temp']} AS rev_aux3 WHERE rev_aux3.revactor_page = {$this->tableNames['page']}.page_id) <= {$option})\" );\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " public function confirm()\n {\n $task = $this->getTask();\n $comment = $this->getComment();\n\n $this->response->html($this->template->render('comment/remove', array(\n 'comment' => $comment,\n 'task' => $task,\n 'title' => t('Remove a comment')\n )));\n }", "label_name": "CWE-200", "label": 10} +{"code": " protected function checkMaintenanceMode()\n {\n if (Yii::$app->settings->get('maintenanceMode')) {\n if (!Yii::$app->user->isGuest) {\n Yii::$app->user->logout();\n Yii::$app->getView()->warn(Yii::t('error', 'Maintenance mode activated: You have been automatically logged out and will no longer have access the platform until the maintenance has been completed.'));\n }\n return Yii::$app->getResponse()->redirect(['/user/auth/login']);\n }\n }", "label_name": "CWE-863", "label": 11} +{"code": " fwrite(STDERR, sprintf(\"%2d %s ==> %s\\n\", $i + 1, $test, var_export($result, true)));", "label_name": "CWE-330", "label": 12} +{"code": " public function actionPublishPost() {\n $post = new Events;\n // $user = $this->loadModel($id);\n if (isset($_POST['text']) && $_POST['text'] != \"\") {\n $post->text = $_POST['text'];\n $post->visibility = $_POST['visibility'];\n if (isset($_POST['associationId']))\n $post->associationId = $_POST['associationId'];\n //$soc->attributes = $_POST['Social'];\n //die(var_dump($_POST['Social']));\n $post->user = Yii::app()->user->getName();\n $post->type = 'feed';\n $post->subtype = $_POST['subtype'];\n $post->lastUpdated = time();\n $post->timestamp = time();\n if ($post->save()) {\n if (!empty($post->associationId) && $post->associationId != Yii::app()->user->getId()) {\n\n $notif = new Notification;\n\n $notif->type = 'social_post';\n $notif->createdBy = $post->user;\n $notif->modelType = 'Profile';\n $notif->modelId = $post->associationId;\n\n $notif->user = Yii::app()->db->createCommand()\n ->select('username')\n ->from('x2_users')\n ->where('id=:id', array(':id' => $post->associationId))\n ->queryScalar();\n\n // $prof = X2Model::model('Profile')->findByAttributes(array('username'=>$post->user));\n // $notif->text = \"$prof->fullName posted on your profile.\";\n // $notif->record = \"profile:$prof->id\";\n // $notif->viewed = 0;\n $notif->createDate = time();\n // $subject=X2Model::model('Profile')->findByPk($id);\n // $notif->user = $subject->username;\n $notif->save();\n }\n }\n }\n }", "label_name": "CWE-20", "label": 0} +{"code": "\t\tpublic function createTag($name, $options = NULL)\n\t\t{\n\t\t\t$this->run('tag', $options, $name);\n\t\t\treturn $this;\n\t\t}", "label_name": "CWE-77", "label": 14} +{"code": " public function search() {\n// global $db, $user;\n global $db;\n\n $sql = \"select DISTINCT(a.id) as id, a.firstname as firstname, a.middlename as middlename, a.lastname as lastname, a.organization as organization, a.email as email \";\n $sql .= \"from \" . $db->prefix . \"addresses as a \"; //R JOIN \" . \n //$db->prefix . \"billingmethods as bm ON bm.addresses_id=a.id \";\n $sql .= \" WHERE match (a.firstname,a.lastname,a.email,a.organization) against ('\" . $this->params['query'] .\n \"*' IN BOOLEAN MODE) \";\n $sql .= \"order by match (a.firstname,a.lastname,a.email,a.organization) against ('\" . $this->params['query'] . \"*' IN BOOLEAN MODE) ASC LIMIT 12\";\n $res = $db->selectObjectsBySql($sql);\n foreach ($res as $key=>$record) {\n $res[$key]->title = $record->firstname . ' ' . $record->lastname;\n }\n //eDebug($sql);\n $ar = new expAjaxReply(200, gt('Here\\'s the items you wanted'), $res);\n $ar->send();\n }", "label_name": "CWE-74", "label": 1} +{"code": " static function isSearchable() {\r\n return true;\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public function confirm() {\n global $db;\n \n // make sure we have what we need.\n if (empty($this->params['key'])) expQueue::flashAndFlow('error', gt('The security key for account was not supplied.'));\n if (empty($this->params['id'])) expQueue::flashAndFlow('error', gt('The subscriber id for account was not supplied.'));\n \n // verify the id/key pair \n $id = $db->selectValue('subscribers','id', 'id='.$this->params['id'].' AND hash=\"'.$this->params['key'].'\"');\n if (empty($id)) expQueue::flashAndFlow('error', gt('We could not find any subscriptions matching the ID and Key you provided.'));\n \n // activate this users pending subscriptions\n $sub = new stdClass();\n $sub->enabled = 1;\n $db->updateObject($sub, 'expeAlerts_subscribers', 'subscribers_id='.$id);\n \n // find the users active subscriptions\n $ealerts = expeAlerts::getBySubscriber($id);\n assign_to_template(array(\n 'ealerts'=>$ealerts\n ));\n }", "label_name": "CWE-74", "label": 1} +{"code": " $modelName = ucfirst ($module->name);\n if (class_exists ($modelName)) {\n // prefix widget class name with custom module model name and a delimiter\n $cache[$widgetType][$modelName.'::TemplatesGridViewProfileWidget'] =\n Yii::t(\n 'app', '{modelName} Summary', array ('{modelName}' => $modelName));\n }\n }\n }\n }\n return $cache[$widgetType];\n }", "label_name": "CWE-20", "label": 0} +{"code": "\tpublic function Set($_var = '', $_value = '', $_vartrusted = false, $_valuetrusted = false) {\n\n\t\tif ($_var != ''\n\t\t\t&& $_value != ''\n\t\t) {\n\t\t\tif (!$_vartrusted) {\n\t\t\t\t$_var = strip_tags($_var);\n\t\t\t}\n\n\t\t\tif (!$_valuetrusted) {\n\t\t\t\t$_value = strip_tags($_value, '
');\n\t\t\t}\n\n\t\t\tif (strtolower($_var) == 'message'\n\t\t\t\t|| strtolower($_var) == 'subject'\n\t\t\t) {\n\t\t\t\t$_value = $this->convertLatin1ToHtml($_value);\n\t\t\t}\n\n\t\t\t$this->t_data[$_var] = $_value;\n\t\t}\n\t}", "label_name": "CWE-732", "label": 13} +{"code": " public function getFilePath($fileName = null)\n {\n if ($fileName === null) {\n $fileName = $this->fileName;\n }\n\n return $this->theme->getPath().'/'.$this->dirName.'/'.$fileName;\n }", "label_name": "CWE-610", "label": 17} +{"code": " function edit_freeform() {\r\n $section = isset($this->params['id']) ? $this->section->find($this->params['id']) : new section($this->params);\r\n if ($section->parent == -1) {\r\n notfoundController::handle_not_found();\r\n exit;\r\n } // doesn't work for standalone pages\r\n if (empty($section->id)) {\r\n $section->public = 1;\r\n if (!isset($section->parent)) {\r\n // This is another precaution. The parent attribute\r\n // should ALWAYS be set by the caller.\r\n //FJD - if that's the case, then we should die.\r\n notfoundController::handle_not_authorized();\r\n exit;\r\n //$section->parent = 0;\r\n }\r\n }\r\n assign_to_template(array(\r\n 'section' => $section,\r\n 'glyphs' => self::get_glyphs(),\r\n ));\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " private function _getMetaTags()\n {\n $retval = '';\n $retval .= '';\n $retval .= '';\n $retval .= '';\n return $retval;\n }", "label_name": "CWE-20", "label": 0} +{"code": "function XMLRPCendRequest($requestid) {\n\tglobal $user;\n\t$requestid = processInputData($requestid, ARG_NUMERIC);\n\t$userRequests = getUserRequests('all', $user['id']);\n\t$found = 0;\n\tforeach($userRequests as $req) {\n\t\tif($req['id'] == $requestid) {\n\t\t\t$request = getRequestInfo($requestid);\n\t\t\t$found = 1;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif(! $found)\n\t\treturn array('status' => 'error',\n\t\t 'errorcode' => 1,\n\t\t 'errormsg' => 'unknown requestid');\n\n\tdeleteRequest($request);\n\treturn array('status' => 'success');\n}", "label_name": "CWE-20", "label": 0} +{"code": " public static function restoreX2AuthManager () {\n if (isset (self::$_oldAuthManagerComponent)) {\n Yii::app()->setComponent ('authManager', self::$_oldAuthManagerComponent);\n } else {\n throw new CException ('X2AuthManager component could not be restored'); \n }\n }", "label_name": "CWE-20", "label": 0} +{"code": "function execute_backup($command) {\n\t$backup_options = get_option('dbmanager_options');\n\tcheck_backup_files();\n\n\tif( realpath( $backup_options['path'] ) === false ) {\n\t\treturn sprintf( __( '%s is not a valid backup path', 'wp-dbmanager' ), stripslashes( $backup_options['path'] ) );\n\t} else if( dbmanager_is_valid_path( $backup_options['mysqldumppath'] ) === 0 ) {\n\t\treturn sprintf( __( '%s is not a valid mysqldump path', 'wp-dbmanager' ), stripslashes( $backup_options['mysqldumppath'] ) );\n\t} else if( dbmanager_is_valid_path( $backup_options['mysqlpath'] ) === 0 ) {\n\t\treturn sprintf( __( '%s is not a valid mysql path', 'wp-dbmanager' ), stripslashes( $backup_options['mysqlpath'] ) );\n\t}\n\n\tif(substr(PHP_OS, 0, 3) == 'WIN') {\n\t\t$writable_dir = $backup_options['path'];\n\t\t$tmpnam = $writable_dir.'/wp-dbmanager.bat';\n\t\t$fp = fopen($tmpnam, 'w');\n\t\tfwrite($fp, $command);\n\t\tfclose($fp);\n\t\tsystem($tmpnam.' > NUL', $error);\n\t\tunlink($tmpnam);\n\t} else {\n\t\tpassthru($command, $error);\n\t}\n\treturn $error;\n}", "label_name": "CWE-20", "label": 0} +{"code": " public function approve_submit() {\n global $history;\n \n if (empty($this->params['id'])) {\n flash('error', gt('No ID supplied for comment to approve'));\n $lastUrl = expHistory::getLast('editable');\n }\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n $require_login = empty($this->params['require_login']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];\n $require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];\n $require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n $notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];\n \n $simplenote = new expSimpleNote($this->params['id']);\n //FIXME here is where we might sanitize the note before approving it\n $simplenote->body = $this->params['body'];\n $simplenote->approved = $this->params['approved'];\n $simplenote->save();\n \n $lastUrl = makelink($history->history[$history->history['lasts']['type']][count($history->history[$history->history['lasts']['type']])-1]['params']);\n if (!empty($this->params['tab']))\n {\n $lastUrl .= \"#\".$this->params['tab'];\n }\n redirect_to($lastUrl);\n }", "label_name": "CWE-74", "label": 1} +{"code": " public function delete() {\n if (!AuthUser::hasPermission('file_manager_delete')) {\n Flash::set('error', __('You do not have sufficient permissions to delete a file or directory.'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n\n $paths = func_get_args();\n\n $file = urldecode(join('/', $paths));\n \n // CSRF checks\n if (isset($_GET['csrf_token'])) {\n $csrf_token = $_GET['csrf_token'];\n if (!SecureToken::validateToken($csrf_token, BASE_URL.'plugin/file_manager/delete/'.$file)) {\n Flash::set('error', __('Invalid CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n }\n else {\n Flash::set('error', __('No CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n\n $file = FILES_DIR . '/' . str_replace('..', '', $file);\n $filename = array_pop($paths);\n $paths = join('/', $paths);\n\n if (is_file($file)) {\n if (!unlink($file))\n Flash::set('error', __('Permission denied!'));\n }\n else {\n if (!$this->_rrmdir($file))\n Flash::set('error', __('Permission denied!'));\n }\n\n redirect(get_url('plugin/file_manager/browse/' . $paths));\n }", "label_name": "CWE-20", "label": 0} +{"code": "\t function manage_upcharge() {\n\t\t$this->loc->src = \"@globalstoresettings\";\n $config = new expConfig($this->loc);\n\t\t$this->config = $config->config;\n\n\t\t$gc = new geoCountry(); \n $countries = $gc->find('all');\n \n $gr = new geoRegion(); \n $regions = $gr->find('all',null,'rank asc,name asc');\n assign_to_template(array(\n 'countries'=>$countries,\n 'regions'=>$regions,\n 'upcharge'=>!empty($this->config['upcharge'])?$this->config['upcharge']:''\n ));\n\t }", "label_name": "CWE-74", "label": 1} +{"code": " public function delete($id)\n {\n $this->CRUD->delete($id);\n $responsePayload = $this->CRUD->getResponsePayload();\n if (!empty($responsePayload)) {\n return $responsePayload;\n }\n $this->set('metaGroup', 'Trust Circles');\n }", "label_name": "CWE-668", "label": 7} +{"code": " public function confirm()\n {\n $task = $this->getTask();\n $comment = $this->getComment();\n\n $this->response->html($this->template->render('comment/remove', array(\n 'comment' => $comment,\n 'task' => $task,\n 'title' => t('Remove a comment')\n )));\n }", "label_name": "CWE-200", "label": 10} +{"code": " public function update()\n {\n $project = $this->getProject();\n\n $values = $this->request->getValues();\n list($valid, $errors) = $this->swimlaneValidator->validateModification($values);\n\n if ($valid) {\n if ($this->swimlaneModel->update($values['id'], $values)) {\n $this->flash->success(t('Swimlane updated successfully.'));\n return $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));\n } else {\n $errors = array('name' => array(t('Another swimlane with the same name exists in the project')));\n }\n }\n\n return $this->edit($values, $errors);\n }", "label_name": "CWE-200", "label": 10} +{"code": "\tpublic function replace_save_pre_shortcode( $shortcode_match ) {\r\n\t\t$content = $shortcode_match[0];\r\n\t\t$tag_index = array_search( 'geo_mashup_save_location', $shortcode_match ); \r\n\t\tif ( $tag_index !== false ) {\r\n\t\t\t// There is an inline location - save the attributes\r\n\t\t\t$this->inline_location = shortcode_parse_atts( stripslashes( $shortcode_match[$tag_index+1] ) );\r\n\r\n\t\t\t// If lat and lng are missing, try to geocode based on address\r\n\t\t\t$success = false;\r\n\t\t\tif ( ( empty( $this->inline_location['lat'] ) or empty( $this->inline_location['lng'] ) ) and !empty( $this->inline_location['address'] ) ) {\r\n\t\t\t\t$query = $this->inline_location['address'];\r\n\t\t\t\t$this->inline_location = GeoMashupDB::blank_object_location( ARRAY_A );\r\n\t\t\t\t$success = GeoMashupDB::geocode( $query, $this->inline_location );\r\n\t\t\t\tif ( !$success ) {\r\n\t\t\t\t\t// Delay and try again\r\n\t\t\t\t\tsleep( 1 );\r\n\t\t\t\t\t$success = GeoMashupDB::geocode( $query, $this->inline_location );\r\n\t\t\t\t}\r\n\t\t\t} else if ( is_numeric ( $this->inline_location['lat'] ) and is_numeric( $this->inline_location['lng'] ) ) {\r\n\t\t\t\t// lat and lng were supplied\r\n\t\t\t\t$success = true;\r\n\t\t\t}\r\n\r\n\t\t\tif ( $success ) {\r\n\t\t\t\t// Remove the tag\r\n\t\t\t\t$content = '';\r\n\t\t\t} else {\r\n\t\t\t\t$message = ( is_wp_error( GeoMashupDB::$geocode_error ) ? GeoMashupDB::$geocode_error->get_error_message() : __( 'Address not found - try making it less detailed', 'GeoMashup' ) );\r\n\t\t\t\t$content = str_replace( ']', ' geocoding_error=\"' . $message . '\"]', $content );\r\n\t\t\t\t$this->inline_location = null;\r\n\t\t\t}\r\n\t\t} \r\n\t\treturn $content;\r\n\t}\r", "label_name": "CWE-20", "label": 0} +{"code": " function showallSubcategories() {\n// global $db;\n\n expHistory::set('viewable', $this->params);\n// $parent = isset($this->params['cat']) ? $this->params['cat'] : expSession::get('catid');\n $catid = expSession::get('catid');\n $parent = !empty($catid) ? $catid : (!empty($this->params['cat']) ? $this->params['cat'] : 0);\n $category = new storeCategory($parent);\n $categories = $category->getEcomSubcategories();\n $ancestors = $category->pathToNode();\n assign_to_template(array(\n 'categories' => $categories,\n 'ancestors' => $ancestors,\n 'category' => $category\n ));\n }", "label_name": "CWE-20", "label": 0} +{"code": " return $fa->nameGlyph($icons, 'icon-');\r\n }\r\n } else {\r\n return array();\r\n }\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " private function generateTempFileData()\n {\n return [\n 'name' => md5(mt_rand()),\n 'tmp_name' => tempnam(sys_get_temp_dir(), ''),\n 'type' => 'image/jpeg',\n 'size' => mt_rand(1000, 10000),\n 'error' => '0',\n ];\n }", "label_name": "CWE-330", "label": 12} +{"code": "\tpublic static function login() {\n\t\tuser::login(expString::sanitize($_POST['username']),expString::sanitize($_POST['password']));\n\t\tif (!isset($_SESSION[SYS_SESSION_KEY]['user'])) { // didn't successfully log in\n\t\t\tflash('error', gt('Invalid Username / Password'));\n\t\t\tif (expSession::is_set('redirecturl_error')) {\n\t\t\t\t$url = expSession::get('redirecturl_error');\n\t\t\t\texpSession::un_set('redirecturl_error');\n\t\t\t\theader(\"Location: \".$url);\n\t\t\t} else {\n\t\t\t\texpHistory::back();\n\t\t\t}\n\t\t} else { // we're logged in\n\t\t\tglobal $user;\n\n if (expSession::get('customer-login')) expSession::un_set('customer-login');\n\t\t\tif (!empty($_POST['username'])) flash('message', gt('Welcome back').' '.expString::sanitize($_POST['username']));\n if ($user->isAdmin()) {\n expHistory::back();\n } else {\n foreach ($user->groups as $g) {\n if (!empty($g->redirect)) {\n $url = URL_FULL.$g->redirect;\n break;\n }\n }\n if (isset($url)) {\n header(\"Location: \".$url);\n } else {\n expHistory::back();\n }\n }\n\t\t}\n\t}", "label_name": "CWE-74", "label": 1} +{"code": " public function update() {\n\n //populate the alt tag field if the user didn't\n if (empty($this->params['alt'])) $this->params['alt'] = $this->params['title'];\n \n // call expController update to save the image\n parent::update();\n }", "label_name": "CWE-74", "label": 1} +{"code": " public function getCookiePathsDataProvider()\n {\n return [\n ['', '/'],\n ['/', '/'],\n ['/foo', '/'],\n ['/foo/bar', '/foo'],\n ['/foo/bar/', '/foo/bar'],\n ['foo', '/'],\n ['foo/bar', '/'],\n ['foo/bar/', '/'],\n ];\n }", "label_name": "CWE-200", "label": 10} +{"code": " public function validate() {\n global $db;\n // check for an sef url field. If it exists make sure it's valid and not a duplicate\n //this needs to check for SEF URLS being turned on also: TODO\n\n if (property_exists($this, 'sef_url') && !(in_array('sef_url', $this->do_not_validate))) {\n if (empty($this->sef_url)) $this->makeSefUrl();\n if (!isset($this->validates['is_valid_sef_name']['sef_url'])) $this->validates['is_valid_sef_name']['sef_url'] = array();\n if (!isset($this->validates['uniqueness_of']['sef_url'])) $this->validates['uniqueness_of']['sef_url'] = array();\n }\n\n // safeguard again loc data not being pass via forms...sometimes this happens when you're in a router\n // mapped view and src hasn't been passed in via link to the form \n if (isset($this->id) && empty($this->location_data)) {\n $loc = $db->selectValue($this->tablename, 'location_data', 'id=' . $this->id);\n if (!empty($loc)) $this->location_data = $loc;\n }\n\n // run the validation as defined in the models\n if (!isset($this->validates)) return true;\n $messages = array();\n $post = empty($_POST) ? array() : expString::sanitize($_POST);\n foreach ($this->validates as $validation=> $field) {\n foreach ($field as $key=> $value) {\n $fieldname = is_numeric($key) ? $value : $key;\n $opts = is_numeric($key) ? array() : $value;\n $ret = expValidator::$validation($fieldname, $this, $opts);\n if (!is_bool($ret)) {\n $messages[] = $ret;\n expValidator::setErrorField($fieldname);\n unset($post[$fieldname]);\n }\n }\n }\n\n if (count($messages) >= 1) expValidator::failAndReturnToForm($messages, $post);\n }", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic function setMultiSectionSeparators( ?array $separators ) {\n\t\t$this->multiSectionSeparators = (array)$separators ?? [];\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " ->first(function (User $user) {\n return $user->getPreference('blocksPd', false);\n }) !== null;", "label_name": "CWE-269", "label": 6} +{"code": " public function testOnKernelResponseListenerRemovesItself()\n {\n $session = $this->createMock(SessionInterface::class);\n $session->expects($this->any())->method('getName')->willReturn('SESSIONNAME');\n $tokenStorage = $this->createMock(TokenStorageInterface::class);\n $dispatcher = $this->createMock(EventDispatcherInterface::class);\n\n $listener = new ContextListener($tokenStorage, [], 'key123', null, $dispatcher);\n\n $request = new Request();\n $request->attributes->set('_security_firewall_run', true);\n $request->setSession($session);\n\n $event = new ResponseEvent($this->createMock(HttpKernelInterface::class), $request, HttpKernelInterface::MAIN_REQUEST, new Response());\n\n $dispatcher->expects($this->once())\n ->method('removeListener')\n ->with(KernelEvents::RESPONSE, [$listener, 'onKernelResponse']);\n\n $listener->onKernelResponse($event);\n }", "label_name": "CWE-287", "label": 4} +{"code": " $evs = $this->event->find('all', \"id=\" . $edate->event_id . $featuresql);\r\n foreach ($evs as $key=>$event) {\r\n if ($condense) {\r\n $eventid = $event->id;\r\n $multiday_event = array_filter($events, create_function('$event', 'global $eventid; return $event->id === $eventid;'));\r\n if (!empty($multiday_event)) {\r\n unset($evs[$key]);\r\n continue;\r\n }\r\n }\r\n $evs[$key]->eventstart += $edate->date;\r\n $evs[$key]->eventend += $edate->date;\r\n $evs[$key]->date_id = $edate->id;\r\n if (!empty($event->expCat)) {\r\n $catcolor = empty($event->expCat[0]->color) ? null : trim($event->expCat[0]->color);\r\n// if (substr($catcolor,0,1)=='#') $catcolor = '\" style=\"color:'.$catcolor.';';\r\n $evs[$key]->color = $catcolor;\r\n }\r\n }\r\n if (count($events) < 500) { // magic number to not crash loop?\r\n $events = array_merge($events, $evs);\r\n } else {\r\n// $evs[$key]->title = gt('Too many events to list').', '.(count($edates)-count($events)).' '.gt('not displayed!');\r\n// $events = array_merge($events, $evs);\r\n flash('notice',gt('Too many events to list').', '.(count($edates)-count($events)).' '.gt('not displayed!'));\r\n break; // keep from breaking system by too much data\r\n }\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " private function generateFakeFileData()\n {\n return [\n 'name' => md5(mt_rand()),\n 'tmp_name' => md5(mt_rand()),\n 'type' => 'image/jpeg',\n 'size' => mt_rand(1000, 10000),\n 'error' => '0',\n ];\n }", "label_name": "CWE-330", "label": 12} +{"code": " public function showall_tags() {\n $images = $this->image->find('all');\n $used_tags = array();\n foreach ($images as $image) {\n foreach($image->expTag as $tag) {\n if (isset($used_tags[$tag->id])) {\n $used_tags[$tag->id]->count++;\n } else {\n $exptag = new expTag($tag->id);\n $used_tags[$tag->id] = $exptag;\n $used_tags[$tag->id]->count = 1;\n }\n \n }\n }\n \n assign_to_template(array(\n 'tags'=>$used_tags\n ));\n } ", "label_name": "CWE-74", "label": 1} +{"code": "\t\t\t$result = $search->getSearchResults($item->query, false, true);\n\t\t\tif(empty($result) && !in_array($item->query, $badSearchArr)) {\n\t\t\t\t$badSearchArr[] = $item->query;\n\t\t\t\t$badSearch[$ctr2]['query'] = $item->query;\n\t\t\t\t$badSearch[$ctr2]['count'] = $db->countObjects(\"search_queries\", \"query='{$item->query}'\");\n\t\t\t\t$ctr2++;\n\t\t\t}\n\t\t\t\n\t\t}\n\t\n\t\t//Check if the user choose from the dropdown\n\t\tif(!empty($user_default)) {\n\t\t\tif($user_default == $anonymous) {\n\t\t\t\t$u_id = 0;\n\t\t\t} else {\n\t\t\t\t$u_id = $user_default;\n\t\t\t}\n\t\t\t$where .= \"user_id = {$u_id}\";\n\t\t}\n\t\n\t\t//Get all the search query records\n\t\t$records = $db->selectObjects('search_queries', $where);\n for ($i = 0, $iMax = count($records); $i < $iMax; $i++) {\n\t\t\tif(!empty($records[$i]->user_id)) {\n\t\t\t\t$u = user::getUserById($records[$i]->user_id);\n\t\t\t\t$records[$i]->user = $u->firstname . ' ' . $u->lastname;\n\t\t\t}\n\t\t}\n\t\t\n $page = new expPaginator(array(\n 'records' => $records,\n 'where'=>1,\n 'model'=>'search_queries',\n 'limit'=>(isset($this->config['limit']) && $this->config['limit'] != '') ? 10 : $this->config['limit'],\n 'order'=>empty($this->config['order']) ? 'timestamp' : $this->config['order'],\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->baseclassname,\n 'action'=>$this->params['action'],\n 'columns'=>array(\n 'ID'=>'id',\n gt('Query')=>'query',\n gt('Timestamp')=>'timestamp',\n gt('User')=>'user_id',\n ),\n ));\n\n $uname['id'] = implode($uname['id'],',');\n $uname['name'] = implode($uname['name'],',');\n assign_to_template(array(\n 'page'=>$page,\n 'users'=>$uname,\n 'user_default' => $user_default,\n 'badSearch' => $badSearch\n ));\n\t\t\n\t}", "label_name": "CWE-74", "label": 1} +{"code": "\tfunction test_anon_comments_require_email() {\n\t\tadd_filter( 'xmlrpc_allow_anonymous_comments', '__return_true' );\n\n\t\t$comment_args = array(\n\t\t\t1,\n\t\t\t'',\n\t\t\t'',\n\t\t\tself::$post->ID,\n\t\t\tarray(\n\t\t\t\t'author' => 'WordPress',\n\t\t\t\t'author_email' => 'noreply at wordpress.org',\n\t\t\t\t'content' => 'Test Anon Comments',\n\t\t\t),\n\t\t);\n\n\t\t$result = $this->myxmlrpcserver->wp_newComment( $comment_args );\n\t\t$this->assertIXRError( $result );\n\t\t$this->assertSame( 403, $result->code );\n\t}", "label_name": "CWE-862", "label": 8} +{"code": " public function search_external() {\n// global $db, $user;\n global $db;\n\n $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 \";\n $sql .= \"from \" . $db->prefix . \"external_addresses as a \"; //R JOIN \" . \n //$db->prefix . \"billingmethods as bm ON bm.addresses_id=a.id \";\n $sql .= \" WHERE match (a.firstname,a.lastname,a.email,a.organization) against ('\" . $this->params['query'] .\n \"*' IN BOOLEAN MODE) \";\n $sql .= \"order by match (a.firstname,a.lastname,a.email,a.organization) against ('\" . $this->params['query'] . \"*' IN BOOLEAN MODE) ASC LIMIT 12\";\n $res = $db->selectObjectsBySql($sql);\n foreach ($res as $key=>$record) {\n $res[$key]->title = $record->firstname . ' ' . $record->lastname;\n }\n //eDebug($sql);\n $ar = new expAjaxReply(200, gt('Here\\'s the items you wanted'), $res);\n $ar->send();\n }", "label_name": "CWE-74", "label": 1} +{"code": " public function gc($force = false, $expiredOnly = true)\n {\n if ($force || mt_rand(0, 1000000) < $this->gcProbability) {\n $this->gcRecursive($this->cachePath, $expiredOnly);\n }\n }", "label_name": "CWE-330", "label": 12} +{"code": " $cLoc = serialize(expCore::makeLocation('container','@section' . $page->id));\r\n $ret .= scan_container($cLoc, $page->id);\r\n $ret .= scan_page($page->id);\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public function StartTLS() {\n $this->error = null; # to avoid confusion\n\n if(!$this->connected()) {\n $this->error = array(\"error\" => \"Called StartTLS() without being connected\");\n return false;\n }\n\n fputs($this->smtp_conn,\"STARTTLS\" . $this->CRLF);\n\n $rply = $this->get_lines();\n $code = substr($rply,0,3);\n\n if($this->do_debug >= 2) {\n $this->edebug(\"SMTP -> FROM SERVER:\" . $rply . $this->CRLF . '
');\n }\n\n if($code != 220) {\n $this->error =\n array(\"error\" => \"STARTTLS not accepted from server\",\n \"smtp_code\" => $code,\n \"smtp_msg\" => substr($rply,4));\n if($this->do_debug >= 1) {\n $this->edebug(\"SMTP -> ERROR: \" . $this->error[\"error\"] . \": \" . $rply . $this->CRLF . '
');\n }\n return false;\n }\n\n // Begin encrypted connection\n if(!stream_socket_enable_crypto($this->smtp_conn, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {\n return false;\n }\n\n return true;\n }", "label_name": "CWE-20", "label": 0} +{"code": " $name = ucfirst($module->name);\n if (in_array($name, $skipModules)) {\n continue;\n }\n if($name != 'Document'){\n $controllerName = $name.'Controller';\n if(file_exists('protected/modules/'.$module->name.'/controllers/'.$controllerName.'.php')){\n Yii::import(\"application.modules.$module->name.controllers.$controllerName\");\n $controller = new $controllerName($controllerName);\n $model = $controller->modelClass;\n if(class_exists($model)){\n $moduleList[$model] = Yii::t('app', $module->title);\n }\n }\n }\n }\n return $moduleList;\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function manage() {\n expHistory::set('viewable', $this->params);\n \n $page = new expPaginator(array(\n\t\t\t'model'=>'order_status',\n\t\t\t'where'=>1,\n 'limit'=>10,\n\t\t\t'order'=>'rank',\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->params['controller'],\n 'action'=>$this->params['action'],\n //'columns'=>array('Name'=>'title')\n ));\n\n\t\tassign_to_template(array(\n 'page'=>$page\n ));\n }", "label_name": "CWE-74", "label": 1} +{"code": " public static function hasChildren($i) {\r\n global $sections;\r\n\r\n if (($i + 1) >= count($sections)) return false;\r\n return ($sections[$i]->depth < $sections[$i + 1]->depth) ? true : false;\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": "\tprivate static function dumpParsedRefs( $parser, $label ) {\n\t\t// if (!preg_match(\"/Query Q/\",$parser->mTitle->getText())) return '';\n\t\techo '
parser mLinks: ';\n\t\tob_start();\n\t\tvar_dump( $parser->getOutput()->mLinks );\n\t\t$a = ob_get_contents();\n\t\tob_end_clean();\n\t\techo htmlspecialchars( $a, ENT_QUOTES );\n\t\techo '
';\n\t\techo '
parser mTemplates: ';\n\t\tob_start();\n\t\tvar_dump( $parser->getOutput()->mTemplates );\n\t\t$a = ob_get_contents();\n\t\tob_end_clean();\n\t\techo htmlspecialchars( $a, ENT_QUOTES );\n\t\techo '
';\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " public function actionHideWidget() {\n if (isset($_POST['name'])) {\n $name = $_POST['name'];\n\n $layout = Yii::app()->params->profile->getLayout();\n\n // the widget could be in any of the blocks in the page, so check all of them\n foreach ($layout as $b => &$block) {\n if (isset($block[$name])) {\n if ($b == 'right') {\n $layout['hiddenRight'][$name] = $block[$name];\n } else {\n $layout['hidden'][$name] = $block[$name];\n }\n unset($block[$name]);\n Yii::app()->params->profile->saveLayout($layout);\n break;\n }\n }\n\n // make a list of hidden widgets, using
  • , to send back to the browser\n $list = \"\";\n foreach ($layout['hidden'] as $name => $widget) {\n $list .= \"
  • {$widget['title']}
  • \";\n }\n foreach ($layout['hiddenRight'] as $name => $widget) {\n $list .= \"
  • {$widget['title']}
  • \";\n }\n\n echo Yii::app()->params->profile->getWidgetMenu();\n }\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function testGetDropdownConnect($params, $expected, $session_params = []) {\n $this->login();\n\n $bkp_params = [];\n //set session params if any\n if (count($session_params)) {\n foreach ($session_params as $param => $value) {\n if (isset($_SESSION[$param])) {\n $bkp_params[$param] = $_SESSION[$param];\n }\n $_SESSION[$param] = $value;\n }\n }\n\n $params['_idor_token'] = \\Session::getNewIDORToken($params['itemtype'] ?? '');\n\n $result = \\Dropdown::getDropdownConnect($params, false);\n\n //reset session params before executing test\n if (count($session_params)) {\n foreach ($session_params as $param => $value) {\n if (isset($bkp_params[$param])) {\n $_SESSION[$param] = $bkp_params[$param];\n } else {\n unset($_SESSION[$param]);\n }\n }\n }\n\n $this->array($result)->isIdenticalTo($expected);\n }", "label_name": "CWE-862", "label": 8} +{"code": " private function catchWarning ($errno, $errstr, $errfile, $errline) {\n $this->error[] = array(\n 'error' => \"Connecting to the POP3 server raised a PHP warning: \",\n 'errno' => $errno,\n 'errstr' => $errstr\n );\n }", "label_name": "CWE-20", "label": 0} +{"code": "function httpsTestController($serverPort) {\n $args = array('HTTPS' => '');\n var_dump(request(php_uname('n'), $serverPort, \"test_https.php\",\n [], [], $args));\n}", "label_name": "CWE-668", "label": 7} +{"code": "\t\t\t\t\t$text = wfMessage( 'intersection_noincludecats', $args )->text();\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ( empty( $text ) ) {\n\t\t\t\t$text = wfMessage( 'dpl_log_' . $errorMessageId, $args )->text();\n\t\t\t}\n\t\t\t$this->buffer[] = '

    Extension:DynamicPageList (DPL), version ' . DPL_VERSION . ': ' . $text . '

    ';\n\t\t}\n\t\treturn false;\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " public function searchNew() {\n global $db, $user;\n //$this->params['query'] = str_ireplace('-','\\-',$this->params['query']);\n $sql = \"select DISTINCT(p.id) as id, p.title, model, sef_url, f.id as fileid, \";\n $sql .= \"match (p.title,p.model,p.body) against ('\" . $this->params['query'] . \"*' IN BOOLEAN MODE) as relevance, \";\n $sql .= \"CASE when p.model like '\" . $this->params['query'] . \"%' then 1 else 0 END as modelmatch, \";\n $sql .= \"CASE when p.title like '%\" . $this->params['query'] . \"%' then 1 else 0 END as titlematch \";\n $sql .= \"from \" . $db->prefix . \"product as p INNER JOIN \" .\n $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 .\n \"expFiles as f ON cef.expFiles_id = f.id WHERE \";\n if (!$user->isAdmin()) $sql .= '(p.active_type=0 OR p.active_type=1) AND ';\n $sql .= \" match (p.title,p.model,p.body) against ('\" . $this->params['query'] . \"*' IN BOOLEAN MODE) AND p.parent_id=0 \";\n $sql .= \" HAVING relevance > 0 \";\n //$sql .= \"GROUP BY p.id \"; \n $sql .= \"order by modelmatch,titlematch,relevance desc LIMIT 10\";\n\n eDebug($sql);\n $res = $db->selectObjectsBySql($sql);\n eDebug($res, true);\n $ar = new expAjaxReply(200, gt('Here\\'s the items you wanted'), $res);\n $ar->send();\n }", "label_name": "CWE-74", "label": 1} +{"code": "\t\t $controller = new $ctlname();\n\t\t if (method_exists($controller,'isSearchable') && $controller->isSearchable()) {\n//\t\t\t $mods[$controller->name()] = $controller->addContentToSearch();\n $mods[$controller->searchName()] = $controller->addContentToSearch();\n\t\t }\n\t }\n\t\n\t uksort($mods,'strnatcasecmp');\n\t assign_to_template(array(\n 'mods'=>$mods\n ));\n }", "label_name": "CWE-74", "label": 1} +{"code": " function updateObject($object, $table, $where=null, $identifier='id', $is_revisioned=false) {\n\n if ($is_revisioned) {\n $object->revision_id++;\n //if ($table==\"text\") eDebug($object);\n $res = $this->insertObject($object, $table);\n //if ($table==\"text\") eDebug($object,true); \n $this->trim_revisions($table, $object->$identifier, WORKFLOW_REVISION_LIMIT);\n return $res;\n }\n $sql = \"UPDATE \" . $this->prefix . \"$table SET \";\n foreach (get_object_vars($object) as $var => $val) {\n //We do not want to save any fields that start with an '_'\n //if($is_revisioned && $var=='revision_id') $val++;\n if ($var{0} != '_') {\n if (is_array($val) || is_object($val)) {\n $val = serialize($val); \n $sql .= \"`$var`='\".$val.\"',\";\n } else {\n $sql .= \"`$var`='\" . $this->escapeString($val) . \"',\";\n }\n }\n }\n $sql = substr($sql, 0, -1) . \" WHERE \";\n if ($where != null)\n $sql .= $this->injectProof($where);\n else\n $sql .= \"`\" . $identifier . \"`=\" . $object->$identifier;\n //if ($table == 'text') eDebug($sql,true); \n $res = (@mysqli_query($this->connection, $sql) != false);\n return $res;\n }", "label_name": "CWE-74", "label": 1} +{"code": " protected function setUp()\n {\n $this->originalTrustedHeaderName = Request::getTrustedHeaderName(Request::HEADER_CLIENT_IP);\n }", "label_name": "CWE-20", "label": 0} +{"code": " function addDiscountToCart() {\n// global $user, $order;\n global $order;\n //lookup discount to see if it's real and valid, and not already in our cart\n //this will change once we allow more than one coupon code\n\n $discount = new discounts();\n $discount = $discount->getCouponByName($this->params['coupon_code']);\n\n if (empty($discount)) {\n flash('error', gt(\"This discount code you entered does not exist.\"));\n //redirect_to(array('controller'=>'cart', 'action'=>'checkout')); \n expHistory::back();\n }\n\n //check to see if it's in our cart already\n if ($this->isDiscountInCart($discount->id)) {\n flash('error', gt(\"This discount code is already in your cart.\"));\n //redirect_to(array('controller'=>'cart', 'action'=>'checkout'));\n expHistory::back();\n }\n\n //this should really be reworked, as it shoudn't redirect directly and not return\n $validateDiscountMessage = $discount->validateDiscount();\n if ($validateDiscountMessage == \"\") {\n //if all good, add to cart, otherwise it will have redirected\n $od = new order_discounts();\n $od->orders_id = $order->id;\n $od->discounts_id = $discount->id;\n $od->coupon_code = $discount->coupon_code;\n $od->title = $discount->title;\n $od->body = $discount->body;\n $od->save();\n // set this to just the discount applied via this coupon?? if so, when though? $od->discount_total = ??;\n flash('message', gt(\"The discount code has been applied to your cart.\"));\n } else {\n flash('error', $validateDiscountMessage);\n }\n //redirect_to(array('controller'=>'cart', 'action'=>'checkout')); \n expHistory::back();\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function editAlt() {\n global $user; \n $file = new expFile($this->params['id']);\n if ($user->id==$file->poster || $user->isAdmin()) {\n $file->alt = $this->params['newValue'];\n $file->save();\n $ar = new expAjaxReply(200, gt('Your alt was updated successfully'), $file);\n } else {\n $ar = new expAjaxReply(300, gt(\"You didn't create this file, so you can't edit it.\"));\n }\n $ar->send();\n echo json_encode($file); //FIXME we exit before hitting this\n } ", "label_name": "CWE-74", "label": 1} +{"code": " public function manage_sitemap() {\r\n global $db, $user, $sectionObj, $sections;\r\n\r\n expHistory::set('viewable', $this->params);\r\n $id = $sectionObj->id;\r\n $current = null;\r\n // all we need to do is determine the current section\r\n $navsections = $sections;\r\n if ($sectionObj->parent == -1) {\r\n $current = $sectionObj;\r\n } else {\r\n foreach ($navsections as $section) {\r\n if ($section->id == $id) {\r\n $current = $section;\r\n break;\r\n }\r\n }\r\n }\r\n assign_to_template(array(\r\n 'sasections' => $db->selectObjects('section', 'parent=-1'),\r\n 'sections' => $navsections,\r\n 'current' => $current,\r\n 'canManage' => ((isset($user->is_acting_admin) && $user->is_acting_admin == 1) ? 1 : 0),\r\n ));\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": "\t\t\t\t} elseif ( $sSecLabel[0] == '{' ) {\n\t\t\t\t\t// Uses LST::includeTemplate() from LabeledSectionTransclusion extension to include templates from the page\n\t\t\t\t\t// primary syntax {template}suffix\n\t\t\t\t\t$template1 = trim( substr( $sSecLabel, 1, strpos( $sSecLabel, '}' ) - 1 ) );\n\t\t\t\t\t$template2 = trim( str_replace( '}', '', substr( $sSecLabel, 1 ) ) );\n\t\t\t\t\t// alternate syntax: {template|surrogate}\n\t\t\t\t\tif ( $template2 == $template1 && strpos( $template1, '|' ) > 0 ) {\n\t\t\t\t\t\t$template1 = preg_replace( '/\\|.*/', '', $template1 );\n\t\t\t\t\t\t$template2 = preg_replace( '/^.+\\|/', '', $template2 );\n\t\t\t\t\t}\n\t\t\t\t\t//Why the hell was defaultTemplateSuffix be passed all over the place for just fucking here? --Alexia\n\t\t\t\t\t$secPieces = LST::includeTemplate( $this->parser, $this, $s, $article, $template1, $template2, $template2 . $this->getTemplateSuffix(), $mustMatch, $mustNotMatch, $this->includePageParsed, implode( ', ', $article->mCategoryLinks ) );\n\t\t\t\t\t$secPiece[$s] = implode( isset( $this->multiSectionSeparators[$s] ) ? $this->replaceTagCount( $this->multiSectionSeparators[$s], $filteredCount ) : '', $secPieces );\n\t\t\t\t\tif ( $this->getDominantSectionCount() >= 0 && $s == $this->getDominantSectionCount() && count( $secPieces ) > 1 ) {\n\t\t\t\t\t\t$dominantPieces = $secPieces;\n\t\t\t\t\t}\n\t\t\t\t\tif ( ( $mustMatch != '' || $mustNotMatch != '' ) && count( $secPieces ) <= 1 && $secPieces[0] == '' ) {\n\t\t\t\t\t\t$matchFailed = true; // NOTHING MATCHED\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} else {", "label_name": "CWE-400", "label": 2} +{"code": "\tprivate function setDefaults() {\n\t\t$this->setParameter( 'defaulttemplatesuffix', '.default' );\n\n\t\t$parameters = $this->getParametersForRichness();\n\t\tforeach ( $parameters as $parameter ) {\n\t\t\tif ( $this->getData( $parameter )['default'] !== null && !( $this->getData( $parameter )['default'] === false && $this->getData( $parameter )['boolean'] === true ) ) {\n\t\t\t\tif ( $parameter == 'debug' ) {\n\t\t\t\t\t\\DynamicPageListHooks::setDebugLevel( $this->getData( $parameter )['default'] );\n\t\t\t\t}\n\t\t\t\t$this->setParameter( $parameter, $this->getData( $parameter )['default'] );\n\t\t\t}\n\t\t}\n\t}", "label_name": "CWE-400", "label": 2} +{"code": "\tfunction __construct() {\n\t\tparent::__construct( 'GlobalNewFiles' );\n\t}", "label_name": "CWE-20", "label": 0} +{"code": " public function delete() {\n global $db, $history;\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n $require_login = empty($this->params['require_login']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];\n $require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];\n $require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n $notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];\n \n if (empty($this->params['id'])) {\n flash('error', gt('Missing id for the comment you would like to delete'));\n $lastUrl = expHistory::getLast('editable');\n }\n \n // delete the note\n $simplenote = new expSimpleNote($this->params['id']);\n $rows = $simplenote->delete();\n \n // delete the assocication too\n $db->delete($simplenote->attachable_table, 'expsimplenote_id='.$this->params['id']); \n \n // send the user back where they came from.\n $lastUrl = expHistory::getLast('editable');\n if (!empty($this->params['tab']))\n {\n $lastUrl .= \"#\".$this->params['tab'];\n }\n redirect_to($lastUrl);\n }", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic function manage_versions() {\n\t expHistory::set('manageable', $this->params);\n\t \n\t $hv = new help_version();\n\t $current_version = $hv->find('first', 'is_current=1');\n\t \n\t $sql = 'SELECT hv.*, COUNT(h.title) AS num_docs FROM '.DB_TABLE_PREFIX.'_help h ';\n\t $sql .= 'RIGHT JOIN '.DB_TABLE_PREFIX.'_help_version hv ON h.help_version_id=hv.id GROUP BY hv.version';\n\n\t $page = new expPaginator(array(\n 'sql'=>$sql,\n 'limit'=>30,\n 'order' => (isset($this->params['order']) ? $this->params['order'] : 'version'),\n 'dir' => (isset($this->params['dir']) ? $this->params['dir'] : 'DESC'),\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->baseclassname,\n 'action'=>$this->params['action'],\n 'src'=>$this->loc->src,\n 'columns'=>array(\n gt('Version')=>'version',\n gt('Title')=>'title',\n gt('Current')=>'is_current',\n gt('# of Docs')=>'num_docs'\n ),\n ));\n\t \n\t assign_to_template(array(\n 'current_version'=>$current_version,\n 'page'=>$page\n ));\n\t}", "label_name": "CWE-74", "label": 1} +{"code": " function productFeed() {\n// global $db;\n //check query password to avoid DDOS\n /*\n * condition = new\n * description \n * id - SKU \n * link \n * price \n * title \n * brand - manufacturer \n * image link - fullsized image, up to 10, comma seperated \n * product type - category - \"Electronics > Audio > Audio Accessories MP3 Player Accessories\",\"Health & Beauty > Healthcare > Biometric Monitors > Pedometers\" \n */\n $out = '\"id\",\"condition\",\"description\",\"like\",\"price\",\"title\",\"brand\",\"image link\",\"product type\"' . chr(13) . chr(10);\n\n $p = new product();\n $prods = $p->find('all', 'parent_id=0 AND ');\n //$prods = $db->selectObjects('product','parent_id=0 AND');\n }", "label_name": "CWE-74", "label": 1} +{"code": " public function getCompiledPath($path)\n {\n return $this->cachePath.'/'.sha1($path).'.php';\n }", "label_name": "CWE-327", "label": 3} +{"code": " fwrite(STDERR, sprintf(\"%2d %s ==> %s\\n\", $i + 1, $test, var_export($result, true)));", "label_name": "CWE-330", "label": 12} +{"code": "\tpublic function loginForm( WebRequest $request ) { // Step 13\n\t\t$out = $this->getOutput();\n\t\t$username = $request->getVal('username');\n\t\t$codes = SOA2Login::codes( $username );\n\t\t$out->addHTML(Html::openElement('form', [ 'method' => 'POST' ]));\n\t\t$out->addHTML(Html::hidden('username', $username));\n\t\t$out->addHTML(Html::hidden('token', $codes['csrf'])); // Step 14\n\t\t$profile = Html::element(\n\t\t\t'a',\n\t\t\t[\n\t\t\t\t'href' => sprintf(SOA2_PROFILE_URL, urlencode($username)),\n\t\t\t\t'target' => '_new'\n\t\t\t],\n\t\t\twfMessage('soa2-your-profile')->plain()\n\t\t);\n\t\t// Step 16\n\t\t$out->addHTML(Html::rawElement(\n\t\t\t'p', [],\n\t\t\twfMessage('soa2-vercode-explanation')->rawParams($profile)->parse()\n\t\t));\n\t\t$out->addHTML(Html::rawElement('p', [], Html::element(\n\t\t\t'code', [], $codes['code']\n\t\t)));\n\t\t$out->addHTML(Html::rawElement('p', [], Html::submitButton(\n\t\t\twfMessage('soa2-login')->plain(), []\n\t\t)));\n\t\t$out->addHTML(Html::closeElement('form'));\n\t}", "label_name": "CWE-863", "label": 11} +{"code": " private function decryptContentEncryptionKey($private_key_or_secret) {\n switch ($this->header['alg']) {\n case 'RSA1_5':\n $rsa = $this->rsa($private_key_or_secret, RSA::ENCRYPTION_PKCS1);\n $this->content_encryption_key = $rsa->decrypt($this->jwe_encrypted_key);\n break;\n case 'RSA-OAEP':\n $rsa = $this->rsa($private_key_or_secret, RSA::ENCRYPTION_OAEP);\n $this->content_encryption_key = $rsa->decrypt($this->jwe_encrypted_key);\n break;\n case 'dir':\n $this->content_encryption_key = $private_key_or_secret;\n break;\n case 'A128KW':\n case 'A256KW':\n case 'ECDH-ES':\n case 'ECDH-ES+A128KW':\n case 'ECDH-ES+A256KW':\n throw new JOSE_Exception_UnexpectedAlgorithm('Algorithm not supported');\n default:\n throw new JOSE_Exception_UnexpectedAlgorithm('Unknown algorithm');\n }\n if (!$this->content_encryption_key) {\n # NOTE:\n # Not to disclose timing difference between CEK decryption error and others.\n # Mitigating Bleichenbacher Attack on PKCS#1 v1.5\n # ref.) http://inaz2.hatenablog.com/entry/2016/01/26/222303\n $this->generateContentEncryptionKey(null);\n }\n }", "label_name": "CWE-200", "label": 10} +{"code": " public function AddCC($address, $name = '') {\n return $this->AddAnAddress('cc', $address, $name);\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function update_discount() {\n $id = empty($this->params['id']) ? null : $this->params['id'];\n $discount = new discounts($id);\n // find required shipping method if needed\n if ($this->params['required_shipping_calculator_id'] > 0) {\n $this->params['required_shipping_method'] = $this->params['required_shipping_methods'][$this->params['required_shipping_calculator_id']];\n } else {\n $this->params['required_shipping_calculator_id'] = 0;\n }\n \n $discount->update($this->params);\n expHistory::back();\n }", "label_name": "CWE-74", "label": 1} +{"code": " public function theme_switch() {\n if (!expUtil::isReallyWritable(BASE.'framework/conf/config.php')) { // we can't write to the config.php file\n flash('error',gt('The file /framework/conf/config.php is NOT Writeable. You will be unable to change the theme.'));\n }\n \texpSettings::change('DISPLAY_THEME_REAL', $this->params['theme']);\n\t expSession::set('display_theme',$this->params['theme']);\n\t $sv = isset($this->params['sv'])?$this->params['sv']:'';\n\t if (strtolower($sv)=='default') {\n\t $sv = '';\n\t }\n\t expSettings::change('THEME_STYLE_REAL',$sv);\n\t expSession::set('theme_style',$sv);\n\t expDatabase::install_dbtables(); // update tables to include any custom definitions in the new theme\n\n // $message = (MINIFY != 1) ? \"Exponent is now minifying Javascript and CSS\" : \"Exponent is no longer minifying Javascript and CSS\" ;\n // flash('message',$message);\n\t $message = gt(\"You have selected the\").\" '\".$this->params['theme'].\"' \".gt(\"theme\");\n\t if ($sv != '') {\n\t\t $message .= ' '.gt('with').' '.$this->params['sv'].' '.gt('style variation');\n\t }\n\t flash('message',$message);\n// expSession::un_set('framework');\n expSession::set('force_less_compile', 1);\n// expTheme::removeSmartyCache();\n expSession::clearAllUsersSessionCache();\n \texpHistory::returnTo('manageable');\n }\t", "label_name": "CWE-74", "label": 1} +{"code": " public function chmod() {\n if (!AuthUser::hasPermission('file_manager_chmod')) {\n Flash::set('error', __('You do not have sufficient permissions to change the permissions on a file or directory.'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n\n // CSRF checks\n if (isset($_POST['csrf_token'])) {\n $csrf_token = $_POST['csrf_token'];\n if (!SecureToken::validateToken($csrf_token, BASE_URL.'plugin/file_manager/chmod')) {\n Flash::set('error', __('Invalid CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n }\n else {\n Flash::set('error', __('No CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n \n $data = $_POST['file'];\n $data['name'] = str_replace('..', '', $data['name']);\n $file = FILES_DIR . '/' . $data['name'];\n\n if (file_exists($file)) {\n if (@!chmod($file, octdec($data['mode'])))\n Flash::set('error', __('Permission denied!'));\n }\n else {\n Flash::set('error', __('File or directory not found!'));\n }\n\n $path = substr($data['name'], 0, strrpos($data['name'], '/'));\n redirect(get_url('plugin/file_manager/browse/' . $path));\n }", "label_name": "CWE-20", "label": 0} +{"code": " function insertObject($object, $table) {\n //if ($table==\"text\") eDebug($object,true); \n $sql = \"INSERT INTO `\" . $this->prefix . \"$table` (\";\n $values = \") VALUES (\";\n foreach (get_object_vars($object) as $var => $val) {\n //We do not want to save any fields that start with an '_'\n if ($var{0} != '_') {\n $sql .= \"`$var`,\";\n if ($values != \") VALUES (\") {\n $values .= \",\";\n }\n $values .= \"'\" . $this->escapeString($val) . \"'\";\n }\n }\n $sql = substr($sql, 0, -1) . substr($values, 0) . \")\";\n //if($table=='text')eDebug($sql,true);\n if (@mysqli_query($this->connection, $sql) != false) {\n $id = mysqli_insert_id($this->connection);\n return $id;\n } else\n return 0;\n }", "label_name": "CWE-74", "label": 1} +{"code": " public function params()\n {\n $project = $this->getProject();\n $values = $this->request->getValues();\n\n if (empty($values['action_name']) || empty($values['project_id']) || empty($values['event_name'])) {\n $this->create();\n return;\n }\n\n $action = $this->actionManager->getAction($values['action_name']);\n $action_params = $action->getActionRequiredParameters();\n\n if (empty($action_params)) {\n $this->doCreation($project, $values + array('params' => array()));\n }\n\n $projects_list = $this->projectUserRoleModel->getActiveProjectsByUser($this->userSession->getId());\n unset($projects_list[$project['id']]);\n\n $this->response->html($this->template->render('action_creation/params', array(\n 'values' => $values,\n 'action_params' => $action_params,\n 'columns_list' => $this->columnModel->getList($project['id']),\n 'users_list' => $this->projectUserRoleModel->getAssignableUsersList($project['id']),\n 'projects_list' => $projects_list,\n 'colors_list' => $this->colorModel->getList(),\n 'categories_list' => $this->categoryModel->getList($project['id']),\n 'links_list' => $this->linkModel->getList(0, false),\n 'priorities_list' => $this->projectTaskPriorityModel->getPriorities($project),\n 'project' => $project,\n 'available_actions' => $this->actionManager->getAvailableActions(),\n 'swimlane_list' => $this->swimlaneModel->getList($project['id']),\n 'events' => $this->actionManager->getCompatibleEvents($values['action_name']),\n )));\n }", "label_name": "CWE-200", "label": 10} +{"code": " protected function setUp()\n {\n static::$functions = [];\n static::$fopen = null;\n static::$fread = null;\n parent::setUp();\n $this->security = new ExposedSecurity();\n $this->security->derivationIterations = 1000; // speed up test running\n }", "label_name": "CWE-330", "label": 12} +{"code": " protected function forceChangePassword()\n {\n if (!Yii::$app->user->isMustChangePasswordUrl()) {\n return Yii::$app->getResponse()->redirect(Url::toRoute(Yii::$app->user->mustChangePasswordRoute));\n }\n }", "label_name": "CWE-863", "label": 11} +{"code": " public function testGetDropdownValue($params, $expected, $session_params = []) {\n $this->login();\n\n $bkp_params = [];\n //set session params if any\n if (count($session_params)) {\n foreach ($session_params as $param => $value) {\n if (isset($_SESSION[$param])) {\n $bkp_params[$param] = $_SESSION[$param];\n }\n $_SESSION[$param] = $value;\n }\n }\n\n $params['_idor_token'] = \\Session::getNewIDORToken($params['itemtype'] ?? '');\n\n $result = \\Dropdown::getDropdownValue($params, false);\n\n //reset session params before executing test\n if (count($session_params)) {\n foreach ($session_params as $param => $value) {\n if (isset($bkp_params[$param])) {\n $_SESSION[$param] = $bkp_params[$param];\n } else {\n unset($_SESSION[$param]);\n }\n }\n }\n\n $this->array($result)->isIdenticalTo($expected);\n }", "label_name": "CWE-862", "label": 8} +{"code": " function showByModel() {\n global $order, $template, $db;\n\n expHistory::set('viewable', $this->params);\n $product = new product();\n $model = $product->find(\"first\", 'model=\"' . $this->params['model'] . '\"');\n //eDebug($model);\n $product_type = new $model->product_type($model->id);\n //eDebug($product_type);\n $tpl = $product_type->getForm('show');\n if (!empty($tpl)) $template = new controllertemplate($this, $tpl);\n //eDebug($template);\n $this->grabConfig(); // grab the global config\n assign_to_template(array(\n 'config' => $this->config,\n 'product' => $product_type,\n 'last_category' => $order->lastcat\n ));\n }", "label_name": "CWE-20", "label": 0} +{"code": "\tpublic function setItemAttributes( $attributes ) {\n\t\t$this->itemAttributes = \\Sanitizer::fixTagAttributes( $attributes, 'li' );\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " function categoryBreadcrumb() {\n// global $db, $router;\n\n //eDebug($this->category);\n\n /*if(isset($router->params['action']))\n {\n $ancestors = $this->category->pathToNode(); \n }else if(isset($router->params['section']))\n {\n $current = $db->selectObject('section',' id= '.$router->params['section']);\n $ancestors[] = $current;\n if( $current->parent != -1 || $current->parent != 0 )\n { \n while ($db->selectObject('section',' id= '.$router->params['section']);)\n if ($section->id == $id) {\n $current = $section;\n break;\n }\n }\n }\n eDebug($sections);\n $ancestors = $this->category->pathToNode(); \n }*/\n\n $ancestors = $this->category->pathToNode();\n // eDebug($ancestors);\n assign_to_template(array(\n 'ancestors' => $ancestors\n ));\n }", "label_name": "CWE-74", "label": 1} +{"code": " $db->insertObject($obj, 'expeAlerts_subscribers');\n }\n \n $count = count($this->params['ealerts']);\n \n if ($count > 0) {\n flash('message', gt(\"Your subscriptions have been updated. You are now subscriber to\").\" \".$count.' '.gt('E-Alerts.'));\n } else {\n flash('error', gt(\"You have been unsubscribed from all E-Alerts.\"));\n }\n \n expHistory::back();\n }", "label_name": "CWE-74", "label": 1} +{"code": "\t\t\tforeach($paths as $path)\n\t\t\t{\n\t\t\t\t// Convert wild-cards to RegEx\n\t\t\t\t$path = str_replace(array(':any', '*'), '.*', str_replace(':num', '[0-9]+', $path));\n\n\t\t\t\t// Does the RegEx match?\n\t\t\t\tif (!empty($_SERVER['HTTP_HOST']) AND preg_match('#^'.$path.'$#', $_SERVER['HTTP_HOST']))\n\t\t\t\t{\n\t\t\t\t\tdefine('ENVIRONMENT', $env);\n\t\t\t\t\tbreak 2;\n\t\t\t\t}\n\t\t\t}", "label_name": "CWE-74", "label": 1} +{"code": " public function checkRedirect(RequestInterface $request, array $options, ResponseInterface $response)\n {\n if (\\strpos((string) $response->getStatusCode(), '3') !== 0\n || !$response->hasHeader('Location')\n ) {\n return $response;\n }\n\n $this->guardMax($request, $response, $options);\n $nextRequest = $this->modifyRequest($request, $options, $response);\n\n // If authorization is handled by curl, unset it if host is different.\n if ($request->getUri()->getHost() !== $nextRequest->getUri()->getHost()\n && defined('\\CURLOPT_HTTPAUTH')\n ) {\n unset(\n $options['curl'][\\CURLOPT_HTTPAUTH],\n $options['curl'][\\CURLOPT_USERPWD]\n );\n }\n\n if (isset($options['allow_redirects']['on_redirect'])) {\n ($options['allow_redirects']['on_redirect'])(\n $request,\n $response,\n $nextRequest->getUri()\n );\n }\n\n $promise = $this($nextRequest, $options);\n\n // Add headers to be able to track history of redirects.\n if (!empty($options['allow_redirects']['track_redirects'])) {\n return $this->withTracking(\n $promise,\n (string) $nextRequest->getUri(),\n $response->getStatusCode()\n );\n }\n\n return $promise;\n }", "label_name": "CWE-200", "label": 10} +{"code": "\tprivate function _allrevisionsbefore( $option ) {\n\t\t$this->addTable( 'revision_actor_temp', 'rev' );\n\t\t$this->addSelect(\n\t\t\t[\n\t\t\t\t'rev.revactor_rev',\n\t\t\t\t'rev.revactor_timestamp'\n\t\t\t]\n\t\t);\n\t\t$this->addOrderBy( 'rev.revactor_rev' );\n\t\t$this->setOrderDir( 'DESC' );\n\t\t$this->addWhere(\n\t\t\t[\n\t\t\t\t$this->tableNames['page'] . '.page_id = rev.revactor_page',\n\t\t\t\t'rev.revactor_timestamp < ' . $this->convertTimestamp( $option )\n\t\t\t]\n\t\t);\n\t}", "label_name": "CWE-400", "label": 2} +{"code": "\t\t\t$eml->prepareBody();\n\t\t}\n\n list ($success, $message) = $this->checkDoNotEmailFields ($eml);\n if (!$success) {\n return array ($success, $message);\n }\n\n\t\t$result = $eml->send($historyFlag);\n\t\tif (isset($result['code']) && $result['code'] == 200) {\n if (YII_UNIT_TESTING) {\n return array(true, $eml->message);\n } else {\n return array(true, \"\");\n }\n } else {\n return array (false, Yii::t('app', \"Email could not be sent\"));\n }\n\t}", "label_name": "CWE-20", "label": 0} +{"code": " public function search(){\n // Warning: Please modify the following code to remove attributes that\n // should not be searched.\n\n $criteria = new CDbCriteria;\n $username = Yii::app()->user->name;\n $criteria->addCondition(\"uploadedBy='$username' OR private=0 OR private=null\");\n $criteria->addCondition(\"associationType != 'theme'\");\n return $this->searchBase($criteria);\n }", "label_name": "CWE-20", "label": 0} +{"code": " $chats[$index]->link = erLhcoreClassXMP::getBaseHost() . $_SERVER['HTTP_HOST'] . erLhcoreClassDesign::baseurl('user/login').'/(r)/'.rawurlencode(base64_encode('chat/single/'.$chat->id));\n }\n }", "label_name": "CWE-116", "label": 15} +{"code": " static function isSearchable() { return true; }\r", "label_name": "CWE-74", "label": 1} +{"code": "function XMLRPCremoveResourceGroupPriv($name, $type, $nodeid, $permissions){\n require_once(\".ht-inc/privileges.php\");\n global $user;\n\n if(! checkUserHasPriv(\"resourceGrant\", $user['id'], $nodeid)){\n return array('status' => 'error',\n 'errorcode' => 53,\n 'errormsg' => 'Unable to remove group privileges on this node');\n }\n if($typeid = getResourceTypeID($type)){\n if(!checkForGroupName($name, 'resource', '', $typeid)){\n return array('status' => 'error',\n 'errorcode' => 28,\n 'errormsg' => 'resource group does not exist');\n }\n $perms = explode(':', $permissions);\n updateResourcePrivs(\"$type/$name\", $nodeid, array(), $perms);\n return array('status' => 'success');\n } else {\n return array('status' => 'error',\n 'errorcode' => 56,\n 'errormsg' => 'Invalid resource type');\n }\n}", "label_name": "CWE-20", "label": 0} +{"code": " $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn];", "label_name": "CWE-863", "label": 11} +{"code": " private function generateFakeFileData()\n {\n return [\n 'name' => md5(mt_rand()),\n 'tmp_name' => md5(mt_rand()),\n 'type' => 'image/jpeg',\n 'size' => mt_rand(1000, 10000),\n 'error' => '0',\n ];\n }", "label_name": "CWE-330", "label": 12} +{"code": " foreach ($nodes as $node) {\r\n if ((($perm == 'view' && $node->public == 1) || expPermissions::check($perm, expCore::makeLocation('navigation', '', $node->id))) && !in_array($node->id, $ignore_ids)) {\r\n if ($node->active == 1) {\r\n $text = str_pad('', ($depth + ($full ? 1 : 0)) * 3, '.', STR_PAD_LEFT) . $node->name;\r\n } else {\r\n $text = str_pad('', ($depth + ($full ? 1 : 0)) * 3, '.', STR_PAD_LEFT) . '(' . $node->name . ')';\r\n }\r\n $ar[$node->id] = $text;\r\n foreach (self::levelDropdownControlArray($node->id, $depth + 1, $ignore_ids, $full, $perm, $addstandalones, $addinternalalias) as $id => $text) {\r\n $ar[$id] = $text;\r\n }\r\n }\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public static function hasChildren($i) {\r\n global $sections;\r\n\r\n if (($i + 1) >= count($sections)) return false;\r\n return ($sections[$i]->depth < $sections[$i + 1]->depth) ? true : false;\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public function chmod() {\n if (!AuthUser::hasPermission('file_manager_chmod')) {\n Flash::set('error', __('You do not have sufficient permissions to change the permissions on a file or directory.'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n\n // CSRF checks\n if (isset($_POST['csrf_token'])) {\n $csrf_token = $_POST['csrf_token'];\n if (!SecureToken::validateToken($csrf_token, BASE_URL.'plugin/file_manager/chmod')) {\n Flash::set('error', __('Invalid CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n }\n else {\n Flash::set('error', __('No CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n \n $data = $_POST['file'];\n $data['name'] = str_replace('..', '', $data['name']);\n $file = FILES_DIR . '/' . $data['name'];\n\n if (file_exists($file)) {\n if (@!chmod($file, octdec($data['mode'])))\n Flash::set('error', __('Permission denied!'));\n }\n else {\n Flash::set('error', __('File or directory not found!'));\n }\n\n $path = substr($data['name'], 0, strrpos($data['name'], '/'));\n redirect(get_url('plugin/file_manager/browse/' . $path));\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function settings() {\n AuthUser::load();\n if (!AuthUser::isLoggedIn()) {\n redirect(get_url('login'));\n } else if (!AuthUser::hasPermission('admin_edit')) {\n Flash::set('error', __('You do not have permission to access the requested page!'));\n redirect(get_url());\n }\n \n $settings = Plugin::getAllSettings('file_manager');\n\n if (!$settings) {\n Flash::set('error', 'Files - ' . __('unable to retrieve plugin settings.'));\n return;\n }\n\n $this->display('file_manager/views/settings', array('settings' => $settings));\n }", "label_name": "CWE-20", "label": 0} +{"code": "\tpublic function approve_toggle() {\n\t if (empty($this->params['id'])) return;\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n// $require_login = empty($this->params['require_login']) ? COMMENTS_REQUIRE_LOGIN : $this->params['require_login'];\n// $require_approval = empty($this->params['require_approval']) ? COMMENTS_REQUIRE_APPROVAL : $this->params['require_approval'];\n// $require_notification = empty($this->params['require_notification']) ? COMMENTS_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n// $notification_email = empty($this->params['notification_email']) ? COMMENTS_NOTIFICATION_EMAIL : $this->params['notification_email'];\n\n\t $comment = new expComment($this->params['id']);\n\t $comment->approved = $comment->approved == 1 ? 0 : 1;\n\t if ($comment->approved) {\n\t\t $this->sendApprovalNotification($comment,$this->params);\n\t }\n\t $comment->save();\n\t expHistory::back();\n\t}", "label_name": "CWE-74", "label": 1} +{"code": " public function Close() {\n $this->error = null; // so there is no confusion\n $this->helo_rply = null;\n if(!empty($this->smtp_conn)) {\n // close the connection and cleanup\n fclose($this->smtp_conn);\n $this->smtp_conn = 0;\n }\n }", "label_name": "CWE-20", "label": 0} +{"code": " function edit_externalalias() {\r\n $section = isset($this->params['id']) ? $this->section->find($this->params['id']) : new section($this->params);\r\n if ($section->parent == -1) {\r\n notfoundController::handle_not_found();\r\n exit;\r\n } // doesn't work for standalone pages\r\n if (empty($section->id)) {\r\n $section->public = 1;\r\n if (!isset($section->parent)) {\r\n // This is another precaution. The parent attribute\r\n // should ALWAYS be set by the caller.\r\n //FJD - if that's the case, then we should die.\r\n notfoundController::handle_not_authorized();\r\n exit;\r\n //$section->parent = 0;\r\n }\r\n }\r\n assign_to_template(array(\r\n 'section' => $section,\r\n 'glyphs' => self::get_glyphs(),\r\n ));\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": "function check_file_dir_name($label) {\n if (empty($label) || preg_match('/[^A-Za-z0-9_.-]/', $label))\n die(xlt(\"ERROR: The following variable contains invalid characters\").\": \". attr($label));\n}", "label_name": "CWE-116", "label": 15} +{"code": " public function event()\n {\n $project = $this->getProject();\n $values = $this->request->getValues();\n\n if (empty($values['action_name']) || empty($values['project_id'])) {\n return $this->create();\n }\n\n return $this->response->html($this->template->render('action_creation/event', array(\n 'values' => $values,\n 'project' => $project,\n 'available_actions' => $this->actionManager->getAvailableActions(),\n 'events' => $this->actionManager->getCompatibleEvents($values['action_name']),\n )));\n }", "label_name": "CWE-200", "label": 10} +{"code": "\t\tpublic function setRemoteUrl($name, $url, array $params = NULL)\n\t\t{\n\t\t\t$this->run('remote', 'set-url', $params, $name, $url);\n\t\t\treturn $this;\n\t\t}", "label_name": "CWE-77", "label": 14} +{"code": " private function checkAuthenticationTag() {\n if ($this->authentication_tag === $this->calculateAuthenticationTag()) {\n return true;\n } else {\n throw new JOSE_Exception_UnexpectedAlgorithm('Invalid authentication tag');\n }\n }", "label_name": "CWE-200", "label": 10} +{"code": "\tstatic function convertUTF($string) {\n\t\treturn $string = str_replace('?', '', htmlspecialchars($string, ENT_IGNORE, 'UTF-8'));\n\t} ", "label_name": "CWE-74", "label": 1} +{"code": " public function execute(&$params){\n $action = new Actions;\n $action->associationType = lcfirst(get_class($params['model']));\n $action->associationId = $params['model']->id;\n $action->subject = $this->parseOption('subject', $params);\n $action->actionDescription = $this->parseOption('description', $params);\n if($params['model']->hasAttribute('assignedTo'))\n $action->assignedTo = $params['model']->assignedTo;\n if($params['model']->hasAttribute('priority'))\n $action->priority = $params['model']->priority;\n if($params['model']->hasAttribute('visibility'))\n $action->visibility = $params['model']->visibility;\n\n if ($action->save()) {\n return array (\n true,\n Yii::t('studio', \"View created action: \").$action->getLink ()\n );\n } else {\n return array(false, array_shift($action->getErrors()));\n }\n\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function testDecrypt($expected, $key, $string) {\n $this->string(\\Toolbox::decrypt($string, $key))->isIdenticalTo($expected);\n }", "label_name": "CWE-327", "label": 3} +{"code": "\t\tpublic function renameTag($oldName, $newName)\n\t\t{\n\t\t\t// http://stackoverflow.com/a/1873932\n\t\t\t// create new as alias to old (`git tag NEW OLD`)\n\t\t\t$this->run('tag', $newName, $oldName);\n\t\t\t// delete old (`git tag -d OLD`)\n\t\t\t$this->removeTag($oldName);\n\t\t\treturn $this;\n\t\t}", "label_name": "CWE-77", "label": 14} +{"code": " public function activate_discount(){ \n if (isset($this->params['id'])) {\n $discount = new discounts($this->params['id']);\n $discount->update($this->params);\n //if ($discount->discountulator->hasConfig() && empty($discount->config)) {\n //flash('messages', $discount->discountulator->name().' requires configuration. Please do so now.');\n //redirect_to(array('controller'=>'billing', 'action'=>'configure', 'id'=>$discount->id));\n //}\n }\n \n expHistory::back();\n }", "label_name": "CWE-74", "label": 1} +{"code": " static function getRSSFeed($url, $cache_duration = DAY_TIMESTAMP) {\n global $CFG_GLPI;\n\n $feed = new SimplePie();\n $feed->set_cache_location(GLPI_RSS_DIR);\n $feed->set_cache_duration($cache_duration);\n\n // proxy support\n if (!empty($CFG_GLPI[\"proxy_name\"])) {\n $prx_opt = [];\n $prx_opt[CURLOPT_PROXY] = $CFG_GLPI[\"proxy_name\"];\n $prx_opt[CURLOPT_PROXYPORT] = $CFG_GLPI[\"proxy_port\"];\n if (!empty($CFG_GLPI[\"proxy_user\"])) {\n $prx_opt[CURLOPT_HTTPAUTH] = CURLAUTH_ANYSAFE;\n $prx_opt[CURLOPT_PROXYUSERPWD] = $CFG_GLPI[\"proxy_user\"].\":\".\n Toolbox::decrypt($CFG_GLPI[\"proxy_passwd\"],\n GLPIKEY);\n }\n $feed->set_curl_options($prx_opt);\n }\n\n $feed->enable_cache(true);\n $feed->set_feed_url($url);\n $feed->force_feed(true);\n // Initialize the whole SimplePie object. Read the feed, process it, parse it, cache it, and\n // all that other good stuff. The feed's information will not be available to SimplePie before\n // this is called.\n $feed->init();\n\n // We'll make sure that the right content type and character encoding gets set automatically.\n // This function will grab the proper character encoding, as well as set the content type to text/html.\n $feed->handle_content_type();\n if ($feed->error()) {\n return false;\n }\n return $feed;\n }", "label_name": "CWE-327", "label": 3} +{"code": " public function browse() {\n $params = func_get_args();\n\n $this->path = join('/', $params);\n // make sure there's a / at the end\n if (substr($this->path, -1, 1) != '/')\n $this->path .= '/';\n\n //security\n // we dont allow back link\n if (strpos($this->path, '..') !== false) {\n /*\n if (Plugin::isEnabled('statistics_api')) {\n $user = null;\n if (AuthUser::isLoggedIn())\n $user = AuthUser::getUserName();\n $ip = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : ($_SERVER['REMOTE_ADDR']);\n $event = array('event_type' => 'hack_attempt', // simple event type identifier\n 'description' => __('A possible hack attempt was detected.'), // translatable description\n 'ipaddress' => $ip,\n 'username' => $user);\n Observer::notify('stats_file_manager_hack_attempt', $event);\n }\n */\n }\n $this->path = str_replace('..', '', $this->path);\n\n // clean up nicely\n $this->path = str_replace('//', '', $this->path);\n\n // we dont allow leading slashes\n $this->path = preg_replace('/^\\//', '', $this->path);\n\n $this->fullpath = FILES_DIR . '/' . $this->path;\n\n // clean up nicely\n $this->fullpath = preg_replace('/\\/\\//', '/', $this->fullpath);\n\n $this->display('file_manager/views/index', array(\n 'dir' => $this->path,\n //'files' => $this->_getListFiles()\n 'files' => $this->_listFiles()\n ));\n }", "label_name": "CWE-20", "label": 0} +{"code": " static function authenticate() {\n if (isset($_REQUEST['backend_login'])) {\n $user = DB_DataObject::factory('users');\n $user->active = true;\n $user->name = $_REQUEST['username'];\n $user->find(true);\n\n // Don't look whether that user exists, so we give less timing information\n // Instead, rely only on having a matching password\n $proffered_password = $_REQUEST['password'];\n if (in_array(\n $user->password,\n self::password_hashes($proffered_password, $user->password_salt)\n )) {\n // Regenerate the session ID, unless it's an IE we're talking to which would use the old session ID to load the frame contents\n // Remove this guard once we no longer use frames\n if(!preg_match('/(?i)msie /', $_SERVER['HTTP_USER_AGENT'])) {\n session_regenerate_id();\n }\n $user->login();\n \n return $user;\n } else {\n Log::warn(\"Failed login for user name '\".$_REQUEST['username'].\"' from \" . $_SERVER['REMOTE_ADDR'].' user-agent '.$_SERVER['HTTP_USER_AGENT']);\n return -1;\n }\n }\n return false;\n }", "label_name": "CWE-522", "label": 19} +{"code": " $comments->records[$key]->avatar = $db->selectObject('user_avatar',\"user_id='\".$record->poster.\"'\");\n }\n\n if (empty($this->params['config']['disable_nested_comments'])) $comments->records = self::arrangecomments($comments->records);\n // eDebug($sql, true);\n \n // count the unapproved comments\n if ($require_approval == 1 && $user->isAdmin()) {\n $sql = 'SELECT count(com.id) as c FROM '.$db->prefix.'expComments com ';\n $sql .= 'JOIN '.$db->prefix.'content_expComments cnt ON com.id=cnt.expcomments_id ';\n $sql .= 'WHERE cnt.content_id='.$this->params['content_id'].\" AND cnt.content_type='\".$this->params['content_type'].\"' \";\n $sql .= 'AND com.approved=0';\n $unapproved = $db->countObjectsBySql($sql);\n } else {\n $unapproved = 0;\n } \n \n $this->config = $this->params['config'];\n $type = !empty($this->params['type']) ? $this->params['type'] : gt('Comment');\n $ratings = !empty($this->params['ratings']) ? true : false;\n\n assign_to_template(array(\n 'comments'=>$comments,\n 'config'=>$this->params['config'],\n 'unapproved'=>$unapproved,\n\t\t\t'content_id'=>$this->params['content_id'], \n\t\t\t'content_type'=>$this->params['content_type'],\n\t\t\t'user'=>$user,\n\t\t\t'hideform'=>$this->params['hideform'],\n\t\t\t'hidecomments'=>$this->params['hidecomments'],\n\t\t\t'title'=>$this->params['title'],\n\t\t\t'formtitle'=>$this->params['formtitle'],\n 'type'=>$type,\n 'ratings'=>$ratings,\n 'require_login'=>$require_login,\n 'require_approval'=>$require_approval,\n 'require_notification'=>$require_notification,\n 'notification_email'=>$notification_email,\n\t\t));\n\t}", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic function delete() {\n\t global $user;\n\n $count = $this->address->find('count', 'user_id=' . $user->id);\n if($count > 1)\n { \n $address = new address($this->params['id']);\n\t if ($user->isAdmin() || ($user->id == $address->user_id)) {\n if ($address->is_billing)\n {\n $billAddress = $this->address->find('first', 'user_id=' . $user->id . \" AND id != \" . $address->id);\n $billAddress->is_billing = true;\n $billAddress->save();\n }\n if ($address->is_shipping) \n {\n $shipAddress = $this->address->find('first', 'user_id=' . $user->id . \" AND id != \" . $address->id);\n $shipAddress->is_shipping = true;\n $shipAddress->save();\n }\n\t parent::delete();\n\t }\n }\n else\n {\n flash(\"error\", gt(\"You must have at least one address.\"));\n }\n\t expHistory::back();\n\t}", "label_name": "CWE-74", "label": 1} +{"code": " public function show()\n {\n $task = $this->getTask();\n $subtask = $this->getSubtask();\n\n $this->response->html($this->template->render('subtask_converter/show', array(\n 'subtask' => $subtask,\n 'task' => $task,\n )));\n }", "label_name": "CWE-200", "label": 10} +{"code": " public function testSmtpConnect()\n {\n $this->Mail->SMTPDebug = 4; //Show connection-level errors\n $this->assertTrue($this->Mail->smtpConnect(), 'SMTP single connect failed');\n $this->Mail->smtpClose();\n $this->Mail->Host = \"ssl://localhost:12345;tls://localhost:587;10.10.10.10:54321;localhost:12345;10.10.10.10\";\n $this->assertFalse($this->Mail->smtpConnect(), 'SMTP bad multi-connect succeeded');\n $this->Mail->smtpClose();\n $this->Mail->Host = \"localhost:12345;10.10.10.10:54321;\" . $_REQUEST['mail_host'];\n $this->assertTrue($this->Mail->smtpConnect(), 'SMTP multi-connect failed');\n $this->Mail->smtpClose();\n $this->Mail->Host = \" localhost:12345 ; \" . $_REQUEST['mail_host'] . ' ';\n $this->assertTrue($this->Mail->smtpConnect(), 'SMTP hosts with stray spaces failed');\n $this->Mail->smtpClose();\n $this->Mail->Host = $_REQUEST['mail_host'];\n //Need to pick a harmless option so as not cause problems of its own! socket:bind doesn't work with Travis-CI\n $this->assertTrue(\n $this->Mail->smtpConnect(array('ssl' => array('verify_depth' => 10))),\n 'SMTP connect with options failed'\n );\n }", "label_name": "CWE-20", "label": 0} +{"code": " foreach ($allgroups as $gid) {\r\n $g = group::getGroupById($gid);\r\n expPermissions::grantGroup($g, 'manage', $sloc);\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " static function author() {\r\n return \"Dave Leffler\";\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public function subscriptions() {\n global $db;\n \n expHistory::set('manageable', $this->params);\n // make sure we have what we need.\n if (empty($this->params['key'])) expQueue::flashAndFlow('error', gt('The security key for account was not supplied.'));\n if (empty($this->params['id'])) expQueue::flashAndFlow('error', gt('The subscriber id for account was not supplied.'));\n \n // verify the id/key pair \n $sub = new subscribers($this->params['id']);\n if (empty($sub->id)) expQueue::flashAndFlow('error', gt('We could not find any subscriptions matching the ID and Key you provided.'));\n \n // get this users subscriptions\n $subscriptions = $db->selectColumn('expeAlerts_subscribers', 'expeAlerts_id', 'subscribers_id='.$sub->id);\n \n // get a list of all available E-Alerts\n $ealerts = new expeAlerts();\n assign_to_template(array(\n 'subscriber'=>$sub,\n 'subscriptions'=>$subscriptions,\n 'ealerts'=>$ealerts->find('all')\n ));\n }", "label_name": "CWE-74", "label": 1} +{"code": " public function edit()\n {\n if((isset($this->params['id']))) $record = new address(intval($this->params['id']));\n else $record = null;\n $config = ecomconfig::getConfig('address_allow_admins_all');\n assign_to_template(array(\n 'record'=>$record,\n 'admin_config'=>$config\n ));\n if (expSession::get('customer-signup')) {\n assign_to_template(array(\n 'checkout'=>true\n ));\n }\n }", "label_name": "CWE-200", "label": 10} +{"code": "function headerTestController($serverPort) {\n $args = array('Authorization' => 'foo');\n var_dump(request(php_uname('n'), $serverPort, \"test_headers.php\",\n [], ['PROXY' => 'foobar'], $args));\n}", "label_name": "CWE-668", "label": 7} +{"code": "\tpublic function addSelect( $fields ) {\n\t\tif ( !is_array( $fields ) ) {\n\t\t\tthrow new \\MWException( __METHOD__ . ': A non-array was passed.' );\n\t\t}\n\t\tforeach ( $fields as $alias => $field ) {\n\t\t\tif ( !is_numeric( $alias ) && array_key_exists( $alias, $this->select ) && $this->select[$alias] != $field ) {\n\t\t\t\t//In case of a code bug that is overwriting an existing field alias throw an exception.\n\t\t\t\tthrow new \\MWException( __METHOD__ . \": Attempted to overwrite existing field alias `{$this->select[$alias]}` AS `{$alias}` with `{$field}` AS `{$alias}`.\" );\n\t\t\t}\n\t\t\t//String alias and does not exist already.\n\t\t\tif ( !is_numeric( $alias ) && !array_key_exists( $alias, $this->select ) ) {\n\t\t\t\t$this->select[$alias] = $field;\n\t\t\t}\n\n\t\t\t//Speed up by not using in_array() or array_key_exists(). Toss the field names into their own array as keys => true to exploit a speedy look up with isset().\n\t\t\tif ( is_numeric( $alias ) && !isset( $this->selectedFields[$field] ) ) {\n\t\t\t\t$this->select[] = $field;\n\t\t\t\t$this->selectedFields[$field] = true;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " static function dropdownConnect($itemtype, $fromtype, $myname, $entity_restrict = -1,\n $onlyglobal = 0, $used = []) {\n global $CFG_GLPI;\n\n $rand = mt_rand();\n\n $field_id = Html::cleanId(\"dropdown_\".$myname.$rand);\n $param = [\n 'entity_restrict' => $entity_restrict,\n 'fromtype' => $fromtype,\n 'itemtype' => $itemtype,\n 'onlyglobal' => $onlyglobal,\n 'used' => $used,\n '_idor_token' => Session::getNewIDORToken($itemtype),\n ];\n\n echo Html::jsAjaxDropdown($myname, $field_id,\n $CFG_GLPI['root_doc'].\"/ajax/getDropdownConnect.php\",\n $param);\n\n return $rand;\n }", "label_name": "CWE-862", "label": 8} +{"code": " function move_standalone() {\r\n expSession::clearAllUsersSessionCache('navigation');\r\n assign_to_template(array(\r\n 'parent' => $this->params['parent'],\r\n ));\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": "\t\t\tVariables::setVar( [ '', '', $variable, $value ] );\n\t\t\tif ( defined( 'ExtVariables::VERSION' ) ) {\n\t\t\t\t\\ExtVariables::get( $this->parser )->setVarValue( $variable, $value );\n\t\t\t}\n\t\t}\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " private function runCallback() {\n foreach ($this->records as &$record) {\n if (isset($record->ref_type)) {\n $refType = $record->ref_type;\n if (class_exists($record->ref_type)) {\n $type = new $refType();\n $classinfo = new ReflectionClass($type);\n if ($classinfo->hasMethod('paginationCallback')) {\n $item = new $type($record->original_id);\n $item->paginationCallback($record);\n }\n }\n }\n } \n }", "label_name": "CWE-74", "label": 1} +{"code": " static function displayname() {\r\n return \"Events\";\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public function checkHTTP($link, $get_body = false)\n {\n if (! function_exists('curl_init')) {\n return null;\n }\n $handle = curl_init($link);\n if ($handle === false) {\n return null;\n }\n PMA_Util::configureCurl($handle);\n curl_setopt($handle, CURLOPT_FOLLOWLOCATION, 0);\n curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1);\n curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, 0);\n curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, 0);\n curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);\n curl_setopt($handle, CURLOPT_TIMEOUT, 5);\n curl_setopt($handle, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);\n if (! defined('TESTSUITE')) {\n session_write_close();\n }\n $data = @curl_exec($handle);\n if (! defined('TESTSUITE')) {\n ini_set('session.use_only_cookies', '0');\n ini_set('session.use_cookies', '0');\n ini_set('session.use_trans_sid', '0');\n ini_set('session.cache_limiter', 'nocache');\n session_start();\n }\n if ($data === false) {\n return null;\n }\n $http_status = curl_getinfo($handle, CURLINFO_HTTP_CODE);\n\n if ($http_status == 200) {\n return $get_body ? $data : true;\n }\n\n if ($http_status == 404) {\n return false;\n }\n return null;\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function testGetEventsPublicProfile(){\n TestingAuxLib::loadX2NonWebUser ();\n TestingAuxLib::suLogin ('testuser');\n\n Yii::app()->settings->historyPrivacy = null;\n $lastEventId=0;\n $lastTimestamp=0;\n $myProfile = Profile::model()->findByAttributes(array('username' => 'testuser2'));\n $events=Events::getEvents(\n $lastEventId,$lastTimestamp,null,$myProfile, false);\n $this->assertEquals (\n array_map (\n function ($event) { return $event->id; }, \n Events::model ()->findAllByAttributes (array (\n 'user' => 'testuser2',\n 'visibility' => 1 \n ))\n ),\n array_map (function ($event) { return $event->id; }, $events['events']));\n\n TestingAuxLib::restoreX2WebUser ();\n }", "label_name": "CWE-20", "label": 0} +{"code": " $comments->records[$key]->avatar = $db->selectObject('user_avatar',\"user_id='\".$record->poster.\"'\");\n }\n\n if (empty($this->params['config']['disable_nested_comments'])) $comments->records = self::arrangecomments($comments->records);\n // eDebug($sql, true);\n \n // count the unapproved comments\n if ($require_approval == 1 && $user->isAdmin()) {\n $sql = 'SELECT count(com.id) as c FROM '.$db->prefix.'expComments com ';\n $sql .= 'JOIN '.$db->prefix.'content_expComments cnt ON com.id=cnt.expcomments_id ';\n $sql .= 'WHERE cnt.content_id='.$this->params['content_id'].\" AND cnt.content_type='\".$this->params['content_type'].\"' \";\n $sql .= 'AND com.approved=0';\n $unapproved = $db->countObjectsBySql($sql);\n } else {\n $unapproved = 0;\n } \n \n $this->config = $this->params['config'];\n $type = !empty($this->params['type']) ? $this->params['type'] : gt('Comment');\n $ratings = !empty($this->params['ratings']) ? true : false;\n\n assign_to_template(array(\n 'comments'=>$comments,\n 'config'=>$this->params['config'],\n 'unapproved'=>$unapproved,\n\t\t\t'content_id'=>$this->params['content_id'], \n\t\t\t'content_type'=>$this->params['content_type'],\n\t\t\t'user'=>$user,\n\t\t\t'hideform'=>$this->params['hideform'],\n\t\t\t'hidecomments'=>$this->params['hidecomments'],\n\t\t\t'title'=>$this->params['title'],\n\t\t\t'formtitle'=>$this->params['formtitle'],\n 'type'=>$type,\n 'ratings'=>$ratings,\n 'require_login'=>$require_login,\n 'require_approval'=>$require_approval,\n 'require_notification'=>$require_notification,\n 'notification_email'=>$notification_email,\n\t\t));\n\t}", "label_name": "CWE-74", "label": 1} +{"code": " public static function getItems($term) {\n $model = X2Model::model(Yii::app()->controller->modelClass);\n if (isset($model)) {\n $tableName = $model->tableName();\n $sql = 'SELECT id, name as value \n FROM ' . $tableName . ' WHERE name LIKE :qterm ORDER BY name ASC';\n $command = Yii::app()->db->createCommand($sql);\n $qterm = $term . '%';\n $command->bindParam(\":qterm\", $qterm, PDO::PARAM_STR);\n $result = $command->queryAll();\n echo CJSON::encode($result);\n }\n Yii::app()->end();\n }", "label_name": "CWE-20", "label": 0} +{"code": "\tpublic function save_user() {\r\n\t\tif ( empty( $_POST['user_id'] ) ) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\t$user_id = $_POST['user_id'];\r\n\r\n\t\tif ( !is_numeric( $user_id ) ) {\r\n\t\t\treturn $user_id;\r\n\t\t}\r\n\r\n\t\tif ( !current_user_can( 'edit_user', $user_id ) ) {\r\n\t\t\treturn $user_id;\r\n\t\t}\r\n\r\n\t\treturn $this->save_posted_object_location( $user_id );\r\n\t}\r", "label_name": "CWE-20", "label": 0} +{"code": "\tstatic function convertUTF($string) {\n\t\treturn $string = str_replace('?', '', htmlspecialchars($string, ENT_IGNORE, 'UTF-8'));\n\t} ", "label_name": "CWE-74", "label": 1} +{"code": " private static function retrieveClosurePattern($pure, $closureName)\n {\n $pattern = '/';\n if (!$pure) {\n $pattern .= preg_quote(self::$registeredDelimiters[0]) . \"\\s*\";\n }\n $pattern .= \"$closureName\\(([a-z0-9,\\.\\s]+)\\)\";\n if (!$pure) {\n $pattern .= \"\\s*\" . preg_quote(self::$registeredDelimiters[1]);\n }\n return $pattern . \"/i\";\n }", "label_name": "CWE-74", "label": 1} +{"code": " $query->whereExists(function ($permissionQuery) use (&$tableDetails, $action) {\n /** @var Builder $permissionQuery */\n $permissionQuery->select(['role_id'])->from('joint_permissions')\n ->whereColumn('joint_permissions.entity_id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])\n ->whereColumn('joint_permissions.entity_type', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])\n ->where('action', '=', $action)\n ->whereIn('role_id', $this->getCurrentUserRoles())\n ->where(function (QueryBuilder $query) {\n $this->addJointHasPermissionCheck($query, $this->currentUser()->id);\n });\n });", "label_name": "CWE-863", "label": 11} +{"code": "\t\t\t$tokens = preg_split( '/ - */', $title );\n\t\t\t$newKey = '';\n\t\t\tforeach ( $tokens as $token ) {\n\t\t\t\t$initial = substr( $token, 0, 1 );\n\t\t\t\tif ( $initial >= '1' && $initial <= '7' ) {\n\t\t\t\t\t$newKey .= $initial;\n\t\t\t\t\t$suit = substr( $token, 1 );\n\t\t\t\t\tif ( $suit == '\u2663' ) {\n\t\t\t\t\t\t$newKey .= '1';\n\t\t\t\t\t} elseif ( $suit == '\u2666' ) {\n\t\t\t\t\t\t$newKey .= '2';\n\t\t\t\t\t} elseif ( $suit == '\u2665' ) {\n\t\t\t\t\t\t$newKey .= '3';\n\t\t\t\t\t} elseif ( $suit == '\u2660' ) {\n\t\t\t\t\t\t$newKey .= '4';\n\t\t\t\t\t} elseif ( strtolower( $suit ) == 'sa' || strtolower( $suit ) == 'nt' ) {\n\t\t\t\t\t\t$newKey .= '5 ';\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$newKey .= $suit;\n\t\t\t\t\t}\n\t\t\t\t} elseif ( strtolower( $initial ) == 'p' ) {\n\t\t\t\t\t$newKey .= '0 ';\n\t\t\t\t} elseif ( strtolower( $initial ) == 'x' ) {\n\t\t\t\t\t$newKey .= '8 ';\n\t\t\t\t} else {\n\t\t\t\t\t$newKey .= $token;\n\t\t\t\t}\n\t\t\t}\n\t\t\t$sortKeys[$key] = $newKey;\n\t\t}\n\t\tasort( $sortKeys );\n\t\tforeach ( $sortKeys as $oldKey => $newKey ) {\n\t\t\t$sortedArticles[] = $articles[$oldKey];\n\t\t}\n\t\treturn $sortedArticles;\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " public function testRemoveAuthorizationHeaderOnRedirect()\n {\n $mock = new MockHandler([\n new Response(302, ['Location' => 'http://test.com']),\n static function (RequestInterface $request) {\n self::assertFalse($request->hasHeader('Authorization'));\n return new Response(200);\n }\n ]);\n $handler = HandlerStack::create($mock);\n $client = new Client(['handler' => $handler]);\n $client->get('http://example.com?a=b', ['auth' => ['testuser', 'testpass']]);\n }", "label_name": "CWE-200", "label": 10} +{"code": "\tprivate function _titlegt( $option ) {\n\t\t$where = '(';\n\t\tif ( substr( $option, 0, 2 ) == '=_' ) {\n\t\t\tif ( $this->parameters->getParameter( 'openreferences' ) ) {\n\t\t\t\t$where .= 'pl_title >= ' . $this->DB->addQuotes( substr( $sTitleGE, 2 ) );\n\t\t\t} else {\n\t\t\t\t$where .= $this->tableNames['page'] . '.page_title >= ' . $this->DB->addQuotes( substr( $option, 2 ) );\n\t\t\t}\n\t\t} else {\n\t\t\tif ( $this->parameters->getParameter( 'openreferences' ) ) {\n\t\t\t\t$where .= 'pl_title > ' . $this->DB->addQuotes( $option );\n\t\t\t} else {\n\t\t\t\t$where .= $this->tableNames['page'] . '.page_title > ' . $this->DB->addQuotes( $option );\n\t\t\t}\n\t\t}\n\t\t$where .= ')';\n\t\t$this->addWhere( $where );\n\t}", "label_name": "CWE-400", "label": 2} +{"code": "\tpublic function enqueue_scripts() {\r\n\t\tglobal $geo_mashup_options, $pagenow, $post;\r\n\r\n\t\t// The location editor works only on posts\r\n\t\tif ( empty( $post ) )\r\n\t\t\treturn null;\r\n\r\n\t\t$load_location_editor = (\r\n\t\t\t\tis_admin() and\r\n\t\t\t\tpreg_match( '/(post|page)(-new|).php/', $pagenow ) and\r\n\t\t\t\tin_array( $post->post_type, $geo_mashup_options->get( 'overall', 'located_post_types' ) )\r\n\t\t\t\t);\r\n\t\t$load_location_editor = apply_filters( 'geo_mashup_load_location_editor', $load_location_editor );\r\n\r\n\t\t// If we're on a post editing page, queue up the form interface elements\r\n\t\tif ( $load_location_editor ) {\r\n\r\n\t\t\t$this->enqueue_form_client_items();\r\n\r\n\t\t} \r\n\t}\r", "label_name": "CWE-20", "label": 0} +{"code": " public function upload() {\n \n // upload the file, but don't save the record yet...\n if ($this->params['resize'] != 'false') {\n $maxwidth = $this->params['max_width'];\n } else {\n $maxwidth = null;\n }\n $file = expFile::fileUpload('Filedata',false,false,null,null,$maxwidth);\n // since most likely this function will only get hit via flash in YUI Uploader\n // and since Flash can't pass cookies, we lose the knowledge of our $user\n // so we're passing the user's ID in as $_POST data. We then instantiate a new $user,\n // and then assign $user->id to $file->poster so we have an audit trail for the upload\n\n if (is_object($file)) {\n $resized = !empty($file->resized) ? true : false;\n $user = new user($this->params['usrid']);\n $file->poster = $user->id;\n $file->posted = $file->last_accessed = time();\n $file->save();\n if (!empty($this->params['cat'])) {\n $expcat = new expCat($this->params['cat']);\n $params['expCat'][0] = $expcat->id;\n $file->update($params);\n }\n\n // a echo so YUI Uploader is notified of the function's completion\n if ($resized) {\n echo gt('File resized and then saved');\n } else {\n echo gt('File saved');\n }\n } else {\n echo gt('File was NOT uploaded!');\n// flash('error',gt('File was not uploaded!'));\n }\n } ", "label_name": "CWE-74", "label": 1} +{"code": " function build_daterange_sql($timestamp, $endtimestamp=null, $field='date', $multiday=false) {\r\n if (empty($endtimestamp)) {\r\n $date_sql = \"((\".$field.\" >= \" . expDateTime::startOfDayTimestamp($timestamp) . \" AND \".$field.\" <= \" . expDateTime::endOfDayTimestamp($timestamp) . \")\";\r\n } else {\r\n $date_sql = \"((\".$field.\" >= \" . expDateTime::startOfDayTimestamp($timestamp) . \" AND \".$field.\" <= \" . expDateTime::endOfDayTimestamp($endtimestamp) . \")\";\r\n }\r\n if ($multiday)\r\n $date_sql .= \" OR (\" . expDateTime::startOfDayTimestamp($timestamp) . \" BETWEEN \".$field.\" AND dateFinished)\";\r\n $date_sql .= \")\";\r\n return $date_sql;\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public function execute(&$params){\n $options = &$this->config['options'];\n\n $event = new Events;\n $notif = new Notification;\n\n $user = $this->parseOption('user', $params);\n\n $type = $this->parseOption('type', $params);\n\n if($type === 'auto'){\n if(!isset($params['model']))\n return array (false, '');\n $notif->modelType = get_class($params['model']);\n $notif->modelId = $params['model']->id;\n $notif->type = $this->getNotifType();\n\n $event->associationType = get_class($params['model']);\n $event->associationId = $params['model']->id;\n $event->type = $this->getEventType();\n if($params['model']->hasAttribute('visibility'))\n $event->visibility = $params['model']->visibility;\n // $event->user = $this->parseOption('user',$params);\n } else{\n $text = $this->parseOption('text', $params);\n\n $notif->type = 'custom';\n $notif->text = $text;\n\n $event->type = 'feed';\n $event->subtype = $type;\n $event->text = $text;\n if($user == 'auto' && isset($params['model']) && \n $params['model']->hasAttribute('assignedTo') && \n !empty($params['model']->assignedTo)){\n\n $event->user = $params['model']->assignedTo;\n }elseif(!empty($user)){\n $event->user = $user;\n }else{\n $event->user = 'admin';\n }\n }\n if(!$this->parseOption('createNotif', $params)) {\n if (!$notif->save()) {\n return array(false, array_shift($notif->getErrors()));\n }\n }\n\n if ($event->save()) {\n return array (true, \"\");\n } else {\n return array(false, array_shift($event->getErrors()));\n }\n\n }", "label_name": "CWE-20", "label": 0} +{"code": " private function getCategory()\n {\n $category = $this->categoryModel->getById($this->request->getIntegerParam('category_id'));\n\n if (empty($category)) {\n throw new PageNotFoundException();\n }\n\n return $category;\n }", "label_name": "CWE-200", "label": 10} +{"code": " function fread($handle, $length)\n {\n if (\\yiiunit\\framework\\base\\SecurityTest::$fread !== null) {\n return \\yiiunit\\framework\\base\\SecurityTest::$fread;\n }\n if (\\yiiunit\\framework\\base\\SecurityTest::$fopen !== null) {\n return $length < 8 ? \\str_repeat('s', $length) : 'test1234';\n }\n\n return \\fread($handle, $length);\n }", "label_name": "CWE-330", "label": 12} +{"code": " function edit_option_master() {\n expHistory::set('editable', $this->params);\n \n $params = isset($this->params['id']) ? $this->params['id'] : $this->params;\n $record = new option_master($params); \n assign_to_template(array(\n 'record'=>$record\n ));\n }", "label_name": "CWE-74", "label": 1} +{"code": " public function getDisplayName ($plural=true) {\n return Yii::t('users', '{user}', array(\n '{user}' => Modules::displayName($plural, 'Users'),\n ));\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function getClone($modelId = null)\n {\n $this->authorize('view', AssetModel::class);\n // Check if the model exists\n if (is_null($model_to_clone = AssetModel::find($modelId))) {\n return redirect()->route('models.index')->with('error', trans('admin/models/message.does_not_exist'));\n }\n\n $model = clone $model_to_clone;\n $model->id = null;\n\n // Show the page\n return view('models/edit')\n ->with('depreciation_list', Helper::depreciationList())\n ->with('item', $model)\n ->with('clone_model', $model_to_clone);\n }", "label_name": "CWE-862", "label": 8} +{"code": " self::removeLevel($kid->id);\r\n }\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $action = $this->actionModel->getById($this->request->getIntegerParam('action_id'));\n\n if (! empty($action) && $this->actionModel->remove($action['id'])) {\n $this->flash->success(t('Action removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this action.'));\n }\n\n $this->response->redirect($this->helper->url->to('ActionController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-200", "label": 10} +{"code": "\tprivate static function init() {\n\t\t\\DPL\\Config::init();\n\n\t\tif ( !isset( self::$createdLinks ) ) {\n\t\t\tself::$createdLinks = [\n\t\t\t\t'resetLinks' => false,\n\t\t\t\t'resetTemplates' => false,\n\t\t\t\t'resetCategories' => false,\n\t\t\t\t'resetImages' => false,\n\t\t\t\t'resetdone' => false,\n\t\t\t\t'elimdone' => false\n\t\t\t];\n\t\t}\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " public function session() {\n // Test if logged in, log in if not, log in.\n try {\n $this->assertElementPresent('css=ul#user-menu');\n } catch (PHPUnit_Framework_AssertionFailedError $e) {\n /* If this isn't the first time we've logged in, we have a problem;\n * the user should have been logged in throughout the life of the\n * test case class. Append t\n */\n if (!$this->firstLogin)\n array_push($this->verificationErrors, $e->toString());\n $this->firstLogin = false;\n $this->login();\n return 0;\n }\n try {\n $this->assertCorrectUser();\n } catch (PHPUnit_Framework_AssertionFailedError $e) {\n /**\n * The browser is logged in but not as the correct user.\n */\n $this->logout();\n $this->login();\n $this->firstLogin = false;\n return 0;\n }\n // Indicator of whether the session was already initialized properly\n return 1;\n }", "label_name": "CWE-20", "label": 0} +{"code": " function columnUpdate($table, $col, $val, $where=1) { \n $res = @mysqli_query($this->connection, \"UPDATE `\" . $this->prefix . \"$table` SET `$col`='\" . $val . \"' WHERE $where\");\n /*if ($res == null)\n return array();\n $objects = array();\n for ($i = 0; $i < mysqli_num_rows($res); $i++)\n $objects[] = mysqli_fetch_object($res);*/\n //return $objects;\n }", "label_name": "CWE-74", "label": 1} +{"code": " public function actionGetItems(){\n $model = X2Model::model ($this->modelClass);\n if (isset ($model)) {\n $tableName = $model->tableName ();\n $sql = \n 'SELECT id, subject as value\n FROM '.$tableName.' WHERE subject LIKE :qterm ORDER BY subject ASC';\n $command = Yii::app()->db->createCommand($sql);\n $qterm = $_GET['term'].'%';\n $command->bindParam(\":qterm\", $qterm, PDO::PARAM_STR);\n $result = $command->queryAll();\n echo CJSON::encode($result);\n }\n Yii::app()->end();\n }", "label_name": "CWE-20", "label": 0} +{"code": "\tpublic function register()\n\t{\n\t\tJSession::checkToken('post') or jexit(JText::_('JINVALID_TOKEN'));\n\n\t\t// Get the application\n\t\t$app = JFactory::getApplication();\n\n\t\t// Get the form data.\n\t\t$data = $this->input->post->get('user', array(), 'array');\n\n\t\t// Get the model and validate the data.\n\t\t$model = $this->getModel('Registration', 'UsersModel');\n\n\t\t$form = $model->getForm();\n\n\t\tif (!$form)\n\t\t{\n\t\t\tJError::raiseError(500, $model->getError());\n\n\t\t\treturn false;\n\t\t}\n\n\t\t$return = $model->validate($form, $data);\n\n\t\t// Check for errors.\n\t\tif ($return === false)\n\t\t{\n\t\t\t// Get the validation messages.\n\t\t\t$errors = $model->getErrors();\n\n\t\t\t// Push up to three validation messages out to the user.\n\t\t\tfor ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++)\n\t\t\t{\n\t\t\t\tif ($errors[$i] instanceof Exception)\n\t\t\t\t{\n\t\t\t\t\t$app->enqueueMessage($errors[$i]->getMessage(), 'notice');\n\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t$app->enqueueMessage($errors[$i], 'notice');\n\t\t\t}\n\n\t\t\t// Save the data in the session.\n\t\t\t$app->setUserState('users.registration.form.data', $data);\n\n\t\t\t// Redirect back to the registration form.\n\t\t\t$this->setRedirect('index.php?option=com_users&view=registration');\n\n\t\t\treturn false;\n\t\t}\n\n\t\t// Finish the registration.\n\t\t$return = $model->register($data);\n\n\t\t// Check for errors.\n\t\tif ($return === false)\n\t\t{\n\t\t\t// Save the data in the session.\n\t\t\t$app->setUserState('users.registration.form.data', $data);\n\n\t\t\t// Redirect back to the registration form.\n\t\t\t$message = JText::sprintf('COM_USERS_REGISTRATION_SAVE_FAILED', $model->getError());\n\t\t\t$this->setRedirect('index.php?option=com_users&view=registration', $message, 'error');\n\n\t\t\treturn false;\n\t\t}\n\n\t\t// Flush the data from the session.\n\t\t$app->setUserState('users.registration.form.data', null);\n\n\t\treturn true;\n\t}", "label_name": "CWE-20", "label": 0} +{"code": "\tpublic function getPurchaseOrderByJSON() {\n\n\t\tif(!empty($this->params['vendor'])) {\n\t\t\t$purchase_orders = $this->purchase_order->find('all', 'vendor_id=' . $this->params['vendor']);\n\t\t} else {\n\t\t\t$purchase_orders = $this->purchase_order->find('all');\n\t\t}\n\n\t\techo json_encode($purchase_orders);\n\t}", "label_name": "CWE-20", "label": 0} +{"code": "\tprivate function _lastmodifiedby( $option ) {\n\t $user = new \\User;\n\n\t $this->addWhere( $this->DB->addQuotes( $user->newFromName( $option )->getActorId() ) . ' = (SELECT revactor_actor FROM ' . $this->tableNames['revision_actor_temp'] . ' WHERE ' . $this->tableNames['revision_actor_temp'] . '.revactor_page=page_id ORDER BY ' . $this->tableNames['revision_actor_temp'] . '.revactor_timestamp DESC LIMIT 1)' );\n\t}", "label_name": "CWE-400", "label": 2} +{"code": "function GoodAuthDigestTestController($serverPort) {\n $args = array('Authorization' => 'Digest username=\"admin\", ' .\n 'realm=\"Restricted area\", nonce=\"564a12611dae8\", ' .\n 'uri=\"/test_auth_digest.php\", cnonce=\"MjIyMTg1\", nc=00000001, ' .\n 'qop=\"auth\", response=\"e544aaed06917adea3e5c74dd49f0e32\", ' .\n 'opaque=\"cdce8a5c95a1427d74df7acbf41c9ce0\"');\n var_dump(request(php_uname('n'), $serverPort, \"test_auth_digest.php\",\n [], [], $args));\n}", "label_name": "CWE-668", "label": 7} +{"code": "\tpublic function getPurchaseOrderByJSON() {\n\n\t\tif(!empty($this->params['vendor'])) {\n\t\t\t$purchase_orders = $this->purchase_order->find('all', 'vendor_id=' . $this->params['vendor']);\n\t\t} else {\n\t\t\t$purchase_orders = $this->purchase_order->find('all');\n\t\t}\n\n\t\techo json_encode($purchase_orders);\n\t}", "label_name": "CWE-20", "label": 0} +{"code": " protected function getSubtask()\n {\n $subtask = $this->subtaskModel->getById($this->request->getIntegerParam('subtask_id'));\n\n if (empty($subtask)) {\n throw new PageNotFoundException();\n }\n\n return $subtask;\n }", "label_name": "CWE-200", "label": 10} +{"code": " function scan_page($parent_id) {\r\n global $db;\r\n\r\n $sections = $db->selectObjects('section','parent=' . $parent_id);\r\n $ret = '';\r\n foreach ($sections as $page) {\r\n $cLoc = serialize(expCore::makeLocation('container','@section' . $page->id));\r\n $ret .= scan_container($cLoc, $page->id);\r\n $ret .= scan_page($page->id);\r\n }\r\n return $ret;\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " function login($redirectCallback = null)\n {\n $aConf = $GLOBALS['_MAX']['CONF'];\n\n if (!is_callable($redirectCallback)) {\n // Set the default callback\n $redirectCallback = array('OA_Auth', 'checkRedirect');\n }\n\n if (call_user_func($redirectCallback)) {\n header('location: http://'.$aConf['webpath']['admin']);\n exit();\n }\n\n if (defined('OA_SKIP_LOGIN')) {\n return OA_Auth::getFakeSessionData();\n }\n\n if (OA_Auth::suppliedCredentials()) {\n $doUser = OA_Auth::authenticateUser();\n\n if (!$doUser) {\n sleep(3);\n OA_Auth::restart($GLOBALS['strUsernameOrPasswordWrong']);\n }\n\n return OA_Auth::getSessionData($doUser);\n }\n\n OA_Auth::restart();\n }", "label_name": "CWE-287", "label": 4} +{"code": " function delete() {\n global $db;\n\n if (empty($this->params['id'])) return false;\n $product_type = $db->selectValue('product', 'product_type', 'id=' . $this->params['id']);\n $product = new $product_type($this->params['id'], true, false);\n //eDebug($product_type); \n //eDebug($product, true);\n //if (!empty($product->product_type_id)) {\n //$db->delete($product_type, 'id='.$product->product_id);\n //}\n\n $db->delete('option', 'product_id=' . $product->id . \" AND optiongroup_id IN (SELECT id from \" . $db->prefix . \"optiongroup WHERE product_id=\" . $product->id . \")\");\n $db->delete('optiongroup', 'product_id=' . $product->id);\n //die();\n $db->delete('product_storeCategories', 'product_id=' . $product->id . ' AND product_type=\"' . $product_type . '\"');\n\n if ($product->product_type == \"product\") {\n if ($product->hasChildren()) {\n $this->deleteChildren();\n }\n }\n\n $product->delete();\n\n flash('message', gt('Product deleted successfully.'));\n expHistory::back();\n }", "label_name": "CWE-74", "label": 1} +{"code": " public function testCheckHTTP()\n {\n if (! function_exists('curl_init')) {\n $this->markTestSkipped('Missing curl extension!');\n }\n $this->assertTrue(\n $this->object->checkHTTP(\"http://www.phpmyadmin.net/test/data\")\n );\n $this->assertContains(\n \"TEST DATA\",\n $this->object->checkHTTP(\"http://www.phpmyadmin.net/test/data\", true)\n );\n $this->assertFalse(\n $this->object->checkHTTP(\"http://www.phpmyadmin.net/test/nothing\")\n );\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function testAuthHeader()\n {\n $restoreInstance = PMA\\libraries\\Response::getInstance();\n\n $mockResponse = $this->getMockBuilder('PMA\\libraries\\Response')\n ->disableOriginalConstructor()\n ->setMethods(array('isAjax', 'headersSent', 'header'))\n ->getMock();\n\n $mockResponse->expects($this->once())\n ->method('isAjax')\n ->with()\n ->will($this->returnValue(false));\n\n $mockResponse->expects($this->any())\n ->method('headersSent')\n ->with()\n ->will($this->returnValue(false));\n\n $mockResponse->expects($this->once())\n ->method('header')\n ->with('Location: http://www.phpmyadmin.net/logout' . ((SID) ? '?' . SID : ''));", "label_name": "CWE-200", "label": 10} +{"code": "\t\tpublic function push($remote = NULL, array $params = NULL)\n\t\t{\n\t\t\t$this->run('push', $remote, $params);\n\t\t\treturn $this;\n\t\t}", "label_name": "CWE-77", "label": 14} +{"code": " public function create_directory() {\n if (!AuthUser::hasPermission('file_manager_mkdir')) {\n Flash::set('error', __('You do not have sufficient permissions to create a directory.'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n \n // CSRF checks\n if (isset($_POST['csrf_token'])) {\n $csrf_token = $_POST['csrf_token'];\n if (!SecureToken::validateToken($csrf_token, BASE_URL.'plugin/file_manager/create_directory')) {\n Flash::set('error', __('Invalid CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n }\n else {\n Flash::set('error', __('No CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n\n $data = $_POST['directory'];\n\n $path = str_replace('..', '', $data['path']);\n $dirname = str_replace('..', '', $data['name']);\n $dir = FILES_DIR . \"/{$path}/{$dirname}\";\n\n if (mkdir($dir)) {\n $mode = Plugin::getSetting('dirmode', 'file_manager');\n chmod($dir, octdec($mode));\n } else {\n Flash::set('error', __('Directory :name has not been created!', array(':name' => $dirname)));\n }\n redirect(get_url('plugin/file_manager/browse/' . $path));\n }", "label_name": "CWE-20", "label": 0} +{"code": "\tprivate function _namespace( $option ) {\n\t\t$option === 0 ?? $option = '0';\n\t\tif ( is_array( $option ) && count( $option ) ) {\n\t\t\tif ( $this->parameters->getParameter( 'openreferences' ) ) {\n\t\t\t\t$this->addWhere(\n\t\t\t\t\t[\n\t\t\t\t\t\t\"{$this->tableNames['pagelinks']}.pl_namespace\"\t=> $option\n\t\t\t\t\t]\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\t$this->addWhere(\n\t\t\t\t\t[\n\t\t\t\t\t\t\"{$this->tableNames['page']}.page_namespace\"\t=> $option\n\t\t\t\t\t]\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " public function testIsExpiredReturnsTrueWhenModificationTimesWarrant()\n {\n $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__);\n $files->shouldReceive('exists')->once()->with(__DIR__.'/'.sha1('foo').'.php')->andReturn(true);\n $files->shouldReceive('lastModified')->once()->with('foo')->andReturn(100);\n $files->shouldReceive('lastModified')->once()->with(__DIR__.'/'.sha1('foo').'.php')->andReturn(0);\n $this->assertTrue($compiler->isExpired('foo'));\n }", "label_name": "CWE-327", "label": 3} +{"code": "\tpublic static function generate_location_json( ) {\r\n\t\t/* TODO: Try to track modification?\r\n\t\tif ( !empty( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) {\r\n\t\t\t$http_time = strtotime( $_SERVER['HTTP_IF_MODIFIED_SINCE'] );\r\n\t\t\t$mod_time = strtotime( $post->post_modified_gmt . ' GMT' );\r\n\t\t\tif ($mod_time <= $http_time) {\r\n\t\t\t\treturn status_header(304); // Not modified\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tstatus_header(200);\r\n\t\theader( 'Last-Modified: ' . mysql2date( 'D, d M Y H:i:s', $post->post_modified_gmt, false ) . ' GMT' );\r\n\t\theader( 'Content-type: text/xml; charset='.get_settings('blog_charset'), true);\r\n\t\theader( 'Cache-control: max-age=300, must-revalidate', true);\r\n\t\theader( 'Expires: ' . gmdate( 'D, d M Y H:i:s', time() + 300 ) . \" GMT\" );\r\n\t\theader( 'Pragma:' );\r\n\t\t */\r\n\t\tstatus_header(200);\r\n\t\theader('Content-type: application/json; charset='.get_option('blog_charset'), true);\r\n\t\theader('Cache-Control: no-cache;', true);\r\n\t\theader('Expires: -1;', true);\r\n\r\n\t\t$json = GeoMashup::get_locations_json($_REQUEST);\r\n\t\tif ( isset( $_REQUEST['callback'] ) )\r\n\t\t\t$json = $_REQUEST['callback'] . '(' . $json . ')';\r\n\t\techo $json;\r\n\t}\r", "label_name": "CWE-20", "label": 0} +{"code": " public function actionGetItems(){\n $sql = \n 'SELECT id, name as value \n FROM x2_templates \n WHERE name \n LIKE :qterm \n ORDER BY name ASC';\n\n $command = Yii::app()->db->createCommand($sql);\n $qterm = $_GET['term'].'%';\n $command->bindParam(\":qterm\", $qterm, PDO::PARAM_STR);\n $result = $command->queryAll();\n echo CJSON::encode($result); exit;\n }", "label_name": "CWE-20", "label": 0} +{"code": " function edit_order_item() {\n $oi = new orderitem($this->params['id'], true, true);\n if (empty($oi->id)) {\n flash('error', gt('Order item doesn\\'t exist.'));\n expHistory::back();\n }\n $oi->user_input_fields = expUnserialize($oi->user_input_fields);\n $params['options'] = $oi->opts;\n $params['user_input_fields'] = $oi->user_input_fields;\n $oi->product = new product($oi->product->id, true, true);\n if ($oi->product->parent_id != 0) {\n $parProd = new product($oi->product->parent_id);\n //$oi->product->optiongroup = $parProd->optiongroup; \n $oi->product = $parProd;\n }\n //FIXME we don't use selectedOpts?\n// $oi->selectedOpts = array();\n// if (!empty($oi->opts)) {\n// foreach ($oi->opts as $opt) {\n// $option = new option($opt[0]);\n// $og = new optiongroup($option->optiongroup_id);\n// if (!isset($oi->selectedOpts[$og->id]) || !is_array($oi->selectedOpts[$og->id]))\n// $oi->selectedOpts[$og->id] = array($option->id);\n// else\n// array_push($oi->selectedOpts[$og->id], $option->id);\n// }\n// }\n //eDebug($oi->selectedOpts);\n\n assign_to_template(array(\n 'oi' => $oi,\n 'params' => $params\n ));\n }", "label_name": "CWE-74", "label": 1} +{"code": " private function _verify($public_key_or_secret, $expected_alg = null) {\n $segments = explode('.', $this->raw);\n $signature_base_string = implode('.', array($segments[0], $segments[1]));\n if (!$expected_alg) {\n # NOTE: might better to warn here\n $expected_alg = $this->header['alg'];\n }\n switch ($expected_alg) {\n case 'HS256':\n case 'HS384':\n case 'HS512':\n return $this->signature === hash_hmac($this->digest(), $signature_base_string, $public_key_or_secret, true);\n case 'RS256':\n case 'RS384':\n case 'RS512':\n return $this->rsa($public_key_or_secret, RSA::SIGNATURE_PKCS1)->verify($signature_base_string, $this->signature);\n case 'ES256':\n case 'ES384':\n case 'ES512':\n throw new JOSE_Exception_UnexpectedAlgorithm('Algorithm not supported');\n case 'PS256':\n case 'PS384':\n case 'PS512':\n return $this->rsa($public_key_or_secret, RSA::SIGNATURE_PSS)->verify($signature_base_string, $this->signature);\n default:\n throw new JOSE_Exception_UnexpectedAlgorithm('Unknown algorithm');\n }\n }", "label_name": "CWE-200", "label": 10} +{"code": "\tpublic static function sortByPriority( $parameters ) {\n\t\tif ( !is_array( $parameters ) ) {\n\t\t\tthrow new \\MWException( __METHOD__ . ': A non-array was passed.' );\n\t\t}\n\t\t//'category' to get category headings first for ordermethod.\n\t\t//'include'/'includepage' to make sure section labels are ready for 'table'.\n\t\t$priority = [\n\t\t\t'distinct'\t\t\t=> 1,\n\t\t\t'openreferences'\t=> 2,\n\t\t\t'ignorecase'\t\t=> 3,\n\t\t\t'category'\t\t\t=> 4,\n\t\t\t'title'\t\t\t\t=> 5,\n\t\t\t'goal'\t\t\t\t=> 6,\n\t\t\t'ordercollation'\t=> 7,\n\t\t\t'ordermethod'\t\t=> 8,\n\t\t\t'includepage'\t\t=> 9,\n\t\t\t'include'\t\t\t=> 10\n\t\t];\n\n\t\t$_first = [];\n\t\tforeach ( $priority as $parameter => $order ) {\n\t\t\tif ( isset( $parameters[$parameter] ) ) {\n\t\t\t\t$_first[$parameter] = $parameters[$parameter];\n\t\t\t\tunset( $parameters[$parameter] );\n\t\t\t}\n\t\t}\n\n\t\t$parameters = $_first + $parameters;\n\n\t\treturn $parameters;\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " public function showall() {\n expHistory::set('viewable', $this->params);\n // figure out if should limit the results\n if (isset($this->params['limit'])) {\n $limit = $this->params['limit'] == 'none' ? null : $this->params['limit'];\n } else {\n $limit = (isset($this->config['limit']) && $this->config['limit'] != '') ? $this->config['limit'] : 10;\n } \n $order = isset($this->config['order']) ? $this->config['order'] : 'publish DESC';\n\n // pull the news posts from the database\n $items = $this->news->find('all', $this->aggregateWhereClause(), $order);\n\n // merge in any RSS news and perform the sort and limit the number of posts we return to the configured amount.\n if (!empty($this->config['pull_rss'])) $items = $this->mergeRssData($items);\n \n // setup the pagination object to paginate the news stories.\n $page = new expPaginator(array(\n 'records'=>$items,\n 'limit'=>$limit,\n 'order'=>$order,\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->params['controller'],\n 'action'=>$this->params['action'],\n 'src'=>$this->loc->src,\n 'view'=>empty($this->params['view']) ? null : $this->params['view']\n ));\n \n assign_to_template(array(\n 'page'=>$page,\n 'items'=>$page->records,\n 'rank'=>($order==='rank')?1:0,\n 'params'=>$this->params,\n ));\n }", "label_name": "CWE-74", "label": 1} +{"code": " foreach($image->expTag as $tag) {\n if (isset($used_tags[$tag->id])) {\n $used_tags[$tag->id]->count++;\n } else {\n $exptag = new expTag($tag->id);\n $used_tags[$tag->id] = $exptag;\n $used_tags[$tag->id]->count = 1;\n }\n \n }", "label_name": "CWE-74", "label": 1} +{"code": "\tfunction unlockTables() {\n $sql = \"UNLOCK TABLES\";\n \n $res = mysqli_query($this->connection, $sql);\n return $res;\n }", "label_name": "CWE-74", "label": 1} +{"code": " function showByModel() {\n global $order, $template, $db;\n\n expHistory::set('viewable', $this->params);\n $product = new product();\n $model = $product->find(\"first\", 'model=\"' . $this->params['model'] . '\"');\n //eDebug($model);\n $product_type = new $model->product_type($model->id);\n //eDebug($product_type);\n $tpl = $product_type->getForm('show');\n if (!empty($tpl)) $template = new controllertemplate($this, $tpl);\n //eDebug($template);\n $this->grabConfig(); // grab the global config\n assign_to_template(array(\n 'config' => $this->config,\n 'product' => $product_type,\n 'last_category' => $order->lastcat\n ));\n }", "label_name": "CWE-20", "label": 0} +{"code": " $section = new section($this->params);\r\n } else {\r\n notfoundController::handle_not_found();\r\n exit;\r\n }\r\n if (!empty($section->id)) {\r\n $check_id = $section->id;\r\n } else {\r\n $check_id = $section->parent;\r\n }\r\n if (expPermissions::check('manage', expCore::makeLocation('navigation', '', $check_id))) {\r\n if (empty($section->id)) {\r\n $section->active = 1;\r\n $section->public = 1;\r\n if (!isset($section->parent)) {\r\n // This is another precaution. The parent attribute\r\n // should ALWAYS be set by the caller.\r\n //FJD - if that's the case, then we should die.\r\n notfoundController::handle_not_authorized();\r\n exit;\r\n //$section->parent = 0;\r\n }\r\n }\r\n assign_to_template(array(\r\n 'section' => $section,\r\n 'glyphs' => self::get_glyphs(),\r\n ));\r\n } else { // User does not have permission to manage sections. Throw a 403\r\n notfoundController::handle_not_authorized();\r\n }\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public function testPopBeforeSmtpGood()\n {\n //Start a fake POP server\n $pid = shell_exec('nohup ./runfakepopserver.sh >/dev/null 2>/dev/null & printf \"%u\" $!');\n $this->pids[] = $pid;\n\n sleep(2);\n //Test a known-good login\n $this->assertTrue(\n POP3::popBeforeSmtp('localhost', 1100, 10, 'user', 'test', $this->Mail->SMTPDebug),\n 'POP before SMTP failed'\n );\n //Kill the fake server\n shell_exec('kill -TERM '.escapeshellarg($pid));\n sleep(2);\n }", "label_name": "CWE-20", "label": 0} +{"code": " public static function checkPermissions($permission,$location) {\r\n global $exponent_permissions_r, $router;\r\n\r\n // only applies to the 'manage' method\r\n if (empty($location->src) && empty($location->int) && (!empty($router->params['action']) && $router->params['action'] == 'manage') || strpos($router->current_url, 'action=manage') !== false) {\r\n if (!empty($exponent_permissions_r['navigation'])) foreach ($exponent_permissions_r['navigation'] as $page) {\r\n foreach ($page as $pageperm) {\r\n if (!empty($pageperm['manage'])) return true;\r\n }\r\n }\r\n }\r\n return false;\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic function testPages () {\n $this->visitPages ( $this->allPages );\n\t}", "label_name": "CWE-20", "label": 0} +{"code": " function edit_option_master() {\n expHistory::set('editable', $this->params);\n \n $params = isset($this->params['id']) ? $this->params['id'] : $this->params;\n $record = new option_master($params); \n assign_to_template(array(\n 'record'=>$record\n ));\n }", "label_name": "CWE-74", "label": 1} +{"code": "function cron_dbmanager_backup() {\n\tglobal $wpdb;\n\t$backup_options = get_option('dbmanager_options');\n\t$backup_email = stripslashes($backup_options['backup_email']);\n\tif(intval($backup_options['backup_period']) > 0) {\n\t\t$backup = array();\n\t\t$backup['date'] = current_time('timestamp');\n\t\t$backup['mysqldumppath'] = $backup_options['mysqldumppath'];\n\t\t$backup['mysqlpath'] = $backup_options['mysqlpath'];\n\t\t$backup['path'] = $backup_options['path'];\n\t\t$backup['password'] = str_replace('$', '\\$', DB_PASSWORD);\n\t\t$backup['host'] = DB_HOST;\n\t\t$backup['port'] = '';\n\t\t$backup['sock'] = '';\n\t\tif(strpos(DB_HOST, ':') !== false) {\n\t\t\t$db_host = explode(':', DB_HOST);\n\t\t\t$backup['host'] = $db_host[0];\n\t\t\tif(intval($db_host[1]) != 0) {\n\t\t\t\t$backup['port'] = ' --port=\"'.intval($db_host[1]).'\"';\n\t\t\t} else {\n\t\t\t\t$backup['sock'] = ' --socket=\"'.$db_host[1].'\"';\n\t\t\t}\n\t\t}\n\t\t$backup['command'] = '';\n\t\t$brace = (substr(PHP_OS, 0, 3) == 'WIN') ? '\"' : '';\n\t\tif(intval($backup_options['backup_gzip']) == 1) {\n\t\t\t$backup['filename'] = $backup['date'].'_-_'.DB_NAME.'.sql.gz';\n\t\t\t$backup['filepath'] = $backup['path'].'/'.$backup['filename'];\n\t\t\t$backup['command'] = $brace.$backup['mysqldumppath'].$brace.' --force --host=\"'.$backup['host'].'\" --user=\"'.DB_USER.'\" --password=\"'.$backup['password'].'\"'.$backup['port'].$backup['sock'].' --add-drop-table --skip-lock-tables '.DB_NAME.' | gzip > '.$brace.$backup['filepath'].$brace;\n\t\t} else {\n\t\t\t$backup['filename'] = $backup['date'].'_-_'.DB_NAME.'.sql';\n\t\t\t$backup['filepath'] = $backup['path'].'/'.$backup['filename'];\n\t\t\t$backup['command'] = $brace.$backup['mysqldumppath'].$brace.' --force --host=\"'.$backup['host'].'\" --user=\"'.DB_USER.'\" --password=\"'.$backup['password'].'\"'.$backup['port'].$backup['sock'].' --add-drop-table --skip-lock-tables '.DB_NAME.' > '.$brace.$backup['filepath'].$brace;\n\t\t}\n\t\texecute_backup($backup['command']);\n\t\tif( !empty( $backup_email ) )\n\t\t{\n\t\t\tdbmanager_email_backup( $backup_email, $backup['filepath'] );\n\t\t}\n\t}\n\treturn;\n}", "label_name": "CWE-20", "label": 0} +{"code": " public function manage() {\n expHistory::set('viewable', $this->params);\n \n $page = new expPaginator(array(\n\t\t\t'model'=>'order_status',\n\t\t\t'where'=>1,\n 'limit'=>10,\n\t\t\t'order'=>'rank',\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->params['controller'],\n 'action'=>$this->params['action'],\n //'columns'=>array('Name'=>'title')\n ));\n\n\t\tassign_to_template(array(\n 'page'=>$page\n ));\n }", "label_name": "CWE-74", "label": 1} +{"code": " public static function initializeNavigation() {\r\n $sections = section::levelTemplate(0, 0);\r\n return $sections;\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": "\tprivate function _addeditdate( $option ) {\n\t\t$this->addTable( 'revision_actor_temp', 'rev' );\n\t\t$this->addSelect( [ 'rev.revactor_timestamp' ] );\n\t\t$this->addWhere(\n\t\t\t[\n\t\t\t\t$this->tableNames['page'] . '.page_id = rev.revactor_page',\n\t\t\t]\n\t\t);\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " $cLoc = serialize(expCore::makeLocation('container','@section' . $page->id));\r\n $ret .= scan_container($cLoc, $page->id);\r\n $ret .= scan_page($page->id);\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public function activate_discount(){ \n if (isset($this->params['id'])) {\n $discount = new discounts($this->params['id']);\n $discount->update($this->params);\n //if ($discount->discountulator->hasConfig() && empty($discount->config)) {\n //flash('messages', $discount->discountulator->name().' requires configuration. Please do so now.');\n //redirect_to(array('controller'=>'billing', 'action'=>'configure', 'id'=>$discount->id));\n //}\n }\n \n expHistory::back();\n }", "label_name": "CWE-74", "label": 1} +{"code": " foreach ($events as $event) {\r\n $extevents[$date][] = $event;\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " foreach ($allusers as $uid) {\r\n $u = user::getUserById($uid);\r\n expPermissions::grant($u, 'manage', $sloc);\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " function function_exists($name)\n {\n if (isset(\\yiiunit\\framework\\base\\SecurityTest::$functions[$name])) {\n return \\yiiunit\\framework\\base\\SecurityTest::$functions[$name];\n }\n\n return \\function_exists($name);\n }", "label_name": "CWE-330", "label": 12} +{"code": " public function index($id)\n {\n $this->paginate['conditions'] = array('GalaxyElement.galaxy_cluster_id' => $id);\n $clusters = $this->paginate();\n $this->set('list', $clusters);\n if ($this->request->is('ajax')) {\n $this->layout = 'ajax';\n $this->render('ajax/index');\n }\n }", "label_name": "CWE-862", "label": 8} +{"code": " public function create_file() {\n if (!AuthUser::hasPermission('file_manager_mkfile')) {\n Flash::set('error', __('You do not have sufficient permissions to create a file.'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n \n // CSRF checks\n if (isset($_POST['csrf_token'])) {\n $csrf_token = $_POST['csrf_token'];\n if (!SecureToken::validateToken($csrf_token, BASE_URL.'plugin/file_manager/create_file')) {\n Flash::set('error', __('Invalid CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n }\n else {\n Flash::set('error', __('No CSRF token found!'));\n redirect(get_url('plugin/file_manager/browse/'));\n }\n\n $data = $_POST['file'];\n\n $path = str_replace('..', '', $data['path']);\n $filename = str_replace('..', '', $data['name']);\n $file = FILES_DIR . DS . $path . DS . $filename;\n\n if (file_put_contents($file, '') !== false) {\n $mode = Plugin::getSetting('filemode', 'file_manager');\n chmod($file, octdec($mode));\n } else {\n Flash::set('error', __('File :name has not been created!', array(':name' => $filename)));\n }\n redirect(get_url('plugin/file_manager/browse/' . $path));\n }", "label_name": "CWE-20", "label": 0} +{"code": " $fileName = ltrim(dirname($fileName) . '/' . basename($fileName, '.js'), '/.');\n\n if (empty($fileName)) {\n continue;\n }\n\n $templateNames[] = $inflector->filter(array(\n 'module' => $moduleName,\n 'controller' => $controllerName,\n 'file' => $fileName)\n );\n }", "label_name": "CWE-20", "label": 0} +{"code": "\tfunction delete_vendor() {\n\t\tglobal $db;\n\t\t\n if (!empty($this->params['id'])){\n\t\t\t$db->delete('vendor', 'id =' .$this->params['id']);\n\t\t}\n expHistory::back();\n }", "label_name": "CWE-74", "label": 1} +{"code": " protected function assertCsvUploaded($csv) {\n $uploadedPath = implode(DIRECTORY_SEPARATOR, array(\n Yii::app()->basePath,\n 'data',\n 'data.csv'\n ));\n $this->assertFileExists ($uploadedPath);\n $this->assertFileEquals ($csv, $uploadedPath);\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function __construct(Project $project)\n {\n parent::__construct('Project #' . $project->getID() . ' is not active and is not a template');\n $this->project = $project;\n }", "label_name": "CWE-863", "label": 11} +{"code": "\tpublic function __construct( Parameters $parameters ) {\n\t\t$this->parameters = $parameters;\n\n\t\t$this->tableNames = self::getTableNames();\n\n\t\t$this->DB = wfGetDB( DB_REPLICA, 'dpl' );\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " public static function fixName($name) {\n $name = preg_replace('/[^A-Za-z0-9\\.]/','_',$name);\n if ($name[0] == '.')\n $name[0] = '_';\n return $name;\n// return preg_replace('/[^A-Za-z0-9\\.]/', '-', $name);\n }", "label_name": "CWE-74", "label": 1} +{"code": " function showallSubcategories() {\n// global $db;\n\n expHistory::set('viewable', $this->params);\n// $parent = isset($this->params['cat']) ? $this->params['cat'] : expSession::get('catid');\n $catid = expSession::get('catid');\n $parent = !empty($catid) ? $catid : (!empty($this->params['cat']) ? $this->params['cat'] : 0);\n $category = new storeCategory($parent);\n $categories = $category->getEcomSubcategories();\n $ancestors = $category->pathToNode();\n assign_to_template(array(\n 'categories' => $categories,\n 'ancestors' => $ancestors,\n 'category' => $category\n ));\n }", "label_name": "CWE-20", "label": 0} +{"code": " public static function parseAndTrimImport($str, $isHTML = false) { //\ufffdDeath from above\ufffd? \ufffd\n //echo \"1
    \"; eDebug($str);\n// global $db;\n\n $str = str_replace(\"\ufffd\", \"’\", $str);\n $str = str_replace(\"\ufffd\", \"‘\", $str);\n $str = str_replace(\"\ufffd\", \"®\", $str);\n $str = str_replace(\"\ufffd\", \"-\", $str);\n $str = str_replace(\"\ufffd\", \"—\", $str);\n $str = str_replace(\"\ufffd\", \"”\", $str);\n $str = str_replace(\"\ufffd\", \"“\", $str);\n $str = str_replace(\"\\r\\n\", \" \", $str);\n $str = str_replace(\"\\,\", \",\", $str);\n $str = str_replace('\"\"', '\"', $str); //do this no matter what...in case someone added a quote in a non HTML field\n if (!$isHTML) {\n //if HTML, then leave the single quotes alone, otheriwse replace w/ special Char \n $str = str_replace('\"', \""\", $str);\n }\n $str = str_replace(\"\ufffd\", \"¼\", $str);\n $str = str_replace(\"\ufffd\", \"½\", $str);\n $str = str_replace(\"\ufffd\", \"¾\", $str);\n //$str = htmlspecialchars($str);\n //$str = utf8_encode($str);\n// if (DB_ENGINE=='mysqli') {\n//\t $str = @mysqli_real_escape_string($db->connection,trim(str_replace(\"\ufffd\", \"™\", $str)));\n// } elseif(DB_ENGINE=='mysql') {\n// $str = @mysql_real_escape_string(trim(str_replace(\"\ufffd\", \"™\", $str)),$db->connection);\n// } else {\n//\t $str = trim(str_replace(\"\ufffd\", \"™\", $str));\n// }\n $str = @expString::escape(trim(str_replace(\"\ufffd\", \"™\", $str)));\n //echo \"2
    \"; eDebug($str,die);\n return $str;\n }", "label_name": "CWE-74", "label": 1} +{"code": "function PMA_secureSession()\n{\n // prevent session fixation and XSS\n // (better to use session_status() if available)\n if ((PMA_PHP_INT_VERSION >= 50400 && session_status() === PHP_SESSION_ACTIVE)\n || (PMA_PHP_INT_VERSION < 50400 && session_id() !== '')\n ) {\n session_regenerate_id(true);\n }\n $_SESSION[' PMA_token '] = md5(uniqid(rand(), true));\n}", "label_name": "CWE-200", "label": 10} +{"code": " function edit_section() {\r\n global $db, $user;\r\n\r\n $parent = new section($this->params['parent']);\r\n if (empty($parent->id)) $parent->id = 0;\r\n assign_to_template(array(\r\n 'haveStandalone' => ($db->countObjects('section', 'parent=-1') && $parent->id >= 0),\r\n 'parent' => $parent,\r\n 'isAdministrator' => $user->isAdmin(),\r\n ));\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public function confirm() {\n global $db;\n \n // make sure we have what we need.\n if (empty($this->params['key'])) expQueue::flashAndFlow('error', gt('The security key for account was not supplied.'));\n if (empty($this->params['id'])) expQueue::flashAndFlow('error', gt('The subscriber id for account was not supplied.'));\n \n // verify the id/key pair \n $id = $db->selectValue('subscribers','id', 'id='.$this->params['id'].' AND hash=\"'.$this->params['key'].'\"');\n if (empty($id)) expQueue::flashAndFlow('error', gt('We could not find any subscriptions matching the ID and Key you provided.'));\n \n // activate this users pending subscriptions\n $sub = new stdClass();\n $sub->enabled = 1;\n $db->updateObject($sub, 'expeAlerts_subscribers', 'subscribers_id='.$id);\n \n // find the users active subscriptions\n $ealerts = expeAlerts::getBySubscriber($id);\n assign_to_template(array(\n 'ealerts'=>$ealerts\n ));\n }", "label_name": "CWE-74", "label": 1} +{"code": "function PMA_linkURL($url)\n{\n if (!preg_match('#^https?://#', $url) || defined('PMA_SETUP')) {\n return $url;\n }\n\n if (!function_exists('PMA_URL_getCommon')) {\n include_once './libraries/url_generating.lib.php';\n }\n $params = array();\n $params['url'] = $url;\n\n $url = PMA_URL_getCommon($params);\n //strip off token and such sensitive information. Just keep url.\n $arr = parse_url($url);\n parse_str($arr[\"query\"], $vars);\n $query = http_build_query(array(\"url\" => $vars[\"url\"]));\n $url = './url.php?' . $query;\n\n return $url;\n}", "label_name": "CWE-200", "label": 10} +{"code": "\tprivate function setFooter( $footer ) {\n\t\tif ( \\DynamicPageListHooks::getDebugLevel() == 5 ) {\n\t\t\t$footer .= '';\n\t\t}\n\t\t$this->footer = $this->replaceVariables( $footer );\n\t}", "label_name": "CWE-400", "label": 2} +{"code": "\tprivate function _notcreatedby( $option ) {\n\t\t$this->addTable( 'revision', 'no_creation_rev' );\n\t\t$this->addTable( 'revision_actor_temp', 'no_creation_rev_actor' );\n\t\t$user = new \\User;\n\n\t\t$this->addWhere( $this->DB->addQuotes( $user->newFromName( $option )->getActorId() ) . ' != no_creation_rev_actor.revactor_actor AND no_creation_rev_actor.revactor_page = page_id AND no_creation_rev.rev_parent_id = 0' );\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " public function putAction(Request $request)\n {\n $this->checkArguments($request);\n $user = $this->tokenStorage->getToken()->getUser();\n $this->userManager->save($request->request->all(), $request->get('locale'), $user->getId(), true);\n\n $user->setFirstName($request->get('firstName'));\n $user->setLastName($request->get('lastName'));\n\n $this->objectManager->flush();\n\n $view = View::create($user);\n\n $context = new Context();\n $context->setGroups(['profile']);\n\n $view->setContext($context);\n\n return $this->viewHandler->handle($view);\n }", "label_name": "CWE-269", "label": 6} +{"code": " public function getXForwardedForData()\n {\n return array(\n array(false, '10.0.0.1'),\n array('10.0.0.2', '10.0.0.2, 10.0.0.1'),\n array('10.0.0.2, 10.0.0.3', '10.0.0.2, 10.0.0.3, 10.0.0.1'),\n );\n }", "label_name": "CWE-20", "label": 0} +{"code": "\tpublic function setHeadItemAttributes( $attributes ) {\n\t\t$this->headItemAttributes = \\Sanitizer::fixTagAttributes( $attributes, 'li' );\n\t}", "label_name": "CWE-400", "label": 2} +{"code": "\tpublic function formatTemplateArg( $arg, $s, $argNr, $firstCall, $maxLength, Article $article ) {\n\t\t$tableFormat = $this->getParameters()->getParameter( 'tablerow' );\n\t\t// we could try to format fields differently within the first call of a template\n\t\t// currently we do not make such a difference\n\n\t\t// if the result starts with a '-' we add a leading space; thus we avoid a misinterpretation of |- as\n\t\t// a start of a new row (wiki table syntax)\n\t\tif ( array_key_exists( \"$s.$argNr\", $tableFormat ) ) {\n\t\t\t$n = -1;\n\t\t\tif ( $s >= 1 && $argNr == 0 && !$firstCall ) {\n\t\t\t\t$n = strpos( $tableFormat[\"$s.$argNr\"], '|' );\n\t\t\t\tif ( $n === false || !( strpos( substr( $tableFormat[\"$s.$argNr\"], 0, $n ), '{' ) === false ) || !( strpos( substr( $tableFormat[\"$s.$argNr\"], 0, $n ), '[' ) === false ) ) {\n\t\t\t\t\t$n = -1;\n\t\t\t\t}\n\t\t\t}\n\t\t\t$result = str_replace( '%%', $arg, substr( $tableFormat[\"$s.$argNr\"], $n + 1 ) );\n\t\t\t$result = str_replace( '%PAGE%', $article->mTitle->getPrefixedText(), $result );\n\t\t\t$result = str_replace( '%IMAGE%', $this->parseImageUrlWithPath( $arg ), $result ); //@TODO: This just blindly passes the argument through hoping it is an image. --Alexia\n\t\t\t$result = $this->cutAt( $maxLength, $result );\n\t\t\tif ( strlen( $result ) > 0 && $result[0] == '-' ) {\n\t\t\t\treturn ' ' . $result;\n\t\t\t} else {\n\t\t\t\treturn $result;\n\t\t\t}\n\t\t}\n\t\t$result = $this->cutAt( $maxLength, $arg );\n\t\tif ( strlen( $result ) > 0 && $result[0] == '-' ) {\n\t\t\treturn ' ' . $result;\n\t\t} else {\n\t\t\treturn $result;\n\t\t}\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " public static function getHost() {\n\n if (isset($_SERVER['HTTP_HOST'])) {\n $site_address = (erLhcoreClassSystem::$httpsMode == true ? 'https:' : 'http:') . '//' . $_SERVER['HTTP_HOST'] ;\n } else if (class_exists('erLhcoreClassInstance')) {\n $site_address = 'https://' . erLhcoreClassInstance::$instanceChat->address . '.' . erConfigClassLhConfig::getInstance()->getSetting( 'site', 'seller_domain');\n } else if (class_exists('erLhcoreClassExtensionLhcphpresque')) {\n $site_address = erLhcoreClassModule::getExtensionInstance('erLhcoreClassExtensionLhcphpresque')->settings['site_address'];\n } else {\n $site_address = '';\n }\n\n return $site_address;\n }", "label_name": "CWE-116", "label": 15} +{"code": " function selectArraysBySql($sql) { \n $res = @mysqli_query($this->connection, $this->injectProof($sql));\n if ($res == null)\n return array();\n $arrays = array();\n for ($i = 0, $iMax = mysqli_num_rows($res); $i < $iMax; $i++)\n $arrays[] = mysqli_fetch_assoc($res);\n return $arrays;\n }", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic static function getSetting( $setting ) {\n\t\treturn ( array_key_exists( $setting, self::$settings ) ? self::$settings[$setting] : null );\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " public function testRemoveAuthorizationHeaderOnRedirect()\n {\n $mock = new MockHandler([\n new Response(302, ['Location' => 'http://test.com']),\n static function (RequestInterface $request) {\n self::assertFalse($request->hasHeader('Authorization'));\n return new Response(200);\n }\n ]);\n $handler = HandlerStack::create($mock);\n $client = new Client(['handler' => $handler]);\n $client->get('http://example.com?a=b', ['auth' => ['testuser', 'testpass']]);\n }", "label_name": "CWE-863", "label": 11} +{"code": "\tprivate function _firstrevisionsince( $option ) {\n\t\t$this->addTable( 'revision_actor_temp', 'rev' );\n\t\t$this->addSelect(\n\t\t\t[\n\t\t\t\t'rev.revactor_rev',\n\t\t\t\t'rev.revactor_timestamp'\n\t\t\t]\n\t\t);\n\t\t// tell the query optimizer not to look at rows that the following subquery will filter out anyway\n\t\t$this->addWhere(\n\t\t\t[\n\t\t\t\t$this->tableNames['page'] . '.page_id = rev.revactor_page',\n\t\t\t\t'rev.revactor_timestamp >= ' . $this->DB->addQuotes( $option )\n\t\t\t]\n\t\t);\n\t\t$this->addWhere(\n\t\t\t[\n\t\t\t\t$this->tableNames['page'] . '.page_id = rev.revactor_page',\n\t\t\t\t'rev.revactor_timestamp = (SELECT MIN(rev_aux_snc.revactor_timestamp) FROM ' . $this->tableNames['revision_actor_temp'] . ' AS rev_aux_snc WHERE rev_aux_snc.revactor_page=rev.revactor_page AND rev_aux_snc.revactor_timestamp >= ' . $this->convertTimestamp( $option ) . ')'\n\t\t\t]\n\t\t);\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " function captureAuthorization() {\n //eDebug($this->params,true);\n $order = new order($this->params['id']);\n /*eDebug($this->params); \n //eDebug($order,true);*/\n //eDebug($order,true);\n //$billing = new billing();\n\n //eDebug($billing, true);\n //$billing->calculator = new $calcname($order->billingmethod[0]->billingcalculator_id);\n $calc = $order->billingmethod[0]->billingcalculator->calculator;\n $calc->config = $order->billingmethod[0]->billingcalculator->config;\n\n //$calc = new $calc-\n //eDebug($calc,true);\n if (!method_exists($calc, 'delayed_capture')) {\n flash('error', gt('The Billing Calculator does not support delayed capture'));\n expHistory::back();\n }\n\n $result = $calc->delayed_capture($order->billingmethod[0], $this->params['capture_amt'], $order);\n\n if (empty($result->errorCode)) {\n flash('message', gt('The authorized payment was successfully captured'));\n expHistory::back();\n\n } else {\n flash('error', gt('An error was encountered while capturing the authorized payment.') . '

    ' . $result->message);\n expHistory::back();\n }\n }", "label_name": "CWE-74", "label": 1} +{"code": " foreach ($elem[2] as $field) {\n echo '\n \n    '.$field[1].' :\n ';\n if ($field[3] === \"masked\") {\n echo '\n
    ';\n } else {\n echo '\n
    ';\n }\n echo '\n \n ';\n }", "label_name": "CWE-269", "label": 6} +{"code": "\tfunction edit_vendor() {\n\t\t$vendor = new vendor();\n\t\t\n\t\tif(isset($this->params['id'])) {\n\t\t\t$vendor = $vendor->find('first', 'id =' .$this->params['id']);\n\t\t\tassign_to_template(array(\n 'vendor'=>$vendor\n ));\n\t\t}\n\t}", "label_name": "CWE-74", "label": 1} +{"code": " public function __construct() {\n $this->smtp_conn = 0;\n $this->error = null;\n $this->helo_rply = null;\n\n $this->do_debug = 0;\n }", "label_name": "CWE-20", "label": 0} +{"code": "\tfunction manage () {\n\t expHistory::set('viewable', $this->params);\n\t\t\n\t\t$vendor = new vendor();\n\t\t$vendors = $vendor->find('all');\n\t\tif(!empty($this->params['vendor'])) {\n\t\t\t$purchase_orders = $this->purchase_order->find('all', 'vendor_id=' . $this->params['vendor']);\n\t\t} else {\n\t\t\t$purchase_orders = $this->purchase_order->find('all');\n\t\t}\n\t\t\n\t\tassign_to_template(array(\n 'purchase_orders'=>$purchase_orders,\n 'vendors' => $vendors,\n 'vendor_id' => @$this->params['vendor']\n ));\n\t}", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic function showall() {\n\t expHistory::set('viewable', $this->params);\n\t $hv = new help_version();\n\t //$current_version = $hv->find('first', 'is_current=1');\n\t $ref_version = $hv->find('first', 'version=\\''.$this->help_version.'\\'');\n\n // pagination parameter..hard coded for now.\t \n\t\t$where = $this->aggregateWhereClause();\n\t $where .= 'AND help_version_id='.(empty($ref_version->id)?'0':$ref_version->id);", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic function formatItem( Article $article, $pageText = null ) {\n\t\tglobal $wgLang;\n\n\t\t$item = '';\n\n\t\t// DPL Article, not MediaWiki.\n\t\t$date = $article->getDate();\n\t\tif ( $date !== null ) {\n\t\t\t$item .= $date . ' ';\n\t\t\tif ( $article->mRevision !== null ) {\n\t\t\t\t$item .= '[{{fullurl:' . $article->mTitle . '|oldid=' . $article->mRevision . '}} ' . htmlspecialchars( $article->mTitle ) . ']';\n\t\t\t} else {\n\t\t\t\t$item .= $article->mLink;\n\t\t\t}\n\t\t} else {\n\t\t\t// output the link to the article\n\t\t\t$item .= $article->mLink;\n\t\t}\n\n\t\tif ( $article->mSize != null ) {\n\t\t\t$byte = 'B';\n\t\t\t$pageLength = $wgLang->formatNum( $article->mSize );\n\t\t\t$item .= \" [{$pageLength} {$byte}]\";\n\t\t}\n\n\t\tif ( $article->mCounter !== null ) {\n\t\t\t$contLang = MediaWikiServices::getInstance()->getContentLanguage();\n\n\t\t\t$item .= ' ' . $contLang->getDirMark() . '(' . wfMessage( 'hitcounters-nviews', $wgLang->formatNum( $article->mCounter ) )->escaped() . ')';\n\t\t}\n\n\t\tif ( $article->mUserLink !== null ) {\n\t\t\t$item .= ' . . [[User:' . $article->mUser . '|' . $article->mUser . ']]';\n\t\t\tif ( $article->mComment != '' ) {\n\t\t\t\t$item .= ' { ' . $article->mComment . ' }';\n\t\t\t}\n\t\t}\n\n\t\tif ( $article->mContributor !== null ) {\n\t\t\t$item .= ' . . [[User:' . $article->mContributor . '|' . $article->mContributor . \" $article->mContrib]]\";\n\t\t}\n\n\t\tif ( !empty( $article->mCategoryLinks ) ) {\n\t\t\t$item .= ' . . ' . wfMessage( 'categories' ) . ': ' . implode( ' | ', $article->mCategoryLinks ) . '';\n\t\t}\n\n\t\tif ( $this->getParameters()->getParameter( 'addexternallink' ) && $article->mExternalLink !== null ) {\n\t\t\t$item .= ' \u2192 ' . $article->mExternalLink;\n\t\t}\n\n\t\tif ( $pageText !== null ) {\n\t\t\t//Include parsed/processed wiki markup content after each item before the closing tag.\n\t\t\t$item .= $pageText;\n\t\t}\n\n\t\t$item = $this->getItemStart() . $item . $this->getItemEnd();\n\n\t\t$item = $this->replaceTagParameters( $item, $article );\n\n\t\treturn $item;\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " public function fromFile($filePath)\n {\n if ($filePath === null) {\n return;\n }\n\n $file = new FileObj($filePath);\n $this->file_name = $file->getFilename();\n $this->file_size = $file->getSize();\n $this->content_type = $file->getMimeType();\n $this->disk_name = $this->getDiskName();\n\n $this->putFile($file->getRealPath(), $this->disk_name);\n\n return $this;\n }", "label_name": "CWE-362", "label": 18} +{"code": " foreach ($day as $extevent) {\r\n $event_cache = new stdClass();\r\n $event_cache->feed = $extgcalurl;\r\n $event_cache->event_id = $extevent->event_id;\r\n $event_cache->title = $extevent->title;\r\n $event_cache->body = $extevent->body;\r\n $event_cache->eventdate = $extevent->eventdate->date;\r\n if (isset($extevent->dateFinished) && $extevent->dateFinished != -68400)\r\n $event_cache->dateFinished = $extevent->dateFinished;\r\n if (isset($extevent->eventstart))\r\n $event_cache->eventstart = $extevent->eventstart;\r\n if (isset($extevent->eventend))\r\n $event_cache->eventend = $extevent->eventend;\r\n if (isset($extevent->is_allday))\r\n $event_cache->is_allday = $extevent->is_allday;\r\n $found = false;\r\n if ($extevent->eventdate->date < $start) // prevent duplicating events crossing month boundaries\r\n $found = $db->selectObject('event_cache','feed=\"'.$extgcalurl.'\" AND event_id=\"'.$event_cache->event_id.'\" AND eventdate='.$event_cache->eventdate);\r\n if (!$found)\r\n $db->insertObject($event_cache,'event_cache');\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " function fopen($filename, $mode)\n {\n if (\\yiiunit\\framework\\base\\SecurityTest::$fopen !== null) {\n return \\yiiunit\\framework\\base\\SecurityTest::$fopen;\n }\n\n return \\fopen($filename, $mode);\n }", "label_name": "CWE-330", "label": 12} +{"code": " public function actionGetItems($modelType){\n \n $sql = 'SELECT id, name as value FROM x2_campaigns WHERE name LIKE :qterm ORDER BY name ASC';\n \n $command = Yii::app()->db->createCommand($sql);\n $qterm = '%'.$_GET['term'].'%';\n $command->bindParam(\":qterm\", $qterm, PDO::PARAM_STR);\n $result = $command->queryAll();\n echo CJSON::encode($result);\n exit;\n }", "label_name": "CWE-20", "label": 0} +{"code": "\tpublic function __construct() {\n\t\t$this->setRichness( Config::getSetting( 'functionalRichness' ) );\n\n\t\tif ( \\DynamicPageListHooks::isLikeIntersection() ) {\n\t\t\t$this->data['ordermethod'] = [\n\t\t\t\t'default'\t=> 'categoryadd',\n\t\t\t\t'values'\t=> [\n\t\t\t\t\t'categoryadd',\n\t\t\t\t\t'lastedit',\n\t\t\t\t\t'none'\n\t\t\t\t]\n\t\t\t];\n\t\t\t$this->data['order'] = [\n\t\t\t\t'default'\t=> 'descending',\n\t\t\t\t'values'\t=> [\n\t\t\t\t\t'ascending',\n\t\t\t\t\t'descending'\n\t\t\t\t]\n\t\t\t];\n\t\t\t$this->data['mode'] = [\n\t\t\t\t'default'\t=> 'unordered',\n\t\t\t\t'values'\t=> [\n\t\t\t\t\t'none',\n\t\t\t\t\t'ordered',\n\t\t\t\t\t'unordered'\n\t\t\t\t]\n\t\t\t];\n\t\t\t$this->data['userdateformat'] = [\n\t\t\t\t'default' => 'Y-m-d: '\n\t\t\t];\n\t\t\t$this->data['allowcachedresults']['default'] = 'true';\n\t\t}\n\t}", "label_name": "CWE-400", "label": 2} +{"code": "\tprivate function _addauthor( $option ) {\n\t\t//Addauthor can not be used with addlasteditor.\n\t\tif ( !isset( $this->parametersProcessed['addlasteditor'] ) || !$this->parametersProcessed['addlasteditor'] ) {\n\t\t\t$this->addTable( 'revision_actor_temp', 'rev' );\n\t\t\t$this->addWhere(\n\t\t\t\t[\n\t\t\t\t\t$this->tableNames['page'] . '.page_id = rev.revactor_page',\n\t\t\t\t\t'rev.revactor_timestamp = (SELECT MIN(rev_aux_min.revactor_timestamp) FROM ' . $this->tableNames['revision_actor_temp'] . ' AS rev_aux_min WHERE rev_aux_min.revactor_page = rev.revactor_page)'\n\t\t\t\t]\n\t\t\t);\n\t\t\t$this->_adduser( null, 'rev' );\n\t\t}\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " public function Turn() {\n $this->error = array(\"error\" => \"This method, TURN, of the SMTP \".\n \"is not implemented\");\n if($this->do_debug >= 1) {\n $this->edebug(\"SMTP -> NOTICE: \" . $this->error[\"error\"] . $this->CRLF . '
    ');\n }\n return false;\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function __construct(\n GlyphFinder $glyph_finder,\n ProjectXMLMerger $project_xml_merger,\n ConsistencyChecker $consistency_checker,\n TemplateDao $template_dao,\n ProjectManager $project_manager,\n EventDispatcherInterface $event_dispatcher,\n ) {\n $this->template_dao = $template_dao;\n $this->templates = [\n AgileALMTemplate::NAME => new AgileALMTemplate($glyph_finder, $project_xml_merger, $consistency_checker),\n ScrumTemplate::NAME => new ScrumTemplate($glyph_finder, $project_xml_merger, $consistency_checker),\n KanbanTemplate::NAME => new KanbanTemplate($glyph_finder, $project_xml_merger, $consistency_checker),\n IssuesTemplate::NAME => new IssuesTemplate($glyph_finder, $consistency_checker, $event_dispatcher),\n EmptyTemplate::NAME => new EmptyTemplate($glyph_finder),\n ];\n $this->project_manager = $project_manager;\n $this->glyph_finder = $glyph_finder;\n\n $this->external_templates = self::getExternalTemplatesByName($event_dispatcher);\n }", "label_name": "CWE-863", "label": 11} +{"code": "\tfunction lockTable($table,$lockType=\"WRITE\") {\n $sql = \"LOCK TABLES `\" . $this->prefix . \"$table` $lockType\";\n \n $res = mysqli_query($this->connection, $sql); \n return $res;\n }", "label_name": "CWE-74", "label": 1} +{"code": "\t\t\tarray_push($newgroupprivs, $type);\n\t}\n\tif(empty($newgroupprivs) || (count($newgroupprivs) == 1 && \n in_array(\"cascade\", $newgroupprivs))) {\n\t\treturn array('status' => 'error',\n 'errorcode' => 53,\n 'errormsg' => 'Invalid or missing permissions list supplied');\n\t}\n updateUserOrGroupPrivs($groupid, $nodeid, $newgroupprivs, array(), \"group\");\n\treturn array('status' => 'success');\n}", "label_name": "CWE-20", "label": 0} +{"code": " public function IsQmail() {\n if (stristr(ini_get('sendmail_path'), 'qmail')) {\n $this->Sendmail = '/var/qmail/bin/sendmail';\n }\n $this->Mailer = 'sendmail';\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function Reset() {\n $this->error = null; // so no confusion is caused\n\n if(!$this->connected()) {\n $this->error = array(\n \"error\" => \"Called Reset() without being connected\");\n return false;\n }\n\n fputs($this->smtp_conn,\"RSET\" . $this->CRLF);\n\n $rply = $this->get_lines();\n $code = substr($rply,0,3);\n\n if($this->do_debug >= 2) {\n $this->edebug(\"SMTP -> FROM SERVER:\" . $rply . $this->CRLF . '
    ');\n }\n\n if($code != 250) {\n $this->error =\n array(\"error\" => \"RSET failed\",\n \"smtp_code\" => $code,\n \"smtp_msg\" => substr($rply,4));\n if($this->do_debug >= 1) {\n $this->edebug(\"SMTP -> ERROR: \" . $this->error[\"error\"] . \": \" . $rply . $this->CRLF . '
    ');\n }\n return false;\n }\n\n return true;\n }", "label_name": "CWE-20", "label": 0} +{"code": "\tfunction show_vendor () {\n\t\t$vendor = new vendor();\n\t\t\n\t\tif(isset($this->params['id'])) {\n\t\t\t$vendor = $vendor->find('first', 'id =' .$this->params['id']);\n\t\t\t$vendor_title = $vendor->title;\n\t\t\t$state = new geoRegion($vendor->state);\n\t\t\t$vendor->state = $state->name;\n\t\t\t//Removed unnecessary fields\n\t\t\tunset(\n $vendor->title,\n $vendor->table,\n $vendor->tablename,\n $vendor->classname,\n $vendor->identifier\n );\n\t\t\n\t\t\tassign_to_template(array(\n 'vendor_title' => $vendor_title,\n 'vendor'=>$vendor\n ));\n\t\t}\n\t}", "label_name": "CWE-74", "label": 1} +{"code": " public function testXForwarderForHeaderForForwardedRequests($xForwardedFor, $expected)\n {\n $this->setNextResponse();\n $server = array('REMOTE_ADDR' => '10.0.0.1');\n if (false !== $xForwardedFor) {\n $server['HTTP_X_FORWARDED_FOR'] = $xForwardedFor;\n }\n $this->request('GET', '/', $server);\n\n $this->assertEquals($expected, $this->kernel->getBackendRequest()->headers->get('X-Forwarded-For'));\n }", "label_name": "CWE-20", "label": 0} +{"code": "\t\tpublic function merge($branch, $options = NULL)\n\t\t{\n\t\t\t$this->run('merge', $options, $branch);\n\t\t\treturn $this;\n\t\t}", "label_name": "CWE-77", "label": 14} +{"code": " public function __get($var) {\r\n\r\n switch ($var) {\r\n\r\n case 'configuration_array':\r\n $this->configuration_array = array();\r\n if ($this->configuration != ''){\r\n $jsonData = json_decode($this->configuration,true);\r\n if ($jsonData !== null) {\r\n $this->configuration_array = $jsonData;\r\n } else {\r\n $this->configuration_array = array();\r\n }\r\n }\r\n return $this->configuration_array;\r\n break;\r\n\r\n case 'name_support':\r\n return $this->name_support = $this->nick;\r\n break;\r\n\r\n case 'has_photo':\r\n return $this->filename != '';\r\n break;\r\n\r\n case 'has_photo_avatar':\r\n return $this->filename != '' || $this->avatar != '';\r\n break;\r\n\r\n case 'photo_path':\r\n $this->photo_path = ($this->filepath != '' ? '//' . $_SERVER['HTTP_HOST'] . erLhcoreClassSystem::instance()->wwwDir() : erLhcoreClassSystem::instance()->wwwImagesDir() ) .'/'. $this->filepath . $this->filename;\r\n return $this->photo_path;\r\n break;\r\n\r\n case 'file_path_server':\r\n return $this->filepath . $this->filename;\r\n break;\r\n\r\n default:\r\n break;\r\n }\r\n }\r", "label_name": "CWE-116", "label": 15} +{"code": " function edit_order_item() {\n $oi = new orderitem($this->params['id'], true, true);\n if (empty($oi->id)) {\n flash('error', gt('Order item doesn\\'t exist.'));\n expHistory::back();\n }\n $oi->user_input_fields = expUnserialize($oi->user_input_fields);\n $params['options'] = $oi->opts;\n $params['user_input_fields'] = $oi->user_input_fields;\n $oi->product = new product($oi->product->id, true, true);\n if ($oi->product->parent_id != 0) {\n $parProd = new product($oi->product->parent_id);\n //$oi->product->optiongroup = $parProd->optiongroup; \n $oi->product = $parProd;\n }\n //FIXME we don't use selectedOpts?\n// $oi->selectedOpts = array();\n// if (!empty($oi->opts)) {\n// foreach ($oi->opts as $opt) {\n// $option = new option($opt[0]);\n// $og = new optiongroup($option->optiongroup_id);\n// if (!isset($oi->selectedOpts[$og->id]) || !is_array($oi->selectedOpts[$og->id]))\n// $oi->selectedOpts[$og->id] = array($option->id);\n// else\n// array_push($oi->selectedOpts[$og->id], $option->id);\n// }\n// }\n //eDebug($oi->selectedOpts);\n\n assign_to_template(array(\n 'oi' => $oi,\n 'params' => $params\n ));\n }", "label_name": "CWE-74", "label": 1} +{"code": " public function getTrustedProxyData()\n {\n return array(\n array(array(), array('127.0.0.1')),\n array(array('10.0.0.2'), array('10.0.0.2', '127.0.0.1')),\n array(array('10.0.0.2', '127.0.0.1'), array('10.0.0.2', '127.0.0.1')),\n );\n }", "label_name": "CWE-20", "label": 0} +{"code": " array_push($stack, $node);\n }\n }\n return array(\n 'status' => 'success',\n 'nodes' => $nodes);\n } else {\n return array(\n 'status' => 'error',\n 'errorcode' => 56,\n 'errormsg' => 'User cannot access node content');\n }\n}", "label_name": "CWE-20", "label": 0} +{"code": " public function beforeAction($action)\n {\n // Bypass when not installed for installer\n if (empty(Yii::$app->params['installed']) &&\n Yii::$app->controller->module != null &&\n Yii::$app->controller->module->id == 'installer') {\n return true;\n }\n\n $this->handleDeprecatedSettings();\n $this->controllerAccess = $this->getControllerAccess($this->rules);\n\n if (!$this->controllerAccess->run()) {\n if (isset($this->controllerAccess->codeCallback) &&\n method_exists($this, $this->controllerAccess->codeCallback)) {\n // Call a specific function for current action filter,\n // may be used to filter a logged in user for some restriction e.g. \"must change password\"\n return call_user_func([$this, $this->controllerAccess->codeCallback]);\n } else if ($this->controllerAccess->code == 401) {\n return $this->loginRequired();\n } else {\n $this->forbidden();\n }\n }\n\n return parent::beforeAction($action);\n }", "label_name": "CWE-863", "label": 11} +{"code": " foreach ($nodes as $node) {\r\n if ((($perm == 'view' && $node->public == 1) || expPermissions::check($perm, expCore::makeLocation('navigation', '', $node->id))) && !in_array($node->id, $ignore_ids)) {\r\n if ($node->active == 1) {\r\n $text = str_pad('', ($depth + ($full ? 1 : 0)) * 3, '.', STR_PAD_LEFT) . $node->name;\r\n } else {\r\n $text = str_pad('', ($depth + ($full ? 1 : 0)) * 3, '.', STR_PAD_LEFT) . '(' . $node->name . ')';\r\n }\r\n $ar[$node->id] = $text;\r\n foreach (self::levelDropdownControlArray($node->id, $depth + 1, $ignore_ids, $full, $perm, $addstandalones, $addinternalalias) as $id => $text) {\r\n $ar[$id] = $text;\r\n }\r\n }\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " function configure() {\n expHistory::set('editable', $this->params);\n // little bit of trickery so that that categories can have their own configs\n \n $this->loc->src = \"@globalstoresettings\";\n $config = new expConfig($this->loc);\n $this->config = $config->config;\n $pullable_modules = expModules::listInstalledControllers($this->baseclassname, $this->loc);\n $views = expTemplate::get_config_templates($this, $this->loc);\n \n $gc = new geoCountry(); \n $countries = $gc->find('all');\n \n $gr = new geoRegion(); \n $regions = $gr->find('all');\n \n assign_to_template(array(\n 'config'=>$this->config,\n 'pullable_modules'=>$pullable_modules,\n 'views'=>$views,\n 'countries'=>$countries,\n 'regions'=>$regions,\n 'title'=>static::displayname()\n ));\n } ", "label_name": "CWE-74", "label": 1} +{"code": " public function testCookiePathWithEmptySetCookiePath($uriPath, $cookiePath)\n {\n $response = (new Response(200))\n ->withAddedHeader(\n 'Set-Cookie',\n \"foo=bar; expires={$this->futureExpirationDate()}; domain=www.example.com; path=;\"\n )\n ->withAddedHeader(\n 'Set-Cookie',\n \"bar=foo; expires={$this->futureExpirationDate()}; domain=www.example.com; path=foobar;\"\n )\n ;\n $request = (new Request('GET', $uriPath))->withHeader('Host', 'www.example.com');\n $this->jar->extractCookies($request, $response);\n\n self::assertSame($cookiePath, $this->jar->toArray()[0]['Path']);\n self::assertSame($cookiePath, $this->jar->toArray()[1]['Path']);\n }", "label_name": "CWE-200", "label": 10} +{"code": " public function crossOriginRedirectProvider()\n {\n return [\n ['http://example.com?a=b', 'http://test.com/', false],\n ['https://example.com?a=b', 'https://test.com/', false],\n ['http://example.com?a=b', 'https://test.com/', false],\n ['https://example.com?a=b', 'http://test.com/', false],\n ['http://example.com?a=b', 'http://example.com/', true],\n ['https://example.com?a=b', 'https://example.com/', true],\n ['http://example.com?a=b', 'https://example.com/', true],\n ['https://example.com?a=b', 'http://example.com/', false],\n ];\n }", "label_name": "CWE-200", "label": 10} +{"code": " public function __construct(\n CartService $cartService,\n int $defaultTtl,\n bool $httpCacheEnabled,\n MaintenanceModeResolver $maintenanceModeResolver\n ) {\n $this->cartService = $cartService;\n $this->defaultTtl = $defaultTtl;\n $this->httpCacheEnabled = $httpCacheEnabled;\n $this->maintenanceResolver = $maintenanceModeResolver;\n }", "label_name": "CWE-200", "label": 10} +{"code": " public function safePath($filename = 'data.csv'){\n return implode(DIRECTORY_SEPARATOR, array(\n Yii::app()->basePath,\n 'data',\n $filename\n ));\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $filter = $this->customFilterModel->getById($this->request->getIntegerParam('filter_id'));\n\n $this->checkPermission($project, $filter);\n\n if ($this->customFilterModel->remove($filter['id'])) {\n $this->flash->success(t('Custom filter removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this custom filter.'));\n }\n\n $this->response->redirect($this->helper->url->to('CustomFilterController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-200", "label": 10} +{"code": "\tpublic function paramRules() {\n\t\treturn array(\n\t\t\t'title' => Yii::t('studio',$this->title),\n\t\t\t'info' => Yii::t('studio',$this->info),\n\t\t\t'modelRequired' => 'Contacts',\n\t\t\t'options' => array(\n\t\t\t\tarray(\n 'name'=>'listId',\n 'label'=>Yii::t('studio','List'),\n 'type'=>'link',\n 'linkType'=>'X2List',\n 'linkSource'=>Yii::app()->createUrl(\n\t\t\t\t\t CActiveRecord::model('X2List')->autoCompleteSource\n\t\t\t\t )\n ),\n\t\t\t));\n\t}", "label_name": "CWE-20", "label": 0} +{"code": " public function disable()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $swimlane_id = $this->request->getIntegerParam('swimlane_id');\n\n if ($this->swimlaneModel->disable($project['id'], $swimlane_id)) {\n $this->flash->success(t('Swimlane updated successfully.'));\n } else {\n $this->flash->failure(t('Unable to update this swimlane.'));\n }\n\n $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-200", "label": 10} +{"code": " function showByModel() {\n global $order, $template, $db;\n\n expHistory::set('viewable', $this->params);\n $product = new product();\n $model = $product->find(\"first\", 'model=\"' . $this->params['model'] . '\"');\n //eDebug($model);\n $product_type = new $model->product_type($model->id);\n //eDebug($product_type);\n $tpl = $product_type->getForm('show');\n if (!empty($tpl)) $template = new controllertemplate($this, $tpl);\n //eDebug($template);\n $this->grabConfig(); // grab the global config\n assign_to_template(array(\n 'config' => $this->config,\n 'product' => $product_type,\n 'last_category' => $order->lastcat\n ));\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function getBranches()\n {\n if (null === $this->branches) {\n $branches = array();\n $bookmarks = array();\n\n $this->process->execute('hg branches', $output, $this->repoDir);\n foreach ($this->process->splitLines($output) as $branch) {\n if ($branch && Preg::isMatch('(^([^\\s]+)\\s+\\d+:([a-f0-9]+))', $branch, $match)) {\n $branches[$match[1]] = $match[2];\n }\n }\n\n $this->process->execute('hg bookmarks', $output, $this->repoDir);\n foreach ($this->process->splitLines($output) as $branch) {\n if ($branch && Preg::isMatch('(^(?:[\\s*]*)([^\\s]+)\\s+\\d+:(.*)$)', $branch, $match)) {\n $bookmarks[$match[1]] = $match[2];\n }\n }\n\n // Branches will have preference over bookmarks\n $this->branches = array_merge($bookmarks, $branches);\n }\n\n return $this->branches;\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function saveConfig() { \n if (!empty($this->params['aggregate']) || !empty($this->params['pull_rss'])) {\n if ($this->params['order'] == 'rank ASC') {\n expValidator::failAndReturnToForm(gt('User defined ranking is not allowed when aggregating or pull RSS data feeds.'), $this->params);\n }\n }\n \n parent::saveConfig();\n }", "label_name": "CWE-74", "label": 1} +{"code": "function twig_array_reduce(Environment $env, $array, $arrow, $initial = null)\n{\n if (!$arrow instanceof Closure && $env->hasExtension('\\Twig\\Extension\\SandboxExtension') && $env->getExtension('\\Twig\\Extension\\SandboxExtension')->isSandboxed()) {\n throw new RuntimeError('The callable passed to the \"reduce\" filter must be a Closure in sandbox mode.');\n }\n\n if (!\\is_array($array)) {\n if (!$array instanceof \\Traversable) {\n throw new RuntimeError(sprintf('The \"reduce\" filter only works with arrays or \"Traversable\", got \"%s\" as first argument.', \\gettype($array)));\n }\n\n $array = iterator_to_array($array);\n }\n\n return array_reduce($array, $arrow, $initial);\n}", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic function editspeed() {\n global $db;\n\n if (empty($this->params['id'])) return false;\n $calcname = $db->selectValue('shippingcalculator', 'calculator_name', 'id='.$this->params['id']);\n $calc = new $calcname($this->params['id']);\n assign_to_template(array(\n 'calculator'=>$calc\n ));\n\t\t\n }", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic function update_groupdiscounts() {\n\t global $db;\n\t \n\t if (empty($this->params['id'])) {\n\t // look for existing discounts for the same group\n\t $existing_id = $db->selectValue('groupdiscounts', 'id', 'group_id='.$this->params['group_id']);\n\t if (!empty($existing_id)) flashAndFlow('error',gt('There is already a discount for that group.'));\n\t }\n\n $gd = new groupdiscounts();\n\t $gd->update($this->params);\n\t expHistory::back();\n\t}", "label_name": "CWE-74", "label": 1} +{"code": " public function getError() {\n return $this->error;\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function configure() {\n $this->config['defaultbanner'] = array();\n if (!empty($this->config['defaultbanner_id'])) {\n $this->config['defaultbanner'][] = new expFile($this->config['defaultbanner_id']);\n } \n\t parent::configure();\n\t $banners = $this->banner->find('all', null, 'companies_id');\n\t assign_to_template(array(\n 'banners'=>$banners,\n 'title'=>static::displayname()\n ));\n\t}", "label_name": "CWE-74", "label": 1} +{"code": " public function testFirstTrustedProxyIsSetAsRemote()\n {\n $expectedSubRequest = Request::create('/');\n $expectedSubRequest->headers->set('Surrogate-Capability', 'abc=\"ESI/1.0\"');\n $expectedSubRequest->server->set('REMOTE_ADDR', '1.1.1.1');\n\n if (Request::getTrustedHeaderName(Request::HEADER_CLIENT_IP)) {\n $expectedSubRequest->headers->set('x-forwarded-for', array('127.0.0.1'));\n $expectedSubRequest->server->set('HTTP_X_FORWARDED_FOR', '127.0.0.1');\n }\n\n Request::setTrustedProxies(array('1.1.1.1'));\n\n $strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest($expectedSubRequest));\n\n $request = Request::create('/');\n $request->headers->set('Surrogate-Capability', 'abc=\"ESI/1.0\"');\n $strategy->render('/', $request);\n\n Request::setTrustedProxies(array());\n }", "label_name": "CWE-20", "label": 0} +{"code": " foreach ($grpusers as $u) {\r\n $emails[$u->email] = trim(user::getUserAttribution($u->id));\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " private function edebug($str) {\n if ($this->Debugoutput == \"error_log\") {\n error_log($str);\n } else {\n echo $str;\n }\n }", "label_name": "CWE-20", "label": 0} +{"code": " function delete() {\n global $db;\n\n if (empty($this->params['id'])) return false;\n $product_type = $db->selectValue('product', 'product_type', 'id=' . $this->params['id']);\n $product = new $product_type($this->params['id'], true, false);\n //eDebug($product_type); \n //eDebug($product, true);\n //if (!empty($product->product_type_id)) {\n //$db->delete($product_type, 'id='.$product->product_id);\n //}\n\n $db->delete('option', 'product_id=' . $product->id . \" AND optiongroup_id IN (SELECT id from \" . $db->prefix . \"optiongroup WHERE product_id=\" . $product->id . \")\");\n $db->delete('optiongroup', 'product_id=' . $product->id);\n //die();\n $db->delete('product_storeCategories', 'product_id=' . $product->id . ' AND product_type=\"' . $product_type . '\"');\n\n if ($product->product_type == \"product\") {\n if ($product->hasChildren()) {\n $this->deleteChildren();\n }\n }\n\n $product->delete();\n\n flash('message', gt('Product deleted successfully.'));\n expHistory::back();\n }", "label_name": "CWE-74", "label": 1} +{"code": " $description = \"User (\" . $this->User->id . \"): \" . $this->Auth->user('email');\n $fieldsResult = \"Password changed.\";\n }\n\n // query\n $this->Log = ClassRegistry::init('Log');\n $this->Log->create();\n $this->Log->save(array(\n 'org' => $this->Auth->user('Organisation')['name'],\n 'model' => $model,\n 'model_id' => $modelId,\n 'email' => $this->Auth->user('email'),\n 'action' => $action,\n 'title' => $description,\n 'change' => isset($fieldsResult) ? $fieldsResult : ''));\n\n // write to syslogd as well\n App::import('Lib', 'SysLog.SysLog');\n $syslog = new SysLog();\n if (isset($fieldsResult) && $fieldsResult) {\n $syslog->write('notice', $description . ' -- ' . $action . ' -- ' . $fieldsResult);\n } else {\n $syslog->write('notice', $description . ' -- ' . $action);\n }\n }", "label_name": "CWE-269", "label": 6} +{"code": " $criteria->addCondition (\n 'user IN (' .\n 'SELECT DISTINCT b.username ' .\n 'FROM x2_group_to_user a JOIN x2_group_to_user b ' .\n 'ON a.groupId=b.groupId ' .\n 'WHERE a.username=:getAccessCriteria_username' .\n ') OR (user = :getAccessCriteria_username)');\n } else { // default history privacy (public or assigned)\n $criteria->addCondition (\"(user=:getAccessCriteria_username OR visibility=1)\");\n }\n }\n\n if ($profile) {\n $criteria->params[':getAccessCriteria_profileUsername'] = $profile->username;\n /* only show events associated with current profile which current user has\n permission to see */\n $criteria->addCondition (\"user=:getAccessCriteria_profileUsername\");\n if (!Yii::app()->params->isAdmin) {\n $criteria->addCondition (\"visibility=1\");\n }\n }\n return $criteria;\n }", "label_name": "CWE-20", "label": 0} +{"code": " function searchCategory() {\r\n return gt('Event');\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public function saveConfig() { \n if (!empty($this->params['aggregate']) || !empty($this->params['pull_rss'])) {\n if ($this->params['order'] == 'rank ASC') {\n expValidator::failAndReturnToForm(gt('User defined ranking is not allowed when aggregating or pull RSS data feeds.'), $this->params);\n }\n }\n \n parent::saveConfig();\n }", "label_name": "CWE-74", "label": 1} +{"code": "function XMLRPCgetUserGroupPrivs($name, $affiliation, $nodeid){\n require_once(\".ht-inc/privileges.php\");\n global $user;\n\n if(! checkUserHasPriv(\"userGrant\", $user['id'], $nodeid)){\n return array('status' => 'error',\n 'errorcode' => 53,\n 'errormsg' => 'Unable to add resource group to this node');\n }\n\n\t$validate = array('name' => $name,\n\t 'affiliation' => $affiliation);\n\t$rc = validateAPIgroupInput($validate, 1);\n\tif($rc['status'] == 'error')\n\t\treturn $rc;\n\n $privileges = array();\n $nodePrivileges = getNodePrivileges($nodeid, 'usergroups');\n $cascadedNodePrivileges = getNodeCascadePrivileges($nodeid, 'usergroups'); \n $cngp = $cascadedNodePrivileges['usergroups'];\n $ngp = $nodePrivileges['usergroups'];\n if(array_key_exists($name, $cngp)){\n foreach($cngp[$name]['privs'] as $p){\n if(! array_key_exists($name, $ngp) ||\n ! in_array(\"block\", $ngp[$name]['privs'])){\n array_push($privileges, $p);\n }\n }\n }\n if(array_key_exists($name, $ngp)){\n foreach($ngp[$name]['privs'] as $p){\n if($p != \"block\"){\n array_push($privileges, $p);\n }\n }\n }\n\n return array(\n 'status' => 'success',\n 'privileges' => array_unique($privileges));\n}", "label_name": "CWE-20", "label": 0} +{"code": " foreach ($days as $event) {\r\n if (empty($event->eventdate->date) || ($viewrange == 'upcoming' && $event->eventdate->date < time()))\r\n break;\r\n if (empty($event->eventstart))\r\n $event->eventstart = $event->eventdate->date;\r\n $extitem[] = $event;\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic function __construct( \\DPL\\Parameters $parameters, \\Parser $parser ) {\n\t\tparent::__construct( $parameters, $parser );\n\t\t$this->textSeparator = $parameters->getParameter( 'inlinetext' );\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " public function showUnpublished() {\n expHistory::set('viewable', $this->params);\n \n // setup the where clause for looking up records.\n $where = parent::aggregateWhereClause();\n $where = \"((unpublish != 0 AND unpublish < \".time().\") OR (publish > \".time().\")) AND \".$where;\n if (isset($this->config['only_featured'])) $where .= ' AND is_featured=1';\n\n $page = new expPaginator(array(\n 'model'=>'news',\n 'where'=>$where,\n 'limit'=>25,\n 'order'=>'unpublish',\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->baseclassname,\n 'action'=>$this->params['action'],\n 'src'=>$this->loc->src,\n 'columns'=>array(\n gt('Title')=>'title',\n gt('Published On')=>'publish',\n gt('Status')=>'unpublish'\n ),\n ));\n \n assign_to_template(array(\n 'page'=>$page\n ));\n }", "label_name": "CWE-74", "label": 1} +{"code": " function reparent_standalone() {\r\n $standalone = $this->section->find($this->params['page']);\r\n if ($standalone) {\r\n $standalone->parent = $this->params['parent'];\r\n $standalone->update();\r\n expSession::clearAllUsersSessionCache('navigation');\r\n expHistory::back();\r\n } else {\r\n notfoundController::handle_not_found();\r\n }\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": "\tfunction manage_vendors () {\n\t expHistory::set('viewable', $this->params);\n\t\t$vendor = new vendor();\n\t\t\n\t\t$vendors = $vendor->find('all');\n\t\tassign_to_template(array(\n 'vendors'=>$vendors\n ));\n\t}", "label_name": "CWE-74", "label": 1} +{"code": " function edit_section() {\r\n global $db, $user;\r\n\r\n $parent = new section($this->params['parent']);\r\n if (empty($parent->id)) $parent->id = 0;\r\n assign_to_template(array(\r\n 'haveStandalone' => ($db->countObjects('section', 'parent=-1') && $parent->id >= 0),\r\n 'parent' => $parent,\r\n 'isAdministrator' => $user->isAdmin(),\r\n ));\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic function Archive() {\n\n\t\t// Update \"main\" ticket\n\t\t$upd_stmt = Database::prepare('\n\t\t\tUPDATE `' . TABLE_PANEL_TICKETS . '` SET `archived` = \"1\" WHERE `id` = :tid'\n\t\t);\n\t\tDatabase::pexecute($upd_stmt, array('tid' => $this->tid));\n\n\t\t// Update \"answers\" to ticket\n\t\t$upd_stmt = Database::prepare('\n\t\t\tUPDATE `' . TABLE_PANEL_TICKETS . '` SET `archived` = \"1\" WHERE `answerto` = :tid'\n\t\t);\n\t\tDatabase::pexecute($upd_stmt, array('tid' => $this->tid));\n\t\treturn true;\n\t}", "label_name": "CWE-732", "label": 13} +{"code": "\t\t\treturn \"__NOTOC____NOEDITSECTION__\" . \\CategoryViewer::shortList( $articleLinks, $articleStartChars );\n\t\t}\n\t\treturn '';\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " public static function isPublic($s) {\r\n if ($s == null) {\r\n return false;\r\n }\r\n while ($s->public && $s->parent > 0) {\r\n $s = new section($s->parent);\r\n }\r\n $lineage = (($s->public) ? 1 : 0);\r\n return $lineage;\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public static function getHelpVersion($version_id) {\n global $db;\n\n return $db->selectValue('help_version', 'version', 'id=\"'.$version_id.'\"');\n }", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic function setPageTextMatchNotRegex( array $pageTextMatchNotRegex = [] ) {\n\t\t$this->pageTextMatchNotRegex = (array)$pageTextMatchNotRegex;\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " function searchCategory() {\r\n return gt('Event');\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " $this->subtaskTimeTrackingModel->logEndTime($subtaskId, $this->userSession->getId());\n $this->subtaskTimeTrackingModel->updateTaskTimeTracking($task['id']);\n }", "label_name": "CWE-200", "label": 10} +{"code": " public function testAuthCheckDecryptPassword()\n {\n $GLOBALS['cfg']['Server']['auth_swekey_config'] = 'testConfigSwekey';\n $GLOBALS['server'] = 1;\n $_REQUEST['old_usr'] = '';\n $_REQUEST['pma_username'] = '';\n $_COOKIE['pmaServer-1'] = 'pmaServ1';\n $_COOKIE['pmaUser-1'] = 'pmaUser1';\n $_COOKIE['pmaPass-1'] = 'pmaPass1';\n $_COOKIE['pma_iv-1'] = base64_encode('testiv09testiv09');\n $GLOBALS['cfg']['blowfish_secret'] = 'secret';\n $_SESSION['last_valid_captcha'] = true;\n $_SESSION['last_access_time'] = time() - 1000;\n $GLOBALS['cfg']['LoginCookieValidity'] = 1440;\n\n // mock for blowfish function\n $this->object = $this->getMockBuilder('AuthenticationCookie')\n ->disableOriginalConstructor()\n ->setMethods(array('cookieDecrypt'))\n ->getMock();\n\n $this->object->expects($this->at(1))\n ->method('cookieDecrypt')\n ->will($this->returnValue(\"\\xff(blank)\"));\n\n $this->assertTrue(\n $this->object->authCheck()\n );\n\n $this->assertTrue(\n $GLOBALS['from_cookie']\n );\n\n $this->assertEquals(\n '',\n $GLOBALS['PHP_AUTH_PW']\n );\n\n }", "label_name": "CWE-200", "label": 10} +{"code": " public function testNotRemoveAuthorizationHeaderOnRedirect()\n {\n $mock = new MockHandler([\n new Response(302, ['Location' => 'http://example.com/2']),\n static function (RequestInterface $request) {\n self::assertTrue($request->hasHeader('Authorization'));\n return new Response(200);\n }\n ]);\n $handler = HandlerStack::create($mock);\n $client = new Client(['handler' => $handler]);\n $client->get('http://example.com?a=b', ['auth' => ['testuser', 'testpass']]);\n }", "label_name": "CWE-200", "label": 10} +{"code": "\tpublic function wp_footer() {\r\n\t\tglobal $geo_mashup_options;\r\n\t\tif ( $this->add_form_script ) {\r\n\t\t\tGeoMashup::register_script( \r\n\t\t\t\t\t'geo-mashup-comment-form', \r\n\t\t\t\t\t'js/comment-form.js', \r\n\t\t\t\t\tarray( 'jquery' ), \r\n\t\t\t\t\tGEO_MASHUP_VERSION, \r\n\t\t\t\t\ttrue );\r\n\t\t\t\t\t\r\n\t\t\twp_localize_script( 'geo-mashup-comment-form', 'geo_mashup_comment_form_settings', array( 'geonames_username' => $geo_mashup_options->get( 'overall', 'geonames_username' ) ) );\r\n\t\t\twp_print_scripts( 'geo-mashup-comment-form' );\r\n\t\t}\r\n\t}\r", "label_name": "CWE-20", "label": 0} +{"code": " foreach ($grpusers as $u) {\r\n $emails[$u->email] = trim(user::getUserAttribution($u->id));\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic static function dplParserFunction( &$parser ) {\n\t\tself::setLikeIntersection( false );\n\n\t\t$parser->addTrackingCategory( 'dpl-parserfunc-tracking-category' );\n\n\t\t// callback for the parser function {{#dpl:\t or {{DynamicPageList::\n\t\t$input = \"\";\n\n\t\t$numargs = func_num_args();\n\t\tif ( $numargs < 2 ) {\n\t\t\t$input = \"#dpl: no arguments specified\";\n\t\t\treturn str_replace( '\u00a7', '<', '\u00a7pre>\u00a7nowiki>' . $input . '\u00a7/nowiki>\u00a7/pre>' );\n\t\t}\n\n\t\t// fetch all user-provided arguments (skipping $parser)\n\t\t$arg_list = func_get_args();\n\t\tfor ( $i = 1; $i < $numargs; $i++ ) {\n\t\t\t$p1 = $arg_list[$i];\n\t\t\t$input .= str_replace( \"\\n\", \"\", $p1 ) . \"\\n\";\n\t\t}\n\n\t\t$parse = new \\DPL\\Parse();\n\t\t$dplresult = $parse->parse( $input, $parser, $reset, $eliminate, false );\n\t\treturn [ // parser needs to be coaxed to do further recursive processing\n\t\t\t$parser->getPreprocessor()->preprocessToObj( $dplresult, Parser::PTD_FOR_INCLUSION ),\n\t\t\t'isLocalObj' => true,\n\t\t\t'title' => $parser->getTitle()\n\t\t];\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " foreach ($days as $value) {\r\n $regitem[] = $value;\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public function destroy(PaymentMethod $paymentMethod)\n {\n $this->authorize('delete', $paymentMethod);\n\n $payments = $paymentMethod->payments;\n\n if ($payments->count() > 0) {\n return respondJson('payments_attached', 'Payments Attached.');\n }\n\n $paymentMethod->delete();\n\n return response()->json([\n 'success' => 'Payment method deleted successfully',\n ]);\n }", "label_name": "CWE-862", "label": 8} +{"code": "\tfunction manage_vendors () {\n\t expHistory::set('viewable', $this->params);\n\t\t$vendor = new vendor();\n\t\t\n\t\t$vendors = $vendor->find('all');\n\t\tassign_to_template(array(\n 'vendors'=>$vendors\n ));\n\t}", "label_name": "CWE-74", "label": 1} +{"code": " function manage() {\r\n global $db, $router, $user;\r\n\r\n expHistory::set('manageable', $router->params);\r\n assign_to_template(array(\r\n 'canManageStandalones' => self::canManageStandalones(),\r\n 'sasections' => $db->selectObjects('section', 'parent=-1'),\r\n 'user' => $user,\r\n// 'canManagePagesets' => $user->isAdmin(),\r\n// 'templates' => $db->selectObjects('section_template', 'parent=0'),\r\n ));\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public static function parseAndTrim($str, $isHTML = false) { //\ufffdDeath from above\ufffd? \ufffd\n //echo \"1
    \"; eDebug($str);\n// global $db;\n\n $str = str_replace(\"\ufffd\", \"’\", $str);\n $str = str_replace(\"\ufffd\", \"‘\", $str);\n $str = str_replace(\"\ufffd\", \"®\", $str);\n $str = str_replace(\"\ufffd\", \"-\", $str);\n $str = str_replace(\"\ufffd\", \"—\", $str);\n $str = str_replace(\"\ufffd\", \"”\", $str);\n $str = str_replace(\"\ufffd\", \"“\", $str);\n $str = str_replace(\"\\r\\n\", \" \", $str);\n //$str = str_replace(\",\",\"\\,\",$str); \n\n $str = str_replace('\\\"', \""\", $str);\n $str = str_replace('\"', \""\", $str);\n $str = str_replace(\"\ufffd\", \"¼\", $str);\n $str = str_replace(\"\ufffd\", \"½\", $str);\n $str = str_replace(\"\ufffd\", \"¾\", $str);\n //$str = htmlspecialchars($str);\n //$str = utf8_encode($str);\n// if (DB_ENGINE=='mysqli') {\n//\t $str = @mysqli_real_escape_string($db->connection,trim(str_replace(\"\ufffd\", \"™\", $str)));\n// } elseif(DB_ENGINE=='mysql') {\n// $str = @mysql_real_escape_string(trim(str_replace(\"\ufffd\", \"™\", $str)),$db->connection);\n// } else {\n//\t $str = trim(str_replace(\"\ufffd\", \"™\", $str));\n// }\n $str = @expString::escape(trim(str_replace(\"\ufffd\", \"™\", $str)));\n //echo \"2
    \"; eDebug($str,die);\n return $str;\n }", "label_name": "CWE-74", "label": 1} +{"code": " public function upload() {\n \n // upload the file, but don't save the record yet...\n if ($this->params['resize'] != 'false') {\n $maxwidth = $this->params['max_width'];\n } else {\n $maxwidth = null;\n }\n $file = expFile::fileUpload('Filedata',false,false,null,null,$maxwidth);\n // since most likely this function will only get hit via flash in YUI Uploader\n // and since Flash can't pass cookies, we lose the knowledge of our $user\n // so we're passing the user's ID in as $_POST data. We then instantiate a new $user,\n // and then assign $user->id to $file->poster so we have an audit trail for the upload\n\n if (is_object($file)) {\n $resized = !empty($file->resized) ? true : false;\n $user = new user($this->params['usrid']);\n $file->poster = $user->id;\n $file->posted = $file->last_accessed = time();\n $file->save();\n if (!empty($this->params['cat'])) {\n $expcat = new expCat($this->params['cat']);\n $params['expCat'][0] = $expcat->id;\n $file->update($params);\n }\n\n // a echo so YUI Uploader is notified of the function's completion\n if ($resized) {\n echo gt('File resized and then saved');\n } else {\n echo gt('File saved');\n }\n } else {\n echo gt('File was NOT uploaded!');\n// flash('error',gt('File was not uploaded!'));\n }\n } ", "label_name": "CWE-74", "label": 1} +{"code": "function getResourceGroupID($groupdname) {\n\tlist($type, $name) = explode('/', $groupdname);\n\t$query = \"SELECT g.id \"\n\t . \"FROM resourcegroup g, \"\n\t . \"resourcetype t \"\n\t . \"WHERE g.name = '$name' AND \"\n\t . \"t.name = '$type' AND \"\n\t . \"g.resourcetypeid = t.id\";\n\t$qh = doQuery($query, 371);\n\tif($row = mysql_fetch_row($qh))\n\t\treturn $row[0];\n\telse\n\t\treturn NULL;\n}", "label_name": "CWE-20", "label": 0} +{"code": " public function manage()\n {\n expHistory::set('manageable',$this->params);\n $gc = new geoCountry();\n $countries = $gc->find('all');\n \n $gr = new geoRegion(); \n $regions = $gr->find('all',null,'rank asc,name asc');\n \n assign_to_template(array(\n 'countries'=>$countries,\n 'regions'=>$regions\n ));\n }", "label_name": "CWE-74", "label": 1} +{"code": " function searchName() {\r\n return gt(\"Calendar Event\");\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": "\t\t\t\t$path = Helpers::isAbsolute($item) ? $item : ($this->getRepositoryPath() . DIRECTORY_SEPARATOR . $item);\n\n\t\t\t\tif (!file_exists($path)) {\n\t\t\t\t\tthrow new GitException(\"The path at '$item' does not represent a valid file.\");\n\t\t\t\t}\n\n\t\t\t\t$this->run('add', $item);\n\t\t\t}", "label_name": "CWE-77", "label": 14} +{"code": "\t\t$params = ['uitype' => 71, 'displaytype' => 1, 'typeofdata' => 'N~O', 'isEditableReadOnly' => false, 'maximumlength' => '99999999999999999'];", "label_name": "CWE-20", "label": 0} +{"code": " public function pending() {\n// global $db;\n \n // make sure we have what we need.\n if (empty($this->params['id'])) expQueue::flashAndFlow('error', gt('Your subscriber ID was not supplied.'));\n\n // find the subscriber and their pending subscriptions\n $ealerts = expeAlerts::getPendingBySubscriber($this->params['id']);\n $subscriber = new subscribers($this->params['id']);\n \n // render the template\n assign_to_template(array(\n 'subscriber'=>$subscriber,\n 'ealerts'=>$ealerts\n ));\n }", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic static function wpSetUpBeforeClass( $factory ) {\n\t\tself::make_user_by_role( 'administrator' );\n\t\tself::$post = $factory->post->create_and_get();\n\t}", "label_name": "CWE-862", "label": 8} +{"code": " public function enable()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $swimlane_id = $this->request->getIntegerParam('swimlane_id');\n\n if ($this->swimlaneModel->enable($project['id'], $swimlane_id)) {\n $this->flash->success(t('Swimlane updated successfully.'));\n } else {\n $this->flash->failure(t('Unable to update this swimlane.'));\n }\n\n $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-200", "label": 10} +{"code": "\tpublic function fixsessions() {\n\t global $db;\n\n//\t\t$test = $db->sql('CHECK TABLE '.$db->prefix.'sessionticket');\n\t\t$fix = $db->sql('REPAIR TABLE '.$db->prefix.'sessionticket');\n\t\tflash('message', gt('Sessions Table was Repaired'));\n\t\texpHistory::back();\n\t}", "label_name": "CWE-74", "label": 1} +{"code": " public static function getHelpVersionId($version) {\n global $db;\n\n return $db->selectValue('help_version', 'id', 'version=\"'.$version.'\"');\n }", "label_name": "CWE-74", "label": 1} +{"code": " function searchByModelForm() {\n // get the search terms\n $terms = $this->params['search_string'];\n\n $sql = \"model like '%\" . $terms . \"%'\";\n\n $limit = !empty($this->config['limit']) ? $this->config['limit'] : 10;\n $page = new expPaginator(array(\n 'model' => 'product',\n 'where' => $sql,\n 'limit' => !empty($this->config['pagination_default']) ? $this->config['pagination_default'] : $limit,\n 'order' => 'title',\n 'dir' => 'DESC',\n 'page' => (isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller' => $this->params['controller'],\n 'action' => $this->params['action'],\n 'columns' => array(\n gt('Model #') => 'model',\n gt('Product Name') => 'title',\n gt('Price') => 'base_price'\n ),\n ));\n\n assign_to_template(array(\n 'page' => $page,\n 'terms' => $terms\n ));\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function handle($stanza, $parent = false)\n {\n $message = $stanza->forwarded->message;\n\n $jid = explode('/',(string)$message->attributes()->from);\n $to = current(explode('/',(string)$message->attributes()->to));\n\n if($message->composing)\n $this->event('composing', array($jid[0], $to));\n if($message->paused)\n $this->event('paused', array($jid[0], $to));\n if($message->gone)\n $this->event('gone', array($jid[0], $to));\n\n if($message->body || $message->subject) {\n $m = new \\Modl\\Message;\n $m->set($message, $stanza->forwarded);\n\n if(!preg_match('#^\\?OTR#', $m->body)) {\n $md = new \\Modl\\MessageDAO;\n $md->set($m);\n\n $this->pack($m);\n $this->deliver();\n }\n }\n }", "label_name": "CWE-20", "label": 0} +{"code": " function prepareInputForAdd($input) {\n\n //If it's the first ldap directory then set it as the default directory\n if (!self::getNumberOfServers()) {\n $input['is_default'] = 1;\n }\n\n if (isset($input[\"rootdn_passwd\"]) && !empty($input[\"rootdn_passwd\"])) {\n $input[\"rootdn_passwd\"] = Toolbox::encrypt(stripslashes($input[\"rootdn_passwd\"]), GLPIKEY);\n }\n\n return $input;\n }", "label_name": "CWE-327", "label": 3} +{"code": "\tpublic function addJoin( $tableAlias, $joinConditions ) {\n\t\tif ( empty( $tableAlias ) || empty( $joinConditions ) ) {\n\t\t\tthrow new \\MWException( __METHOD__ . ': An empty join clause was passed.' );\n\t\t}\n\t\tif ( isset( $this->join[$tableAlias] ) ) {\n\t\t\tthrow new \\MWException( __METHOD__ . ': Attempted to overwrite existing join clause.' );\n\t\t}\n\t\t$this->join[$tableAlias] = $joinConditions;\n\t\treturn true;\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " static function isSearchable() {\r\n return true;\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": "function wp_validate_redirect($location, $default = '') {\n\t$location = trim( $location );\n\t// browsers will assume 'http' is your protocol, and will obey a redirect to a URL starting with '//'\n\tif ( substr($location, 0, 2) == '//' )\n\t\t$location = 'http:' . $location;\n\n\t// In php 5 parse_url may fail if the URL query part contains http://, bug #38143\n\t$test = ( $cut = strpos($location, '?') ) ? substr( $location, 0, $cut ) : $location;\n\n\t// @-operator is used to prevent possible warnings in PHP < 5.3.3.\n\t$lp = @parse_url($test);\n\n\t// Give up if malformed URL\n\tif ( false === $lp )\n\t\treturn $default;\n\n\t// Allow only http and https schemes. No data:, etc.\n\tif ( isset($lp['scheme']) && !('http' == $lp['scheme'] || 'https' == $lp['scheme']) )\n\t\treturn $default;\n\n\t// Reject if certain components are set but host is not. This catches urls like https:host.com for which parse_url does not set the host field.\n\tif ( ! isset( $lp['host'] ) && ( isset( $lp['scheme'] ) || isset( $lp['user'] ) || isset( $lp['pass'] ) || isset( $lp['port'] ) ) ) {\n\t\treturn $default;\n\t}\n\n\t// Reject malformed components parse_url() can return on odd inputs.\n\tforeach ( array( 'user', 'pass', 'host' ) as $component ) {\n\t\tif ( isset( $lp[ $component ] ) && strpbrk( $lp[ $component ], ':/?#@' ) ) {\n\t\t\treturn $default;\n\t\t}\n\t}\n\n\t$wpp = parse_url(home_url());\n\n\t/**\n\t * Filters the whitelist of hosts to redirect to.\n\t *\n\t * @since 2.3.0\n\t *\n\t * @param array $hosts An array of allowed hosts.\n\t * @param bool|string $host The parsed host; empty if not isset.\n\t */\n\t$allowed_hosts = (array) apply_filters( 'allowed_redirect_hosts', array($wpp['host']), isset($lp['host']) ? $lp['host'] : '' );\n\n\tif ( isset($lp['host']) && ( !in_array($lp['host'], $allowed_hosts) && $lp['host'] != strtolower($wpp['host'])) )\n\t\t$location = $default;\n\n\treturn $location;\n}", "label_name": "CWE-20", "label": 0} +{"code": " static function displayname() {\n return gt(\"e-Commerce Category Manager\");\n }", "label_name": "CWE-74", "label": 1} +{"code": " public function crossOriginRedirectProvider()\n {\n return [\n ['http://example.com?a=b', 'http://test.com/', false],\n ['https://example.com?a=b', 'https://test.com/', false],\n ['http://example.com?a=b', 'https://test.com/', false],\n ['https://example.com?a=b', 'http://test.com/', false],\n ['http://example.com?a=b', 'http://example.com/', true],\n ['https://example.com?a=b', 'https://example.com/', true],\n ['http://example.com?a=b', 'https://example.com/', true],\n ['https://example.com?a=b', 'http://example.com/', false],\n ];\n }", "label_name": "CWE-200", "label": 10} +{"code": "function XMLRPCaddImageToGroup($name, $imageid){\n $groups = getUserResources(array(\"imageAdmin\"), array(\"manageGroup\"), 1);\n \n if($groupid = getResourceGroupID(\"image/$name\")){\n if(!array_key_exists($groupid, $groups['image'])){\n return array('status' => 'error',\n 'errorcode' => 46,\n 'errormsg' => 'Unable to access image group');\n }\n $resources = getUserResources(array(\"imageAdmin\"), array(\"manageGroup\"));\n if(!array_key_exists($imageid, $resources['image'])){\n return array('status' => 'error',\n 'errorcode' => 47,\n 'errormsg' => 'Unable to access image');\n }\n\n $allimages = getImages();\n $query = \"INSERT IGNORE INTO resourcegroupmembers \"\n . \"(resourceid, resourcegroupid) VALUES \"\n . \"({$allimages[$imageid]['resourceid']}, $groupid)\";\n doQuery($query, 287);\n return array('status' => 'success');\n } else {\n return array('status' => 'error',\n 'errorcode' => 83,\n 'errormsg' => 'invalid resource group name');\n }\n}", "label_name": "CWE-20", "label": 0} +{"code": " function addDiscountToCart() {\n// global $user, $order;\n global $order;\n //lookup discount to see if it's real and valid, and not already in our cart\n //this will change once we allow more than one coupon code\n\n $discount = new discounts();\n $discount = $discount->getCouponByName($this->params['coupon_code']);\n\n if (empty($discount)) {\n flash('error', gt(\"This discount code you entered does not exist.\"));\n //redirect_to(array('controller'=>'cart', 'action'=>'checkout')); \n expHistory::back();\n }\n\n //check to see if it's in our cart already\n if ($this->isDiscountInCart($discount->id)) {\n flash('error', gt(\"This discount code is already in your cart.\"));\n //redirect_to(array('controller'=>'cart', 'action'=>'checkout'));\n expHistory::back();\n }\n\n //this should really be reworked, as it shoudn't redirect directly and not return\n $validateDiscountMessage = $discount->validateDiscount();\n if ($validateDiscountMessage == \"\") {\n //if all good, add to cart, otherwise it will have redirected\n $od = new order_discounts();\n $od->orders_id = $order->id;\n $od->discounts_id = $discount->id;\n $od->coupon_code = $discount->coupon_code;\n $od->title = $discount->title;\n $od->body = $discount->body;\n $od->save();\n // set this to just the discount applied via this coupon?? if so, when though? $od->discount_total = ??;\n flash('message', gt(\"The discount code has been applied to your cart.\"));\n } else {\n flash('error', $validateDiscountMessage);\n }\n //redirect_to(array('controller'=>'cart', 'action'=>'checkout')); \n expHistory::back();\n }", "label_name": "CWE-20", "label": 0} +{"code": " private function generateTempFileData()\n {\n return [\n 'name' => md5(mt_rand()),\n 'tmp_name' => tempnam(sys_get_temp_dir(), ''),\n 'type' => 'image/jpeg',\n 'size' => mt_rand(1000, 10000),\n 'error' => '0',\n ];\n }", "label_name": "CWE-330", "label": 12} +{"code": " public function remove()\n {\n $project = $this->getProject();\n $this->checkCSRFParam();\n $column_id = $this->request->getIntegerParam('column_id');\n\n if ($this->columnModel->remove($column_id)) {\n $this->flash->success(t('Column removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this column.'));\n }\n\n $this->response->redirect($this->helper->url->to('ColumnController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-200", "label": 10} +{"code": " public function Authorise ($host, $port = false, $tval = false, $username, $password, $debug_level = 0) {\n $this->host = $host;\n\n // If no port value is passed, retrieve it\n if ($port == false) {\n $this->port = $this->POP3_PORT;\n } else {\n $this->port = $port;\n }\n\n // If no port value is passed, retrieve it\n if ($tval == false) {\n $this->tval = $this->POP3_TIMEOUT;\n } else {\n $this->tval = $tval;\n }\n\n $this->do_debug = $debug_level;\n $this->username = $username;\n $this->password = $password;\n\n // Refresh the error log\n $this->error = null;\n\n // Connect\n $result = $this->Connect($this->host, $this->port, $this->tval);\n\n if ($result) {\n $login_result = $this->Login($this->username, $this->password);\n\n if ($login_result) {\n $this->Disconnect();\n\n return true;\n }\n\n }\n\n // We need to disconnect regardless if the login succeeded\n $this->Disconnect();\n\n return false;\n }", "label_name": "CWE-20", "label": 0} +{"code": " function connect() {\n\n return $this->connectToServer($this->fields['host'], $this->fields['port'],\n $this->fields['rootdn'],\n Toolbox::decrypt($this->fields['rootdn_passwd'], GLPIKEY),\n $this->fields['use_tls'],\n $this->fields['deref_option']);\n }", "label_name": "CWE-327", "label": 3} +{"code": "\tprivate function __construct($userinfo, $tid = - 1) {\n\t\t$this->userinfo = $userinfo;\n\t\t$this->tid = $tid;\n\n\t\t// initialize data array\n\t\t$this->initData();\n\n\t\t// read data from database\n\t\t$this->readData();\n\t}", "label_name": "CWE-732", "label": 13} +{"code": " public function testIpAddressOfRangedTrustedProxyIsSetAsRemote()\n {\n $expectedSubRequest = Request::create('/');\n $expectedSubRequest->headers->set('Surrogate-Capability', 'abc=\"ESI/1.0\"');\n $expectedSubRequest->server->set('REMOTE_ADDR', '1.1.1.1');\n $expectedSubRequest->headers->set('x-forwarded-for', array('127.0.0.1'));\n $expectedSubRequest->server->set('HTTP_X_FORWARDED_FOR', '127.0.0.1');\n\n Request::setTrustedProxies(array('1.1.1.1/24'));\n\n $strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest($expectedSubRequest));\n\n $request = Request::create('/');\n $request->headers->set('Surrogate-Capability', 'abc=\"ESI/1.0\"');\n $strategy->render('/', $request);\n\n Request::setTrustedProxies(array());\n }", "label_name": "CWE-20", "label": 0} +{"code": " $modelNames[ucfirst($module->name)] = self::getModelTitle($modelName);\n }\n asort ($modelNames);\n if ($criteria !== null) {\n return $modelNames;\n } else {\n self::$_modelNames = $modelNames;\n }\n }\n return self::$_modelNames;\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function search() {\n// global $db, $user;\n global $db;\n\n $sql = \"select DISTINCT(a.id) as id, a.firstname as firstname, a.middlename as middlename, a.lastname as lastname, a.organization as organization, a.email as email \";\n $sql .= \"from \" . $db->prefix . \"addresses as a \"; //R JOIN \" . \n //$db->prefix . \"billingmethods as bm ON bm.addresses_id=a.id \";\n $sql .= \" WHERE match (a.firstname,a.lastname,a.email,a.organization) against ('\" . $this->params['query'] .\n \"*' IN BOOLEAN MODE) \";\n $sql .= \"order by match (a.firstname,a.lastname,a.email,a.organization) against ('\" . $this->params['query'] . \"*' IN BOOLEAN MODE) ASC LIMIT 12\";\n $res = $db->selectObjectsBySql($sql);\n foreach ($res as $key=>$record) {\n $res[$key]->title = $record->firstname . ' ' . $record->lastname;\n }\n //eDebug($sql);\n $ar = new expAjaxReply(200, gt('Here\\'s the items you wanted'), $res);\n $ar->send();\n }", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic static function getSubcategories( $categoryName, $depth = 1 ) {\n\t\t$DB = wfGetDB( DB_REPLICA, 'dpl' );\n\n\t\tif ( $depth > 2 ) {\n\t\t\t//Hard constrain depth because lots of recursion is bad.\n\t\t\t$depth = 2;\n\t\t}\n\t\t$categories = [];\n\t\t$result = $DB->select(\n\t\t\t[ 'page', 'categorylinks' ],\n\t\t\t[ 'page_title' ],\n\t\t\t[\n\t\t\t\t'page_namespace'\t\t=> intval( NS_CATEGORY ),\n\t\t\t\t'categorylinks.cl_to'\t=> str_replace( ' ', '_', $categoryName )\n\t\t\t],\n\t\t\t__METHOD__,\n\t\t\t[ 'DISTINCT' ],\n\t\t\t[\n\t\t\t\t'categorylinks' => [\n\t\t\t\t\t'INNER JOIN',\n\t\t\t\t\t'page.page_id = categorylinks.cl_from'\n\t\t\t\t]\n\t\t\t]\n\t\t);\n\t\twhile ( $row = $result->fetchRow() ) {\n\t\t\t$categories[] = $row['page_title'];\n\t\t\tif ( $depth > 1 ) {\n\t\t\t\t$categories = array_merge( $categories, self::getSubcategories( $row['page_title'], $depth - 1 ) );\n\t\t\t}\n\t\t}\n\t\t$categories = array_unique( $categories );\n\t\t$DB->freeResult( $result );\n\t\treturn $categories;\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " $masteroption->delete();\n }\n \n // delete the mastergroup\n $db->delete('optiongroup', 'optiongroup_master_id='.$mastergroup->id);\n $mastergroup->delete();\n \n expHistory::back();\n }", "label_name": "CWE-74", "label": 1} +{"code": " $layout[$loc] = array_merge($layout[$loc],$data);\n }\n }\n }\n return $layout;\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function Recipient($to) {\n $this->error = null; // so no confusion is caused\n\n if(!$this->connected()) {\n $this->error = array(\n \"error\" => \"Called Recipient() without being connected\");\n return false;\n }\n\n fputs($this->smtp_conn,\"RCPT TO:<\" . $to . \">\" . $this->CRLF);\n\n $rply = $this->get_lines();\n $code = substr($rply,0,3);\n\n if($this->do_debug >= 2) {\n $this->edebug(\"SMTP -> FROM SERVER:\" . $rply . $this->CRLF . '
    ');\n }\n\n if($code != 250 && $code != 251) {\n $this->error =\n array(\"error\" => \"RCPT not accepted from server\",\n \"smtp_code\" => $code,\n \"smtp_msg\" => substr($rply,4));\n if($this->do_debug >= 1) {\n $this->edebug(\"SMTP -> ERROR: \" . $this->error[\"error\"] . \": \" . $rply . $this->CRLF . '
    ');\n }\n return false;\n }\n return true;\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function testClientIpIsAlwaysLocalhostForForwardedRequests()\n {\n $this->setNextResponse();\n $this->request('GET', '/', array('REMOTE_ADDR' => '10.0.0.1'));\n\n $this->assertEquals('127.0.0.1', $this->kernel->getBackendRequest()->server->get('REMOTE_ADDR'));\n }", "label_name": "CWE-20", "label": 0} +{"code": "\tprivate function convertTimestamp( $inputDate ) {\n\t\t$timestamp = $inputDate;\n\t\tswitch ( $inputDate ) {\n\t\t\tcase 'today':\n\t\t\t\t$timestamp = date( 'YmdHis' );\n\t\t\t\tbreak;\n\t\t\tcase 'last hour':\n\t\t\t\t$date = new \\DateTime();\n\t\t\t\t$date->sub( new \\DateInterval( 'P1H' ) );\n\t\t\t\t$timestamp = $date->format( 'YmdHis' );\n\t\t\t\tbreak;\n\t\t\tcase 'last day':\n\t\t\t\t$date = new \\DateTime();\n\t\t\t\t$date->sub( new \\DateInterval( 'P1D' ) );\n\t\t\t\t$timestamp = $date->format( 'YmdHis' );\n\t\t\t\tbreak;\n\t\t\tcase 'last week':\n\t\t\t\t$date = new \\DateTime();\n\t\t\t\t$date->sub( new \\DateInterval( 'P7D' ) );\n\t\t\t\t$timestamp = $date->format( 'YmdHis' );\n\t\t\t\tbreak;\n\t\t\tcase 'last month':\n\t\t\t\t$date = new \\DateTime();\n\t\t\t\t$date->sub( new \\DateInterval( 'P1M' ) );\n\t\t\t\t$timestamp = $date->format( 'YmdHis' );\n\t\t\t\tbreak;\n\t\t\tcase 'last year':\n\t\t\t\t$date = new \\DateTime();\n\t\t\t\t$date->sub( new \\DateInterval( 'P1Y' ) );\n\t\t\t\t$timestamp = $date->format( 'YmdHis' );\n\t\t\t\tbreak;\n\t\t}\n\n\t\tif ( is_numeric( $timestamp ) ) {\n\t\t\treturn $this->DB->addQuotes( $timestamp );\n\t\t}\n\t\treturn 0;\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " static function description() {\n return gt(\"This module is for managing categories in your store.\");\n }", "label_name": "CWE-74", "label": 1} +{"code": " function showallSubcategories() {\n// global $db;\n\n expHistory::set('viewable', $this->params);\n// $parent = isset($this->params['cat']) ? $this->params['cat'] : expSession::get('catid');\n $catid = expSession::get('catid');\n $parent = !empty($catid) ? $catid : (!empty($this->params['cat']) ? $this->params['cat'] : 0);\n $category = new storeCategory($parent);\n $categories = $category->getEcomSubcategories();\n $ancestors = $category->pathToNode();\n assign_to_template(array(\n 'categories' => $categories,\n 'ancestors' => $ancestors,\n 'category' => $category\n ));\n }", "label_name": "CWE-20", "label": 0} +{"code": "\tpublic static function dumpArray( $arg ) {\n\t\t$numargs = count( $arg );\n\t\tif ( $numargs < 3 ) {\n\t\t\treturn '';\n\t\t}\n\t\t$var = trim( $arg[2] );\n\t\t$text = \" array {$var} = {\";\n\t\t$n = 0;\n\t\tif ( array_key_exists( $var, self::$memoryArray ) ) {\n\t\t\tforeach ( self::$memoryArray[$var] as $value ) {\n\t\t\t\tif ( $n++ > 0 ) {\n\t\t\t\t\t$text .= ', ';\n\t\t\t\t}\n\t\t\t\t$text .= \"{$value}\";\n\t\t\t}\n\t\t}\n\t\treturn $text . \"}\\n\";\n\t}", "label_name": "CWE-400", "label": 2} +{"code": "\t\t\t\t} elseif ( $sSecLabel[0] != '{' ) {\n\t\t\t\t\t$limpos = strpos( $sSecLabel, '[' );\n\t\t\t\t\t$cutLink = 'default';\n\t\t\t\t\t$skipPattern = [];\n\t\t\t\t\tif ( $limpos > 0 && $sSecLabel[strlen( $sSecLabel ) - 1] == ']' ) {\n\t\t\t\t\t\t// regular expressions which define a skip pattern may precede the text\n\t\t\t\t\t\t$fmtSec = explode( '~', substr( $sSecLabel, $limpos + 1, strlen( $sSecLabel ) - $limpos - 2 ) );\n\t\t\t\t\t\t$sSecLabel = substr( $sSecLabel, 0, $limpos );\n\t\t\t\t\t\t$cutInfo = explode( \" \", $fmtSec[count( $fmtSec ) - 1], 2 );\n\t\t\t\t\t\t$maxLength = intval( $cutInfo[0] );\n\t\t\t\t\t\tif ( array_key_exists( '1', $cutInfo ) ) {\n\t\t\t\t\t\t\t$cutLink = $cutInfo[1];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tforeach ( $fmtSec as $skipKey => $skipPat ) {\n\t\t\t\t\t\t\tif ( $skipKey == count( $fmtSec ) - 1 ) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t$skipPattern[] = $skipPat;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif ( $maxLength < 0 ) {\n\t\t\t\t\t\t$maxLength = -1; // without valid limit include whole section\n\t\t\t\t\t}\n\t\t\t\t}", "label_name": "CWE-400", "label": 2} +{"code": " public function __construct(OrderService $orderService)\n {\n $this->orderService = $orderService;\n }", "label_name": "CWE-200", "label": 10} +{"code": " public function IsSendmail() {\n if (!stristr(ini_get('sendmail_path'), 'sendmail')) {\n $this->Sendmail = '/var/qmail/bin/sendmail';\n }\n $this->Mailer = 'sendmail';\n }", "label_name": "CWE-20", "label": 0} +{"code": " $section = new section(intval($page));\r\n if ($section) {\r\n// self::deleteLevel($section->id);\r\n $section->delete();\r\n }\r\n }\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": "\tfunction edit() {\n\t if (empty($this->params['content_id'])) {\n\t flash('message',gt('An error occurred: No content id set.'));\n expHistory::back(); \n\t } \n /* The global constants can be overridden by passing appropriate params */\n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n// $require_login = empty($this->params['require_login']) ? COMMENTS_REQUIRE_LOGIN : $this->params['require_login'];\n// $require_approval = empty($this->params['require_approval']) ? COMMENTS_REQUIRE_APPROVAL : $this->params['require_approval'];\n// $require_notification = empty($this->params['require_notification']) ? COMMENTS_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n// $notification_email = empty($this->params['notification_email']) ? COMMENTS_NOTIFICATION_EMAIL : $this->params['notification_email'];\n \n \n\t $id = empty($this->params['id']) ? null : $this->params['id'];\n\t $comment = new expComment($id);\n //FIXME here is where we might sanitize the comment before displaying/editing it\n\t\tassign_to_template(array(\n\t\t 'content_id'=>$this->params['content_id'],\n 'content_type'=>$this->params['content_type'],\n\t\t 'comment'=>$comment\n\t\t));\n\t}\t", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic static function login() {\n\t\tuser::login(expString::sanitize($_POST['username']),expString::sanitize($_POST['password']));\n\t\tif (!isset($_SESSION[SYS_SESSION_KEY]['user'])) { // didn't successfully log in\n\t\t\tflash('error', gt('Invalid Username / Password'));\n\t\t\tif (expSession::is_set('redirecturl_error')) {\n\t\t\t\t$url = expSession::get('redirecturl_error');\n\t\t\t\texpSession::un_set('redirecturl_error');\n\t\t\t\theader(\"Location: \".$url);\n\t\t\t} else {\n\t\t\t\texpHistory::back();\n\t\t\t}\n\t\t} else { // we're logged in\n\t\t\tglobal $user;\n\n if (expSession::get('customer-login')) expSession::un_set('customer-login');\n\t\t\tif (!empty($_POST['username'])) flash('message', gt('Welcome back').' '.expString::sanitize($_POST['username']));\n if ($user->isAdmin()) {\n expHistory::back();\n } else {\n foreach ($user->groups as $g) {\n if (!empty($g->redirect)) {\n $url = URL_FULL.$g->redirect;\n break;\n }\n }\n if (isset($url)) {\n header(\"Location: \".$url);\n } else {\n expHistory::back();\n }\n }\n\t\t}\n\t}", "label_name": "CWE-74", "label": 1} +{"code": " public function resetauthkey($id = null)\n {\n if (!$this->_isAdmin() && Configure::read('MISP.disableUserSelfManagement')) {\n throw new MethodNotAllowedException('User self-management has been disabled on this instance.');\n }\n if ($id == 'me') {\n $id = $this->Auth->user('id');\n }\n if (!$this->userRole['perm_auth']) {\n throw new MethodNotAllowedException('Invalid action.');\n }\n $this->User->id = $id;\n if (!$id || !$this->User->exists($id)) {\n throw new MethodNotAllowedException('Invalid user.');\n }\n $user = $this->User->read();\n $oldKey = $this->User->data['User']['authkey'];\n if (!$this->_isSiteAdmin() && !($this->_isAdmin() && $this->Auth->user('org_id') == $this->User->data['User']['org_id']) && ($this->Auth->user('id') != $id)) {\n throw new MethodNotAllowedException('Invalid user.');\n }\n $newkey = $this->User->generateAuthKey();\n $this->User->saveField('authkey', $newkey);\n $this->__extralog(\n 'reset_auth_key',\n 'Authentication key for user ' . $user['User']['id'] . ' (' . $user['User']['email'] . ')',\n $fieldsResult = 'authkey(' . $oldKey . ') => (' . $newkey . ')'\n );\n if (!$this->_isRest()) {\n $this->Flash->success(__('New authkey generated.', true));\n $this->_refreshAuth();\n $this->redirect($this->referer());\n } else {\n return $this->RestResponse->saveSuccessResponse('User', 'resetauthkey', $id, $this->response->type(), 'Authkey updated: ' . $newkey);\n }\n }", "label_name": "CWE-269", "label": 6} +{"code": " public function delete(DeleteInvoiceRequest $request)\n {\n $this->authorize('delete multiple invoices');\n\n Invoice::destroy($request->ids);\n\n return response()->json([\n 'success' => true,\n ]);\n }", "label_name": "CWE-862", "label": 8} +{"code": "\tstatic public function getPriorityText($_lng, $_priority = 0)\n\t{\n\t\tswitch($_priority)\n\t\t{\n\t\t\tcase 1:\n\t\t\t\treturn $_lng['ticket']['high'];\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\treturn $_lng['ticket']['normal'];\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn $_lng['ticket']['low'];\n\t\t\t\tbreak;\n\t\t}\n\t}", "label_name": "CWE-732", "label": 13} +{"code": " private function getSwimlane()\n {\n $swimlane = $this->swimlaneModel->getById($this->request->getIntegerParam('swimlane_id'));\n\n if (empty($swimlane)) {\n throw new PageNotFoundException();\n }\n\n return $swimlane;\n }", "label_name": "CWE-200", "label": 10} +{"code": " function showByModel() {\n global $order, $template, $db;\n\n expHistory::set('viewable', $this->params);\n $product = new product();\n $model = $product->find(\"first\", 'model=\"' . $this->params['model'] . '\"');\n //eDebug($model);\n $product_type = new $model->product_type($model->id);\n //eDebug($product_type);\n $tpl = $product_type->getForm('show');\n if (!empty($tpl)) $template = new controllertemplate($this, $tpl);\n //eDebug($template);\n $this->grabConfig(); // grab the global config\n assign_to_template(array(\n 'config' => $this->config,\n 'product' => $product_type,\n 'last_category' => $order->lastcat\n ));\n }", "label_name": "CWE-20", "label": 0} +{"code": "\tstatic function validUTF($string) {\n\t\tif(!mb_check_encoding($string, 'UTF-8') OR !($string === mb_convert_encoding(mb_convert_encoding($string, 'UTF-32', 'UTF-8' ), 'UTF-8', 'UTF-32'))) {\n\t\t\treturn false;\n\t\t}\t\t\n\t\treturn true;\n\t}", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic function setItemAttributes( $attributes ) {\n\t\t$this->itemAttributes = \\Sanitizer::fixTagAttributes( $attributes, 'li' );\n\t}", "label_name": "CWE-400", "label": 2} +{"code": "\tprivate function initData() {\n\n\t\t$this->Set('customer', 0, true, true);\n\t\t$this->Set('admin', 1, true, true);\n\t\t$this->Set('subject', '', true, true);\n\t\t$this->Set('category', '0', true, true);\n\t\t$this->Set('priority', '2', true, true);\n\t\t$this->Set('message', '', true, true);\n\t\t$this->Set('dt', 0, true, true);\n\t\t$this->Set('lastchange', 0, true, true);\n\t\t$this->Set('ip', '', true, true);\n\t\t$this->Set('status', '0', true, true);\n\t\t$this->Set('lastreplier', '0', true, true);\n\t\t$this->Set('by', '0', true, true);\n\t\t$this->Set('answerto', '0', true, true);\n\t\t$this->Set('archived', '0', true, true);\n\t}", "label_name": "CWE-732", "label": 13} +{"code": " foreach ($days as $value) {\r\n $regitem[] = $value;\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public function confirm()\n {\n $project = $this->getProject();\n $swimlane = $this->getSwimlane();\n\n $this->response->html($this->helper->layout->project('swimlane/remove', array(\n 'project' => $project,\n 'swimlane' => $swimlane,\n )));\n }", "label_name": "CWE-200", "label": 10} +{"code": " $body = str_replace(array(\"\\n\"), \"
    \", $body);\r\n } else {\r\n // It's going elsewhere (doesn't like quoted-printable)\r\n $body = str_replace(array(\"\\n\"), \" -- \", $body);\r\n }\r\n $title = $items[$i]->title;\r\n\r\n $msg .= \"BEGIN:VEVENT\\n\";\r\n $msg .= $dtstart . $dtend;\r\n $msg .= \"UID:\" . $items[$i]->date_id . \"\\n\";\r\n $msg .= \"DTSTAMP:\" . date(\"Ymd\\THis\", time()) . \"Z\\n\";\r\n if ($title) {\r\n $msg .= \"SUMMARY:$title\\n\";\r\n }\r\n if ($body) {\r\n $msg .= \"DESCRIPTION;ENCODING=QUOTED-PRINTABLE:\" . $body . \"\\n\";\r\n }\r\n //\tif($link_url) { $msg .= \"URL: $link_url\\n\";}\r\n if (!empty($this->config['usecategories'])) {\r\n if (!empty($items[$i]->expCat[0]->title)) {\r\n $msg .= \"CATEGORIES:\".$items[$i]->expCat[0]->title.\"\\n\";\r\n } else {\r\n $msg .= \"CATEGORIES:\".$this->config['uncat'].\"\\n\";\r\n }\r\n }\r\n $msg .= \"END:VEVENT\\n\";\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " function edit() {\r\n global $template;\r\n\r\n parent::edit();\r\n $allforms = array();\r\n $allforms[\"\"] = gt('Disallow Feedback');\r\n // calculate which event date is the one being edited\r\n $event_key = 0;\r\n foreach ($template->tpl->tpl_vars['record']->value->eventdate as $key=>$d) {\r\n \t if ($d->id == $this->params['date_id']) $event_key = $key;\r\n \t}\r\n\r\n assign_to_template(array(\r\n 'allforms' => array_merge($allforms, expTemplate::buildNameList(\"forms\", \"event/email\", \"tpl\", \"[!_]*\")),\r\n 'checked_date' => !empty($this->params['date_id']) ? $this->params['date_id'] : null,\r\n 'event_key' => $event_key,\r\n ));\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public function SetFrom($address, $name = '', $auto = 1) {\n $address = trim($address);\n $name = trim(preg_replace('/[\\r\\n]+/', '', $name)); //Strip breaks and trim\n if (!$this->ValidateAddress($address)) {\n $this->SetError($this->Lang('invalid_address').': '. $address);\n if ($this->exceptions) {\n throw new phpmailerException($this->Lang('invalid_address').': '.$address);\n }\n if ($this->SMTPDebug) {\n $this->edebug($this->Lang('invalid_address').': '.$address);\n }\n return false;\n }\n $this->From = $address;\n $this->FromName = $name;\n if ($auto) {\n if (empty($this->ReplyTo)) {\n $this->AddAnAddress('Reply-To', $address, $name);\n }\n if (empty($this->Sender)) {\n $this->Sender = $address;\n }\n }\n return true;\n }", "label_name": "CWE-20", "label": 0} +{"code": " $src = substr($ref->source, strlen($prefix)) . $section->id;\r\n if (call_user_func(array($ref->module, 'hasContent'))) {\r\n $oloc = expCore::makeLocation($ref->module, $ref->source);\r\n $nloc = expCore::makeLocation($ref->module, $src);\r\n if ($ref->module != \"container\") {\r\n call_user_func(array($ref->module, 'copyContent'), $oloc, $nloc);\r\n } else {\r\n call_user_func(array($ref->module, 'copyContent'), $oloc, $nloc, $section->id);\r\n }\r\n }\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": "\t function update_upcharge() {\n $this->loc->src = \"@globalstoresettings\";\n $config = new expConfig($this->loc);\n\t\t$this->config = $config->config;\n\t\t\n\t\t//This will make sure that only the country or region that given a rate value will be saved in the db\n\t\t$upcharge = array();\n\t\tforeach($this->params['upcharge'] as $key => $item) {\n\t\t\tif(!empty($item)) {\n\t\t\t\t$upcharge[$key] = $item;\n\t\t\t}\n\t\t}\n\t\t$this->config['upcharge'] = $upcharge;\n\t\t\n $config->update(array('config'=>$this->config));\n flash('message', gt('Configuration updated'));\n expHistory::back();\n }", "label_name": "CWE-74", "label": 1} +{"code": " public function remove()\n {\n $this->checkCSRFParam();\n $project = $this->getProject();\n $action = $this->actionModel->getById($this->request->getIntegerParam('action_id'));\n\n if (! empty($action) && $this->actionModel->remove($action['id'])) {\n $this->flash->success(t('Action removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this action.'));\n }\n\n $this->response->redirect($this->helper->url->to('ActionController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-200", "label": 10} +{"code": " public function recipient($toaddr)\n {\n return $this->sendCommand(\n 'RCPT TO',\n 'RCPT TO:<' . $toaddr . '>',\n array(250, 251)\n );\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function save() {\n $data = $_POST['file'];\n\n // security (remove all ..)\n $data['name'] = str_replace('..', '', $data['name']);\n $file = FILES_DIR . DS . $data['name'];\n \n // CSRF checks\n if (isset($_POST['csrf_token'])) {\n $csrf_token = $_POST['csrf_token'];\n if (!SecureToken::validateToken($csrf_token, BASE_URL.'plugin/file_manager/save/'.$data['name'])) {\n Flash::set('error', __('Invalid CSRF token found!'));\n redirect(get_url('plugin/file_manager/view/'.$data['name']));\n }\n }\n else {\n Flash::set('error', __('No CSRF token found!'));\n redirect(get_url('plugin/file_manager/view/'.$data['name']));\n }\n \n if (file_exists($file)) {\n if (file_put_contents($file, $data['content']) !== false) {\n Flash::set('success', __('File has been saved with success!'));\n } else {\n Flash::set('error', __('File is not writable! File has not been saved!'));\n }\n } else {\n if (file_put_contents($file, $data['content'])) {\n Flash::set('success', __('File :name has been created with success!', array(':name' => $data['name'])));\n } else {\n Flash::set('error', __('Directory is not writable! File has not been saved!'));\n }\n }\n\n // save and quit or save and continue editing ?\n if (isset($_POST['commit'])) {\n redirect(get_url('plugin/file_manager/browse/' . substr($data['name'], 0, strrpos($data['name'], '/'))));\n } else {\n redirect(get_url('plugin/file_manager/view/' . $data['name'] . (endsWith($data['name'], URL_SUFFIX) ? '?has_url_suffix=1' : '')));\n }", "label_name": "CWE-20", "label": 0} +{"code": "\tfunction getTextColumns($table) {\n\t\t$sql = \"SHOW COLUMNS FROM \" . $this->prefix.$table . \" WHERE type = 'text' OR type like 'varchar%'\";\n\t\t$res = @mysqli_query($this->connection, $sql);\n\t\tif ($res == null)\n return array();\n\t\t$records = array();\n\t\twhile($row = mysqli_fetch_object($res)) {\n\t\t\t$records[] = $row->Field;\n\t\t}\n\t\t\n\t\treturn $records;\n\t}", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic static function dplReplaceParserFunction( &$parser, $text, $pat = '', $repl = '' ) {\n\t\t$parser->addTrackingCategory( 'dplreplace-parserfunc-tracking-category' );\n\t\tif ( $text == '' || $pat == '' ) {\n\t\t\treturn '';\n\t\t}\n\t\t# convert \\n to a real newline character\n\t\t$repl = str_replace( '\\n', \"\\n\", $repl );\n\n\t\t# replace\n\t\tif ( !self::isRegexp( $pat ) ) {\n\t\t\t$pat = '`' . str_replace( '`', '\\`', $pat ) . '`';\n\t\t}\n\n\t\treturn @preg_replace( $pat, $repl, $text );\n\t}", "label_name": "CWE-400", "label": 2} +{"code": "\tpublic function approve_submit() {\n\t if (empty($this->params['id'])) {\n\t flash('error', gt('No ID supplied for comment to approve'));\n\t expHistory::back();\n\t }\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n// $require_login = empty($this->params['require_login']) ? COMMENTS_REQUIRE_LOGIN : $this->params['require_login'];\n// $require_approval = empty($this->params['require_approval']) ? COMMENTS_REQUIRE_APPROVAL : $this->params['require_approval'];\n// $require_notification = empty($this->params['require_notification']) ? COMMENTS_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n// $notification_email = empty($this->params['notification_email']) ? COMMENTS_NOTIFICATION_EMAIL : $this->params['notification_email'];\n\t \n\t $comment = new expComment($this->params['id']);\n\t $comment->body = $this->params['body'];\n\t $comment->approved = $this->params['approved'];\n\t $comment->save();\n\t expHistory::back();\n\t}", "label_name": "CWE-74", "label": 1} +{"code": " public function actionGetItems(){\n $model = X2Model::model ($this->modelClass);\n if (isset ($model)) {\n $tableName = $model->tableName ();\n $sql = \n 'SELECT id, fileName as value\n FROM '.$tableName.' \n WHERE associationType!=\"theme\" and fileName LIKE :qterm \n ORDER BY fileName ASC';\n $command = Yii::app()->db->createCommand($sql);\n $qterm = $_GET['term'].'%';\n $command->bindParam(\":qterm\", $qterm, PDO::PARAM_STR);\n $result = $command->queryAll();\n echo CJSON::encode($result);\n }\n Yii::app()->end();\n }", "label_name": "CWE-20", "label": 0} +{"code": "\tprivate function _minoredits( $option ) {\n\t\tif ( isset( $option ) && $option == 'exclude' ) {\n\t\t\t$this->addTable( 'revision', 'revision' );\n\t\t\t$this->addWhere( 'revision.rev_minor_edit = 0' );\n\t\t}\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " $object->size = convert_size($cur->getSize());\n $object->mtime = date('D, j M, Y', $cur->getMTime());\n list($object->perms, $object->chmod) = $this->_getPermissions($cur->getPerms());\n \n // Find the file type\n $object->type = $this->_getFileType($cur);\n\n // make the link depending on if it's a file or a dir\n if ($cur->isDir()) {\n $object->link = 'path . $object->name) . '\">' . $object->name . '';\n } else {\n $object->link = 'path . $object->name . (endsWith($object->name, URL_SUFFIX) ? '?has_url_suffix=1' : '')) . '\">' . $object->name . '';\n }\n\n $files[$object->name] = $object;\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function actionGetLists() {\n if (!Yii::app()->user->checkAccess('ContactsAdminAccess')) {\n $condition = ' AND (visibility=\"1\" OR assignedTo=\"Anyone\" OR assignedTo=\"' . Yii::app()->user->getName() . '\"';\n /* x2temp */\n $groupLinks = Yii::app()->db->createCommand()->select('groupId')->from('x2_group_to_user')->where('userId=' . Yii::app()->user->getId())->queryColumn();\n if (!empty($groupLinks))\n $condition .= ' OR assignedTo IN (' . implode(',', $groupLinks) . ')';\n\n $condition .= ' OR (visibility=2 AND assignedTo IN\n (SELECT username FROM x2_group_to_user WHERE groupId IN\n (SELECT groupId FROM x2_group_to_user WHERE userId=' . Yii::app()->user->getId() . '))))';\n } else {\n $condition = '';\n }\n // Optional search parameter for autocomplete\n $qterm = isset($_GET['term']) ? $_GET['term'] . '%' : '';\n $result = Yii::app()->db->createCommand()\n ->select('id,name as value')\n ->from('x2_lists')\n ->where('modelName=\"Contacts\" AND type!=\"campaign\" AND name LIKE :qterm' . $condition, array(':qterm' => $qterm))\n ->order('name ASC')\n ->queryAll();\n echo CJSON::encode($result);\n }", "label_name": "CWE-20", "label": 0} +{"code": "\tprivate function setHeader( $header ) {\n\t\tif ( \\DynamicPageListHooks::getDebugLevel() == 5 ) {\n\t\t\t$header = '
    ' . $header;\n\t\t}\n\t\t$this->header = $this->replaceVariables( $header );\n\t}", "label_name": "CWE-400", "label": 2}
    +{"code": "\tpublic function admin_print_scripts( $not_used ) {\r\n\t\t// Load any uploaded KML into the search map - only works with browser uploader\r\n\t\t\r\n\t\t// See if wp_upload_handler found uploaded KML\r\n\t\t$kml_url = get_transient( 'gm_uploaded_kml_url' );\r\n\t\tif (strlen($kml_url) > 0) {\r\n\t\t\t// Load the KML in the location editor\r\n\t\t\techo '\r\n\t\t\t\t';\r\n\t\t\tdelete_transient( 'gm_uploaded_kml_url' );\r\n\t\t}\r\n\t}\r", "label_name": "CWE-20", "label": 0}
    +{"code": "                $banner->increaseImpressions();\n            }\n        }\n        \n        // assign banner to the template and show it!\n        assign_to_template(array(\n            'banners'=>$banners\n        ));\n    }", "label_name": "CWE-74", "label": 1}
    +{"code": "    public function upload() {\n        if (!AuthUser::hasPermission('file_manager_upload')) {\n            Flash::set('error', __('You do not have sufficient permissions to upload a file.'));\n            redirect(get_url('plugin/file_manager/browse/'));\n        }\n        \n        // CSRF checks\n        if (isset($_POST['csrf_token'])) {\n            $csrf_token = $_POST['csrf_token'];\n            if (!SecureToken::validateToken($csrf_token, BASE_URL.'plugin/file_manager/upload')) {\n                Flash::set('error', __('Invalid CSRF token found!'));\n                redirect(get_url('plugin/file_manager/browse/'));\n            }\n        }\n        else {\n            Flash::set('error', __('No CSRF token found!'));\n            redirect(get_url('plugin/file_manager/browse/'));\n        }\n        \n        $mask = Plugin::getSetting('umask', 'file_manager');\n        umask(octdec($mask));\n\n        $data = $_POST['upload'];\n        $path = str_replace('..', '', $data['path']);\n        $overwrite = isset($data['overwrite']) ? true : false;\n\n        // Clean filenames\n        $filename = preg_replace('/ /', '_', $_FILES['upload_file']['name']);\n        $filename = preg_replace('/[^a-z0-9_\\-\\.]/i', '', $filename);\n\n        if (isset($_FILES)) {\n            $file = $this->_upload_file($filename, FILES_DIR . '/' . $path . '/', $_FILES['upload_file']['tmp_name'], $overwrite);\n\n            if ($file === false)\n                Flash::set('error', __('File has not been uploaded!'));\n        }\n        redirect(get_url('plugin/file_manager/browse/' . $path));\n    }", "label_name": "CWE-20", "label": 0}
    +{"code": "                    $db->updateObject($value, 'section');\r\n                }\r\n                $db->updateObject($moveSec, 'section');\r\n                //handle re-ranking of previous parent\r\n                $oldSiblings = $db->selectObjects(\"section\", \"parent=\" . $oldParent . \" AND rank>\" . $oldRank . \" ORDER BY rank\");\r\n                $rerank      = 1;\r\n                foreach ($oldSiblings as $value) {\r\n                    if ($value->id != $moveSec->id) {\r\n                        $value->rank = $rerank;\r\n                        $db->updateObject($value, 'section');\r\n                        $rerank++;\r\n                    }\r\n                }\r\n                if ($oldParent != $moveSec->parent) {\r\n                    //we need to re-rank the children of the parent that the moving section has just left\r\n                    $childOfLastMove = $db->selectObjects(\"section\", \"parent=\" . $oldParent . \" ORDER BY rank\");\r\n                    for ($i = 0, $iMax = count($childOfLastMove); $i < $iMax; $i++) {\r\n                        $childOfLastMove[$i]->rank = $i;\r\n                        $db->updateObject($childOfLastMove[$i], 'section');\r\n                    }\r\n                }\r\n            }\r\n        }\r\n        self::checkForSectionalAdmins($move);\r\n        expSession::clearAllUsersSessionCache('navigation');\r\n    }\r", "label_name": "CWE-74", "label": 1}
    +{"code": "    protected function generateVerifyCode()\n    {\n        if ($this->minLength > $this->maxLength) {\n            $this->maxLength = $this->minLength;\n        }\n        if ($this->minLength < 3) {\n            $this->minLength = 3;\n        }\n        if ($this->maxLength > 20) {\n            $this->maxLength = 20;\n        }\n        $length = mt_rand($this->minLength, $this->maxLength);\n\n        $letters = 'bcdfghjklmnpqrstvwxyz';\n        $vowels = 'aeiou';\n        $code = '';\n        for ($i = 0; $i < $length; ++$i) {\n            if ($i % 2 && mt_rand(0, 10) > 2 || !($i % 2) && mt_rand(0, 10) > 9) {\n                $code .= $vowels[mt_rand(0, 4)];\n            } else {\n                $code .= $letters[mt_rand(0, 20)];\n            }\n        }\n\n        return $code;\n    }", "label_name": "CWE-330", "label": 12}
    +{"code": "    static function description() {\r\n        return \"Manage events and schedules, and optionally publish them.\";\r\n    }\r", "label_name": "CWE-74", "label": 1}
    +{"code": "            foreach ($evs as $key=>$event) {\r\n                if ($condense) {\r\n                    $eventid = $event->id;\r\n                    $multiday_event = array_filter($events, create_function('$event', 'global $eventid; return $event->id === $eventid;'));\r\n                    if (!empty($multiday_event)) {\r\n                        unset($evs[$key]);\r\n                        continue;\r\n                    }\r\n                }\r\n                $evs[$key]->eventstart += $edate->date;\r\n                $evs[$key]->eventend += $edate->date;\r\n                $evs[$key]->date_id = $edate->id;\r\n                if (!empty($event->expCat)) {\r\n                    $catcolor = empty($event->expCat[0]->color) ? null : trim($event->expCat[0]->color);\r\n//                    if (substr($catcolor,0,1)=='#') $catcolor = '\" style=\"color:'.$catcolor.';';\r\n                    $evs[$key]->color = $catcolor;\r\n                }\r\n            }\r", "label_name": "CWE-74", "label": 1}
    +{"code": "\tpublic function init() {\r\n\t\tglobal $geo_mashup_options, $pagenow;\r\n\r\n\t\t// Enable this interface when the option is set and we're on a destination page\r\n\t\t$enabled = is_admin() &&\r\n\t\t\t$geo_mashup_options->get( 'overall', 'located_object_name', 'user' ) == 'true' &&\r\n\t\t\tpreg_match( '/(user-edit|profile).php/', $pagenow );\r\n\t\t$enabled = apply_filters( 'geo_mashup_load_user_editor', $enabled );\r\n\r\n\t\t// If enabled, register all the interface elements\r\n\t\tif ( $enabled ) { \r\n\r\n\t\t\t// Form generation\r\n\t\t\tadd_action( 'show_user_profile', array( &$this, 'print_form' ) );\r\n\t\t\tadd_action( 'edit_user_profile', array( &$this, 'print_form' ) );\r\n\t\t\t// MAYBEDO: add location to registration page?\r\n\r\n\t\t\t// Form processing\r\n\t\t\tadd_action( 'personal_options_update', array( &$this, 'save_user'));\r\n\t\t\tadd_action( 'edit_user_profile_update', array( &$this, 'save_user'));\r\n\r\n\t\t\t$this->enqueue_form_client_items();\r\n\t\t}\r\n\t}\r", "label_name": "CWE-20", "label": 0}
    +{"code": "\tfunction manage () {\n\t    expHistory::set('viewable', $this->params);\n\t\t\n\t\t$vendor = new vendor();\n\t\t$vendors = $vendor->find('all');\n\t\tif(!empty($this->params['vendor'])) {\n\t\t\t$purchase_orders = $this->purchase_order->find('all', 'vendor_id=' . $this->params['vendor']);\n\t\t} else {\n\t\t\t$purchase_orders = $this->purchase_order->find('all');\n\t\t}\n\t\t\n\t\tassign_to_template(array(\n            'purchase_orders'=>$purchase_orders,\n            'vendors' => $vendors,\n            'vendor_id' => @$this->params['vendor']\n        ));\n\t}", "label_name": "CWE-74", "label": 1}
    +{"code": "    public function manage_sitemap() {\r\n        global $db, $user, $sectionObj, $sections;\r\n\r\n        expHistory::set('viewable', $this->params);\r\n        $id      = $sectionObj->id;\r\n        $current = null;\r\n        // all we need to do is determine the current section\r\n        $navsections = $sections;\r\n        if ($sectionObj->parent == -1) {\r\n            $current = $sectionObj;\r\n        } else {\r\n            foreach ($navsections as $section) {\r\n                if ($section->id == $id) {\r\n                    $current = $section;\r\n                    break;\r\n                }\r\n            }\r\n        }\r\n        assign_to_template(array(\r\n            'sasections'   => $db->selectObjects('section', 'parent=-1'),\r\n            'sections'     => $navsections,\r\n            'current'      => $current,\r\n            'canManage'    => ((isset($user->is_acting_admin) && $user->is_acting_admin == 1) ? 1 : 0),\r\n        ));\r\n    }\r", "label_name": "CWE-74", "label": 1}
    +{"code": "  public function IsMail() {\n    $this->Mailer = 'mail';\n  }", "label_name": "CWE-20", "label": 0}
    +{"code": "    public function getViewFileParams () {\n        if (!isset ($this->_viewFileParams)) {\n            $this->_viewFileParams = array_merge (\n                parent::getViewFileParams (),\n                array (\n                    'chartType' => $this->chartType,\n\t\t\t        'chartSettingsDataProvider' => self::getChartSettingsProvider (\n                        $this->chartType),\n                    'eventTypes' =>\n                        array ('all'=>Yii::t('app', 'All Events')) + Events::$eventLabels,\n                    'socialSubtypes' => json_decode (\n\t\t\t            Dropdowns::model()->findByPk(113)->options,true),\n                    'visibilityFilters' => array (\n                        '1'=>'Public',\n                        '0'=>'Private',\n                    ),\n                    'suppressChartSettings' => false,\n                    'chartType' => 'usersChart',\n                    'widgetUID' => $this->widgetUID,\n                    'metricTypes' => User::getUserOptions (),\n                )\n            );\n        }\n        return $this->_viewFileParams;\n    }", "label_name": "CWE-20", "label": 0}
    +{"code": "\t\tforeach($return as $index => $value) {\n\t\t\tif(! is_string($value))\n\t\t\t\t$return[$index] = $defaultvalue;\n\t\t\telseif($addslashes)\n\t\t\t\t$return[$index] = addslashes($value);\n\t\t}", "label_name": "CWE-20", "label": 0}
    +{"code": "        static::$functions = ['random_bytes' => false, 'openssl_random_pseudo_bytes' => false, 'mcrypt_create_iv' => false];", "label_name": "CWE-330", "label": 12}
    +{"code": "            $v = trim($v);\n            if ($v !== '') {\n                $_POST[$key][] = $v;\n            }\n        }\n    }", "label_name": "CWE-200", "label": 10}
    +{"code": "    public function manage_messages() {\n        expHistory::set('manageable', $this->params);\n        \n        $page = new expPaginator(array(\n\t\t\t'model'=>'order_status_messages',\n\t\t\t'where'=>1,\n            'limit'=>10,\n\t\t\t'order'=>'body',\n            'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n            'controller'=>$this->params['controller'],\n            'action'=>$this->params['action'],\n\t\t\t//'columns'=>array('Name'=>'title')\n        ));\n\n        //eDebug($page);\n\t\tassign_to_template(array(\n            'page'=>$page\n        ));\n    }", "label_name": "CWE-74", "label": 1}
    +{"code": "\tpublic function getPurchaseOrderByJSON() {\n\n\t\tif(!empty($this->params['vendor'])) {\n\t\t\t$purchase_orders = $this->purchase_order->find('all', 'vendor_id=' . $this->params['vendor']);\n\t\t} else {\n\t\t\t$purchase_orders = $this->purchase_order->find('all');\n\t\t}\n\n\t\techo json_encode($purchase_orders);\n\t}", "label_name": "CWE-20", "label": 0}
    +{"code": "\tfunction edit() {\n\t    if (empty($this->params['content_id'])) {\n\t        flash('message',gt('An error occurred: No content id set.'));\n            expHistory::back();  \n\t    } \n        /* The global constants can be overridden by passing appropriate params */\n        //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n//        $require_login = empty($this->params['require_login']) ? COMMENTS_REQUIRE_LOGIN : $this->params['require_login'];\n//        $require_approval = empty($this->params['require_approval']) ? COMMENTS_REQUIRE_APPROVAL : $this->params['require_approval'];\n//        $require_notification = empty($this->params['require_notification']) ? COMMENTS_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n//        $notification_email = empty($this->params['notification_email']) ? COMMENTS_NOTIFICATION_EMAIL : $this->params['notification_email'];\n        \n        \n\t    $id = empty($this->params['id']) ? null : $this->params['id'];\n\t    $comment = new expComment($id);\n        //FIXME here is where we might sanitize the comment before displaying/editing it\n\t\tassign_to_template(array(\n\t\t    'content_id'=>$this->params['content_id'],\n            'content_type'=>$this->params['content_type'],\n\t\t    'comment'=>$comment\n\t\t));\n\t}\t", "label_name": "CWE-74", "label": 1}
    +{"code": "    public function remove()\n    {\n        $this->checkCSRFParam();\n        $project = $this->getProject();\n        $swimlane_id = $this->request->getIntegerParam('swimlane_id');\n\n        if ($this->swimlaneModel->remove($project['id'], $swimlane_id)) {\n            $this->flash->success(t('Swimlane removed successfully.'));\n        } else {\n            $this->flash->failure(t('Unable to remove this swimlane.'));\n        }\n\n        $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));\n    }", "label_name": "CWE-200", "label": 10}
    +{"code": "    public function approve_submit() {\n        global $history;\n        \n        if (empty($this->params['id'])) {\n            flash('error', gt('No ID supplied for comment to approve'));\n            $lastUrl = expHistory::getLast('editable');\n        }\n        \n        /* The global constants can be overriden by passing appropriate params */ \n        //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n        $require_login = empty($this->params['require_login']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];\n        $require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];\n        $require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n        $notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];\n        \n        $simplenote = new expSimpleNote($this->params['id']);\n        //FIXME here is where we might sanitize the note before approving it\n        $simplenote->body = $this->params['body'];\n        $simplenote->approved = $this->params['approved'];\n        $simplenote->save();\n        \n        $lastUrl = makelink($history->history[$history->history['lasts']['type']][count($history->history[$history->history['lasts']['type']])-1]['params']);\n        if (!empty($this->params['tab']))\n        {\n            $lastUrl .= \"#\".$this->params['tab'];\n        }\n        redirect_to($lastUrl);\n    }", "label_name": "CWE-74", "label": 1}
    +{"code": "        function scan_page($parent_id) {\r\n            global $db;\r\n\r\n            $sections = $db->selectObjects('section','parent=' . $parent_id);\r\n            $ret = '';\r\n            foreach ($sections as $page) {\r\n                $cLoc = serialize(expCore::makeLocation('container','@section' . $page->id));\r\n                $ret .= scan_container($cLoc, $page->id);\r\n                $ret .= scan_page($page->id);\r\n            }\r\n            return $ret;\r\n        }\r", "label_name": "CWE-74", "label": 1}
    +{"code": "    public function manage() {\n        expHistory::set('manageable', $this->params);\n        \n        // build out a SQL query that gets all the data we need and is sortable.\n        $sql  = 'SELECT b.*, c.title as companyname, f.expfiles_id as file_id ';\n        $sql .= 'FROM '.DB_TABLE_PREFIX.'_banner b, '.DB_TABLE_PREFIX.'_companies c , '.DB_TABLE_PREFIX.'_content_expFiles f ';\n        $sql .= 'WHERE b.companies_id = c.id AND (b.id = f.content_id AND f.content_type=\"banner\")';\n\t\t\n\t\t$page = new expPaginator(array(\n\t\t\t'model'=>'banner',\n\t\t\t'sql'=>$sql,\n\t\t\t'order'=>'title',\n            'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n            'controller'=>$this->params['controller'],\n            'action'=>$this->params['action'],\n            'src'=>$this->loc->src,\n\t\t\t'columns'=>array(\n                gt('Title')=>'title',\n                gt('Company')=>'companyname',\n                gt('Impressions')=>'impressions',\n                gt('Clicks')=>'clicks'\n            )\n        ));\n\n\t\tassign_to_template(array(\n            'page'=>$page\n        ));\n    }", "label_name": "CWE-74", "label": 1}
    +{"code": "function barcode_encode_genbarcode($code,$encoding)\n{\n    global $genbarcode_loc;\n\n    // Clean parameters\n    if (preg_match(\"/^ean$/i\", $encoding) && strlen($code)==13) $code=substr($code,0,12);\n    if (!$encoding) $encoding=\"ANY\";\n    $encoding=preg_replace(\"/[\\\\\\|]/\", \"_\", $encoding);\n    $code=preg_replace(\"/[\\\\\\|]/\", \"_\", $code);\n\n    $command=escapeshellarg($genbarcode_loc);\n    $paramclear=\" \\\"\".str_replace(\"\\\"\", \"\\\\\\\"\",$code).\"\\\" \\\"\".str_replace(\"\\\"\", \"\\\\\\\"\",strtoupper($encoding)).\"\\\"\";\n\n    $fullcommandclear=$command.\" \".$paramclear.\" 2>&1\";\n    //print $fullcommandclear.\"
    \\n\";\n\n dol_syslog(\"Run command \".$fullcommandclear);\n $fp=popen($fullcommandclear, \"r\");\n if ($fp)\n {\n $bars=fgets($fp, 1024);\n $text=fgets($fp, 1024);\n $encoding=fgets($fp, 1024);\n pclose($fp);\n }\n else\n {\n dol_syslog(\"barcode.lib.php::barcode_encode_genbarcode failed to run popen \".$fullcommandclear, LOG_ERR);\n return false;\n }\n //var_dump($bars);\n $ret=array(\n\t\t\"encoding\" => trim($encoding),\n\t\t\"bars\" => trim($bars),\n\t\t\"text\" => trim($text)\n );\n //var_dump($ret);\n if (!$ret['encoding']) return false;\n if (!$ret['bars']) return false;\n if (!$ret['text']) return false;\n return $ret;\n}", "label_name": "CWE-20", "label": 0} +{"code": "\tfunction test_valid_comment() {\n\t\t$result = $this->myxmlrpcserver->wp_newComment(\n\t\t\tarray(\n\t\t\t\t1,\n\t\t\t\t'administrator',\n\t\t\t\t'administrator',\n\t\t\t\tself::$post->ID,\n\t\t\t\tarray(\n\t\t\t\t\t'content' => rand_str( 100 ),\n\t\t\t\t),\n\t\t\t)\n\t\t);\n\n\t\t$this->assertNotIXRError( $result );\n\t}", "label_name": "CWE-862", "label": 8} +{"code": " public function approve_toggle() {\n global $history;\n \n if (empty($this->params['id'])) return;\n \n /* The global constants can be overriden by passing appropriate params */ \n //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet\n $require_login = empty($this->params['require_login']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];\n $require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];\n $require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];\n $notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];\n \n \n $simplenote = new expSimpleNote($this->params['id']);\n $simplenote->approved = $simplenote->approved == 1 ? 0 : 1;\n $simplenote->save();\n \n $lastUrl = makelink($history->history[$history->history['lasts']['type']][count($history->history[$history->history['lasts']['type']])-1]['params']);\n if (!empty($this->params['tab']))\n {\n $lastUrl .= \"#\".$this->params['tab'];\n }\n redirect_to($lastUrl);\n }", "label_name": "CWE-74", "label": 1} +{"code": " public function confirm()\n {\n $project = $this->getProject();\n\n $this->response->html($this->helper->layout->project('column/remove', array(\n 'column' => $this->columnModel->getById($this->request->getIntegerParam('column_id')),\n 'project' => $project,\n )));\n }", "label_name": "CWE-200", "label": 10} +{"code": " public function confirm()\n {\n $task = $this->getTask();\n $link = $this->getTaskLink();\n\n $this->response->html($this->template->render('task_internal_link/remove', array(\n 'link' => $link,\n 'task' => $task,\n )));\n }", "label_name": "CWE-200", "label": 10} +{"code": " public function confirm()\n {\n $task = $this->getTask();\n $link = $this->getTaskLink();\n\n $this->response->html($this->template->render('task_internal_link/remove', array(\n 'link' => $link,\n 'task' => $task,\n )));\n }", "label_name": "CWE-200", "label": 10} +{"code": " private function getResponse ($size = 128) {\n $pop3_response = fgets($this->pop_conn, $size);\n\n return $pop3_response;\n }", "label_name": "CWE-20", "label": 0} +{"code": " function process_subsections($parent_section, $subtpl) {\r\n global $db, $router;\r\n\r\n $section = new stdClass();\r\n $section->parent = $parent_section->id;\r\n $section->name = $subtpl->name;\r\n $section->sef_name = $router->encode($section->name);\r\n $section->subtheme = $subtpl->subtheme;\r\n $section->active = $subtpl->active;\r\n $section->public = $subtpl->public;\r\n $section->rank = $subtpl->rank;\r\n $section->page_title = $subtpl->page_title;\r\n $section->keywords = $subtpl->keywords;\r\n $section->description = $subtpl->description;\r\n $section->id = $db->insertObject($section, 'section');\r\n self::process_section($section, $subtpl);\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " function update_optiongroup_master() {\n global $db;\n\n $id = empty($this->params['id']) ? null : $this->params['id'];\n $og = new optiongroup_master($id);\n $oldtitle = $og->title;\n $og->update($this->params);\n \n // if the title of the master changed we should update the option groups that are already using it.\n if ($oldtitle != $og->title) {\n $db->sql('UPDATE '.$db->prefix.'optiongroup SET title=\"'.$og->title.'\" WHERE title=\"'.$oldtitle.'\"');\n }\n \n expHistory::back();\n }", "label_name": "CWE-74", "label": 1} +{"code": " public static function returnChildrenAsJSON() {\r\n global $db;\r\n\r\n //$nav = section::levelTemplate(intval($_REQUEST['id'], 0));\r\n $id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;\r\n $nav = $db->selectObjects('section', 'parent=' . $id, 'rank');\r\n //FIXME $manage_all is moot w/ cascading perms now?\r\n $manage_all = false;\r\n if (expPermissions::check('manage', expCore::makeLocation('navigation', '', $id))) {\r\n $manage_all = true;\r\n }\r\n //FIXME recode to use foreach $key=>$value\r\n $navcount = count($nav);\r\n for ($i = 0; $i < $navcount; $i++) {\r\n if ($manage_all || expPermissions::check('manage', expCore::makeLocation('navigation', '', $nav[$i]->id))) {\r\n $nav[$i]->manage = 1;\r\n $view = true;\r\n } else {\r\n $nav[$i]->manage = 0;\r\n $view = $nav[$i]->public ? true : expPermissions::check('view', expCore::makeLocation('navigation', '', $nav[$i]->id));\r\n }\r\n $nav[$i]->link = expCore::makeLink(array('section' => $nav[$i]->id), '', $nav[$i]->sef_name);\r\n if (!$view) unset($nav[$i]);\r\n }\r\n $nav= array_values($nav);\r\n// $nav[$navcount - 1]->last = true;\r\n if (count($nav)) $nav[count($nav) - 1]->last = true;\r\n// echo expJavascript::ajaxReply(201, '', $nav);\r\n $ar = new expAjaxReply(201, '', $nav);\r\n $ar->send();\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " static function displayname() { return gt(\"Navigation\"); }\r", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic function update_version() {\n\t // get the current version\n\t $hv = new help_version();\n\t $current_version = $hv->find('first', 'is_current=1');\n\t \n\t // check to see if the we have a new current version and unset the old current version.\n\t if (!empty($this->params['is_current'])) {\n//\t $db->sql('UPDATE '.DB_TABLE_PREFIX.'_help_version set is_current=0');\n help_version::clearHelpVersion();\n\t }\n\t expSession::un_set('help-version');\n\n\t // save the version\n\t $id = empty($this->params['id']) ? null : $this->params['id'];\n\t $version = new help_version();\n\t // if we don't have a current version yet so we will force this one to be it\n\t if (empty($current_version->id)) $this->params['is_current'] = 1;\n\t $version->update($this->params);\n\t \n\t // if this is a new version we need to copy over docs\n\t if (empty($id)) {\n\t self::copydocs($current_version->id, $version->id);\t \n\t }\n // let's update the search index to reflect the current help version\n searchController::spider();\n\n\t flash('message', gt('Saved help version').' '.$version->version);\n\t expHistory::back();\n\t}", "label_name": "CWE-74", "label": 1} +{"code": " $rst[$key] = self::parseAndTrim($st, $unescape);\n }\n return $rst;\n }\n\n $str = str_replace(\"
    \",\" \",$str);\n $str = str_replace(\"
    \",\" \",$str);\n $str = str_replace(\"
    \",\" \",$str);\n $str = str_replace(\"
    \",\" \",$str);\n $str = str_replace(\"\\r\\n\",\" \",$str);\n $str = str_replace('\"',\""\",$str);\n $str = str_replace(\"'\",\"'\",$str);\n $str = str_replace(\"\u2019\",\"’\",$str);\n $str = str_replace(\"\u2018\",\"‘\",$str);\n $str = str_replace(\"\u00ae\",\"®\",$str);\n $str = str_replace(\"\u2013\",\"-\", $str);\n $str = str_replace(\"\u2014\",\"—\", $str);\n $str = str_replace(\"\u201d\",\"”\", $str);\n $str = str_replace(\"\u201c\",\"“\", $str);\n $str = str_replace(\"\u00bc\",\"¼\",$str);\n $str = str_replace(\"\u00bd\",\"½\",$str);\n $str = str_replace(\"\u00be\",\"¾\",$str);\n\t\t$str = str_replace(\"\u2122\",\"™\", $str);\n\t\t$str = trim($str);\n\t\t\n if ($unescape) {\n\t\t\t$str = stripcslashes($str); \n\t\t} else {\n\t $str = addslashes($str);\n }\n\n return $str;\n }", "label_name": "CWE-74", "label": 1} +{"code": " protected function renderText ($field, $makeLinks, $textOnly, $encode) {\n $fieldName = $field->fieldName;\n $value = preg_replace(\"/(\\
    )|\\n/\",\" \",$this->owner->$fieldName);\n return Yii::app()->controller->convertUrls($this->render ($value, $encode));\n }", "label_name": "CWE-20", "label": 0} +{"code": "\tprivate function _addfirstcategorydate( $option ) {\n\t\t//@TODO: This should be programmatically determining which categorylink table to use instead of assuming the first one.\n\t\t$this->addSelect(\n\t\t\t[\n\t\t\t\t'cl_timestamp'\t=> \"DATE_FORMAT(cl1.cl_timestamp, '%Y%m%d%H%i%s')\"\n\t\t\t]\n\t\t);\n\t}", "label_name": "CWE-400", "label": 2} +{"code": "\tpublic function initializeObject() {\n\t\t$this->initializeFormStateFromRequest();\n\t\t$this->initializeCurrentPageFromRequest();\n\n\t\tif (!$this->isFirstRequest()) {\n\t\t\t$this->processSubmittedFormValues();\n\t\t}\n\t}", "label_name": "CWE-20", "label": 0} +{"code": " public static function initializeNavigation() {\r\n $sections = section::levelTemplate(0, 0);\r\n return $sections;\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public function confirm()\n {\n $project = $this->getProject();\n\n $this->response->html($this->helper->layout->project('action/remove', array(\n 'action' => $this->actionModel->getById($this->request->getIntegerParam('action_id')),\n 'available_events' => $this->eventManager->getAll(),\n 'available_actions' => $this->actionManager->getAvailableActions(),\n 'project' => $project,\n 'title' => t('Remove an action')\n )));\n }", "label_name": "CWE-200", "label": 10} +{"code": " function delete_option_master() {\n global $db;\n\n $masteroption = new option_master($this->params['id']);\n \n // delete any implementations of this option master\n $db->delete('option', 'option_master_id='.$masteroption->id);\n $masteroption->delete('optiongroup_master_id=' . $masteroption->optiongroup_master_id);\n //eDebug($masteroption);\n expHistory::back();\n }", "label_name": "CWE-74", "label": 1} +{"code": " protected function getComment()\n {\n $comment = $this->commentModel->getById($this->request->getIntegerParam('comment_id'));\n\n if (empty($comment)) {\n throw new PageNotFoundException();\n }\n\n if (! $this->userSession->isAdmin() && $comment['user_id'] != $this->userSession->getId()) {\n throw new AccessForbiddenException();\n }\n\n return $comment;\n }", "label_name": "CWE-200", "label": 10} +{"code": " public static function showModal($params) {\n\n if (!isset($params['argument']) || empty($params['argument'])) {\n return array(\n 'processed' => true,\n 'process_status' => erTranslationClassLhTranslation::getInstance()->getTranslation('chat/chatcommand', 'Please provide modal URL!')\n );\n }\n\n $paramsURL = explode(' ',$params['argument']);\n $URL = array_shift($paramsURL);\n\n if (is_numeric($URL)) {\n $URL = (erLhcoreClassSystem::$httpsMode == true ? 'https:' : 'http:') . '//' . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . erLhcoreClassDesign::baseurldirect('form/formwidget') . '/' . $URL;\n }", "label_name": "CWE-116", "label": 15} +{"code": "\t\t\t$text = preg_replace( $skipPat, '', $text );\n\t\t}\n\n\t\tif ( self::open( $parser, $part1 ) ) {\n\n\t\t\t//Handle recursion here, so we can break cycles.\n\t\t\tif ( $recursionCheck == false ) {\n\t\t\t\t$text = $parser->preprocess( $text, $parser->mTitle, $parser->mOptions );\n\t\t\t\tself::close( $parser, $part1 );\n\t\t\t}\n\n\t\t\tif ( $maxLength > 0 ) {\n\t\t\t\t$text = self::limitTranscludedText( $text, $maxLength, $link );\n\t\t\t}\n\t\t\tif ( $trim ) {\n\t\t\t\treturn trim( $text );\n\t\t\t} else {\n\t\t\t\treturn $text;\n\t\t\t}\n\t\t} else {\n\t\t\treturn \"[[\" . $title->getPrefixedText() . \"]]\" . \"\";\n\t\t}\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " public function IsSMTP() {\n $this->Mailer = 'smtp';\n }", "label_name": "CWE-20", "label": 0} +{"code": " function reset_stats() {\n// global $db;\n\n // reset the counters\n// $db->sql ('UPDATE '.$db->prefix.'banner SET impressions=0 WHERE 1');\n banner::resetImpressions();\n// $db->sql ('UPDATE '.$db->prefix.'banner SET clicks=0 WHERE 1');\n banner::resetClicks();\n \n // let the user know we did stuff. \n flash('message', gt(\"Banner statistics reset.\"));\n expHistory::back();\n }", "label_name": "CWE-74", "label": 1} +{"code": " public function testPOSTForRestProjectManager()\n {\n $post_resource = json_encode([\n 'label' => 'Test Request 9748',\n 'shortname' => 'test9748',\n 'description' => 'Test of Request 9748 for REST API Project Creation',\n 'is_public' => true,\n 'template_id' => 100,\n ]);\n\n $response = $this->getResponseByName(\n REST_TestDataBuilder::TEST_USER_DELEGATED_REST_PROJECT_MANAGER_NAME,\n $this->request_factory->createRequest(\n 'POST',\n 'projects'\n )->withBody(\n $this->stream_factory->createStream(\n $post_resource\n )\n )\n );\n\n $project = json_decode($response->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR);\n self::assertEquals(201, $response->getStatusCode());\n self::assertArrayHasKey(\"id\", $project);\n }", "label_name": "CWE-863", "label": 11} +{"code": " public static function validateByRegex($path, $values, $regex)\n {\n $result = preg_match($regex, $values[$path]);\n return array($path => ($result ? '' : __('Incorrect value!')));\n }", "label_name": "CWE-200", "label": 10} +{"code": " recyclebin::sendToRecycleBin($loc, $parent);\r\n //FIXME if we delete the module & sectionref the module completely disappears\r\n// if (class_exists($secref->module)) {\r\n// $modclass = $secref->module;\r\n// //FIXME: more module/controller glue code\r\n// if (expModules::controllerExists($modclass)) {\r\n// $modclass = expModules::getControllerClassName($modclass);\r\n// $mod = new $modclass($loc->src);\r\n// $mod->delete_instance();\r\n// } else {\r\n// $mod = new $modclass();\r\n// $mod->deleteIn($loc);\r\n// }\r\n// }\r\n }\r\n// $db->delete('sectionref', 'section=' . $parent);\r\n $db->delete('section', 'parent=' . $parent);\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public static function parseAndTrim($str, $isHTML = false) { //\ufffdDeath from above\ufffd? \ufffd\n //echo \"1
    \"; eDebug($str);\n// global $db;\n\n $str = str_replace(\"\ufffd\", \"’\", $str);\n $str = str_replace(\"\ufffd\", \"‘\", $str);\n $str = str_replace(\"\ufffd\", \"®\", $str);\n $str = str_replace(\"\ufffd\", \"-\", $str);\n $str = str_replace(\"\ufffd\", \"—\", $str);\n $str = str_replace(\"\ufffd\", \"”\", $str);\n $str = str_replace(\"\ufffd\", \"“\", $str);\n $str = str_replace(\"\\r\\n\", \" \", $str);\n //$str = str_replace(\",\",\"\\,\",$str); \n\n $str = str_replace('\\\"', \""\", $str);\n $str = str_replace('\"', \""\", $str);\n $str = str_replace(\"\ufffd\", \"¼\", $str);\n $str = str_replace(\"\ufffd\", \"½\", $str);\n $str = str_replace(\"\ufffd\", \"¾\", $str);\n //$str = htmlspecialchars($str);\n //$str = utf8_encode($str);\n// if (DB_ENGINE=='mysqli') {\n//\t $str = @mysqli_real_escape_string($db->connection,trim(str_replace(\"\ufffd\", \"™\", $str)));\n// } elseif(DB_ENGINE=='mysql') {\n// $str = @mysql_real_escape_string(trim(str_replace(\"\ufffd\", \"™\", $str)),$db->connection);\n// } else {\n//\t $str = trim(str_replace(\"\ufffd\", \"™\", $str));\n// }\n $str = @expString::escape(trim(str_replace(\"\ufffd\", \"™\", $str)));\n //echo \"2
    \"; eDebug($str,die);\n return $str;\n }", "label_name": "CWE-74", "label": 1} +{"code": "\tfunction delete_vendor() {\n\t\tglobal $db;\n\t\t\n if (!empty($this->params['id'])){\n\t\t\t$db->delete('vendor', 'id =' .$this->params['id']);\n\t\t}\n expHistory::back();\n }", "label_name": "CWE-74", "label": 1} +{"code": " public static function getHost() {\n\n if (isset($_SERVER['HTTP_HOST'])) {\n $site_address = (erLhcoreClassSystem::$httpsMode == true ? 'https:' : 'http:') . '//' . $_SERVER['HTTP_HOST'] ;\n } else if (class_exists('erLhcoreClassInstance')) {\n $site_address = 'https://' . erLhcoreClassInstance::$instanceChat->address . '.' . erConfigClassLhConfig::getInstance()->getSetting( 'site', 'seller_domain');\n } else if (class_exists('erLhcoreClassExtensionLhcphpresque')) {\n $site_address = erLhcoreClassModule::getExtensionInstance('erLhcoreClassExtensionLhcphpresque')->settings['site_address'];\n } else {\n $site_address = '';\n }\n\n return $site_address;\n }", "label_name": "CWE-116", "label": 15} +{"code": " private function isWindows()\n {\n return DIRECTORY_SEPARATOR !== '/';\n }", "label_name": "CWE-330", "label": 12} +{"code": "\tpublic static function onParserFirstCallInit( Parser &$parser ) {\n\t\tself::init();\n\n\t\t//DPL offers the same functionality as Intersection. So we register the tag in case LabeledSection Extension is not installed so that the section markers are removed.\n\t\tif ( \\DPL\\Config::getSetting( 'handleSectionTag' ) ) {\n\t\t\t$parser->setHook( 'section', [ __CLASS__, 'dplTag' ] );\n\t\t}\n\n\t\t$parser->setHook( 'DPL', [ __CLASS__, 'dplTag' ] );\n\t\t$parser->setHook( 'DynamicPageList', [ __CLASS__, 'intersectionTag' ] );\n\n\t\t$parser->setFunctionHook( 'dpl', [ __CLASS__, 'dplParserFunction' ] );\n\t\t$parser->setFunctionHook( 'dplnum', [ __CLASS__, 'dplNumParserFunction' ] );\n\t\t$parser->setFunctionHook( 'dplvar', [ __CLASS__, 'dplVarParserFunction' ] );\n\t\t$parser->setFunctionHook( 'dplreplace', [ __CLASS__, 'dplReplaceParserFunction' ] );\n\t\t$parser->setFunctionHook( 'dplchapter', [ __CLASS__, 'dplChapterParserFunction' ] );\n\t\t$parser->setFunctionHook( 'dplmatrix', [ __CLASS__, 'dplMatrixParserFunction' ] );\n\n\t\treturn true;\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " function __construct(bool $connect = false) {\n global $CFG_GLPI;\n\n $options = [\n 'base_uri' => GLPI_MARKETPLACE_PLUGINS_API_URI,\n 'connect_timeout' => self::TIMEOUT,\n ];\n\n // add proxy string if configured in glpi\n if (!empty($CFG_GLPI[\"proxy_name\"])) {\n $proxy_creds = !empty($CFG_GLPI[\"proxy_user\"])\n ? $CFG_GLPI[\"proxy_user\"].\":\".Toolbox::decrypt($CFG_GLPI[\"proxy_passwd\"], GLPIKEY).\"@\"\n : \"\";\n $proxy_string = \"http://{$proxy_creds}\".$CFG_GLPI['proxy_name'].\":\".$CFG_GLPI['proxy_port'];\n $options['proxy'] = $proxy_string;\n }\n\n // init guzzle client with base options\n $this->httpClient = new Guzzle_Client($options);\n }", "label_name": "CWE-327", "label": 3} +{"code": "\tprivate function _stablepages( $option ) {\n\t\tif ( function_exists( 'efLoadFlaggedRevs' ) ) {\n\t\t\t//Do not add this again if 'qualitypages' has already added it.\n\t\t\tif ( !$this->parametersProcessed['qualitypages'] ) {\n\t\t\t\t$this->addJoin(\n\t\t\t\t\t'flaggedpages',\n\t\t\t\t\t[\n\t\t\t\t\t\t\"LEFT JOIN\",\n\t\t\t\t\t\t\"page_id = fp_page_id\"\n\t\t\t\t\t]\n\t\t\t\t);\n\t\t\t}\n\t\t\tswitch ( $option ) {\n\t\t\t\tcase 'only':\n\t\t\t\t\t$this->addWhere(\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t'fp_stable IS NOT NULL'\n\t\t\t\t\t\t]\n\t\t\t\t\t);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'exclude':\n\t\t\t\t\t$this->addWhere(\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t'fp_stable'\t=> null\n\t\t\t\t\t\t]\n\t\t\t\t\t);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}", "label_name": "CWE-400", "label": 2} +{"code": "\tpublic function update($user, $notrigger = 0)\n\t{\n\t\tglobal $langs, $conf;\n\n\t\t$error = 0;\n\n\t\t// Clean parameters\n\t\t$this->address = ($this->address > 0 ? $this->address : $this->address);\n\t\t$this->zip = ($this->zip > 0 ? $this->zip : $this->zip);\n\t\t$this->town = ($this->town > 0 ? $this->town : $this->town);\n\t\t$this->country_id = ($this->country_id > 0 ? $this->country_id : $this->country_id);\n\t\t$this->country = ($this->country ? $this->country : $this->country);\n\n\t\t$this->db->begin();\n\n\t\t$sql = \"UPDATE \".MAIN_DB_PREFIX.\"don SET \";\n\t\t$sql .= \"amount = \".price2num($this->amount);\n\t\t$sql .= \",fk_payment = \".($this->modepaymentid ? $this->modepaymentid : \"null\");", "label_name": "CWE-20", "label": 0} +{"code": "function XMLRPCremoveImageFromGroup($name, $imageid){\n $groups = getUserResources(array(\"imageAdmin\"), array(\"manageGroup\"), 1);\n \n if($groupid = getResourceGroupID(\"image/$name\")){\n if(!array_key_exists($groupid, $groups['image'])){\n return array('status' => 'error',\n 'errorcode' => 46,\n 'errormsg' => 'Unable to access image group');\n }\n $resources = getUserResources(array(\"imageAdmin\"), array(\"manageGroup\"));\n if(!array_key_exists($imageid, $resources['image'])){\n return array('status' => 'error',\n 'errorcode' => 47,\n 'errormsg' => 'Unable to access image');\n }\n\n $allimages = getImages();\n $query = \"DELETE FROM resourcegroupmembers \"\n . \"WHERE resourceid={$allimages[$imageid]['resourceid']} \"\n . \"AND resourcegroupid=$groupid\";\n doQuery($query, 287);\n return array('status' => 'success');\n } else {\n return array('status' => 'error',\n 'errorcode' => 83,\n 'errormsg' => 'invalid resource group name');\n }\n}", "label_name": "CWE-20", "label": 0} +{"code": " function send_feedback() {\r\n $success = false;\r\n if (isset($this->params['id'])) {\r\n $ed = new eventdate($this->params['id']);\r\n// $email_addrs = array();\r\n if ($ed->event->feedback_email != '') {\r\n $msgtemplate = expTemplate::get_template_for_action($this, 'email/_' . $this->params['formname'], $this->loc);\r\n $msgtemplate->assign('params', $this->params);\r\n $msgtemplate->assign('event', $ed);\r\n $email_addrs = explode(',', $ed->event->feedback_email);\r\n //This is an easy way to remove duplicates\r\n $email_addrs = array_flip(array_flip($email_addrs));\r\n $email_addrs = array_map('trim', $email_addrs);\r\n $mail = new expMail();\r\n $success += $mail->quickSend(array(\r\n \"text_message\" => $msgtemplate->render(),\r\n 'to' => $email_addrs,\r\n 'from' => !empty($this->params['email']) ? $this->params['email'] : trim(SMTP_FROMADDRESS),\r\n 'subject' => $this->params['subject'],\r\n ));\r\n }\r\n }\r\n\r\n if ($success) {\r\n flashAndFlow('message', gt('Your feedback was successfully sent.'));\r\n } else {\r\n flashAndFlow('error', gt('We could not send your feedback. Please contact your administrator.'));\r\n }\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " protected function registerBackendPermissions()\n {\n BackendAuth::registerCallback(function ($manager) {\n $manager->registerPermissions('October.System', [\n 'system.manage_updates' => [\n 'label' => 'system::lang.permissions.manage_software_updates',\n 'tab' => 'system::lang.permissions.name'\n ],\n 'system.access_logs' => [\n 'label' => 'system::lang.permissions.access_logs',\n 'tab' => 'system::lang.permissions.name'\n ],\n 'system.manage_mail_settings' => [\n 'label' => 'system::lang.permissions.manage_mail_settings',\n 'tab' => 'system::lang.permissions.name'\n ],\n 'system.manage_mail_templates' => [\n 'label' => 'system::lang.permissions.manage_mail_templates',\n 'tab' => 'system::lang.permissions.name'\n ]\n ]);\n });\n }", "label_name": "CWE-269", "label": 6} +{"code": "\tpublic static function newFromRow( $row, Parameters $parameters, \\Title $title, $pageNamespace, $pageTitle ) {\n\t\tglobal $wgLang;\n\n\t\t$article = new Article( $title, $pageNamespace );\n\n\t\t$revActorName = null;\n\t\tif ( isset( $row['revactor_actor'] ) ) {\n\t\t\t$revActorName = User::newFromActorId( $row['revactor_actor'] )->getName();\n\t\t}\n\n\t\t$titleText = $title->getText();\n\t\tif ( $parameters->getParameter( 'shownamespace' ) === true ) {\n\t\t\t$titleText = $title->getPrefixedText();\n\t\t}\n\t\t$replaceInTitle = $parameters->getParameter( 'replaceintitle' );\n\t\tif ( is_array( $replaceInTitle ) && count( $replaceInTitle ) === 2 ) {\n\t\t\t$titleText = preg_replace( $replaceInTitle[0], $replaceInTitle[1], $titleText );\n\t\t}\n\n\t\t//Chop off title if longer than the 'titlemaxlen' parameter.\n\t\tif ( $parameters->getParameter( 'titlemaxlen' ) !== null && strlen( $titleText ) > $parameters->getParameter( 'titlemaxlen' ) ) {\n\t\t\t$titleText = substr( $titleText, 0, $parameters->getParameter( 'titlemaxlen' ) ) . '...';\n\t\t}\n\t\tif ( $parameters->getParameter( 'showcurid' ) === true && isset( $row['page_id'] ) ) {\n\t\t\t$articleLink = '[' . $title->getLinkURL( [ 'curid' => $row['page_id'] ] ) . ' ' . htmlspecialchars( $titleText ) . ']';\n\t\t} else {\n\t\t\t$articleLink = '[[' . ( $parameters->getParameter( 'escapelinks' ) && ( $pageNamespace == NS_CATEGORY || $pageNamespace == NS_FILE ) ? ':' : '' ) . $title->getFullText() . '|' . htmlspecialchars( $titleText ) . ']]';\n\t\t}", "label_name": "CWE-400", "label": 2} +{"code": " $date->delete(); // event automatically deleted if all assoc eventdates are deleted\r\n }\r\n expHistory::back();\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic function myaddressbook() {\n\t\tglobal $user;\n\n\t\t// check if the user is logged in.\n\t\texpQueue::flashIfNotLoggedIn('message',gt('You must be logged in to manage your address book.'));\n if (!$user->isAdmin() && $this->params['user_id'] != $user->id) {\n unset($this->params['user_id']);\n }\n\t\texpHistory::set('viewable', $this->params);\n\t\t$userid = (empty($this->params['user_id'])) ? $user->id : $this->params['user_id'];\n\t\tassign_to_template(array(\n 'addresses'=>$this->address->find('all', 'user_id='.$userid)\n ));\n\t}", "label_name": "CWE-200", "label": 10} +{"code": " function fopen($filename, $mode)\n {\n if (\\yiiunit\\framework\\base\\SecurityTest::$fopen !== null) {\n return \\yiiunit\\framework\\base\\SecurityTest::$fopen;\n }\n\n return \\fopen($filename, $mode);\n }", "label_name": "CWE-330", "label": 12} +{"code": "\tprivate static function executeTag( $input, array $args, Parser $parser, PPFrame $frame ) {\n\t\t// entry point for user tag or \n\t\t// create list and do a recursive parse of the output\n\n\t\t$parse = new \\DPL\\Parse();\n\t\tif ( \\DPL\\Config::getSetting( 'recursiveTagParse' ) ) {\n\t\t\t$input = $parser->recursiveTagParse( $input, $frame );\n\t\t}\n\n\t\t$text = $parse->parse( $input, $parser, $reset, $eliminate, true );\n\n\t\tif ( isset( $reset['templates'] ) && $reset['templates'] ) {\t// we can remove the templates by save/restore\n\t\t\t$saveTemplates = $parser->getOutput()->mTemplates;\n\t\t}\n\t\tif ( isset( $reset['categories'] ) && $reset['categories'] ) {\t// we can remove the categories by save/restore\n\t\t\t$saveCategories = $parser->getOutput()->mCategories;\n\t\t}\n\t\tif ( isset( $reset['images'] ) && $reset['images'] ) {\t// we can remove the images by save/restore\n\t\t\t$saveImages = $parser->getOutput()->mImages;\n\t\t}\n\t\t$parsedDPL = $parser->recursiveTagParse( $text );\n\t\tif ( isset( $reset['templates'] ) && $reset['templates'] ) {\n\t\t\t$parser->getOutput()->mTemplates = $saveTemplates;\n\t\t}\n\t\tif ( isset( $reset['categories'] ) && $reset['categories'] ) {\n\t\t\t$parser->getOutput()->mCategories = $saveCategories;\n\t\t}\n\t\tif ( isset( $reset['images'] ) && $reset['images'] ) {\n\t\t\t$parser->getOutput()->mImages = $saveImages;\n\t\t}\n\n\t\treturn $parsedDPL;\n\t}", "label_name": "CWE-400", "label": 2} +{"code": "\tfunction selectBillingOptions() {\n\t\t\n\t}", "label_name": "CWE-74", "label": 1} +{"code": " PMA_sendHeaderLocation($GLOBALS['cfg']['Server']['LogoutURL']);\n } else {\n PMA_sendHeaderLocation($GLOBALS['cfg']['Server']['SignonURL']);\n }\n\n if (!defined('TESTSUITE')) {\n exit();\n } else {\n return false;\n }\n }", "label_name": "CWE-200", "label": 10} +{"code": "function get_filedisplay_views() {\n expTemplate::get_filedisplay_views();\n\n $paths = array(\n BASE.'framework/modules/common/views/file/',\n BASE.'themes/'.DISPLAY_THEME.'modules/common/views/file/',\n );\n \n $views = array();\n foreach ($paths as $path) {\n if (is_readable($path)) {\n $dh = opendir($path);\n while (($file = readdir($dh)) !== false) {\n if (is_readable($path.'/'.$file) && substr($file, -4) == '.tpl' && substr($file, -14) != '.bootstrap.tpl' && substr($file, -15) != '.bootstrap3.tpl' && substr($file, -10) != '.newui.tpl') {\n $filename = substr($file, 0, -4);\n $views[$filename] = gt($filename);\n }\n }\n }\n }\n \n return $views;\n}", "label_name": "CWE-74", "label": 1} +{"code": " public function actionGetItems(){\n // We need to select the id both as 'id' and 'value' in order to correctly populate the association form.\n $sql = 'SELECT id, id as value FROM x2_services WHERE id LIKE :qterm ORDER BY id ASC';\n $command = Yii::app()->db->createCommand($sql);\n $qterm = $_GET['term'].'%';\n $command->bindParam(\":qterm\", $qterm, PDO::PARAM_STR);\n $result = $command->queryAll();\n echo CJSON::encode($result);\n exit;\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function showUnpublished() {\n expHistory::set('viewable', $this->params);\n \n // setup the where clause for looking up records.\n $where = parent::aggregateWhereClause();\n $where = \"((unpublish != 0 AND unpublish < \".time().\") OR (publish > \".time().\")) AND \".$where;\n if (isset($this->config['only_featured'])) $where .= ' AND is_featured=1';\n\n $page = new expPaginator(array(\n 'model'=>'news',\n 'where'=>$where,\n 'limit'=>25,\n 'order'=>'unpublish',\n 'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),\n 'controller'=>$this->baseclassname,\n 'action'=>$this->params['action'],\n 'src'=>$this->loc->src,\n 'columns'=>array(\n gt('Title')=>'title',\n gt('Published On')=>'publish',\n gt('Status')=>'unpublish'\n ),\n ));\n \n assign_to_template(array(\n 'page'=>$page\n ));\n }", "label_name": "CWE-74", "label": 1} +{"code": "\tfunction update_vendor() {\n\t\t$vendor = new vendor();\n\t\t\n\t\t$vendor->update($this->params['vendor']);\n expHistory::back();\n }", "label_name": "CWE-74", "label": 1} +{"code": "\t function manage_upcharge() {\n\t\t$this->loc->src = \"@globalstoresettings\";\n $config = new expConfig($this->loc);\n\t\t$this->config = $config->config;\n\n\t\t$gc = new geoCountry(); \n $countries = $gc->find('all');\n \n $gr = new geoRegion(); \n $regions = $gr->find('all',null,'rank asc,name asc');\n assign_to_template(array(\n 'countries'=>$countries,\n 'regions'=>$regions,\n 'upcharge'=>!empty($this->config['upcharge'])?$this->config['upcharge']:''\n ));\n\t }", "label_name": "CWE-74", "label": 1} +{"code": "\t\t $controller = new $ctlname();\n\t\t if (method_exists($controller,'isSearchable') && $controller->isSearchable()) {\n//\t\t\t $mods[$controller->name()] = $controller->addContentToSearch();\n $mods[$controller->searchName()] = $controller->addContentToSearch();\n\t\t }\n\t }\n\t\n\t uksort($mods,'strnatcasecmp');\n\t assign_to_template(array(\n 'mods'=>$mods\n ));\n }", "label_name": "CWE-74", "label": 1} +{"code": "\tpublic static function setupMigration( Parser &$parser ) {\n\t\t$parser->setHook( 'Intersection', [ __CLASS__, 'intersectionTag' ] );\n\t\t$parser->addTrackingCategory( 'dpl-intersection-tracking-category' );\n\n\t\tself::init();\n\n\t\treturn true;\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " function function_exists($name)\n {\n if (isset(\\yiiunit\\framework\\base\\SecurityTest::$functions[$name])) {\n return \\yiiunit\\framework\\base\\SecurityTest::$functions[$name];\n }\n\n return \\function_exists($name);\n }", "label_name": "CWE-330", "label": 12} +{"code": " public function remove()\n {\n $project = $this->getProject();\n $this->checkCSRFParam();\n $column_id = $this->request->getIntegerParam('column_id');\n\n if ($this->columnModel->remove($column_id)) {\n $this->flash->success(t('Column removed successfully.'));\n } else {\n $this->flash->failure(t('Unable to remove this column.'));\n }\n\n $this->response->redirect($this->helper->url->to('ColumnController', 'index', array('project_id' => $project['id'])));\n }", "label_name": "CWE-200", "label": 10} +{"code": " public function confirm()\n {\n $project = $this->getProject();\n $category = $this->getCategory();\n\n $this->response->html($this->helper->layout->project('category/remove', array(\n 'project' => $project,\n 'category' => $category,\n )));\n }", "label_name": "CWE-200", "label": 10} +{"code": " public function testHttpCacheIsSetAsATrustedProxy(array $existing, array $expected)\n {\n Request::setTrustedProxies($existing);\n\n $this->setNextResponse();\n $this->request('GET', '/', array('REMOTE_ADDR' => '10.0.0.1'));\n\n $this->assertEquals($expected, Request::getTrustedProxies());\n\n Request::setTrustedProxies(array());\n }", "label_name": "CWE-20", "label": 0} +{"code": " foreach ($page as $pageperm) {\r\n if (!empty($pageperm['manage'])) return true;\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " public function getItems2 (\n $prefix='', $page=0, $limit=20, $valueAttr='name', $nameAttr='name') {\n\n $modelClass = get_class ($this->owner);\n $model = CActiveRecord::model ($modelClass);\n $table = $model->tableName ();\n $offset = intval ($page) * intval ($limit);\n\n AuxLib::coerceToArray ($valueAttr);\n $modelClass::checkThrowAttrError (array_merge ($valueAttr, array ($nameAttr)));\n $params = array ();\n if ($prefix !== '') {\n $params[':prefix'] = $prefix . '%';\n }\n $offset = abs ((int) $offset);\n $limit = abs ((int) $limit);\n $command = Yii::app()->db->createCommand (\"\n SELECT \" . implode (',', $valueAttr) . \", $nameAttr as __name\n FROM $table\n WHERE \" . ($prefix === '' ? \n '1=1' : ($nameAttr . ' LIKE :prefix')\n ) . \"\n ORDER BY __name\n LIMIT $offset, $limit\n \");", "label_name": "CWE-20", "label": 0} +{"code": "\tpublic static function getStylesheet($styleName)\n\t{\n\t\t// Get custom stylesheet, of the default stylesheet if the custom stylesheet does not exist\n\t\t$stylesheet = get_option($styleName, '');\n\n\t\tif (strlen($stylesheet) <= 0)\n\t\t{\n\t\t\t$stylesheetFile = SlideshowPluginMain::getPluginPath() . DIRECTORY_SEPARATOR . 'style' . DIRECTORY_SEPARATOR . 'SlideshowPlugin' . DIRECTORY_SEPARATOR . $styleName . '.css';\n\n\t\t\tif (!file_exists($stylesheetFile))\n\t\t\t{\n\t\t\t\t$stylesheetFile = SlideshowPluginMain::getPluginPath() . DIRECTORY_SEPARATOR . 'style' . DIRECTORY_SEPARATOR . 'SlideshowPlugin' . DIRECTORY_SEPARATOR . 'style-light.css';\n\t\t\t}\n\n\t\t\t// Get contents of stylesheet\n\t\t\tob_start();\n\t\t\tinclude($stylesheetFile);\n\t\t\t$stylesheet .= ob_get_clean();\n\t\t}\n\n\t\t// Replace the URL placeholders with actual URLs and add a unique identifier to separate stylesheets\n\t\t$stylesheet = str_replace('%plugin-url%', SlideshowPluginMain::getPluginUrl(), $stylesheet);\n\t\t$stylesheet = str_replace('%site-url%', get_bloginfo('url'), $stylesheet);\n\t\t$stylesheet = str_replace('%stylesheet-url%', get_stylesheet_directory_uri(), $stylesheet);\n\t\t$stylesheet = str_replace('%template-url%', get_template_directory_uri(), $stylesheet);\n\t\t$stylesheet = str_replace('.slideshow_container', '.slideshow_container_' . $styleName, $stylesheet);\n\n\t\treturn $stylesheet;\n\t}", "label_name": "CWE-200", "label": 10} +{"code": "\tpublic function delete_version() {\n\t if (empty($this->params['id'])) {\n\t flash('error', gt('The version you are trying to delete could not be found'));\n\t }\n\t \n\t // get the version\n\t $version = new help_version($this->params['id']);\n\t if (empty($version->id)) {\n\t flash('error', gt('The version you are trying to delete could not be found'));\n\t }\n\t \n\t // if we have errors than lets get outta here!\n\t if (!expQueue::isQueueEmpty('error')) expHistory::back();\n\t \n\t // delete the version\n\t $version->delete();\n\t \n\t expSession::un_set('help-version');\n\n\t flash('message', gt('Deleted version').' '.$version->version.' '.gt('and all documents in that version.'));\n\t expHistory::back();\t \n\t}", "label_name": "CWE-74", "label": 1} +{"code": "\t\tpublic static function save_uploaded_user_avatar() {\n\t\t\t$avatar_data = wp_parse_args(\n\t\t\t\tLP_Request::get( 'lp-user-avatar-crop' ),\n\t\t\t\tarray(\n\t\t\t\t\t'name' => '',\n\t\t\t\t\t'width' => '',\n\t\t\t\t\t'height' => '',\n\t\t\t\t\t'points' => '',\n\t\t\t\t\t'nonce' => '',\n\t\t\t\t)\n\t\t\t);\n\n\t\t\t$current_user_id = get_current_user_id();\n\n\t\t\tif ( ! wp_verify_nonce( $avatar_data['nonce'], 'save-uploaded-profile-' . $current_user_id ) ) {\n\t\t\t\tdie( 'ERROR VERIFY NONCE!' );\n\t\t\t}\n\n\t\t\t$url = learn_press_update_user_profile_avatar();\n\t\t\tif ( $url ) {\n\t\t\t\t$user = learn_press_get_current_user();\n\n\t\t\t\tlearn_press_send_json(\n\t\t\t\t\tarray(\n\t\t\t\t\t\t'success' => true,\n\t\t\t\t\t\t'avatar' => sprintf( '', $url ),\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\t};\n\n\t\t\twp_die();\n\t\t}", "label_name": "CWE-610", "label": 17} +{"code": " foreach ($evs as $key=>$event) {\r\n if ($condense) {\r\n $eventid = $event->id;\r\n $multiday_event = array_filter($events, create_function('$event', 'global $eventid; return $event->id === $eventid;'));\r\n if (!empty($multiday_event)) {\r\n unset($evs[$key]);\r\n continue;\r\n }\r\n }\r\n $evs[$key]->eventstart += $edate->date;\r\n $evs[$key]->eventend += $edate->date;\r\n $evs[$key]->date_id = $edate->id;\r\n if (!empty($event->expCat)) {\r\n $catcolor = empty($event->expCat[0]->color) ? null : trim($event->expCat[0]->color);\r\n// if (substr($catcolor,0,1)=='#') $catcolor = '\" style=\"color:'.$catcolor.';';\r\n $evs[$key]->color = $catcolor;\r\n }\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " protected function getComment()\n {\n $comment = $this->commentModel->getById($this->request->getIntegerParam('comment_id'));\n\n if (empty($comment)) {\n throw new PageNotFoundException();\n }\n\n if (! $this->userSession->isAdmin() && $comment['user_id'] != $this->userSession->getId()) {\n throw new AccessForbiddenException();\n }\n\n return $comment;\n }", "label_name": "CWE-200", "label": 10} +{"code": " $this->markTestSkipped('Function openssl_random_pseudo_bytes need LibreSSL version >=2.1.5 or Windows system on server');\n }\n }\n\n static::$functions = $functions;\n\n // test various string lengths\n for ($length = 1; $length < 64; $length++) {\n $key1 = $this->security->generateRandomKey($length);\n $this->assertInternalType('string', $key1);\n $this->assertEquals($length, strlen($key1));\n $key2 = $this->security->generateRandomKey($length);\n $this->assertInternalType('string', $key2);\n $this->assertEquals($length, strlen($key2));\n if ($length >= 7) { // avoid random test failure, short strings are likely to collide\n $this->assertNotEquals($key1, $key2);\n }\n }\n\n // test for /dev/urandom, reading larger data to see if loop works properly\n $length = 1024 * 1024;\n $key1 = $this->security->generateRandomKey($length);\n $this->assertInternalType('string', $key1);\n $this->assertEquals($length, strlen($key1));\n $key2 = $this->security->generateRandomKey($length);\n $this->assertInternalType('string', $key2);\n $this->assertEquals($length, strlen($key2));\n $this->assertNotEquals($key1, $key2);\n\n // force /dev/urandom reading loop to deal with chunked data\n // the above test may have read everything in one run.\n // not sure if this can happen in real life but if it does\n // we should be prepared\n static::$fopen = fopen('php://memory', 'rwb');\n $length = 1024 * 1024;\n $key1 = $this->security->generateRandomKey($length);\n $this->assertInternalType('string', $key1);\n $this->assertEquals($length, strlen($key1));\n }", "label_name": "CWE-330", "label": 12} +{"code": "\tpublic function __construct(string $appName,\n\t\t\t\t\t\t\t\tIRequest $request,\n\t\t\t\t\t\t\t\tITimeFactory $timeFactory,\n\t\t\t\t\t\t\t\tIInitialState $initialState,\n\t\t\t\t\t\t\t\tBookingService $bookingService,\n\t\t\t\t\t\t\t\tAppointmentConfigService $appointmentConfigService,\n\t\t\t\t\t\t\t\tURLGenerator $urlGenerator,\n\t\t\t\t\t\t\t\tLoggerInterface $logger) {\n\t\tparent::__construct($appName, $request);\n\n\t\t$this->bookingService = $bookingService;\n\t\t$this->timeFactory = $timeFactory;\n\t\t$this->appointmentConfigService = $appointmentConfigService;\n\t\t$this->initialState = $initialState;\n\t\t$this->urlGenerator = $urlGenerator;\n\t\t$this->logger = $logger;\n\t}", "label_name": "CWE-77", "label": 14} +{"code": "\tpublic function goingForthAndBackStoresFormValuesOfSecondPageAndTriggersValidationOnlyWhenGoingForward() {\n\t\t$this->browser->request('http://localhost/test/form/simpleform/ThreePageFormWithValidation');\n\n\t\t$this->gotoNextFormPage($this->browser->getForm());\n\n\t\t$form = $this->browser->getForm();\n\t\t$form['--three-page-form-with-validation']['text2-1']->setValue('My Text on the second page');\n\t\t$this->gotoPreviousFormPage($form);\n\t\t$this->gotoNextFormPage($this->browser->getForm());\n\t\t$r = $this->gotoNextFormPage($this->browser->getForm());\n\n\t\t$this->assertSame(' error', $this->browser->getCrawler()->filterXPath('//*[contains(@class,\"error\")]//input[@id=\"three-page-form-with-validation-text2-1\"]')->attr('class'));\n\t\t$form = $this->browser->getForm();\n\t\t$form['--three-page-form-with-validation']['text2-1']->setValue('42');\n\t\t$this->gotoNextFormPage($form);\n\n\t\t$form = $this->browser->getForm();\n\t\t$this->assertSame('', $form['--three-page-form-with-validation']['text3-1']->getValue());\n\t}", "label_name": "CWE-20", "label": 0} +{"code": " public function activate_address()\n {\n global $db, $user;\n\n $object = new stdClass();\n $object->id = $this->params['id'];\n $db->setUniqueFlag($object, 'addresses', $this->params['is_what'], \"user_id=\" . $user->id);\n flash(\"message\", gt(\"Successfully updated address.\"));\n expHistory::back(); \n }", "label_name": "CWE-74", "label": 1} +{"code": " function addDiscountToCart() {\n// global $user, $order;\n global $order;\n //lookup discount to see if it's real and valid, and not already in our cart\n //this will change once we allow more than one coupon code\n\n $discount = new discounts();\n $discount = $discount->getCouponByName($this->params['coupon_code']);\n\n if (empty($discount)) {\n flash('error', gt(\"This discount code you entered does not exist.\"));\n //redirect_to(array('controller'=>'cart', 'action'=>'checkout')); \n expHistory::back();\n }\n\n //check to see if it's in our cart already\n if ($this->isDiscountInCart($discount->id)) {\n flash('error', gt(\"This discount code is already in your cart.\"));\n //redirect_to(array('controller'=>'cart', 'action'=>'checkout'));\n expHistory::back();\n }\n\n //this should really be reworked, as it shoudn't redirect directly and not return\n $validateDiscountMessage = $discount->validateDiscount();\n if ($validateDiscountMessage == \"\") {\n //if all good, add to cart, otherwise it will have redirected\n $od = new order_discounts();\n $od->orders_id = $order->id;\n $od->discounts_id = $discount->id;\n $od->coupon_code = $discount->coupon_code;\n $od->title = $discount->title;\n $od->body = $discount->body;\n $od->save();\n // set this to just the discount applied via this coupon?? if so, when though? $od->discount_total = ??;\n flash('message', gt(\"The discount code has been applied to your cart.\"));\n } else {\n flash('error', $validateDiscountMessage);\n }\n //redirect_to(array('controller'=>'cart', 'action'=>'checkout')); \n expHistory::back();\n }", "label_name": "CWE-20", "label": 0} +{"code": " public function __construct(\n AuthManager $auth,\n Encrypter $encrypter,\n Google2FA $google2FA,\n Repository $config,\n CacheRepository $cache,\n RecoveryTokenRepository $recoveryTokenRepository,\n UserRepositoryInterface $repository\n ) {\n parent::__construct($auth, $config);\n\n $this->google2FA = $google2FA;\n $this->cache = $cache;\n $this->repository = $repository;\n $this->encrypter = $encrypter;\n $this->recoveryTokenRepository = $recoveryTokenRepository;\n }", "label_name": "CWE-287", "label": 4} +{"code": " public function editTitle() {\n global $user;\n $file = new expFile($this->params['id']);\n if ($user->id==$file->poster || $user->isAdmin()) {\n $file->title = $this->params['newValue'];\n $file->save();\n $ar = new expAjaxReply(200, gt('Your title was updated successfully'), $file);\n } else {\n $ar = new expAjaxReply(300, gt(\"You didn't create this file, so you can't edit it.\"));\n }\n $ar->send();\n } ", "label_name": "CWE-74", "label": 1} +{"code": " public static function restoreX2WebUser () {\n if (isset (self::$_oldUserComponent)) {\n Yii::app()->setComponent ('user', self::$_oldUserComponent);\n } else {\n throw new CException ('X2WebUser component could not be restored'); \n }\n }", "label_name": "CWE-20", "label": 0} +{"code": "function barcode_print($code, $encoding=\"ANY\", $scale = 2 ,$mode = \"png\")\n{\n // DOLCHANGE LDR Add log\n dol_syslog(\"barcode.lib.php::barcode_print $code $encoding $scale $mode\");\n\n $bars=barcode_encode($code,$encoding);\n\n if (! $bars)\n {\n // DOLCHANGE LDR Return error message instead of array\n $error='Bad Value '.$code.' for encoding '.$encoding;\n dol_syslog('barcode.lib.php::barcode_print '.$error, LOG_ERR);\n return $error;\n }\n if (! $mode) $mode=\"png\";\n //if (preg_match(\"/^(text|txt|plain)$/i\",$mode)) print barcode_outtext($bars['text'],$bars['bars']);\n //elseif (preg_match(\"/^(html|htm)$/i\",$mode)) print barcode_outhtml($bars['text'],$bars['bars'], $scale,0, 0);\n //else\n barcode_outimage($bars['text'], $bars['bars'], $scale, $mode);\n return $bars;\n}", "label_name": "CWE-20", "label": 0} +{"code": " ->where('owned_by', '=', $userIdToCheck);\n });\n }", "label_name": "CWE-863", "label": 11} +{"code": " public function testRedirectLinkGeneration () {\n Yii::app()->controller = new MarketingController (\n 'campaign', new MarketingModule ('campaign', null));\n $_SERVER['SERVER_NAME'] = 'localhost';\n $cmb = $this->instantiate();\n $contact = $this->contacts('testUser_unsent');\n $campaign = $this->campaign('redirectLinkGeneration');\n $url = preg_replace ('/^[^\"]*\"([^\"]*)\".*$/', '$1', $campaign->content);\n list($subject,$message,$uniqueId) = $cmb->prepareEmail(\n $this->campaign('redirectLinkGeneration'),\n $contact,$this->listItem('testUser_unsent')->emailAddress);\n $this->assertRegExp ('/'.preg_quote (urlencode ($url)).'/', $message);\n\n }", "label_name": "CWE-20", "label": 0} +{"code": "\t\t\t$cols = explode( '}:', $label );\n\t\t\tif ( count( $cols ) <= 1 ) {\n\t\t\t\tif ( array_key_exists( $t, $_tableRow ) ) {\n\t\t\t\t\t$tableRow[$groupNr] = $_tableRow[$t];\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t$n = count( explode( ':', $cols[1] ) );\n\t\t\t\t$colNr = -1;\n\t\t\t\t$t--;\n\t\t\t\tfor ( $i = 1; $i <= $n; $i++ ) {\n\t\t\t\t\t$colNr++;\n\t\t\t\t\t$t++;\n\t\t\t\t\tif ( array_key_exists( $t, $_tableRow ) ) {\n\t\t\t\t\t\t$tableRow[$groupNr . '.' . $colNr] = $_tableRow[$t];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn $tableRow;\n\t}", "label_name": "CWE-400", "label": 2} +{"code": "\tprivate function _notlastmodifiedby( $option ) {\n\t\t$user = new \\User;\n\t\t$this->addWhere( $this->DB->addQuotes( $user->newFromName( $option )->getActorId() ) . ' != (SELECT revactor_actor FROM ' . $this->tableNames['revision_actor_temp'] . ' WHERE ' . $this->tableNames['revision_actor_temp'] . '.revactor_page=page_id ORDER BY ' . $this->tableNames['revision_actor_temp'] . '.revactor_timestamp DESC LIMIT 1)' );\n\t}", "label_name": "CWE-400", "label": 2} +{"code": " public function testESIHeaderIsKeptInSubrequest()\n {\n $expectedSubRequest = Request::create('/');\n $expectedSubRequest->headers->set('Surrogate-Capability', 'abc=\"ESI/1.0\"');\n\n if (Request::getTrustedHeaderName(Request::HEADER_CLIENT_IP)) {\n $expectedSubRequest->headers->set('x-forwarded-for', array('127.0.0.1'));\n $expectedSubRequest->server->set('HTTP_X_FORWARDED_FOR', '127.0.0.1');\n }\n\n $strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest($expectedSubRequest));\n\n $request = Request::create('/');\n $request->headers->set('Surrogate-Capability', 'abc=\"ESI/1.0\"');\n $strategy->render('/', $request);\n }", "label_name": "CWE-20", "label": 0} +{"code": "\tstatic public function getInstanceOf($_usernfo, $_tid) {\n\t\tif (!isset(self::$tickets[$_tid])) {\n\t\t\tself::$tickets[$_tid] = new ticket($_usernfo, $_tid);\n\t\t}\n\t\treturn self::$tickets[$_tid];\n\t}", "label_name": "CWE-732", "label": 13} +{"code": " function edit() {\r\n global $template;\r\n\r\n parent::edit();\r\n $allforms = array();\r\n $allforms[\"\"] = gt('Disallow Feedback');\r\n // calculate which event date is the one being edited\r\n $event_key = 0;\r\n foreach ($template->tpl->tpl_vars['record']->value->eventdate as $key=>$d) {\r\n \t if ($d->id == $this->params['date_id']) $event_key = $key;\r\n \t}\r\n\r\n assign_to_template(array(\r\n 'allforms' => array_merge($allforms, expTemplate::buildNameList(\"forms\", \"event/email\", \"tpl\", \"[!_]*\")),\r\n 'checked_date' => !empty($this->params['date_id']) ? $this->params['date_id'] : null,\r\n 'event_key' => $event_key,\r\n ));\r\n }\r", "label_name": "CWE-74", "label": 1} +{"code": " $files[$key]->save();\n }\n \n// eDebug($files,true);\n }", "label_name": "CWE-74", "label": 1} +{"code": " private function isWindows()\n {\n return DIRECTORY_SEPARATOR !== '/';\n }", "label_name": "CWE-330", "label": 12} +{"code": "mxDualRuler.prototype.setUnit=function(b){this.vRuler.setUnit(b);this.hRuler.setUnit(b)};mxDualRuler.prototype.setStyle=function(b){this.vRuler.setStyle(b);this.hRuler.setStyle(b)};mxDualRuler.prototype.destroy=function(){this.vRuler.destroy();this.hRuler.destroy();this.ui.refresh=this.editorUiRefresh;mxGuide.prototype.move=this.origGuideMove;mxGuide.prototype.destroy=this.origGuideDestroy;this.ui.getDiagramContainerOffset=this.editorUiGetDiagContOffset};function mxFreehand(b){var f=null!=b.view&&null!=b.view.canvas?b.view.canvas.ownerSVGElement:null;if(null!=b.container&&null!=f){b.addListener(mxEvent.ESCAPE,mxUtils.bind(this,function(){this.stopDrawing()}));var l=mxFreehand.prototype.NORMAL_SMOOTHING,d=null,u=[],t,D=[],c,e=!1,g=!0,k=!0,m=!0,q=!0,v=[],x=!1,A=!0,z=!1,L={size:12,thinning:.5,smoothing:.5,streamline:.5,start:{taper:0,cap:!0},end:{taper:0,cap:!0}},M=!1;this.setClosedPath=function(J){e=J};this.setAutoClose=function(J){g=J};this.setAutoInsert=", "label_name": "CWE-20", "label": 0} +{"code": " stringEscapeFn: function(c) {\n return '\\\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);\n },", "label_name": "CWE-74", "label": 1} +{"code": "D;var E=y(\".odPreview\"),J=y(\"#odFiles\");b=function(N,Q){Q=Q||document;return Q.querySelectorAll(N)}(\".odCatListTitle\");for(D=0;D 0) {\n patternedFilenameWithoutTheFilename = pattern.replace(new RegExp(path.sep+'[^'+path.sep+']*$'), '')\n .replace(/\\{z\\}/, '' + zoom);\n }\n return mkdirp(outPath + path.sep + patternedFilenameWithoutTheFilename)\n .then(()=>{\n var command = 'convert ' + inPath +\n ' -crop ' + tileSize + 'x' + tileSize +\n ' -set filename:tile \"' + patternedFilename + '\"' +\n ' -quality ' + quality + ' +repage +adjoin' +\n ' \"' + outPath + '/%[filename:tile]' + dotExtension + '\"' ;\n execSync(command);\n });\n}", "label_name": "CWE-77", "label": 14} +{"code": " current: function() {\n return this.state[this.state.computing];\n }", "label_name": "CWE-74", "label": 1} +{"code": "function(n){g.editorUiRefresh.apply(b,arguments);u()};u();var q=document.createElement(\"canvas\");q.width=m.offsetWidth;q.height=m.offsetHeight;m.style.overflow=\"hidden\";q.style.position=\"relative\";m.appendChild(q);var v=q.getContext(\"2d\");this.ui=b;var x=b.editor.graph;this.graph=x;this.container=m;this.canvas=q;var A=function(n,y,K,B,F){n=Math.round(n);y=Math.round(y);K=Math.round(K);B=Math.round(B);v.beginPath();v.moveTo(n+.5,y+.5);v.lineTo(K+.5,B+.5);v.stroke();F&&(l?(v.save(),v.translate(n,y),\nv.rotate(-Math.PI/2),v.fillText(F,0,0),v.restore()):v.fillText(F,n,y))},z=function(){v.clearRect(0,0,q.width,q.height);v.beginPath();v.lineWidth=.7;v.strokeStyle=k.strokeClr;v.setLineDash([]);v.font=\"9px Arial\";v.textAlign=\"center\";var n=x.view.scale,y=x.view.getBackgroundPageBounds(),K=x.view.translate,B=x.pageVisible;K=B?e+(l?y.y-x.container.scrollTop:y.x-x.container.scrollLeft):e+(l?K.y*n-x.container.scrollTop:K.x*n-x.container.scrollLeft);var F=0;B&&(F=x.getPageLayout(),F=l?F.y*x.pageFormat.height:", "label_name": "CWE-20", "label": 0} +{"code": "var T=document.createElement(\"tbody\"),P=(new Date).toDateString();null!=b.currentPage&&null!=b.pages&&(e=mxUtils.indexOf(b.pages,b.currentPage));for(q=f.length-1;0<=q;q--){var O=function(R){var Y=new Date(R.modifiedDate),da=null;if(0<=Y.getTime()){var ha=function(ea){v.stop();D.innerHTML=\"\";var aa=mxUtils.parseXml(ea),ua=b.editor.extractGraphModel(aa.documentElement,!0);if(null!=ua){var la=function(Fa){null!=Fa&&(Fa=Aa(Editor.parseDiagramNode(Fa)));return Fa},Aa=function(Fa){var xa=Fa.getAttribute(\"background\");", "label_name": "CWE-20", "label": 0} +{"code": "e},ConnectionPointsDialog=function(b,e){function f(){null!=m&&m.destroy()}var c=document.createElement(\"div\");c.style.userSelect=\"none\";var m=null;this.init=function(){function n(F,H){F=new mxCell(\"\",new mxGeometry(F,H,6,6),\"shape=mxgraph.basic.x;fillColor=#29b6f2;strokeColor=#29b6f2;points=[];rotatable=0;resizable=0;connectable=0;editable=0;\");F.vertex=!0;F.cp=!0;return p.addCell(F)}function v(F){F=p.getSelectionCells();p.deleteCells(F)}function d(){var F=parseInt(D.value)||0;F=0>F?0:100'+Graph.compress('')+\"\",qa(Ta,mxEvent.getClientX(Ma),mxEvent.getClientY(Ma))):(b.sidebar.currentElt=\nna,Ra=!0,ma(oa,function(Ua){Ra&&b.sidebar.currentElt==na&&qa(Ua,mxEvent.getClientX(Ma),mxEvent.getClientY(Ma));Ra=!1})))}var na=document.createElement(\"div\");na.className=\"geTemplate\";na.style.position=\"relative\";na.style.height=Ha+\"px\";na.style.width=ra+\"px\";var Ka=null,Ia=oa;Editor.isDarkMode()&&(na.style.filter=\"invert(100%)\");null!=ya?na.setAttribute(\"title\",mxResources.get(ya,null,ya)):null!=wa&&0D;D++)for(var t=D,F=0;8>F;F++)t=1==(t&1)?3988292384^t>>>1:t>>>1,Editor.crcTable[D]=t;Editor.updateCRC=function(u,J,N,W){for(var S=0;S>>8;return u};Editor.crc32=function(u){for(var J=-1,N=0;N>>8^Editor.crcTable[(J^u.charCodeAt(N))&255];return(J^-1)>>>0};Editor.writeGraphModelToPng=function(u,J,N,W,S){function P(sa,Ba){var ta=", "label_name": "CWE-20", "label": 0} +{"code": "function u(){mxShape.call(this)}function J(){mxShape.call(this)}function N(){mxRectangleShape.call(this)}function W(){mxShape.call(this)}function S(){mxShape.call(this)}function P(){mxShape.call(this)}function Z(){mxShape.call(this)}function oa(){mxShape.call(this)}function va(){mxCylinder.call(this)}function Aa(){mxCylinder.call(this)}function sa(){mxRectangleShape.call(this)}function Ba(){mxDoubleEllipse.call(this)}function ta(){mxDoubleEllipse.call(this)}function Na(){mxArrowConnector.call(this);\nthis.spacing=0}function Ca(){mxArrowConnector.call(this);this.spacing=0}function Ra(){mxActor.call(this)}function ab(){mxRectangleShape.call(this)}function Ka(){mxActor.call(this)}function bb(){mxActor.call(this)}function Pa(){mxActor.call(this)}function Za(){mxActor.call(this)}function z(){mxActor.call(this)}function L(){mxActor.call(this)}function M(){mxActor.call(this)}function T(){mxActor.call(this)}function ca(){mxActor.call(this)}function ia(){mxActor.call(this)}function ma(){mxEllipse.call(this)}", "label_name": "CWE-20", "label": 0} +{"code": "this.customFonts)))}finally{V.getModel().endUpdate()}}}));this.editorUi.showDialog(W.container,380,Editor.enableWebFonts?250:180,!0,!0);W.init()}),z,null,!0)})))}})();function DiagramPage(b,e){this.node=b;null!=e?this.node.setAttribute(\"id\",e):null==this.getId()&&this.node.setAttribute(\"id\",Editor.guid())}DiagramPage.prototype.node=null;DiagramPage.prototype.root=null;DiagramPage.prototype.viewState=null;DiagramPage.prototype.getId=function(){return this.node.getAttribute(\"id\")};DiagramPage.prototype.getName=function(){return this.node.getAttribute(\"name\")};", "label_name": "CWE-20", "label": 0} +{"code": " inputs: function(input, watchId) {\n return function(scope, value, locals, inputs) {\n if (inputs) return inputs[watchId];\n return input(scope, value, locals);\n };\n }", "label_name": "CWE-74", "label": 1} +{"code": "this.spacing=0}function Ca(){mxArrowConnector.call(this);this.spacing=0}function Ra(){mxActor.call(this)}function ab(){mxRectangleShape.call(this)}function Ka(){mxActor.call(this)}function bb(){mxActor.call(this)}function Pa(){mxActor.call(this)}function Za(){mxActor.call(this)}function z(){mxActor.call(this)}function L(){mxActor.call(this)}function M(){mxActor.call(this)}function T(){mxActor.call(this)}function ca(){mxActor.call(this)}function ia(){mxActor.call(this)}function ma(){mxEllipse.call(this)}", "label_name": "CWE-20", "label": 0} +{"code": "var CommentsWindow=function(b,e,f,c,m,n){function v(){for(var K=O.getElementsByTagName(\"div\"),F=0,H=0;Hthis.state.width?10:0)+2+\"px\",this.moveHandle.style.top=this.state.y+this.state.height+(40>this.state.height?10:0)+2+\"px\")};var K=mxVertexHandler.prototype.setHandlesVisible;mxVertexHandler.prototype.setHandlesVisible=function(H){K.apply(this,\narguments);null!=this.moveHandle&&(this.moveHandle.style.display=H?\"\":\"none\")};var F=mxVertexHandler.prototype.destroy;mxVertexHandler.prototype.destroy=function(H,S){F.apply(this,arguments);null!=this.moveHandle&&(this.moveHandle.parentNode.removeChild(this.moveHandle),this.moveHandle=null)}};if(\"undefined\"!==typeof Sidebar){var f=Sidebar.prototype.createAdvancedShapes;Sidebar.prototype.createAdvancedShapes=function(){var c=f.apply(this,arguments),m=this.graph;return c.concat([this.addEntry(\"tree container\",", "label_name": "CWE-20", "label": 0} +{"code": "this.put(\"editCell\",new Menu(mxUtils.bind(this,function(R,fa){var la=this.editorUi.editor.graph,ra=la.getSelectionCell();ka.call(this,R,ra,null,fa);this.addMenuItems(R,[\"editTooltip\"],fa);la.model.isVertex(ra)&&this.addMenuItems(R,[\"editGeometry\"],fa);this.addMenuItems(R,[\"-\",\"edit\"],fa)})));this.addPopupMenuCellEditItems=function(R,fa,la,ra){R.addSeparator();this.addSubmenu(\"editCell\",R,ra,mxResources.get(\"edit\"))};this.put(\"file\",new Menu(mxUtils.bind(this,function(R,fa){var la=O.getCurrentFile();", "label_name": "CWE-20", "label": 0} +{"code": "this.window.setLocation(q,v)});mxEvent.addListener(window,\"resize\",m);this.destroy=function(){mxEvent.removeListener(window,\"resize\",m);this.window.destroy()}},TagsWindow=function(b,f,l,d,u){var t=b.editor.graph,D=b.editor.graph.createTagsDialog(mxUtils.bind(this,function(){return this.window.isVisible()}),null,function(g,k){if(t.isEnabled()){var m=new FilenameDialog(b,\"\",mxResources.get(\"add\"),function(q){b.hideDialog();if(null!=q&&0>2);E+=\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\".charAt((N&3)<<4);E+=\"==\";break}Q=u.charCodeAt(J++);if(J==T){E+=\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\".charAt(N>>2);E+=\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\".charAt((N&", "label_name": "CWE-20", "label": 0} +{"code": "l.isRemoteFileFormat(B,d.name)?l.isOffline()?l.showError(mxResources.get(\"error\"),mxResources.get(\"notInOffline\"),null,k):l.parseFileData(B,mxUtils.bind(this,function(I){4==I.readyState&&(200<=I.status&&299>=I.status?g(I.responseText):k())}),d.name):k()}):A||k()}},function(q){k(q)}):k()});\"undefined\"!==typeof JSZip||this.loadingExtensions||this.isOffline(!0)?p():(this.loadingExtensions=!0,mxscript(\"js/extensions.min.js\",p))};EditorUi.prototype.importFile=function(d,g,k,l,p,q,x,y,A,B,I,O){B=null!=\nB?B:!0;var t=!1,z=null,L=mxUtils.bind(this,function(C){var D=null;null!=C&&\"+\";var g=e.getElementsByTagName(\"span\")[0];g.style.fontSize=\"18px\";g.style.marginRight=\"5px\";mxUtils.write(e,mxResources.get(\"moreShapes\")+\"...\");mxEvent.addListener(e,mxClient.IS_POINTER?\"pointerdown\":\"mousedown\",mxUtils.bind(this,function(k){k.preventDefault()}));mxEvent.addListener(e,\"click\",mxUtils.bind(this,\nfunction(k){this.actions.get(\"shapes\").funct();mxEvent.consume(k)}));c.appendChild(e);return c};EditorUi.prototype.handleError=function(c,e,g,k,m,q,v){var x=null!=this.spinner&&null!=this.spinner.pause?this.spinner.pause():function(){},A=null!=c&&null!=c.error?c.error:c;if(null!=c&&(\"1\"==urlParams.test||null!=c.stack)&&null!=c.message)try{v?null!=window.console&&console.error(\"EditorUi.handleError:\",c):EditorUi.logError(\"Caught: \"+(\"\"==c.message&&null!=c.name)?c.name:c.message,c.filename,c.lineNumber,", "label_name": "CWE-20", "label": 0} +{"code": " self._getForwarded = function(message) {\n\n try {\n var forwarded_message = $(message.getNode()).find('forwarded[xmlns=\"' + NS_URN_FORWARD + '\"]:first message:first');\n\n if(forwarded_message[0]) {\n return JSJaCPacket.wrapNode(forwarded_message[0]);\n }\n\n return null;\n } catch(e) {\n Console.error('Carbons._getForwarded', e);\n }\n\n };", "label_name": "CWE-20", "label": 0} +{"code": " isExpOperator: function(ch) {\n return (ch === '-' || ch === '+' || this.isNumber(ch));\n },", "label_name": "CWE-74", "label": 1} +{"code": "k&&k(x)}}),k)};EditorUi.prototype.removeDatabaseItem=function(c,e,g,k){this.openDatabase(mxUtils.bind(this,function(m){k=k||\"objects\";Array.isArray(k)||(k=[k],c=[c]);m=m.transaction(k,\"readwrite\");m.oncomplete=e;m.onerror=g;for(var q=0;qu.excludeCells.indexOf(E[T].id)&&J.push(E[T]);", "label_name": "CWE-20", "label": 0} +{"code": "ua.prototype.constraints=mxEllipse.prototype.constraints;Qa.prototype.constraints=mxEllipse.prototype.constraints;Ra.prototype.constraints=mxRectangleShape.prototype.constraints;Ta.prototype.constraints=mxRectangleShape.prototype.constraints;wa.prototype.getConstraints=function(c,l,x){c=[];var p=Math.min(l,x/2),v=Math.min(l-p,Math.max(0,parseFloat(mxUtils.getValue(this.style,\"size\",this.size)))*l);c.push(new mxConnectionConstraint(new mxPoint(0,.5),!1,null));c.push(new mxConnectionConstraint(new mxPoint(0,\n0),!1,null,v,0));c.push(new mxConnectionConstraint(new mxPoint(0,0),!1,null,.5*(v+l-p),0));c.push(new mxConnectionConstraint(new mxPoint(0,0),!1,null,l-p,0));c.push(new mxConnectionConstraint(new mxPoint(1,.5),!1,null));c.push(new mxConnectionConstraint(new mxPoint(0,0),!1,null,l-p,x));c.push(new mxConnectionConstraint(new mxPoint(0,0),!1,null,.5*(v+l-p),x));c.push(new mxConnectionConstraint(new mxPoint(0,0),!1,null,v,x));return c};va.prototype.getConstraints=function(c,l,x){l=parseFloat(mxUtils.getValue(c,", "label_name": "CWE-20", "label": 0} +{"code": "S&&S(M)}}))}catch(L){null!=S&&S(L)}}),N,sa)}catch(Pa){null!=S&&S(Pa)}};Editor.crcTable=[];for(var D=0;256>D;D++)for(var t=D,F=0;8>F;F++)t=1==(t&1)?3988292384^t>>>1:t>>>1,Editor.crcTable[D]=t;Editor.updateCRC=function(u,J,N,W){for(var S=0;S>>8;return u};Editor.crc32=function(u){for(var J=-1,N=0;N>>8^Editor.crcTable[(J^u.charCodeAt(N))&255];return(J^-1)>>>0};Editor.writeGraphModelToPng=function(u,J,N,W,S){function P(sa,Ba){var ta=", "label_name": "CWE-20", "label": 0} +{"code": " 'binary/': function(left, right, context) {\n return function(scope, locals, assign, inputs) {\n var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);\n return context ? {value: arg} : arg;\n };\n },", "label_name": "CWE-74", "label": 1} +{"code": "return P.apply(this,arguments)};mxGraphView.prototype.createEnumerationValue=function(u){u=decodeURIComponent(mxUtils.getValue(u.style,\"enumerateValue\",\"\"));\"\"==u&&(u=++this.enumerationState);return'
    '+mxUtils.htmlEntities(u)+\"
    \"};mxGraphView.prototype.redrawEnumerationState=function(u){var E=\"1\"==mxUtils.getValue(u.style,\"enumerate\",0);E&&null==u.secondLabel?(u.secondLabel=new mxText(\"\",new mxRectangle,mxConstants.ALIGN_LEFT,\nmxConstants.ALIGN_BOTTOM),u.secondLabel.size=12,u.secondLabel.state=u,u.secondLabel.dialect=mxConstants.DIALECT_STRICTHTML,this.graph.cellRenderer.initializeLabel(u,u.secondLabel)):E||null==u.secondLabel||(u.secondLabel.destroy(),u.secondLabel=null);E=u.secondLabel;if(null!=E){var J=u.view.scale,T=this.createEnumerationValue(u);u=this.graph.model.isVertex(u.cell)?new mxRectangle(u.x+u.width-4*J,u.y+4*J,0,0):mxRectangle.fromPoint(u.view.getPoint(u));E.bounds.equals(u)&&E.value==T&&E.scale==J||(E.bounds=\nu,E.value=T,E.scale=J,E.redraw())}};var K=mxGraphView.prototype.validateBackgroundPage;mxGraphView.prototype.validateBackgroundPage=function(){K.apply(this,arguments);if(mxClient.IS_GC&&null!=this.getDrawPane()){var u=this.getDrawPane().parentNode;!this.graph.mathEnabled||mxClient.NO_FO||null!=this.webKitForceRepaintNode&&null!=this.webKitForceRepaintNode.parentNode||\"svg\"!=this.graph.container.firstChild.nodeName?null==this.webKitForceRepaintNode||this.graph.mathEnabled&&(\"svg\"==this.graph.container.firstChild.nodeName||", "label_name": "CWE-20", "label": 0} +{"code": "return na}function B(){function pa(oa,na){var Ja=mxResources.get(oa);null==Ja&&(Ja=oa.substring(0,1).toUpperCase()+oa.substring(1));18=Z.scrollHeight&&", "label_name": "CWE-20", "label": 0} +{"code": "ca.src=\"/images/icon-search.svg\"};b.sidebar.hideTooltip();b.sidebar.currentElt=da;Da=!0;ca.src=\"/images/aui-wait.gif\";ha.isExt?g(ha,pa,function(){A(mxResources.get(\"cantLoadPrev\"));Da=!1;ca.src=\"/images/icon-search.svg\"}):ia(ha.url,pa)}}function t(ha,da,ca){if(null!=E){for(var la=E.className.split(\" \"),ia=0;ia=na.getStatus()?la(na.getText(),pa):ia()})):la(b.emptyDiagramXml,pa)},la=function(pa,na){y||b.hideDialog(!0);e(pa,na,qa,da)},ia=function(){A(mxResources.get(\"cannotLoad\"));ma()},ma=function(){J=qa;za.className=\"geTempDlgCreateBtn\";da&&(Ga.className=\"geTempDlgOpenBtn\")},", "label_name": "CWE-20", "label": 0} +{"code": "this.spacing=0}function Ca(){mxArrowConnector.call(this);this.spacing=0}function Ra(){mxActor.call(this)}function ab(){mxRectangleShape.call(this)}function Ka(){mxActor.call(this)}function bb(){mxActor.call(this)}function Pa(){mxActor.call(this)}function Za(){mxActor.call(this)}function z(){mxActor.call(this)}function L(){mxActor.call(this)}function M(){mxActor.call(this)}function T(){mxActor.call(this)}function ca(){mxActor.call(this)}function ia(){mxActor.call(this)}function ma(){mxEllipse.call(this)}", "label_name": "CWE-20", "label": 0} +{"code": "F.setGraphEnabled;F.setGraphEnabled=function(){sa.apply(this,arguments);null!=this.tabContainer&&(ka.style.visibility=this.tabContainer.style.visibility,this.diagramContainer.style.bottom=\"hidden\"!=this.tabContainer.style.visibility&&null==T?this.tabContainerHeight+\"px\":\"0px\")}}X.appendChild(S);X.appendChild(F.diagramContainer);K.appendChild(X);F.updateTabContainer();!EditorUi.windowed&&(\"1\"==urlParams.sketch||1E3<=c)&&\"1\"!=urlParams.embedInline&&b(this,!0);null==T&&X.appendChild(F.tabContainer);", "label_name": "CWE-20", "label": 0} +{"code": "if(null!=P&&null!=P.originalSrc)if(!G)P={src:P.originalSrc};else if(G&&null!=this.themes&&\"darkTheme\"==this.defaultThemeName){var K=this.stylesheet,F=this.shapeForegroundColor,H=this.shapeBackgroundColor;this.stylesheet=this.getDefaultStylesheet();this.shapeBackgroundColor=\"#ffffff\";this.shapeForegroundColor=\"#000000\";P=d.createImageForPageLink(P.originalSrc);this.shapeBackgroundColor=H;this.shapeForegroundColor=F;this.stylesheet=K}return P};var x=this.clearDefaultStyle;this.clearDefaultStyle=function(){x.apply(this,\narguments)};this.isOffline()||\"undefined\"===typeof window.EditDataDialog||(EditDataDialog.placeholderHelpLink=\"https://www.diagrams.net/doc/faq/predefined-placeholders\");if(/viewer\\.diagrams\\.net$/.test(window.location.hostname)||/embed\\.diagrams\\.net$/.test(window.location.hostname))this.editor.editBlankUrl=\"https://app.diagrams.net/\";var y=d.editor.getEditBlankUrl;this.editor.getEditBlankUrl=function(D){D=null!=D?D:\"\";\"1\"==urlParams.dev&&(D+=(0= 0) {\n array.splice(index, 1);\n }\n return index;\n}", "label_name": "CWE-74", "label": 1} +{"code": "this.init=function(){function G(H){if(null!=H){var S=H.getAttribute(\"background\");if(null==S||\"\"==S||S==mxConstants.NONE)S=Editor.isDarkMode()?\"transparent\":\"#ffffff\";z.style.backgroundColor=S;(new mxCodec(H.ownerDocument)).decode(H,L.getModel());L.maxFitScale=1;L.fit(8);L.center()}return H}function N(H){null!=H&&(H=G(Editor.parseDiagramNode(H)));return H}mxEvent.addListener(F,\"change\",function(H){y=parseInt(F.value);N(K[y]);mxEvent.consume(H)});if(\"mxfile\"==n.nodeName){var J=n.getElementsByTagName(\"diagram\");", "label_name": "CWE-20", "label": 0} +{"code": "null!=this.linkHint&&(this.linkHint.style.visibility=\"\")};var Za=mxEdgeHandler.prototype.destroy;mxEdgeHandler.prototype.destroy=function(){Za.apply(this,arguments);null!=this.linkHint&&(this.linkHint.parentNode.removeChild(this.linkHint),this.linkHint=null);null!=this.changeHandler&&(this.graph.getModel().removeListener(this.changeHandler),this.graph.getSelectionModel().removeListener(this.changeHandler),this.changeHandler=null)}}();(function(){function b(c,l,x){mxShape.call(this);this.line=c;this.stroke=l;this.strokewidth=null!=x?x:1;this.updateBoundsFromLine()}function e(){mxSwimlane.call(this)}function k(){mxSwimlane.call(this)}function n(){mxCylinder.call(this)}function D(){mxCylinder.call(this)}function t(){mxActor.call(this)}function F(){mxCylinder.call(this)}function d(){mxCylinder.call(this)}function f(){mxCylinder.call(this)}function g(){mxCylinder.call(this)}function m(){mxShape.call(this)}function q(){mxShape.call(this)}", "label_name": "CWE-20", "label": 0} +{"code": "EditorUi.initMinimalTheme=function(){function b(C,D){if(EditorUi.windowed){var G=C.editor.graph;G.popupMenuHandler.hideMenu();if(null==C.formatWindow){D=\"1\"==urlParams.sketch?Math.max(10,C.diagramContainer.clientWidth-241):Math.max(10,C.diagramContainer.clientWidth-248);var P=\"1\"==urlParams.winCtrls&&\"1\"==urlParams.sketch?80:60;G=\"1\"==urlParams.embedInline?580:\"1\"==urlParams.sketch?580:Math.min(566,G.container.clientHeight-10);C.formatWindow=new n(C,mxResources.get(\"format\"),D,P,240,G,function(F){var H=\nC.createFormat(F);H.init();C.addListener(\"darkModeChanged\",mxUtils.bind(this,function(){H.refresh()}));return H});C.formatWindow.window.addListener(mxEvent.SHOW,mxUtils.bind(this,function(){C.formatWindow.window.fit()}));C.formatWindow.window.minimumSize=new mxRectangle(0,0,240,80)}else C.formatWindow.window.setVisible(null!=D?D:!C.formatWindow.window.isVisible())}else{if(null==C.formatElt){C.formatElt=m();var K=C.createFormat(C.formatElt);K.init();C.formatElt.style.border=\"none\";C.formatElt.style.width=\n\"240px\";C.formatElt.style.borderLeft=\"1px solid gray\";C.formatElt.style.right=\"0px\";C.addListener(\"darkModeChanged\",mxUtils.bind(this,function(){K.refresh()}))}G=C.diagramContainer.parentNode;null!=C.formatElt.parentNode?(C.formatElt.parentNode.removeChild(C.formatElt),G.style.right=\"0px\"):(G.parentNode.appendChild(C.formatElt),G.style.right=C.formatElt.style.width)}}function e(C,D){function G(H,S){var V=C.menus.get(H);H=F.addMenu(S,mxUtils.bind(this,function(){V.funct.apply(this,arguments)}));H.style.cssText=", "label_name": "CWE-20", "label": 0} +{"code": "function snake_case(name, separator) {\n separator = separator || '_';\n return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {\n return (pos ? separator : '') + letter.toLowerCase();\n });\n}", "label_name": "CWE-74", "label": 1} +{"code": "document.createElement(\"link\");N.setAttribute(\"rel\",\"preload\");N.setAttribute(\"href\",T);N.setAttribute(\"as\",\"font\");N.setAttribute(\"crossorigin\",\"\");E.parentNode.insertBefore(N,E)}}}};Editor.trimCssUrl=function(u){return u.replace(RegExp(\"^[\\\\s\\\"']+\",\"g\"),\"\").replace(RegExp(\"[\\\\s\\\"']+$\",\"g\"),\"\")};Editor.GOOGLE_FONTS=\"https://fonts.googleapis.com/css?family=\";Editor.GUID_ALPHABET=\"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_\";Editor.GUID_LENGTH=20;Editor.guid=function(u){u=null!=", "label_name": "CWE-20", "label": 0} +{"code": "var configure = function( app, configObject ) {\n\tif( typeof configObject !== \"undefined\" ) {\n\t\tconfiguration.directory = configObject.directory || configuration.directory;\n\t\tconfiguration.extension = configObject.extension || configuration.extension;\n\t\tconfiguration.objectNotation = configObject.objectNotation || configuration.objectNotation;\n\t}\n\n\t// Register routes\n\tapp.get( \"/i18n/:locale\", i18nRoutes.i18n );\n\tapp.get( \"/i18n/:locale/:phrase\", i18nRoutes.translate );\n};", "label_name": "CWE-400", "label": 2} +{"code": "ma);H.moveCells(ma,N,W)},!0,u);u=null}else if(\"organic\"==P||\"auto\"==P&&ma.length>y.length){H.view.validate();var wa=new mxFastOrganicLayout(H);wa.forceConstant=3*fa;wa.disableEdgeStyle=!1;wa.resetEdges=!1;var Ea=wa.isVertexIgnored;wa.isVertexIgnored=function(Da){return Ea.apply(this,arguments)||0>mxUtils.indexOf(y,Da)};this.executeLayout(function(){wa.execute(H.getDefaultParent());Fa()},!0,u);u=null}}this.hideDialog()}finally{H.model.endUpdate()}null!=u&&u()}}catch(Da){this.handleError(Da)}};EditorUi.prototype.getSearch=", "label_name": "CWE-20", "label": 0} +{"code": "if(jQuery)(function(jQuery){jQuery.extend(jQuery.fn,{uploadify:function(options){jQuery(this).each(function(){settings=jQuery.extend({id:jQuery(this).attr('id'),uploader:'uploadify.swf',script:'uploadify.php',expressInstall:null,folder:'',height:30,width:110,cancelImg:'cancel.png',wmode:'opaque',scriptAccess:'sameDomain',fileDataName:'Filedata',method:'POST',queueSizeLimit:999,simUploadLimit:1,queueID:false,displayData:'percentage',onInit:function(){},onSelect:function(){},onQueueFull:function(){},onCheck:function(){},onCancel:function(){},onError:function(){},onProgress:function(){},onComplete:function(){},onAllComplete:function(){}},options);var pagePath=location.pathname;pagePath=pagePath.split('/');pagePath.pop();pagePath=pagePath.join('/')+'/';var data={};data.uploadifyID=settings.id;data.pagepath=pagePath;if(settings.buttonImg)data.buttonImg=escape(settings.buttonImg);if(settings.buttonText)data.buttonText=escape(settings.buttonText);if(settings.rollover)data.rollover=true;data.script=settings.script;data.folder=escape(settings.folder);if(settings.scriptData){var scriptDataString='';for(var name in settings.scriptData){scriptDataString+='&'+name+'='+settings.scriptData[name];}", "label_name": "CWE-20", "label": 0} +{"code": "function(){try{var O=I.width,t=I.height;if(0==O&&0==t){var z=A.result,L=z.indexOf(\",\"),C=decodeURIComponent(escape(atob(z.substring(L+1)))),D=mxUtils.parseXml(C).getElementsByTagName(\"svg\");0=x.status?q(x.responseText):this.handleError({message:mxResources.get(413==x.status?\"drawingTooLarge\":\"invalidOrMissingFile\")},mxResources.get(\"errorLoadingFile\")))}));else if(this.isLucidChartData(c))/(\\.json)$/i.test(e)&&(e=e.substring(0,e.length-5)+\".drawio\"),this.convertLucidChart(c,mxUtils.bind(this,", "label_name": "CWE-20", "label": 0} +{"code": "function(J){mxEvent.isConsumed(J)||((mxEvent.isControlDown(J)||mxClient.IS_MAC&&mxEvent.isMetaDown(J))&&13==J.keyCode?(E.click(),mxEvent.consume(J)):27==J.keyCode&&(u.click(),mxEvent.consume(J)))}));E.focus();E.className=\"geCommentEditBtn gePrimaryBtn\";X.appendChild(E);F.insertBefore(X,M);W.style.display=\"none\";M.style.display=\"none\";U.focus()}function g(K,F){F.innerHTML=\"\";K=new Date(K.modifiedDate);var H=b.timeSince(K);null==H&&(H=mxResources.get(\"lessThanAMinute\"));mxUtils.write(F,mxResources.get(\"timeAgo\",\n[H],\"{1} ago\"));F.setAttribute(\"title\",K.toLocaleDateString()+\" \"+K.toLocaleTimeString())}function k(K){var F=document.createElement(\"img\");F.className=\"geCommentBusyImg\";F.src=IMAGE_PATH+\"/spin.gif\";K.appendChild(F);K.busyImg=F}function l(K){K.style.border=\"1px solid red\";K.removeChild(K.busyImg)}function p(K){K.style.border=\"\";K.removeChild(K.busyImg)}function q(K,F,H,S,V){function M(N,Q,R){var Y=document.createElement(\"li\");Y.className=\"geCommentAction\";var ba=document.createElement(\"a\");ba.className=", "label_name": "CWE-20", "label": 0} +{"code": "y,mxUtils.bind(this,function(){var C=null;if(!n){C=parseInt(H.value);var I=parseInt(U.value);C=J.checked||C==G&&I==G?null:{from:Math.max(0,Math.min(F-1,C-1)),to:Math.max(0,Math.min(F-1,I-1))}}d.downloadFile(\"pdf\",null,null,!Q.checked,n?!0:!J.checked&&null==C,!W.checked,null!=X&&X.checked,null,null,V.checked,null!=p&&p.checked,C)}),null,mxResources.get(\"export\"));d.showDialog(y.container,300,K,!0,!0)}else d.showDialog((new PrintDialog(d,mxResources.get(\"formatPdf\"))).container,360,null!=d.pages&&1<", "label_name": "CWE-20", "label": 0} +{"code": "mxCellRenderer.prototype.destroy=function(u){D.apply(this,arguments);null!=u.secondLabel&&(u.secondLabel.destroy(),u.secondLabel=null)};mxCellRenderer.prototype.getShapesForState=function(u){return[u.shape,u.text,u.secondLabel,u.control]};var G=mxGraphView.prototype.resetValidationState;mxGraphView.prototype.resetValidationState=function(){G.apply(this,arguments);this.enumerationState=0};var P=mxGraphView.prototype.stateValidated;mxGraphView.prototype.stateValidated=function(u){null!=u.shape&&this.redrawEnumerationState(u);\nreturn P.apply(this,arguments)};mxGraphView.prototype.createEnumerationValue=function(u){u=decodeURIComponent(mxUtils.getValue(u.style,\"enumerateValue\",\"\"));\"\"==u&&(u=++this.enumerationState);return'
    '+mxUtils.htmlEntities(u)+\"
    \"};mxGraphView.prototype.redrawEnumerationState=function(u){var E=\"1\"==mxUtils.getValue(u.style,\"enumerate\",0);E&&null==u.secondLabel?(u.secondLabel=new mxText(\"\",new mxRectangle,mxConstants.ALIGN_LEFT,", "label_name": "CWE-20", "label": 0} +{"code": "var T=document.createElement(\"tbody\"),N=(new Date).toDateString();null!=b.currentPage&&null!=b.pages&&(g=mxUtils.indexOf(b.pages,b.currentPage));for(q=e.length-1;0<=q;q--){var Q=function(R){var Y=new Date(R.modifiedDate),ba=null;if(0<=Y.getTime()){var ea=function(fa){x.stop();v.innerHTML=\"\";var aa=mxUtils.parseXml(fa),va=b.editor.extractGraphModel(aa.documentElement,!0);if(null!=va){var ja=function(Ha){null!=Ha&&(Ha=Ba(Editor.parseDiagramNode(Ha)));return Ha},Ba=function(Ha){var ra=Ha.getAttribute(\"background\");\nif(null==ra||\"\"==ra||ra==mxConstants.NONE)ra=d.defaultPageBackgroundColor;n.style.backgroundColor=ra;(new mxCodec(Ha.ownerDocument)).decode(Ha,d.getModel());d.maxFitScale=1;d.fit(8);d.center();return Ha};M.style.display=\"none\";M.innerHTML=\"\";t=aa;z=fa;k=parseSelectFunction=null;l=0;if(\"mxfile\"==va.nodeName){aa=va.getElementsByTagName(\"diagram\");k=[];for(fa=0;fa 0 && !this.peek('}', ')', ';', ']'))\n body.push(this.expressionStatement());\n if (!this.expect(';')) {\n return { type: AST.Program, body: body};\n }\n }\n },", "label_name": "CWE-74", "label": 1} +{"code": "null!=u.showRemoteCursors&&(EditorUi.prototype.showRemoteCursors=u.showRemoteCursors)}};Editor.configureFontCss=function(u){if(null!=u){Editor.prototype.fontCss=u;var E=document.getElementsByTagName(\"script\")[0];if(null!=E&&null!=E.parentNode){var J=document.createElement(\"style\");J.setAttribute(\"type\",\"text/css\");J.appendChild(document.createTextNode(u));E.parentNode.insertBefore(J,E);u=u.split(\"url(\");for(J=1;JtileRec(inPath, outPath, zoom, tileSize, tempDir, pattern, zoomToDisplay, options.invertZoom, quality))\n .then(()=>rimraf(tempDir));\n};", "label_name": "CWE-77", "label": 14} +{"code": "function getBlockNodes(nodes) {\n // TODO(perf): update `nodes` instead of creating a new object?\n var node = nodes[0];\n var endNode = nodes[nodes.length - 1];\n var blockNodes;\n\n for (var i = 1; node !== endNode && (node = node.nextSibling); i++) {\n if (blockNodes || nodes[i] !== node) {\n if (!blockNodes) {\n blockNodes = jqLite(slice.call(nodes, 0, i));\n }\n blockNodes.push(node);\n }\n }\n\n return blockNodes || nodes;\n}", "label_name": "CWE-74", "label": 1} +{"code": "[H];!u(H)&&!d(H)||D(H)||x.traverse(H,!0,function(U,Q){var W=null!=Q&&x.isTreeEdge(Q);W&&0>mxUtils.indexOf(S,Q)&&S.push(Q);(null==Q||W)&&0>mxUtils.indexOf(S,U)&&S.push(U);return null==Q||W});return S};var G=mxVertexHandler.prototype.init;mxVertexHandler.prototype.init=function(){G.apply(this,arguments);(u(this.state.cell)||d(this.state.cell))&&!D(this.state.cell)&&0this.state.width?10:0)+2+\"px\",this.moveHandle.style.top=this.state.y+this.state.height+(40>this.state.height?10:0)+2+\"px\")};var J=mxVertexHandler.prototype.setHandlesVisible;mxVertexHandler.prototype.setHandlesVisible=function(H){J.apply(this,", "label_name": "CWE-20", "label": 0} +{"code": "(new mxCodec(p.ownerDocument)).decode(p)}return this.defaultStylesheet};Graph.prototype.isViewer=function(){return urlParams.viewer};var K=Graph.prototype.getSvg;Graph.prototype.getSvg=function(p,C,I,T,P,O,R,Y,da,ha,Z,ea,aa,ua){var la=null,Aa=null,Fa=null;ea||null==this.themes||\"darkTheme\"!=this.defaultThemeName||(la=this.stylesheet,Aa=this.shapeForegroundColor,Fa=this.shapeBackgroundColor,this.shapeForegroundColor=\"darkTheme\"==this.defaultThemeName?\"#000000\":Editor.lightColor,this.shapeBackgroundColor=\n\"darkTheme\"==this.defaultThemeName?\"#ffffff\":Editor.darkColor,this.stylesheet=this.getDefaultStylesheet(),this.refresh());var xa=K.apply(this,arguments),Da=this.getCustomFonts();if(Z&&0').src;mxWindow.prototype.closeImage=Graph.createSvgImage(18,10,'').src;", "label_name": "CWE-20", "label": 0} +{"code": "else{U=function(){var N=Math.max(l.container.scrollLeft,Math.min(l.container.scrollLeft+l.container.clientWidth-M.cursor.clientWidth,E)),Q=Math.max(l.container.scrollTop-22,Math.min(l.container.scrollTop+l.container.clientHeight-M.cursor.clientHeight,J));T.style.opacity=N!=E||Q!=J?0:1;M.cursor.style.left=N+\"px\";M.cursor.style.top=Q+\"px\";M.cursor.style.display=\"\"};var X=l.view.translate,u=l.view.scale,E=(X.x+M.lastCursor.x)*u+8,J=(X.y+M.lastCursor.y)*u-12,T=M.cursor.getElementsByTagName(\"img\")[0];", "label_name": "CWE-20", "label": 0} +{"code": " cp.exec = function (cmd, extra, cb) {\n if (cmd.indexOf('-a') === -1) return cb(null);\n assert.equal('git tag -a v1.0.0 -m \"Message\"', cmd);\n done();\n };", "label_name": "CWE-77", "label": 14} +{"code": "u.freehand.stopDrawing():u.freehand.startDrawing(),this.freehandWindow.window.setVisible(u.freehand.isDrawing()))})).isEnabled=function(){return t()&&mxClient.IS_SVG});d.actions.put(\"exportXml\",new Action(mxResources.get(\"formatXml\")+\"...\",function(){var n=document.createElement(\"div\");n.style.whiteSpace=\"nowrap\";var y=null==d.pages||1>=d.pages.length,K=document.createElement(\"h3\");mxUtils.write(K,mxResources.get(\"formatXml\"));K.style.cssText=\"width:100%;text-align:center;margin-top:0px;margin-bottom:4px\";", "label_name": "CWE-20", "label": 0} +{"code": "function(){return null!=q?q.readyState:3};this.getLastError=function(){return S};this.mouseListeners={startX:0,startY:0,scrollLeft:0,scrollTop:0,mouseDown:function(M,W){},mouseMove:function(M,W){var U,X=-1;return function(){clearTimeout(U);var u=this,E=arguments,J=function(){U=null;X=Date.now();M.apply(u,E)};Date.now()-X>W?J():U=setTimeout(J,W)}}(function(M,W){m(W)},200),mouseUp:function(M,W){m(W)}};l.addMouseListener(this.mouseListeners);this.shareCursorPositionListener=function(){b.isShareCursorPosition()||\nc(\"cursor\",{hide:!0})};b.addListener(\"shareCursorPositionChanged\",this.shareCursorPositionListener);this.selectionChangeListener=function(M,W){M=function(u){return null!=u?u.id:null};var U=null!=b.currentPage?b.currentPage.getId():null,X=W.getProperty(\"added\");W=W.getProperty(\"removed\");c(\"selectionChange\",{pageId:U,removed:X?X.map(M):[],added:W?W.map(M):[]})};l.getSelectionModel().addListener(mxEvent.CHANGE,this.selectionChangeListener);this.cursorHandler=mxUtils.bind(this,function(){for(var M in y)n(y[M])});", "label_name": "CWE-20", "label": 0} +{"code": "function(B){null!=this.formatWindow?this.formatWindow.window.setVisible(null!=B?B:!this.formatWindow.window.isVisible()):b(this)};DiagramFormatPanel.prototype.isMathOptionVisible=function(){return!0};var z=EditorUi.prototype.destroy;EditorUi.prototype.destroy=function(){null!=this.sidebarWindow&&(this.sidebarWindow.window.setVisible(!1),this.sidebarWindow.window.destroy(),this.sidebarWindow=null);null!=this.formatWindow&&(this.formatWindow.window.setVisible(!1),this.formatWindow.window.destroy(),", "label_name": "CWE-20", "label": 0} +{"code": "EditorUi.prototype.cellProperties={id:!0,value:!0,xmlValue:!0,vertex:!0,edge:!0,visible:!0,collapsed:!0,connectable:!0,parent:!0,children:!0,previous:!0,source:!0,target:!0,edges:!0,geometry:!0,style:!0,mxObjectId:!0,mxTransient:!0};EditorUi.prototype.codec=new mxCodec;EditorUi.prototype.applyPatches=function(b,f,l,d,u){if(null!=f)for(var t=0;tm.oldVersion&&q.createObjectStore(\"objects\",{keyPath:\"key\"});\n2>m.oldVersion&&(q.createObjectStore(\"files\",{keyPath:\"title\"}),q.createObjectStore(\"filesInfo\",{keyPath:\"title\"}),EditorUi.migrateStorageFiles=isLocalStorage)}catch(v){null!=e&&e(v)}};k.onsuccess=mxUtils.bind(this,function(m){var q=k.result;this.database=q;EditorUi.migrateStorageFiles&&(StorageFile.migrate(q),EditorUi.migrateStorageFiles=!1);\"app.diagrams.net\"!=location.host||this.drawioMigrationStarted||(this.drawioMigrationStarted=!0,this.getDatabaseItem(\".drawioMigrated3\",mxUtils.bind(this,function(v){if(!v||", "label_name": "CWE-20", "label": 0} +{"code": "La,\"geMenuItem\");null!=Ea?(La.style.backgroundImage=\"url(\"+Ea+\")\",La.style.backgroundPosition=\"center center\",La.style.backgroundRepeat=\"no-repeat\",La.style.backgroundSize=\"24px 24px\",La.style.width=\"34px\",La.innerHTML=\"\"):wa||(La.style.backgroundImage=\"url(\"+mxWindow.prototype.normalizeImage+\")\",La.style.backgroundPosition=\"right 6px center\",La.style.backgroundRepeat=\"no-repeat\",La.style.paddingRight=\"22px\");return La}function X(za,wa,Ea,Da,La,Ya){var Ua=document.createElement(\"a\");Ua.className=\n\"1\"==urlParams.sketch?\"geToolbarButton\":\"geMenuItem\";Ua.style.display=\"inline-block\";Ua.style.boxSizing=\"border-box\";Ua.style.height=\"30px\";Ua.style.padding=\"6px\";Ua.style.position=\"relative\";Ua.style.verticalAlign=\"top\";Ua.style.top=\"0px\";\"1\"==urlParams.sketch&&(Ua.style.borderStyle=\"none\",Ua.style.boxShadow=\"none\",Ua.style.padding=\"6px\",Ua.style.margin=\"0px\");null!=U.statusContainer?V.insertBefore(Ua,U.statusContainer):V.appendChild(Ua);null!=Ya?(Ua.style.backgroundImage=\"url(\"+Ya+\")\",Ua.style.backgroundPosition=\n\"center center\",Ua.style.backgroundRepeat=\"no-repeat\",Ua.style.backgroundSize=\"24px 24px\",Ua.style.width=\"34px\"):mxUtils.write(Ua,za);mxEvent.addListener(Ua,mxClient.IS_POINTER?\"pointerdown\":\"mousedown\",mxUtils.bind(this,function(eb){eb.preventDefault()}));mxEvent.addListener(Ua,\"click\",function(eb){\"disabled\"!=Ua.getAttribute(\"disabled\")&&wa(eb);mxEvent.consume(eb)});null==Ea&&(Ua.style.marginRight=\"4px\");null!=Da&&Ua.setAttribute(\"title\",Da);null!=La&&(za=function(){La.isEnabled()?(Ua.removeAttribute(\"disabled\"),\nUa.style.cursor=\"pointer\"):(Ua.setAttribute(\"disabled\",\"disabled\"),Ua.style.cursor=\"default\")},La.addListener(\"stateChanged\",za),I.addListener(\"enabledChanged\",za),za());return Ua}function ea(za,wa,Ea){Ea=document.createElement(\"div\");Ea.className=\"geMenuItem\";Ea.style.display=\"inline-block\";Ea.style.verticalAlign=\"top\";Ea.style.marginRight=\"6px\";Ea.style.padding=\"0 4px 0 4px\";Ea.style.height=\"30px\";Ea.style.position=\"relative\";Ea.style.top=\"0px\";\"1\"==urlParams.sketch&&(Ea.style.boxShadow=\"none\");", "label_name": "CWE-20", "label": 0} +{"code": "focus:function(){k.focus()}}};EditorUi.prototype.createUrlParameters=function(c,e,g,k,m,q,v){v=null!=v?v:[];k&&(\"https://viewer.diagrams.net\"==EditorUi.lightboxHost&&\"1\"!=urlParams.dev||v.push(\"lightbox=1\"),\"auto\"!=c&&v.push(\"target=\"+c),null!=e&&e!=mxConstants.NONE&&v.push(\"highlight=\"+(\"#\"==e.charAt(0)?e.substring(1):e)),null!=m&&0ea&&(ea=N.strokeWidth/2);u.setStrokeAlpha(u.state.fillAlpha);u.setStrokeColor(N.fill||\"\");u.setStrokeWidth(ea);u.setDashed(!1);this._drawToContext(J,T,N);u.setDashed(ba);u.setStrokeWidth(R);u.setStrokeColor(Q);u.setStrokeAlpha(Y)};E._drawToContext=function(J,T,N){J.begin();for(var Q=0;Q';L.setAttribute(\"title\",mxResources.get(\"showResolved\"));", "label_name": "CWE-20", "label": 0} +{"code": " lazyAssign: function(id, value) {\n var self = this;\n return function() {\n self.assign(id, value);\n };\n },", "label_name": "CWE-74", "label": 1} +{"code": "(k?\"\":Graph.xmlDeclaration+\"\\n\"+Graph.svgFileComment+\"\\n\"+Graph.svgDoctype+\"\\n\")+mxUtils.getXml(K);null!=m&&m(K);return K});e.mathEnabled&&this.editor.addMathCss(q);if(null!=m)this.embedFonts(q,mxUtils.bind(this,function(K){x?this.editor.convertImages(K,mxUtils.bind(this,function(B){y(B)})):y(K)}));else return y(q)};EditorUi.prototype.embedFonts=function(c,e){this.editor.loadFonts(mxUtils.bind(this,function(){try{null!=this.editor.resolvedFontCss&&this.editor.addFontCss(c,this.editor.resolvedFontCss),\nthis.editor.embedExtFonts(mxUtils.bind(this,function(g){try{null!=g&&this.editor.addFontCss(c,g),e(c)}catch(k){e(c)}}))}catch(g){e(c)}}))};EditorUi.prototype.exportImage=function(c,e,g,k,m,q,v,x,A,z,L,M,n){A=null!=A?A:\"png\";if(this.spinner.spin(document.body,mxResources.get(\"exporting\"))){var y=this.editor.graph.isSelectionEmpty();g=null!=g?g:y;null==this.thumbImageCache&&(this.thumbImageCache={});try{this.editor.exportToCanvas(mxUtils.bind(this,function(K){this.spinner.stop();try{this.saveCanvas(K,", "label_name": "CWE-20", "label": 0} +{"code": " static parseOpReturnToChunks(script: Buffer, allow_op_0=false, allow_op_number=false) {\n // \"\"\"Extract pushed bytes after opreturn. Returns list of bytes() objects,\n // one per push.\n let ops: PushDataOperation[];\n \n // Strict refusal of non-push opcodes; bad scripts throw OpreturnError.\"\"\"\n try {\n ops = this.getScriptOperations(script);\n } catch(e) {\n //console.log(e);\n throw Error('Script error');\n }\n\n if(ops[0].opcode !== Script.opcodes.OP_RETURN)\n throw Error('No OP_RETURN');\n let chunks: (Buffer|null)[] = [];\n ops.slice(1).forEach(opitem => {\n if(opitem.opcode > Script.opcodes.OP_16)\n throw Error(\"Non-push opcode\");\n if(opitem.opcode > Script.opcodes.OP_PUSHDATA4) {\n if(opitem.opcode === 80)\n throw Error('Non-push opcode');\n if(!allow_op_number)\n throw Error('OP_1NEGATE to OP_16 not allowed');\n if(opitem.opcode === Script.opcodes.OP_1NEGATE)\n opitem.data = Buffer.from([0x81]);\n else // OP_1 - OP_16\n opitem.data = Buffer.from([opitem.opcode - 80]);\n }\n if(opitem.opcode === Script.opcodes.OP_0 && !allow_op_0){\n throw Error('OP_0 not allowed');\n }\n chunks.push(opitem.data)\n });\n //console.log(chunks);\n return chunks\n }", "label_name": "CWE-20", "label": 0} +{"code": "function addGroup() {\n var name = $(\"#new_name\").val();\n var desc = $(\"#new_desc\").val();\n\n utils.disableAll();\n utils.showAlert(\"info\", \"\", \"Adding group...\", name);\n\n if (name.length === 0) {\n utils.showAlert(\"warning\", \"\", \"Warning\", \"Please specify a group name\");\n return;\n }\n\n $.ajax({\n url: \"scripts/pi-hole/php/groups.php\",\n method: \"post\",\n dataType: \"json\",\n data: { action: \"add_group\", name: name, desc: desc, token: token },\n success: function (response) {\n utils.enableAll();\n if (response.success) {\n utils.showAlert(\"success\", \"fas fa-plus\", \"Successfully added group\", name);\n $(\"#new_name\").val(\"\");\n $(\"#new_desc\").val(\"\");\n table.ajax.reload();\n } else {\n utils.showAlert(\"error\", \"\", \"Error while adding new group\", response.message);\n }\n },\n error: function (jqXHR, exception) {\n utils.enableAll();\n utils.showAlert(\"error\", \"\", \"Error while adding new group\", jqXHR.responseText);\n console.log(exception); // eslint-disable-line no-console\n }\n });\n}", "label_name": "CWE-862", "label": 8} +{"code": " varsPrefix: function(section) {\n return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';\n },", "label_name": "CWE-74", "label": 1} +{"code": "c,b){var e=function(h,f,l){var p=function(n){n&&(this.res=n)};p.prototype=h;p.prototype.constructor=p;h=new p(l);for(var k in f||{})l=f[k],h[k]=l.slice?l.slice():l;return h},g={res:e(c.res,b.res)};g.formatter=e(c.formatter,b.formatter,g.res);g.parser=e(c.parser,b.parser,g.res);t[a]=g};d.compile=function(a){for(var c=/\\[([^\\[\\]]*|\\[[^\\[\\]]*\\])*\\]|([A-Za-z])\\2+|\\.{3}|./g,b,e=[a];b=c.exec(a);)e[e.length]=b[0];return e};d.format=function(a,c,b){c=\"string\"===typeof c?d.compile(c):c;a=d.addMinutes(a,b?", "label_name": "CWE-400", "label": 2} +{"code": " isWhitespace: function(ch) {\n // IE treats non-breaking space as \\u00A0\n return (ch === ' ' || ch === '\\r' || ch === '\\t' ||\n ch === '\\n' || ch === '\\v' || ch === '\\u00A0');\n },", "label_name": "CWE-74", "label": 1} +{"code": "function(e){var f=e.split(\"/\");return 1=v.getStatus()){var d=JSON.parse(v.getText()),g=/\\.png$/i.test(d.name);if(/\\.v(dx|sdx?)$/i.test(d.name)||/\\.gliffy$/i.test(d.name)||/\\.pdf$/i.test(d.name)||!this.ui.useCanvasForExport&&g)this.ui.convertFile(d[\"@microsoft.graph.downloadUrl\"],d.name,null!=d.file?d.file.mimeType:null,this.extension,f,c);", "label_name": "CWE-20", "label": 0} +{"code": "document.createElement(\"div\");pa.className=\"geTempDlgNewDiagramCatItemLbl\";pa.innerHTML=qa;ma.appendChild(pa);Ca.appendChild(ma);mxEvent.addListener(ma,\"click\",function(){function Ka(){var Ra=Ia.querySelector(\".geTemplateDrawioCatLink\");null!=Ra?Ra.click():setTimeout(Ka,200)}Z=!0;var Ia=M.querySelector(\".geTemplatesList\");Ia.style.display=\"block\";Ba.style.width=\"\";Na.style.display=\"\";Na.value=\"\";ba=null;Ka()});fa.style.display=ha.length<=ca?\"none\":\"\"}function G(ha,da,ca){function la(Qa,Ya){var Ma=", "label_name": "CWE-20", "label": 0} +{"code": "q):mxscript(\"js/extensions.min.js\",q))};EditorUi.prototype.generatePlantUmlImage=function(c,e,g,k){function m(x,A,z){c1=x>>2;c2=(x&3)<<4|A>>4;c3=(A&15)<<2|z>>6;c4=z&63;r=\"\";r+=q(c1&63);r+=q(c2&63);r+=q(c3&63);return r+=q(c4&63)}function q(x){if(10>x)return String.fromCharCode(48+x);x-=10;if(26>x)return String.fromCharCode(65+x);x-=26;if(26>x)return String.fromCharCode(97+x);x-=26;return 0==x?\"-\":1==x?\"_\":\"?\"}var v=new XMLHttpRequest;v.open(\"GET\",(\"txt\"==e?PLANT_URL+\"/txt/\":\"png\"==e?PLANT_URL+\"/png/\":\nPLANT_URL+\"/svg/\")+function(x){r=\"\";for(i=0;ithis.status)if(\"txt\"==e)g(this.response);else{var A=new FileReader;A.readAsDataURL(this.response);A.onloadend=function(z){var L=new Image;L.onload=\nfunction(){try{var M=L.width,n=L.height;if(0==M&&0==n){var y=A.result,K=y.indexOf(\",\"),B=decodeURIComponent(escape(atob(y.substring(K+1)))),F=mxUtils.parseXml(B).getElementsByTagName(\"svg\");0 0 && subdomain[dot] === \".\" && subdomain.endsWith(domain);\n}", "label_name": "CWE-200", "label": 10} +{"code": "function(){return null!=q?q.readyState:3};this.getLastError=function(){return S};this.mouseListeners={startX:0,startY:0,scrollLeft:0,scrollTop:0,mouseDown:function(M,W){},mouseMove:function(M,W){var U,X=-1;return function(){clearTimeout(U);var u=this,E=arguments,J=function(){U=null;X=Date.now();M.apply(u,E)};Date.now()-X>W?J():U=setTimeout(J,W)}}(function(M,W){m(W)},200),mouseUp:function(M,W){m(W)}};l.addMouseListener(this.mouseListeners);this.shareCursorPositionListener=function(){b.isShareCursorPosition()||", "label_name": "CWE-20", "label": 0} +{"code": "function(J){k=J};this.setAutoScroll=function(J){m=J};this.setOpenFill=function(J){q=J};this.setStopClickEnabled=function(J){A=J};this.setSelectInserted=function(J){z=J};this.setSmoothing=function(J){l=J};this.setPerfectFreehandMode=function(J){M=J};this.setBrushSize=function(J){L.size=J};this.getBrushSize=function(){return L.size};var n=function(J){x=J;b.getRubberband().setEnabled(!J);b.graphHandler.setSelectEnabled(!J);b.graphHandler.setMoveEnabled(!J);b.container.style.cursor=J?\"crosshair\":\"\";b.fireEvent(new mxEventObject(\"freehandStateChanged\"))};", "label_name": "CWE-20", "label": 0} +{"code": "x[D].apply(this,arguments);null!=G&&C.push(G)}b.sidebar.showEntries(0mxUtils.indexOf(d,y)&&d.push(y);m()})}:function(){var y=document.createElement(\"div\"),A=document.createElement(\"span\");A.style.marginTop=\"6px\";mxUtils.write(A,mxResources.get(\"builtinPlugins\")+\": \");", "label_name": "CWE-20", "label": 0} +{"code": " ConversationSchema.findOneAndUpdate({ _id: cId }, { updatedAt: new Date() }, { new: false }, function (\n err,\n convo\n ) {\n if (err) return done(err)\n if (convo === null || convo === undefined) {\n return done('Invalid Conversation: ' + convo)\n }\n return done(null, convo)\n })\n },", "label_name": "CWE-662", "label": 20} +{"code": "\"-\",\"lockUnlock\",\"enterGroup\"],null,ea),O.addSeparator(),this.addSubmenu(\"layout\",O)):ka.isSelectionEmpty()&&ka.isEnabled()?(O.addSeparator(),this.addMenuItems(O,[\"editData\"],null,ea),O.addSeparator(),this.addSubmenu(\"layout\",O),this.addSubmenu(\"insert\",O),this.addMenuItems(O,[\"-\",\"exitGroup\"],null,ea)):ka.isEnabled()&&this.addMenuItems(O,[\"-\",\"lockUnlock\"],null,ea)};var H=Menus.prototype.addPopupMenuEditItems;Menus.prototype.addPopupMenuEditItems=function(O,X,ea){H.apply(this,arguments);this.editorUi.editor.graph.isSelectionEmpty()&&\nthis.addMenuItems(O,[\"copyAsImage\"],null,ea)};EditorUi.prototype.toggleFormatPanel=function(O){null!=this.formatWindow?this.formatWindow.window.setVisible(null!=O?O:!this.formatWindow.window.isVisible()):b(this)};DiagramFormatPanel.prototype.isMathOptionVisible=function(){return!0};var G=EditorUi.prototype.destroy;EditorUi.prototype.destroy=function(){null!=this.sidebarWindow&&(this.sidebarWindow.window.setVisible(!1),this.sidebarWindow.window.destroy(),this.sidebarWindow=null);null!=this.formatWindow&&", "label_name": "CWE-20", "label": 0} +{"code": "arguments):(this.addOp(this.lineOp,O,R),this.lastX=O,this.lastY=R)};p.prototype.moveTo=function(O,R){this.passThrough?this.originalMoveTo.apply(this.canvas,arguments):(this.addOp(this.moveOp,O,R),this.lastX=O,this.lastY=R,this.firstX=O,this.firstY=R)};p.prototype.close=function(){this.passThrough?this.originalClose.apply(this.canvas,arguments):this.addOp(this.closeOp)};p.prototype.quadTo=function(O,R,Y,da){this.passThrough?this.originalQuadTo.apply(this.canvas,arguments):(this.addOp(this.quadOp,O,\nR,Y,da),this.lastX=Y,this.lastY=da)};p.prototype.curveTo=function(O,R,Y,da,ha,Z){this.passThrough?this.originalCurveTo.apply(this.canvas,arguments):(this.addOp(this.curveOp,O,R,Y,da,ha,Z),this.lastX=ha,this.lastY=Z)};p.prototype.arcTo=function(O,R,Y,da,ha,Z,ea){if(this.passThrough)this.originalArcTo.apply(this.canvas,arguments);else{var aa=mxUtils.arcToCurves(this.lastX,this.lastY,O,R,Y,da,ha,Z,ea);if(null!=aa)for(var ua=0;ua=x?2:6W?J():U=setTimeout(J,W)}}(function(M,W){m(W)},200),mouseUp:function(M,W){m(W)}};l.addMouseListener(this.mouseListeners);this.shareCursorPositionListener=function(){b.isShareCursorPosition()||", "label_name": "CWE-20", "label": 0} +{"code": "(W.removeAttribute(\"disabled\"),W.checked=!m.pageVisible):(W.setAttribute(\"disabled\",\"disabled\"),W.checked=!1)};L=200;var D=1,G=null;if(c.pdfPageExport&&!t){var P=function(){V.value=Math.max(1,Math.min(D,Math.max(parseInt(V.value),parseInt(H.value))));H.value=Math.max(1,Math.min(D,Math.min(parseInt(V.value),parseInt(H.value))))},K=c.addRadiobox(z,\"pages\",mxResources.get(\"allPages\"),!0),F=c.addRadiobox(z,\"pages\",mxResources.get(\"pages\")+\":\",!1,null,!0),H=document.createElement(\"input\");H.style.cssText=", "label_name": "CWE-20", "label": 0} +{"code": "module.exports = function correctMkdir (path, cb) {\n cb = dezalgo(cb)\n cb = inflight('correctMkdir:' + path, cb)\n if (!cb) {\n return log.silly('correctMkdir', path, 'correctMkdir already in flight; waiting')\n } else {\n log.silly('correctMkdir', path, 'correctMkdir not in flight; initializing')\n }\n var stats = {}\n\n if (stats[path]) return cb(null, stats[path])\n\n fs.stat(path, function (er, st) {\n if (er) return makeDirectory(path, stats, cb)\n\n if (!st.isDirectory()) {\n log.error('correctMkdir', 'invalid dir %s', path)\n return cb(er)\n }\n\n var ownerStats = calculateOwner()\n // there's always a chance the permissions could have been frobbed, so fix\n if (st.uid !== ownerStats.uid) {\n stats[path] = ownerStats\n setPermissions(path, ownerStats, cb)\n } else {\n stats[path] = st\n cb(null, stats[path])\n }\n })\n}", "label_name": "CWE-732", "label": 13} +{"code": " isNumber: function(ch) {\n return ('0' <= ch && ch <= '9') && typeof ch === 'string';\n },", "label_name": "CWE-74", "label": 1} +{"code": "exports.quote = function (xs) {\n return xs.map(function (s) {\n if (s && typeof s === 'object') {\n return s.op.replace(/(.)/g, '\\\\$1');\n }\n else if (/[\"\\s]/.test(s) && !/'/.test(s)) {\n return \"'\" + s.replace(/(['\\\\])/g, '\\\\$1') + \"'\";\n }\n else if (/[\"'\\s]/.test(s)) {\n return '\"' + s.replace(/([\"\\\\$`!])/g, '\\\\$1') + '\"';\n }\n else {\n return String(s).replace(/([A-z]:)?([#!\"$&'()*,:;<=>?@\\[\\\\\\]^`{|}])/g, '$1\\\\$2');\n }\n }).join(' ');\n};", "label_name": "CWE-77", "label": 14} +{"code": "1E3<=D&&null!=this.sidebarWindow&&\"1\"!=urlParams.sketch&&this.sidebarWindow.window.setVisible(!0);null!=this.formatWindow&&(1E3<=D||\"1\"==urlParams.sketch)&&this.formatWindow.window.setVisible(!0)}else null!=this.sidebarWindow&&this.sidebarWindow.window.setVisible(!1),null!=this.formatWindow&&this.formatWindow.window.setVisible(!1)};EditorUi.prototype.chromelessWindowResize=function(){};var O=DiagramFormatPanel.prototype.addView;DiagramFormatPanel.prototype.addView=function(C){C=O.apply(this,arguments);\nvar D=this.editorUi,G=D.editor.graph;if(G.isEnabled()&&\"1\"==urlParams.sketch){var P=this.createOption(mxResources.get(\"sketch\"),function(){return Editor.sketchMode},function(K,F){D.setSketchMode(!Editor.sketchMode);null!=F&&mxEvent.isShiftDown(F)||G.updateCellStyles({sketch:K?\"1\":null},G.getVerticesAndEdges())},{install:function(K){this.listener=function(){K(Editor.sketchMode)};D.addListener(\"sketchModeChanged\",this.listener)},destroy:function(){D.removeListener(this.listener)}});C.appendChild(P)}return C};", "label_name": "CWE-20", "label": 0} +{"code": "function(k){this.actions.get(\"shapes\").funct();mxEvent.consume(k)}));c.appendChild(e);return c};EditorUi.prototype.handleError=function(c,e,g,k,m,q,v){var x=null!=this.spinner&&null!=this.spinner.pause?this.spinner.pause():function(){},A=null!=c&&null!=c.error?c.error:c;if(null!=c&&(\"1\"==urlParams.test||null!=c.stack)&&null!=c.message)try{v?null!=window.console&&console.error(\"EditorUi.handleError:\",c):EditorUi.logError(\"Caught: \"+(\"\"==c.message&&null!=c.name)?c.name:c.message,c.filename,c.lineNumber,", "label_name": "CWE-20", "label": 0} +{"code": "function pa(){mxEllipse.call(this)}function ua(){mxEllipse.call(this)}function ya(){mxRhombus.call(this)}function Fa(){mxEllipse.call(this)}function Ma(){mxEllipse.call(this)}function Oa(){mxEllipse.call(this)}function Qa(){mxEllipse.call(this)}function Ta(){mxActor.call(this)}function za(){mxActor.call(this)}function wa(){mxActor.call(this)}function Ea(c,l,x,p){mxShape.call(this);this.bounds=c;this.fill=l;this.stroke=x;this.strokewidth=null!=p?p:1;this.rectStyle=\"square\";this.size=10;this.absoluteCornerSize=", "label_name": "CWE-20", "label": 0} +{"code": "ta.style.width=\"40px\";ta.style.height=\"12px\";ta.style.marginBottom=\"-2px\";ta.style.backgroundImage=\"url(\"+mxWindow.prototype.normalizeImage+\")\";ta.style.backgroundPosition=\"top center\";ta.style.backgroundRepeat=\"no-repeat\";ta.setAttribute(\"title\",\"Minimize\");var Na=!1,Ca=mxUtils.bind(this,function(){S.innerHTML=\"\";if(!Na){var za=function(Da,La,Ya){Da=X(\"\",Da.funct,null,La,Da,Ya);Da.style.width=\"40px\";Da.style.opacity=\"0.7\";return wa(Da,null,\"pointer\")},wa=function(Da,La,Ya){null!=La&&Da.setAttribute(\"title\",", "label_name": "CWE-20", "label": 0} +{"code": "q):mxscript(\"js/extensions.min.js\",q))};EditorUi.prototype.generatePlantUmlImage=function(d,g,k,l){function p(y,A,B){c1=y>>2;c2=(y&3)<<4|A>>4;c3=(A&15)<<2|B>>6;c4=B&63;r=\"\";r+=q(c1&63);r+=q(c2&63);r+=q(c3&63);return r+=q(c4&63)}function q(y){if(10>y)return String.fromCharCode(48+y);y-=10;if(26>y)return String.fromCharCode(65+y);y-=26;if(26>y)return String.fromCharCode(97+y);y-=26;return 0==y?\"-\":1==y?\"_\":\"?\"}var x=new XMLHttpRequest;x.open(\"GET\",(\"txt\"==g?PLANT_URL+\"/txt/\":\"png\"==g?PLANT_URL+\"/png/\":\nPLANT_URL+\"/svg/\")+function(y){r=\"\";for(i=0;ithis.status)if(\"txt\"==g)k(this.response);else{var A=new FileReader;A.readAsDataURL(this.response);A.onloadend=function(B){var I=new Image;I.onload=\nfunction(){try{var O=I.width,t=I.height;if(0==O&&0==t){var z=A.result,L=z.indexOf(\",\"),C=decodeURIComponent(escape(atob(z.substring(L+1)))),D=mxUtils.parseXml(C).getElementsByTagName(\"svg\");0D;D++)for(var t=D,F=0;8>F;F++)t=1==(t&1)?3988292384^t>>>1:t>>>1,Editor.crcTable[D]=t;Editor.updateCRC=function(u,J,N,W){for(var S=0;S>>8;return u};Editor.crc32=function(u){for(var J=-1,N=0;N>>8^Editor.crcTable[(J^u.charCodeAt(N))&255];return(J^-1)>>>0};Editor.writeGraphModelToPng=function(u,J,N,W,S){function P(sa,Ba){var ta=\nva;va+=Ba;return sa.substring(ta,va)}function Z(sa){sa=P(sa,4);return sa.charCodeAt(3)+(sa.charCodeAt(2)<<8)+(sa.charCodeAt(1)<<16)+(sa.charCodeAt(0)<<24)}function oa(sa){return String.fromCharCode(sa>>24&255,sa>>16&255,sa>>8&255,sa&255)}u=u.substring(u.indexOf(\",\")+1);u=window.atob?atob(u):Base64.decode(u,!0);var va=0;if(P(u,8)!=String.fromCharCode(137)+\"PNG\"+String.fromCharCode(13,10,26,10))null!=S&&S();else if(P(u,4),\"IHDR\"!=P(u,4))null!=S&&S();else{P(u,17);S=u.substring(0,va);do{var Aa=Z(u);if(\"IDAT\"==", "label_name": "CWE-20", "label": 0} +{"code": "$.fn.hideWidget = function() {\n $(this).each(function() {\n var widget = $(this);\n\n // slice of the \"x2widget_\" from the id to get widget name\n var widgetName = $(this).attr('id').slice(9); \n\n // console.log ('widgetName = ' + widgetName);\n $.post(yii.scriptUrl+'/site/hideWidget', {name: widgetName}, function(response) {\n widget.slideUp(function() {\n widget.remove();\n if (widgetName === 'RecordViewChart') removeChartWidget ();\n $('#x2-hidden-widgets-menu').replaceWith(response);\n // $('.x2-widget-menu-item').draggable({revert: 'invalid', helper:'clone', revertDuration:200, appendTo:'#x2-hidden-widgets-menu',iframeFix:true});\n $('.x2-hidden-widgets-menu-item').click(function() {\n return handleWidgetMenuItemClick($(this));\n });\n $('.x2-hidden-widgets-menu-item.widget-right').click(function() {\n return handleWidgetRightMenuItemClick($(this));\n });\n });\n });\n });\n};", "label_name": "CWE-20", "label": 0} +{"code": "function forEachSorted(obj, iterator, context) {\n var keys = Object.keys(obj).sort();\n for (var i = 0; i < keys.length; i++) {\n iterator.call(context, obj[keys[i]], keys[i]);\n }\n return keys;\n}", "label_name": "CWE-74", "label": 1} +{"code": "u,E.value=T,E.scale=J,E.redraw())}};var K=mxGraphView.prototype.validateBackgroundPage;mxGraphView.prototype.validateBackgroundPage=function(){K.apply(this,arguments);if(mxClient.IS_GC&&null!=this.getDrawPane()){var u=this.getDrawPane().parentNode;!this.graph.mathEnabled||mxClient.NO_FO||null!=this.webKitForceRepaintNode&&null!=this.webKitForceRepaintNode.parentNode||\"svg\"!=this.graph.container.firstChild.nodeName?null==this.webKitForceRepaintNode||this.graph.mathEnabled&&(\"svg\"==this.graph.container.firstChild.nodeName||\nthis.graph.container.firstChild==this.webKitForceRepaintNode)||(null!=this.webKitForceRepaintNode.parentNode&&this.webKitForceRepaintNode.parentNode.removeChild(this.webKitForceRepaintNode),this.webKitForceRepaintNode=null):(this.webKitForceRepaintNode=document.createElement(\"div\"),this.webKitForceRepaintNode.style.cssText=\"position:absolute;\",u.ownerSVGElement.parentNode.insertBefore(this.webKitForceRepaintNode,u.ownerSVGElement))}};var F=Graph.prototype.refresh;Graph.prototype.refresh=function(){F.apply(this,", "label_name": "CWE-20", "label": 0} +{"code": "c.style.width=\"300px\";c.style.display=\"inline-flex\";c.style.justifyContent=\"center\";c.style.alignItems=\"center\";c.style.position=\"absolute\";var e=document.createElement(\"img\");e.onload=function(){function B(){k.model.setStyle(v,x+u())}k=new Graph(g);k.autoExtend=!1;k.autoScroll=!1;k.setGridEnabled(!1);k.setEnabled(!0);k.setPanning(!1);k.setConnectable(!1);k.getRubberband().setEnabled(!1);k.graphHandler.allowLivePreview=!1;var F=k.createVertexHandler;k.createVertexHandler=function(){var I=F.apply(this,\narguments);I.livePreview=!1;return I};if(null!=l)try{if(\"inset\"==l.substring(0,5)){var G=v.geometry,N=e.width,J=e.height,E=(300-N)/2,H=(300-J)/2,S=l.match(/\\(([^)]+)\\)/)[1].split(/[ ,]+/),U=parseFloat(S[0]),Q=parseFloat(S[1]),W=parseFloat(S[2]),V=parseFloat(S[3]);isFinite(U)&&isFinite(Q)&&isFinite(W)&&isFinite(V)?(G.x=V/100*N+E,G.y=U/100*J+H,G.width=(100-Q)/100*N+E-G.x,G.height=(100-W)/100*J+H-G.y,\"round\"==S[4]?\"50%\"==S[5]?L.setAttribute(\"checked\",\"checked\"):(q=parseInt(S[5]),n.value=q,z.setAttribute(\"checked\",\n\"checked\"),M.style.visibility=\"visible\"):A.setAttribute(\"checked\",\"checked\")):l=null}else l=null}catch(I){}v.style=x+(l?l:u());v.vertex=!0;k.addCell(v,null,null,null,null);k.selectAll();k.addListener(mxEvent.CELLS_MOVED,B);k.addListener(mxEvent.CELLS_RESIZED,B);var X=k.graphHandler.mouseUp,p=k.graphHandler.mouseDown;k.graphHandler.mouseUp=function(){X.apply(this,arguments);g.style.backgroundColor=\"#fff9\"};k.graphHandler.mouseDown=function(){p.apply(this,arguments);g.style.backgroundColor=\"\"};k.dblClick=\nfunction(){};var C=k.getSelectionModel().changeSelection;k.getSelectionModel().changeSelection=function(){C.call(this,[v],[v])}};e.onerror=function(){e.onload=null;e.src=Editor.errorImage};e.setAttribute(\"src\",f);e.style.maxWidth=\"300px\";e.style.maxHeight=\"300px\";c.appendChild(e);D.appendChild(c);var g=document.createElement(\"div\");g.style.width=\"300px\";g.style.height=\"300px\";g.style.overflow=\"hidden\";g.style.backgroundColor=\"#fff9\";D.appendChild(g);var k=null,m=new mxGeometry(100,100,100,100),q=", "label_name": "CWE-20", "label": 0} +{"code": "H+K));var S=(G.x-F)/P*100;P=100-(G.x+G.width-F)/P*100;F=(G.y-H)/K*100;G=100-(G.y+G.height-H)/K*100;return\"inset(\"+mxUtils.format(F)+\"% \"+mxUtils.format(P)+\"% \"+mxUtils.format(G)+\"% \"+mxUtils.format(S)+\"%\"+(C?\" round \"+q+\"%\":D?\" round 50%\":\"\")+\")\"}function n(C){null!=l&&(!0!==C&&(l.model.setGeometry(x,p.clone()),q=5,t.value=q),l.model.setStyle(x,y+m()),l.selectAll(),O.style.visibility=B.checked?\"visible\":\"hidden\")}var v=document.createElement(\"div\"),d=document.createElement(\"div\");d.style.height=\"300px\";", "label_name": "CWE-20", "label": 0} +{"code": "N||null!=T.pageId&&T.pageId==N){U();for(N=0;N {\n initError = err;\n debugLog(\"failed !\", err.message);\n });\n\n transport.on(\"message\", (messageChunk) => {\n // console.log(\"message \", messageChunk);\n done(new Error(\"Not expecting an message\"));\n });\n transport.on(\"close\", (err) => {\n debugLog(\"close\", err);\n if (initError) {\n initError.message.should.match(/BadConnectionRejected/);\n }\n done();\n });\n fakeSocket.client.write(altered_helloMessage);\n }", "label_name": "CWE-400", "label": 2} +{"code": "null);mxEvent.consume(ca)})))}if(null!=L)for(M=0;M=L.status?e(L.responseText):g())}),c.name):g()}):A||g()}},function(q){g(q)}):g()});\"undefined\"!==typeof JSZip||this.loadingExtensions||this.isOffline(!0)?m():(this.loadingExtensions=!0,mxscript(\"js/extensions.min.js\",m))};EditorUi.prototype.importFile=function(c,e,g,k,m,q,v,x,A,z,L,M){z=null!=\nz?z:!0;var n=!1,y=null,K=mxUtils.bind(this,function(B){var F=null;null!=B&&\"l;)v.shift()},N=", "label_name": "CWE-20", "label": 0} +{"code": "this.spacing=0}function Ca(){mxArrowConnector.call(this);this.spacing=0}function Ra(){mxActor.call(this)}function ab(){mxRectangleShape.call(this)}function Ka(){mxActor.call(this)}function bb(){mxActor.call(this)}function Pa(){mxActor.call(this)}function Za(){mxActor.call(this)}function z(){mxActor.call(this)}function L(){mxActor.call(this)}function M(){mxActor.call(this)}function T(){mxActor.call(this)}function ca(){mxActor.call(this)}function ia(){mxActor.call(this)}function ma(){mxEllipse.call(this)}", "label_name": "CWE-20", "label": 0} +{"code": "A||\"snip\"==B||\"default\"==B&&\"snip\"==A?c.lineTo(p-K,ha+.5*K):(\"invRound\"==B||\"default\"==B&&\"invRound\"==A||\"fold\"==B||\"default\"==B&&\"fold\"==A)&&c.lineTo(p-K,ha+K):c.lineTo(p,K)};Ea.prototype.moveNWInner=function(c,l,x,p,v,A,B,ha,K,xa,na){xa||na?!xa&&na?c.moveTo(K,0):xa&&!na?c.moveTo(0,K):\"square\"==B||\"default\"==B&&\"square\"==A?c.moveTo(K,K):\"rounded\"==B||\"default\"==B&&\"rounded\"==A||\"snip\"==B||\"default\"==B&&\"snip\"==A?c.moveTo(K,ha+.5*K):(\"invRound\"==B||\"default\"==B&&\"invRound\"==A||\"fold\"==B||\"default\"==\nB&&\"fold\"==A)&&c.moveTo(K,ha+K):c.moveTo(0,0)};Ea.prototype.lineNWInner=function(c,l,x,p,v,A,B,ha,K,xa,na){xa||na?!xa&&na?c.lineTo(K,0):xa&&!na?c.lineTo(0,K):\"square\"==B||\"default\"==B&&\"square\"==A?c.lineTo(K,K):\"rounded\"==B||\"default\"==B&&\"rounded\"==A||\"snip\"==B||\"default\"==B&&\"snip\"==A?c.lineTo(K,ha+.5*K):(\"invRound\"==B||\"default\"==B&&\"invRound\"==A||\"fold\"==B||\"default\"==B&&\"fold\"==A)&&c.lineTo(K,ha+K):c.lineTo(0,0)};Ea.prototype.paintFolds=function(c,l,x,p,v,A,B,ha,K,xa,na,$a,ib,db,Ga){if(\"fold\"==", "label_name": "CWE-20", "label": 0} +{"code": "e.appendChild(g);this.container=e},NewDialog=function(b,e,f,c,m,n,v,d,g,k,l,p,q,x,y,A,B,I){function O(oa){null!=oa&&(Ha=ra=oa?135:140);oa=!0;if(null!=La)for(;HmxUtils.indexOf(d,m)&&null!=urlParams[m]&&(f+=g+m+\"=\"+urlParams[m],g=\"&\")}else f=window.location.search;return f};EditorUi.prototype.getUrl=function(d){d=null!=d?d:window.location.pathname;var f=0 '+mxUtils.htmlEntities(mxResources.get(\"loading\"))+\"...
    \";x=b.canReplyToReplies();b.commentsSupported()?b.getComments(function(H){function S(U){if(null!=U){U.sort(function(W,V){return new Date(W.modifiedDate)-\nnew Date(V.modifiedDate)});for(var Q=0;Q';c=null!=c?\"&fetch=\"+encodeURIComponent(c):\"\";M(e,'