mcanoglu/cwe-class-group huggingface dataset:
protected function fixupImportedAttributes($modelName, X2Model &$model) {
        if ($modelName === 'Contacts' || $modelName === 'X2Leads')
            $this->fixupImportedContactName ($model);

        if ($modelName === 'Actions' && isset($model->associationType))
            $this->reconstructImportedActionAssoc($model);

        if ($model->hasAttribute('visibility')) {
            // Nobody every remembers to set visibility... set it for them
            if(empty($model->visibility) && ($model->visibility !== 0 && $model->visibility !== "0")
                    || $model->visibility == 'Public') {
                $model->visibility = 1;
            } elseif($model->visibility == 'Private')
                $model->visibility = 0;
        }
        // If date fields were provided, do not create new values for them
        if (!empty($model->createDate) || !empty($model->lastUpdated) ||
                !empty($model->lastActivity)) {
            $now = time();
            if (empty($model->createDate))
                $model->createDate = $now;
            if (empty($model->lastUpdated))
                $model->lastUpdated = $now;
            if ($model->hasAttribute('lastActivity') && empty($model->lastActivity))
                $model->lastActivity = $now;
        }
        if($_SESSION['leadRouting'] == 1){
            $assignee = $this->getNextAssignee();
            if($assignee == "Anyone")
                $assignee = "";
            $model->assignedTo = $assignee;
        }
        // Loop through our override and set the manual data
        foreach($_SESSION['override'] as $attr => $val){
            $model->$attr = $val;
        }
    }

// Vulnerability class: CWE-20
public static function returnChildrenAsJSON() {
        global $db;

        //$nav = section::levelTemplate(intval($_REQUEST['id'], 0));
        $id         = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;
        $nav        = $db->selectObjects('section', 'parent=' . $id, 'rank');
        //FIXME $manage_all is moot w/ cascading perms now?
        $manage_all = false;
        if (expPermissions::check('manage', expCore::makeLocation('navigation', '', $id))) {
            $manage_all = true;
        }
        //FIXME recode to use foreach $key=>$value
        $navcount = count($nav);
        for ($i = 0; $i < $navcount; $i++) {
            if ($manage_all || expPermissions::check('manage', expCore::makeLocation('navigation', '', $nav[$i]->id))) {
                $nav[$i]->manage = 1;
                $view = true;
            } else {
                $nav[$i]->manage = 0;
                $view = $nav[$i]->public ? true : expPermissions::check('view', expCore::makeLocation('navigation', '', $nav[$i]->id));
            }
            $nav[$i]->link = expCore::makeLink(array('section' => $nav[$i]->id), '', $nav[$i]->sef_name);
            if (!$view) unset($nav[$i]);
        }
        $nav= array_values($nav);
//        $nav[$navcount - 1]->last = true;
        if (count($nav)) $nav[count($nav) - 1]->last = true;
//        echo expJavascript::ajaxReply(201, '', $nav);
        $ar = new expAjaxReply(201, '', $nav);
        $ar->send();
    }

// Vulnerability class: CWE-74
public function formatItem( Article $article, $pageText = null ) {
		$item = '';

		if ( $pageText !== null ) {
			//Include parsed/processed wiki markup content after each item before the closing tag.
			$item .= $pageText;
		}

		$item = $this->getItemStart() . $item . $this->getItemEnd();

		$item = $this->replaceTagParameters( $item, $article );

		return $item;
	}

// Vulnerability class: CWE-400
$module_views[$key]['name'] = gt($value['name']);
    }

    // look for a config form for this module's current view    
//    $controller->loc->mod = expModules::getControllerClassName($controller->loc->mod);
    //check to see if hcview was passed along, indicating a hard-coded module
//    if (!empty($controller->params['hcview'])) {
//        $viewname = $controller->params['hcview'];
//    } else {
//        $viewname = $db->selectValue('container', 'view', "internal='".serialize($controller->loc)."'");
//    }
//    $viewconfig = $viewname.'.config';
//    foreach ($modpaths as $path) {
//        if (file_exists($path.'/'.$viewconfig)) {
//            $fileparts = explode('_', $viewname);
//            if ($fileparts[0]=='show'||$fileparts[0]=='showall') array_shift($fileparts);
//            $module_views[$viewname]['name'] = ucwords(implode(' ', $fileparts)).' '.gt('View Configuration');
//            $module_views[$viewname]['file'] =$path.'/'.$viewconfig;
//        }
//    }
    
    // sort the views highest to lowest by filename
    // we are reverse sorting now so our array merge
    // will overwrite property..we will run array_reverse
    // when we're finished to get them back in the right order
    krsort($common_views);
    krsort($module_views);

    if (!empty($moduleconfig)) $common_views = array_merge($common_views, $moduleconfig);
    $views = array_merge($common_views, $module_views);
    $views = array_reverse($views);

    return $views;
}

// Vulnerability class: CWE-74
$result  = $search->getSearchResults($item->query, false, true);
			if(empty($result) && !in_array($item->query, $badSearchArr)) {
				$badSearchArr[] = $item->query;
				$badSearch[$ctr2]['query'] = $item->query;
				$badSearch[$ctr2]['count'] = $db->countObjects("search_queries", "query='{$item->query}'");
				$ctr2++;
			}
			
		}
	
		//Check if the user choose from the dropdown
		if(!empty($user_default)) {
			if($user_default == $anonymous) {
				$u_id = 0;
			} else {
				$u_id = $user_default;
			}
			$where .= "user_id = {$u_id}";
		}
	
		//Get all the search query records
		$records = $db->selectObjects('search_queries', $where);
        for ($i = 0, $iMax = count($records); $i < $iMax; $i++) {
			if(!empty($records[$i]->user_id)) {
				$u = user::getUserById($records[$i]->user_id);
				$records[$i]->user = $u->firstname . ' ' . $u->lastname;
			}
		}
		
        $page = new expPaginator(array(
            'records' => $records,
            'where'=>1,
            'model'=>'search_queries',
            'limit'=>(isset($this->config['limit']) && $this->config['limit'] != '') ? 10 : $this->config['limit'],
            'order'=>empty($this->config['order']) ? 'timestamp' : $this->config['order'],
            'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),
            'controller'=>$this->baseclassname,
            'action'=>$this->params['action'],
            'columns'=>array(
                'ID'=>'id',
                gt('Query')=>'query',
                gt('Timestamp')=>'timestamp',
                gt('User')=>'user_id',
            ),
        ));

        $uname['id'] = implode($uname['id'],',');
        $uname['name'] = implode($uname['name'],',');
        assign_to_template(array(
            'page'=>$page,
            'users'=>$uname,
            'user_default' => $user_default,
            'badSearch' => $badSearch
        ));
		
	}

// Vulnerability class: CWE-74
static function validUTF($string) {
		if(!mb_check_encoding($string, 'UTF-8') OR !($string === mb_convert_encoding(mb_convert_encoding($string, 'UTF-32', 'UTF-8' ), 'UTF-8', 'UTF-32'))) {
			return false;
		}		
		return true;
	}

// Vulnerability class: CWE-74
public function onKernelResponse(ResponseEvent $event)
    {
        if (!$event->isMainRequest()) {
            return;
        }

        $request = $event->getRequest();

        if (!$request->hasSession() || !$request->attributes->get('_security_firewall_run', false)) {
            return;
        }

        if ($this->dispatcher) {
            $this->dispatcher->removeListener(KernelEvents::RESPONSE, [$this, 'onKernelResponse']);
        }
        $this->registered = false;
        $session = $request->getSession();
        $sessionId = $session->getId();
        $usageIndexValue = $session instanceof Session ? $usageIndexReference = &$session->getUsageIndex() : null;
        $token = $this->tokenStorage->getToken();

        if (null === $token || $this->trustResolver->isAnonymous($token)) {
            if ($request->hasPreviousSession()) {
                $session->remove($this->sessionKey);
            }
        } else {
            $session->set($this->sessionKey, serialize($token));

            if (null !== $this->logger) {
                $this->logger->debug('Stored the security token in the session.', ['key' => $this->sessionKey]);
            }
        }

        if ($this->sessionTrackerEnabler && $session->getId() === $sessionId) {
            $usageIndexReference = $usageIndexValue;
        }
    }

// Vulnerability class: CWE-287
private function _categoriesminmax( $option ) {
		if ( is_numeric( $option[0] ) ) {
			$this->addWhere( intval( $option[0] ) . ' <= (SELECT count(*) FROM ' . $this->tableNames['categorylinks'] . ' WHERE ' . $this->tableNames['categorylinks'] . '.cl_from=page_id)' );
		}
		if ( is_numeric( $option[1] ) ) {
			$this->addWhere( intval( $option[1] ) . ' >= (SELECT count(*) FROM ' . $this->tableNames['categorylinks'] . ' WHERE ' . $this->tableNames['categorylinks'] . '.cl_from=page_id)' );
		}
	}

// Vulnerability class: CWE-400
public static function parseAndTrimImport($str, $isHTML = false) { //�Death from above�? �
        //echo "1<br>"; eDebug($str);
//        global $db;

        $str = str_replace("�", "&rsquo;", $str);
        $str = str_replace("�", "&lsquo;", $str);
        $str = str_replace("�", "&#174;", $str);
        $str = str_replace("�", "-", $str);
        $str = str_replace("�", "&#151;", $str);
        $str = str_replace("�", "&rdquo;", $str);
        $str = str_replace("�", "&ldquo;", $str);
        $str = str_replace("\r\n", " ", $str);
        $str = str_replace("\,", ",", $str);
        $str = str_replace('""', '"', $str); //do this no matter what...in case someone added a quote in a non HTML field
        if (!$isHTML) {
            //if HTML, then leave the single quotes alone, otheriwse replace w/ special Char            
            $str = str_replace('"', "&quot;", $str);
        }
        $str = str_replace("�", "&#188;", $str);
        $str = str_replace("�", "&#189;", $str);
        $str = str_replace("�", "&#190;", $str);
        //$str = htmlspecialchars($str);
        //$str = utf8_encode($str);
//        if (DB_ENGINE=='mysqli') {
//	        $str = @mysqli_real_escape_string($db->connection,trim(str_replace("�", "&trade;", $str)));
//        } elseif(DB_ENGINE=='mysql') {
//            $str = @mysql_real_escape_string(trim(str_replace("�", "&trade;", $str)),$db->connection);
//        } else {
//	        $str = trim(str_replace("�", "&trade;", $str));
//        }
        $str = @expString::escape(trim(str_replace("�", "&trade;", $str)));
        //echo "2<br>"; eDebug($str,die);
        return $str;
    }

// Vulnerability class: CWE-74
public function testUserCredentials($email, $password, $server, $port, $security) {
        require_once(realpath(Yii::app()->basePath.'/components/phpMailer/class.phpmailer.php'));
        require_once(realpath(Yii::app()->basePath.'/components/phpMailer/class.smtp.php'));
        $phpMail = new PHPMailer(true);

        $phpMail->isSMTP();
        $phpMail->SMTPAuth = true;
        $phpMail->Username = $email;
        $phpMail->Password = $password;
        $phpMail->Host = $server;
        $phpMail->Port = $port;
        $phpMail->SMTPSecure = $security;

        try {
            $validCredentials = $phpMail->SmtpConnect();
        } catch(phpmailerException $error) {
            $validCredentials = false;
        }
        return $validCredentials;
    }

// Vulnerability class: CWE-20
protected function markCompleted($endStatus, ServiceResponse $serviceResponse, $gatewayMessage)
    {
        parent::markCompleted($endStatus, $serviceResponse, $gatewayMessage);
        $this->createMessage(Message\VoidedResponse::class, $gatewayMessage);

        ErrorHandling::safeExtend($this->payment, 'onVoid', $serviceResponse);
    }

// Vulnerability class: CWE-436
public function delete_version() {
	    if (empty($this->params['id'])) {
	        flash('error', gt('The version you are trying to delete could not be found'));
	    }
	    
	    // get the version
	    $version = new help_version($this->params['id']);
	    if (empty($version->id)) {
	        flash('error', gt('The version you are trying to delete could not be found'));
	    }
	    
	    // if we have errors than lets get outta here!
	    if (!expQueue::isQueueEmpty('error')) expHistory::back();
	    
	    // delete the version
	    $version->delete();
	    
	    expSession::un_set('help-version');

	    flash('message', gt('Deleted version').' '.$version->version.' '.gt('and all documents in that version.'));
	    expHistory::back();	    
	}

// Vulnerability class: CWE-74
private function __pullEvent($eventId, &$successes, &$fails, $eventModel, $server, $user, $jobId)
    {
        $event = $eventModel->downloadEventFromServer(
                $eventId,
                $server
        );
        if (!empty($event)) {
            if ($this->__checkIfEventIsBlockedBeforePull($event)) {
                return false;
            }
            $event = $this->__updatePulledEventBeforeInsert($event, $server, $user);
            if (!$this->__checkIfEventSaveAble($event)) {
                $fails[$eventId] = __('Empty event detected.');
            } else {
                $this->__checkIfPulledEventExistsAndAddOrUpdate($event, $eventId, $successes, $fails, $eventModel, $server, $user, $jobId);
            }
        } else {
            // error
            $fails[$eventId] = __('failed downloading the event') . ': ' . json_encode($event);
        }
        return true;
    }

// Vulnerability class: CWE-269
function showByModel() {
        global $order, $template, $db;

        expHistory::set('viewable', $this->params);
        $product = new product();
        $model = $product->find("first", 'model="' . $this->params['model'] . '"');
        //eDebug($model);
        $product_type = new $model->product_type($model->id);
        //eDebug($product_type);
        $tpl = $product_type->getForm('show');
        if (!empty($tpl)) $template = new controllertemplate($this, $tpl);
        //eDebug($template);
        $this->grabConfig(); // grab the global config
        assign_to_template(array(
            'config'        => $this->config,
            'product'       => $product_type,
            'last_category' => $order->lastcat
        ));
    }

// Vulnerability class: CWE-20
function edit_externalalias() {
        $section = isset($this->params['id']) ? $this->section->find($this->params['id']) : new section($this->params);
        if ($section->parent == -1) {
            notfoundController::handle_not_found();
            exit;
        } // doesn't work for standalone pages
        if (empty($section->id)) {
            $section->public = 1;
            if (!isset($section->parent)) {
                // This is another precaution.  The parent attribute
                // should ALWAYS be set by the caller.
                //FJD - if that's the case, then we should die.
                notfoundController::handle_not_authorized();
                exit;
                //$section->parent = 0;
            }
        }
        assign_to_template(array(
            'section' => $section,
            'glyphs' => self::get_glyphs(),
        ));
    }

// Vulnerability class: CWE-74
private function checkResponse ($string) {
    if (substr($string, 0, 3) !== '+OK') {
      $this->error = array(
        'error' => "Server reported an error: $string",
        'errno' => 0,
        'errstr' => ''
      );

      if ($this->do_debug >= 1) {
        $this->displayErrors();
      }

      return false;
    } else {
      return true;
    }

  }

// Vulnerability class: CWE-20
public function approve_toggle() {
	    if (empty($this->params['id'])) return;
        
        /* The global constants can be overriden by passing appropriate params */ 
        //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet
//        $require_login = empty($this->params['require_login']) ? COMMENTS_REQUIRE_LOGIN : $this->params['require_login'];
//        $require_approval = empty($this->params['require_approval']) ? COMMENTS_REQUIRE_APPROVAL : $this->params['require_approval'];
//        $require_notification = empty($this->params['require_notification']) ? COMMENTS_REQUIRE_NOTIFICATION : $this->params['require_notification'];
//        $notification_email = empty($this->params['notification_email']) ? COMMENTS_NOTIFICATION_EMAIL : $this->params['notification_email'];

	    $comment = new expComment($this->params['id']);
	    $comment->approved = $comment->approved == 1 ? 0 : 1;
	    if ($comment->approved) {
		    $this->sendApprovalNotification($comment,$this->params);
	    }
	    $comment->save();
	    expHistory::back();
	}

// Vulnerability class: CWE-74
private function _minrevisions( $option ) {
		$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})" );
	}

// Vulnerability class: CWE-400
private function getFullOutput( $totalResults = false, $skipHeaderFooter = true ) {
		if ( !$skipHeaderFooter ) {
			$header = '';
			$footer = '';
			//Only override header and footers if specified.
			$_headerType = $this->getHeaderFooterType( 'header', $totalResults );
			if ( $_headerType !== false ) {
				$header = $this->parameters->getParameter( $_headerType );
			}
			$_footerType = $this->getHeaderFooterType( 'footer', $totalResults );
			if ( $_footerType !== false ) {
				$footer = $this->parameters->getParameter( $_footerType );
			}

			$this->setHeader( $header );
			$this->setFooter( $footer );
		}

		if ( !$totalResults && !strlen( $this->getHeader() ) && !strlen( $this->getFooter() ) ) {
			$this->logger->addMessage( \DynamicPageListHooks::WARN_NORESULTS );
		}
		$messages = $this->logger->getMessages( false );

		return ( count( $messages ) ? implode( "<br/>\n", $messages ) : null ) . $this->getHeader() . $this->getOutput() . $this->getFooter();
	}

// Vulnerability class: CWE-400
$ds = self::connectToServer($replicate["host"], $replicate["port"],
                                        $ldap_method['rootdn'],
                                        Toolbox::decrypt($ldap_method['rootdn_passwd'], GLPIKEY),
                                        $ldap_method['use_tls'], $ldap_method['deref_option']);

            // Test with login and password of the user
            if (!$ds
                && !empty($login)) {
               $ds = self::connectToServer($replicate["host"], $replicate["port"], $login,
                                           $password, $ldap_method['use_tls'],
                                           $ldap_method['deref_option']);
            }
            if ($ds) {
               return $ds;
            }
         }
      }

// Vulnerability class: CWE-327
function invalidTestController($port) {
  $host = php_uname('n');

  $filename = __DIR__.'/request-doesnotexist.dat';
  $file = fopen($filename, 'rb');
  $req_dat = fread($file, filesize($filename));
  fclose($file);

  // Repeat the data three times, to make it invalid. This particular bytestream
  // (and ones like it -- repeat 3 times!) in particular used to tickle a
  // use-after-free in the FastCGI support.
  $req_dat = $req_dat . $req_dat . $req_dat;

  $sock = fsockopen($host, $port);
  fwrite($sock, $req_dat);
  fclose($sock);

  // Should still be able to recover and respond to a request over the port on a
  // new TCP connection.
  echo request($host, $port, 'hello.php');
  echo "\n";
}

// Vulnerability class: CWE-668
public static function getTemplateHierarchyFlat($parent, $depth = 1) {
        global $db;

        $arr  = array();
        $kids = $db->selectObjects('section_template', 'parent=' . $parent, 'rank');
//		$kids = expSorter::sort(array('array'=>$kids,'sortby'=>'rank', 'order'=>'ASC'));
        for ($i = 0, $iMax = count($kids); $i < $iMax; $i++) {
            $page        = $kids[$i];
            $page->depth = $depth;
            $page->first = ($i == 0 ? 1 : 0);
            $page->last  = ($i == count($kids) - 1 ? 1 : 0);
            $arr[]       = $page;
            $arr         = array_merge($arr, self::getTemplateHierarchyFlat($page->id, $depth + 1));
        }
        return $arr;
    }

// Vulnerability class: CWE-74
public function admin_delete($id = null)
    {
        if (!$this->request->is('post') && !$this->request->is('delete')) {
            throw new MethodNotAllowedException(__('Action not allowed, post or delete request expected.'));
        }
        if (!$this->_isAdmin()) {
            throw new Exception('Administrators only.');
        }
        $this->User->id = $id;
        $conditions = array('User.id' => $id);
        if (!$this->_isSiteAdmin()) {
            $conditions['org_id'] = $this->Auth->user('org_id');
        }
        $user = $this->User->find('first', array(
                'conditions' => $conditions,
                'recursive' => -1
        ));
        if (empty($user)) {
            throw new NotFoundException(__('Invalid user'));
        }
        $fieldsDescrStr = 'User (' . $id . '): ' . $user['User']['email'];
        if ($this->User->delete($id)) {
            $this->__extralog("delete", $fieldsDescrStr, '');
            if ($this->_isRest()) {
                return $this->RestResponse->saveSuccessResponse('User', 'admin_delete', $id, $this->response->type(), 'User deleted.');
            } else {
                $this->Flash->success(__('User deleted'));
                $this->redirect(array('action' => 'index'));
            }
        }
        $this->Flash->error(__('User was not deleted'));
        $this->redirect(array('action' => 'index'));
    }

// Vulnerability class: CWE-269
public function manage_versions() {
	    expHistory::set('manageable', $this->params);
	    
	    $hv = new help_version();
	    $current_version = $hv->find('first', 'is_current=1');
	    
	    $sql  = 'SELECT hv.*, COUNT(h.title) AS num_docs FROM '.DB_TABLE_PREFIX.'_help h ';
	    $sql .= 'RIGHT JOIN '.DB_TABLE_PREFIX.'_help_version hv ON h.help_version_id=hv.id GROUP BY hv.version';

	    $page = new expPaginator(array(
            'sql'=>$sql,
            'limit'=>30,
            'order'      => (isset($this->params['order']) ? $this->params['order'] : 'version'),
            'dir'        => (isset($this->params['dir']) ? $this->params['dir'] : 'DESC'),
            'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),
            'controller'=>$this->baseclassname,
            'action'=>$this->params['action'],
            'src'=>$this->loc->src,
            'columns'=>array(
                gt('Version')=>'version',
                gt('Title')=>'title',
                gt('Current')=>'is_current',
                gt('# of Docs')=>'num_docs'
            ),
        ));
	    
	    assign_to_template(array(
            'current_version'=>$current_version,
            'page'=>$page
        ));
	}

// Vulnerability class: CWE-74
function twig_array_filter(Environment $env, $array, $arrow)
{
    if (!twig_test_iterable($array)) {
        throw new RuntimeError(sprintf('The "filter" filter expects an array or "Traversable", got "%s".', \is_object($array) ? \get_class($array) : \gettype($array)));
    }

    if (!$arrow instanceof Closure && $env->hasExtension('\Twig\Extension\SandboxExtension') && $env->getExtension('\Twig\Extension\SandboxExtension')->isSandboxed()) {
        throw new RuntimeError('The callable passed to "filter" filter must be a Closure in sandbox mode.');
    }

    if (\is_array($array)) {
        return array_filter($array, $arrow, \ARRAY_FILTER_USE_BOTH);
    }

    // the IteratorIterator wrapping is needed as some internal PHP classes are \Traversable but do not implement \Iterator
    return new \CallbackFilterIterator(new \IteratorIterator($array), $arrow);
}

// Vulnerability class: CWE-74
private function _lastrevisionbefore( $option ) {
		$this->addTable( 'revision_actor_temp', 'rev' );
		$this->addSelect( [ 'rev.revactor_rev', 'rev.revactor_timestamp' ] );
		// tell the query optimizer not to look at rows that the following subquery will filter out anyway
		$this->addWhere(
			[
				$this->tableNames['page'] . '.page_id = rev.revactor_page',
				'rev.revactor_timestamp < ' . $this->convertTimestamp( $option )
			]
		);
		$this->addWhere(
			[
				$this->tableNames['page'] . '.page_id = rev.revactor_page',
				'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 ) . ')'
			]
		);
	}

// Vulnerability class: CWE-400
public function store(CreateAppointmentCalendarRequest $request)
    {
 
        $client_id = null;
        $user = User::where('external_id', $request->user)->first();

        if ($request->client_external_id) {
            $client_id = Client::where('external_id', $request->client_external_id)->first()->id;
            if (!$client_id) {
                return response(__("Client not found"), 422);
            }
        }

        $request_type = null;
        $request_id = null;
        if ($request->source_type && $request->source_external_id) {
            $request_type = $request->source_type;

            $entry = $request_type::whereExternalId($request->source_external_id);
            $request_id = $entry->id;
        }

        if (!$user) {
            return response(__("User not found"), 422);
        }

        $startTime = str_replace(["am", "pm", ' '], "", $request->start_time) . ':00';
        $endTime = str_replace(["am", "pm", ' '], "", $request->end_time) . ':00';

     

        $appointment = Appointment::create([
            'external_id' => Uuid::uuid4()->toString(),
            'source_type' => $request_type,
            'source_id' => $request_id,
            'client_id' => $client_id,
            'title' => $request->title,
            'start_at' => Carbon::parse($request->start_date . " " . $startTime),
            'end_at' => Carbon::parse($request->end_date . " " . $endTime),
            'user_id' => $user->id,
            'color' => $request->color
        ]);
        $appointment->user_external_id = $user->external_id;
        $appointment->start_at = $appointment->start_at;

        return response($appointment);
    }

// Vulnerability class: CWE-862
static function convertXMLFeedSafeChar($str) {
		$str = str_replace("<br>","",$str);
        $str = str_replace("</br>","",$str);
        $str = str_replace("<br/>","",$str);
        $str = str_replace("<br />","",$str);
        $str = str_replace("&quot;",'"',$str);
        $str = str_replace("&#39;","'",$str);
        $str = str_replace("&rsquo;","'",$str);
        $str = str_replace("&lsquo;","'",$str);        
        $str = str_replace("&#174;","",$str);
        $str = str_replace("�","-", $str);
        $str = str_replace("�","-", $str); 
        $str = str_replace("�", '"', $str);
        $str = str_replace("&rdquo;",'"', $str);
        $str = str_replace("�", '"', $str);
        $str = str_replace("&ldquo;",'"', $str);
        $str = str_replace("\r\n"," ",$str); 
        $str = str_replace("�"," 1/4",$str);
        $str = str_replace("&#188;"," 1/4", $str);
        $str = str_replace("�"," 1/2",$str);
        $str = str_replace("&#189;"," 1/2",$str);
        $str = str_replace("�"," 3/4",$str);
        $str = str_replace("&#190;"," 3/4",$str);
        $str = str_replace("�", "(TM)", $str);
        $str = str_replace("&trade;","(TM)", $str);
        $str = str_replace("&reg;","(R)", $str);
        $str = str_replace("�","(R)",$str);        
        $str = str_replace("&","&amp;",$str);      
		$str = str_replace(">","&gt;",$str);      		
        return trim($str);
	}

// Vulnerability class: CWE-74
private static function _aesEncrypt($data, $secret)
    {
        if (!is_string($data)) {
            throw new \InvalidArgumentException('Input parameter "$data" must be a string.');
        }

        if (!function_exists("openssl_encrypt")) {
            throw new \SimpleSAML_Error_Exception('The openssl PHP module is not loaded.');
        }

        $raw    = defined('OPENSSL_RAW_DATA') ? OPENSSL_RAW_DATA : true;
        $key    = openssl_digest($secret, 'sha256');
        $method = 'AES-256-CBC';
        $ivSize = 16;
        $iv     = substr($key, 0, $ivSize);

        return $iv.openssl_encrypt($data, $method, $key, $raw, $iv);
    }

// Vulnerability class: CWE-326
public function disable()
    {
        $this->checkCSRFParam();
        $project = $this->getProject();
        $swimlane_id = $this->request->getIntegerParam('swimlane_id');

        if ($this->swimlaneModel->disable($project['id'], $swimlane_id)) {
            $this->flash->success(t('Swimlane updated successfully.'));
        } else {
            $this->flash->failure(t('Unable to update this swimlane.'));
        }

        $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));
    }

// Vulnerability class: CWE-200
public function logout()
    {
        if ($this->Session->check('Auth.User')) {
            $this->__extralog("logout");
        }
        $this->Flash->info(__('Good-Bye'));
        $user = $this->User->find('first', array(
            'conditions' => array(
                'User.id' => $this->Auth->user('id')
            ),
            'recursive' => -1
        ));
        unset($user['User']['password']);
        $user['User']['action'] = 'logout';
        $this->User->save($user['User'], true, array('id'));
        $this->redirect($this->Auth->logout());
    }

// Vulnerability class: CWE-269
public function downloadfile() {
        if (empty($this->params['fileid'])) {
            flash('error', gt('There was an error while trying to download your file.  No File Specified.'));
            expHistory::back();
        }
        
        $fd = new filedownload($this->params['fileid']); 
        if (empty($this->params['filenum'])) $this->params['filenum'] = 0;

        if (empty($fd->expFile['downloadable'][$this->params['filenum']]->id)) {
            flash('error', gt('There was an error while trying to download your file.  The file you were looking for could not be found.'));
            expHistory::back();
        }        
        
        $fd->downloads++;
        $fd->save();
        
        // this will set the id to the id of the actual file..makes the download go right.
        $this->params['id'] = $fd->expFile['downloadable'][$this->params['filenum']]->id;
        parent::downloadfile();        
    }

// Vulnerability class: CWE-74
$db->updateObject($value, 'section');
                }
                $db->updateObject($moveSec, 'section');
                //handle re-ranking of previous parent
                $oldSiblings = $db->selectObjects("section", "parent=" . $oldParent . " AND rank>" . $oldRank . " ORDER BY rank");
                $rerank      = 1;
                foreach ($oldSiblings as $value) {
                    if ($value->id != $moveSec->id) {
                        $value->rank = $rerank;
                        $db->updateObject($value, 'section');
                        $rerank++;
                    }
                }
                if ($oldParent != $moveSec->parent) {
                    //we need to re-rank the children of the parent that the moving section has just left
                    $childOfLastMove = $db->selectObjects("section", "parent=" . $oldParent . " ORDER BY rank");
                    for ($i = 0, $iMax = count($childOfLastMove); $i < $iMax; $i++) {
                        $childOfLastMove[$i]->rank = $i;
                        $db->updateObject($childOfLastMove[$i], 'section');
                    }
                }
            }
        }
        self::checkForSectionalAdmins($move);
        expSession::clearAllUsersSessionCache('navigation');
    }

// Vulnerability class: CWE-74
function captureAuthorization() {
        //eDebug($this->params,true);
        $order = new order($this->params['id']);
        /*eDebug($this->params); 
        //eDebug($order,true);*/
        //eDebug($order,true);
        //$billing = new billing();

        //eDebug($billing, true);
        //$billing->calculator = new $calcname($order->billingmethod[0]->billingcalculator_id);
        $calc         = $order->billingmethod[0]->billingcalculator->calculator;
        $calc->config = $order->billingmethod[0]->billingcalculator->config;

        //$calc = new $calc-
        //eDebug($calc,true);
        if (!method_exists($calc, 'delayed_capture')) {
            flash('error', gt('The Billing Calculator does not support delayed capture'));
            expHistory::back();
        }

        $result = $calc->delayed_capture($order->billingmethod[0], $this->params['capture_amt'], $order);

        if (empty($result->errorCode)) {
            flash('message', gt('The authorized payment was successfully captured'));
            expHistory::back();

        } else {
            flash('error', gt('An error was encountered while capturing the authorized payment.') . '<br /><br />' . $result->message);
            expHistory::back();
        }
    }

// Vulnerability class: CWE-74
public function bind($dn = null, $password = null)
    {
        /* Fetch current bind credentials. */
        if (empty($dn)) {
            $dn = $this->_config['binddn'];
        }
        if (empty($password)) {
            $password = $this->_config['bindpw'];
        }

        /* Connect first, if we haven't so far.  This will also bind
         * us to the server. */
        if (!$this->_link) {
            /* Store old credentials so we can revert them later, then
             * overwrite config with new bind credentials. */
            $olddn = $this->_config['binddn'];
            $oldpw = $this->_config['bindpw'];

            /* Overwrite bind credentials in config so
             * _connect() knows about them. */
            $this->_config['binddn'] = $dn;
            $this->_config['bindpw'] = $password;

            /* Try to connect with provided credentials. */
            $msg = $this->_connect();

            /* Reset to previous config. */
            $this->_config['binddn'] = $olddn;
            $this->_config['bindpw'] = $oldpw;
            return;
        }

        /* Do the requested bind as we are asked to bind manually. */
        if (empty($dn)) {
            /* Anonymous bind. */
            $msg = @ldap_bind($this->_link);
        } else {
            /* Privileged bind. */
            $msg = @ldap_bind($this->_link, $dn, $password);
        }
        if (!$msg) {
            throw new Horde_Ldap_Exception('Bind failed: ' . @ldap_error($this->_link),
                                           @ldap_errno($this->_link));
        }
    }

// Vulnerability class: CWE-287
private function runCallback() {
        foreach ($this->records as &$record) {
            if (isset($record->ref_type)) {
                $refType = $record->ref_type;
                if (class_exists($record->ref_type)) {
                    $type = new $refType();
                    $classinfo = new ReflectionClass($type);
                    if ($classinfo->hasMethod('paginationCallback')) {
                        $item = new $type($record->original_id);
                        $item->paginationCallback($record);
                    }
                }
            }
        }    
    }

// Vulnerability class: CWE-74
function BadAuthDigestTestController($serverPort) {
  $args = array('Authorization' => 'Digest "username="admin", ' .
    'realm="Restricted area", nonce="564a12f5c065e", ' .
    'uri="/test_auth_digest.php", cnonce="MjIyMTg2", nc=00000001, ' .
    'qop="auth", response="6dfbea52fbf13016476c1879e6436004", ' .
    'opaque="cdce8a5c95a1427d74df7acbf41c9ce0"');
  var_dump(request(php_uname('n'), $serverPort, "test_auth_digest.php",
                  [], [], $args));
}

// Vulnerability class: CWE-668
function update_option_master() {        
        global $db;

        $id = empty($this->params['id']) ? null : $this->params['id'];
        $opt = new option_master($id);
        $oldtitle = $opt->title;
        
        $opt->update($this->params);
        
        // if the title of the master changed we should update the option groups that are already using it.
        if ($oldtitle != $opt->title) {
            
        }$db->sql('UPDATE '.$db->prefix.'option SET title="'.$opt->title.'" WHERE option_master_id='.$opt->id);
        
        expHistory::back();
    }

// Vulnerability class: CWE-74
public function settings_save() {
        AuthUser::load();
        if (!AuthUser::isLoggedIn()) {
            redirect(get_url('login'));
        } else if (!AuthUser::hasPermission('admin_edit')) {
            Flash::set('error', __('You do not have permission to access the requested page!'));
            redirect(get_url());
        }
        
        if (!isset($_POST['settings'])) {
            Flash::set('error', 'File Manager - ' . __('form was not posted.'));
            redirect(get_url('plugin/file_manager/settings'));
        } else {
            $settings = $_POST['settings'];

            if ($settings['umask'] == 0)
                $settings['umask'] = 0;
            elseif (!preg_match('/^0?[0-7]{3}$/', $settings['umask']))
                $settings['umask'] = 0;
            if (strlen($settings['umask']) === 3)
                $settings['umask'] = '0' . $settings['umask'];
            elseif (strlen($settings['umask']) !== 4 && $settings['umask'] != 0)
                $settings['umask'] = 0;

            if (!preg_match('/^0?[0-7]{3}$/', $settings['dirmode']))
                $settings['dirmode'] = '0755';
            if (strlen($settings['dirmode']) === 3)
                $settings['dirmode'] = '0' . $settings['dirmode'];

            if (!preg_match('/^0?[0-7]{3}$/', $settings['filemode']))
                $settings['filemode'] = '0755';
            if (strlen($settings['filemode']) === 3)
                $settings['filemode'] = '0' . $settings['filemode'];
        }

        if (Plugin::setAllSettings($settings, 'file_manager'))
            Flash::setNow('success', 'File Manager - ' . __('plugin settings saved.'));
        else
            Flash::setNow('error', 'File Manager - ' . __('plugin settings not saved!'));

        $this->display('file_manager/views/settings', array('settings' => $settings));
    }

// Vulnerability class: CWE-20
protected function renderImageByImagick($code)
    {
        $backColor = $this->transparent ? new \ImagickPixel('transparent') : new \ImagickPixel('#' . str_pad(dechex($this->backColor), 6, 0, STR_PAD_LEFT));
        $foreColor = new \ImagickPixel('#' . str_pad(dechex($this->foreColor), 6, 0, STR_PAD_LEFT));

        $image = new \Imagick();
        $image->newImage($this->width, $this->height, $backColor);

        $draw = new \ImagickDraw();
        $draw->setFont($this->fontFile);
        $draw->setFontSize(30);
        $fontMetrics = $image->queryFontMetrics($draw, $code);

        $length = strlen($code);
        $w = (int) $fontMetrics['textWidth'] - 8 + $this->offset * ($length - 1);
        $h = (int) $fontMetrics['textHeight'] - 8;
        $scale = min(($this->width - $this->padding * 2) / $w, ($this->height - $this->padding * 2) / $h);
        $x = 10;
        $y = round($this->height * 27 / 40);
        for ($i = 0; $i < $length; ++$i) {
            $draw = new \ImagickDraw();
            $draw->setFont($this->fontFile);
            $draw->setFontSize((int) (mt_rand(26, 32) * $scale * 0.8));
            $draw->setFillColor($foreColor);
            $image->annotateImage($draw, $x, $y, mt_rand(-10, 10), $code[$i]);
            $fontMetrics = $image->queryFontMetrics($draw, $code[$i]);
            $x += (int) $fontMetrics['textWidth'] + $this->offset;
        }

        $image->setImageFormat('png');
        return $image->getImageBlob();
    }

// Vulnerability class: CWE-330
public function Update() {

		// Update "main" ticket
		$upd_stmt = Database::prepare('
			UPDATE `' . TABLE_PANEL_TICKETS . '` SET
                `priority` = :priority,
                `lastchange` = :lastchange,
                `status` = :status,
                `lastreplier` = :lastreplier
                WHERE `id` = :tid'
		);
		$upd_data = array(
			'priority' => $this->Get('priority'),
			'lastchange' => $this->Get('lastchange'),
			'status' => $this->Get('status'),
			'lastreplier' => $this->Get('lastreplier'),
			'tid' => $this->tid
		);
		Database::pexecute($upd_stmt, $upd_data);
		return true;
	}

// Vulnerability class: CWE-732
public function __construct( \DPL\Parameters $parameters, \Parser $parser ) {
		parent::__construct( $parameters, $parser );
		$this->textSeparator = $parameters->getParameter( 'inlinetext' );
		$listSeparators = $parameters->getParameter( 'listseparators' );
		if ( isset( $listSeparators[0] ) ) {
			$this->listStart = $listSeparators[0];
		}
		if ( isset( $listSeparators[1] ) ) {
			$this->itemStart = $listSeparators[1];
		}
		if ( isset( $listSeparators[2] ) ) {
			$this->itemEnd = $listSeparators[2];
		}
		if ( isset( $listSeparators[3] ) ) {
			$this->listEnd = $listSeparators[3];
		}
	}

// Vulnerability class: CWE-400
public function validate($value, $isUserFormat = false)
	{
		if (empty($value)) {
			return;
		}
		if (\is_string($value)) {
			$value = \App\Json::decode($value);
		}
		if (!\is_array($value)) {
			throw new \App\Exceptions\Security('ERR_ILLEGAL_FIELD_VALUE||' . $this->getFieldModel()->getFieldName() . '||' . $this->getFieldModel()->getModuleName() . '||' . $value, 406);
		}
		$currencies = \App\Fields\Currency::getAll(true);
		foreach ($value['currencies'] ?? [] as $id => $currency) {
			if (!isset($currencies[$id])) {
				throw new \App\Exceptions\Security('ERR_ILLEGAL_FIELD_VALUE||' . $this->getFieldModel()->getFieldName() . '||' . $this->getFieldModel()->getModuleName() . '||' . $id, 406);
			}
			$price = $currency['price'];
			if ($isUserFormat) {
				$price = App\Fields\Double::formatToDb($price);
			}
			if (!is_numeric($price)) {
				throw new \App\Exceptions\Security('ERR_ILLEGAL_FIELD_VALUE||' . $this->getFieldModel()->getFieldName() . '||' . $this->getFieldModel()->getModuleName() . '||' . $price, 406);
			}
		}
	}

// Vulnerability class: CWE-20
private function resolveTrustedProxy()
    {
        if (!$trustedProxies = Request::getTrustedProxies()) {
            return '127.0.0.1';
        }

        $firstTrustedProxy = reset($trustedProxies);

        return false !== ($i = strpos($firstTrustedProxy, '/')) ? substr($firstTrustedProxy, 0, $i) : $firstTrustedProxy;
    }

// Vulnerability class: CWE-20
foreach ( $option as $_option ) {
				//Parameter functions return true or false.  The full parameter data will be passed into the Query object later.
				if ( $this->parameters->$parameter( $_option ) === false ) {
					//Do not build this into the output just yet.  It will be collected at the end.
					$this->logger->addMessage( \DynamicPageListHooks::WARN_WRONGPARAM, $parameter, $_option );
				}
			}

// Vulnerability class: CWE-400
public function save() {
        $data = $_POST['file'];

        // security (remove all ..)
        $data['name'] = str_replace('..', '', $data['name']);
        $file = FILES_DIR . DS . $data['name'];
        
        // CSRF checks
        if (isset($_POST['csrf_token'])) {
            $csrf_token = $_POST['csrf_token'];
            if (!SecureToken::validateToken($csrf_token, BASE_URL.'plugin/file_manager/save/'.$data['name'])) {
                Flash::set('error', __('Invalid CSRF token found!'));
                redirect(get_url('plugin/file_manager/view/'.$data['name']));
            }
        }
        else {
            Flash::set('error', __('No CSRF token found!'));
            redirect(get_url('plugin/file_manager/view/'.$data['name']));
        }
        
        if (file_exists($file)) {
            if (file_put_contents($file, $data['content']) !== false) {
                Flash::set('success', __('File has been saved with success!'));
            } else {
                Flash::set('error', __('File is not writable! File has not been saved!'));
            }
        } else {
            if (file_put_contents($file, $data['content'])) {
                Flash::set('success', __('File :name has been created with success!', array(':name' => $data['name'])));
            } else {
                Flash::set('error', __('Directory is not writable! File has not been saved!'));
            }
        }

        // save and quit or save and continue editing ?
        if (isset($_POST['commit'])) {
            redirect(get_url('plugin/file_manager/browse/' . substr($data['name'], 0, strrpos($data['name'], '/'))));
        } else {
            redirect(get_url('plugin/file_manager/view/' . $data['name'] . (endsWith($data['name'], URL_SUFFIX) ? '?has_url_suffix=1' : '')));
        }

// Vulnerability class: CWE-20
function manage() {
	    global $db;
	    
	    expHistory::set('manageable', $this->params);
//	    $classes = array();
        $dir = BASE."framework/modules/ecommerce/billingcalculators";
        if (is_readable($dir)) {
            $dh = opendir($dir);
            while (($file = readdir($dh)) !== false) {
                if (is_file("$dir/$file") && substr("$dir/$file", -4) == ".php") {
                    include_once("$dir/$file");
                    $classname = substr($file, 0, -4);
                    $id = $db->selectValue('billingcalculator', 'id', 'calculator_name="'.$classname.'"');
                    if (empty($id)) {
//                        $calobj = null;
                        $calcobj = new $classname();
                        if ($calcobj->isSelectable() == true) {
                            $obj = new billingcalculator(array(
                                'title'=>$calcobj->name(),
//                                'user_title'=>$calcobj->title,
                                'body'=>$calcobj->description(), 
                                'calculator_name'=>$classname,
                                'enabled'=>false));
                            $obj->save();
                        }
                    }
                }
            }
        }
        
        $bcalc = new billingcalculator();
        $calculators = $bcalc->find('all');
        assign_to_template(array(
            'calculators'=>$calculators
        ));
	}

// Vulnerability class: CWE-74
public function view() {
        $params = func_get_args();
        $content = '';

        $filename = urldecode(join('/', $params));

        // Sanitize filename for securtiy
        // We don't allow backlinks
        if (strpos($filename, '..') !== false) {
            /*
            if (Plugin::isEnabled('statistics_api')) {
                $user = null;
                if (AuthUser::isLoggedIn())
                    $user = AuthUser::getUserName();
                $ip = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : ($_SERVER['REMOTE_ADDR']);
                $event = array('event_type' => 'hack_attempt', // simple event type identifier
                    'description' => __('A possible hack attempt was detected.'), // translatable description
                    'ipaddress' => $ip,
                    'username' => $user);
                Observer::notify('stats_file_manager_hack_attempt', $event);
            }
             */
        }
        $filename = str_replace('..', '', $filename);

        // Clean up nicely
        $filename = str_replace('//', '', $filename);

        // We don't allow leading slashes
        $filename = preg_replace('/^\//', '', $filename);
        
        // Check if file had URL_SUFFIX - if so, append it to filename
        $filename .= (isset($_GET['has_url_suffix']) && $_GET['has_url_suffix']==='1') ? URL_SUFFIX : '';
        
        $file = FILES_DIR . '/' . $filename;
        if (!$this->_isImage($file) && file_exists($file)) {
            $content = file_get_contents($file);
        }
        
        $this->display('file_manager/views/view', array(
            'csrf_token' => SecureToken::generateToken(BASE_URL.'plugin/file_manager/save/'.$filename),
            'is_image' => $this->_isImage($file),
            'filename' => $filename,
            'content' => $content
        ));
    }

// Vulnerability class: CWE-20