<commit_before><?php
class CodeBank extends LeftAndMain implements PermissionProvider {
    public static $url_segment='codeBank';
    public static $tree_class='SnippetLanguage';
    public static $url_rule='/$Action/$ID/$OtherID';
    public static $url_priority=59;
    public static $filter_class='SnippetTreeFilter';
    
    public static $required_permission_codes=array(
                                                    'CODE_BANK_ACCESS'
                                                );
    
    public static $allowed_actions=array(
                                        'index',
                                        'tree',
                                        'EditForm',
                                        'show',
                                        'compare'
                                    );
    
    public static $session_namespace='CodeBank';
    
    /**
     * Constructor
     * @see LeftAndMain::__construct()
     */
    public function __construct() {
        parent::__construct();
        
        //Work around to allow dynamic path
        Config::inst()->update('CodeBank', 'menu_icon', CB_DIR.'/images/menu-icon.png');
    }
    
    /**
     * Initializes the code bank admin
     */
    public function init() {
        parent::init();
        
        Requirements::css(CB_DIR.'/css/CodeBank.css');
        
        Requirements::customScript("var CB_DIR='".CB_DIR."';", 'cb_dir');
        Requirements::javascript(CB_DIR.'/javascript/CodeBank.Tree.js');
        
        if(!empty(CodeBankConfig::CurrentConfig()->IPMessage) && Session::get('CodeBankIPAgreed')!==true) {
            $this->redirect('admin/codeBank/agreement');
        }
    }
    
    public function index($request) {
        // In case we're not showing a specific record, explicitly remove any session state,
        // to avoid it being highlighted in the tree, and causing an edit form to show.
        if(!$request->param('Action')) $this->setCurrentPageId(null);

        return parent::index($request);
    }
    
    /**
     * Override {@link LeftAndMain} Link to allow blank URL segment for CMSMain.
     * @param {string} $action Action to be used
     * @return {string} Resulting link
     */
    public function Link($action=null) {
        $link = Controller::join_links(
            $this->stat('url_base', true),
            $this->stat('url_segment', true), // in case we want to change the segment
            '/', // trailing slash needed if $action is null!
            "$action"
        );
        
        $this->extend('updateLink', $link);
        return $link;
    }
    
    /**
     * Generates the link with search params
     * @param {string} Link to
     * @return {string} Link with search params
     */
    protected function LinkWithSearch($link) {
        // Whitelist to avoid side effects
        $params=array(
                    'q'=>(array)$this->request->getVar('q'),
                    'ParentID'=>$this->request->getVar('ParentID')
                );
        
        $link=Controller::join_links(
                                    $link,
                                    (array_filter(array_values($params)) ? '?'.http_build_query($params):null)
                                );
        
        $this->extend('updateLinkWithSearch', $link);
        return $link;
    }
    
    /**
     * Gets the main tab link
     * @return {string} URL to the main tab
     */
    public function getLinkMain() {
        if($this->currentPageID()!=0 && $this->class=='CodeBankEditSnippet') {
            return $this->LinkWithSearch(Controller::join_links($this->Link('show'), $this->currentPageID()));
        }else if($this->currentPageID()!=0 && $this->class=='CodeBank') {
            $otherID=null;
            if(!empty($this->urlParams['OtherID']) && is_numeric($this->urlParams['OtherID'])) {
                $otherID=intval($this->urlParams['OtherID']);
            }
            
            return $this->LinkWithSearch(Controller::join_links($this->Link('show'), $this->currentPageID(), $otherID));
        }
        
        return $this->LinkWithSearch(singleton('CodeBank')->Link());
    }
    
    /**
     * Gets the form used for viewing snippets
     * @param {int} $id ID of the record to fetch
     * @param {FieldList} $fields Fields to use
     * @return {Form} Form to be used
     */
    public function getEditForm($id=null, $fields=null) {
        if(!$id) {
            $id=$this->currentPageID();
        }
        
        
        $form=parent::getEditForm($id);
        
        
        $record=$this->getRecord($id);
        if($record && !$record->canView()) {
            return Security::permissionFailure($this);
        }
        
        
        if(!$fields) {
            $fields=$form->Fields();
        }
        
        
        $actions=$form->Actions();
        
        
        if($record) {
            $fields->push($idField=new HiddenField("ID", false, $id));
            $actions=new FieldList(
                                    new FormAction('doCopy', _t('CodeBank.COPY', '_Copy')),
                                    new FormAction('doEditRedirect', _t('CodeBank.EDIT', '_Edit')),
                                    new FormAction('doExport', _t('CodeBank.EXPORT', '_Export')),
                                    new FormAction('doPrint', _t('CodeBank.PRINT', '_Print')),
                                    new LabelField('Revision', _t('CodeBank.REVISION', '_Revision').': '),
                                    DropdownField::create('RevisionID', '', $record->Versions()->where('ID<>'.$record->CurrentVersionID)->Map('ID', 'Created'), $this->urlParams['OtherID'], null, '{'._t('CodeBank.CURRENT_REVISION', '_Current Revision').'}')->setDisabled($record->Versions()->Count()<=1)->addExtraClass('no-change-track'),
                                    FormAction::create('compareRevision', _t('CodeBank.COMPARE_WITH_CURRENT', '_Compare with Current'))->setDisabled($record->Versions()->Count()<=1 || empty($this->urlParams['OtherID']) || !is_numeric($this->urlParams['OtherID']))
                                );
            
            
            // Use <button> to allow full jQuery UI styling
            $actionsFlattened=$actions->dataFields();
            if($actionsFlattened) {
                foreach($actionsFlattened as $action) {
                    if($action instanceof FormAction) {
                        $action->setUseButtonTag(true);
                    }
                }
            }
            
            
            if($record->hasMethod('getCMSValidator')) {
                $validator=$record->getCMSValidator();
            }else {
                $validator=new RequiredFields();
            }
            
            
            $fields->replaceField('PackageID', new PackageViewField('PackageID', _t('Snippet.PACKAGE', '_Package'), new ArrayList(array($record->Package())), $record->ID));
            $fields->replaceField('Text', HighlightedContentField::create('SnippetText', _t('Snippet.CODE', '_Code'), $record->Language()->HighlightCode)->setForm($form));
            $fields->addFieldToTab('Root.Main', ReadonlyField::create('CreatorName', _t('CodeBank.CREATOR', '_Creator'), ($record->Creator() ? $record->Creator()->Name:null))->setForm($form));
            $fields->addFieldToTab('Root.Main', ReadonlyField::create('LanguageName', _t('CodeBank.LANGUAGE', '_Language'), $record->Language()->Name)->setForm($form));
            $fields->addFieldToTab('Root.Main', DatetimeField_Readonly::create('LastModified', _t('CodeBank.LAST_MODIFIED', '_Last Modified'), $record->CurrentVersion->LastEdited)->setForm($form));<commit_msg>Fixed package view field displaying all snippets not in a package<commit_after><?php
class CodeBank extends LeftAndMain implements PermissionProvider {
    public static $url_segment='codeBank';
    public static $tree_class='SnippetLanguage';
    public static $url_rule='/$Action/$ID/$OtherID';
    public static $url_priority=59;
    public static $filter_class='SnippetTreeFilter';
    
    public static $required_permission_codes=array(
                                                    'CODE_BANK_ACCESS'
                                                );
    
    public static $allowed_actions=array(
                                        'index',
                                        'tree',
                                        'EditForm',
                                        'show',
                                        'compare'
                                    );
    
    public static $session_namespace='CodeBank';
    
    /**
     * Constructor
     * @see LeftAndMain::__construct()
     */
    public function __construct() {
        parent::__construct();
        
        //Work around to allow dynamic path
        Config::inst()->update('CodeBank', 'menu_icon', CB_DIR.'/images/menu-icon.png');
    }
    
    /**
     * Initializes the code bank admin
     */
    public function init() {
        parent::init();
        
        Requirements::css(CB_DIR.'/css/CodeBank.css');
        
        Requirements::customScript("var CB_DIR='".CB_DIR."';", 'cb_dir');
        Requirements::javascript(CB_DIR.'/javascript/CodeBank.Tree.js');
        
        if(!empty(CodeBankConfig::CurrentConfig()->IPMessage) && Session::get('CodeBankIPAgreed')!==true) {
            $this->redirect('admin/codeBank/agreement');
        }
    }
    
    public function index($request) {
        // In case we're not showing a specific record, explicitly remove any session state,
        // to avoid it being highlighted in the tree, and causing an edit form to show.
        if(!$request->param('Action')) $this->setCurrentPageId(null);

        return parent::index($request);
    }
    
    /**
     * Override {@link LeftAndMain} Link to allow blank URL segment for CMSMain.
     * @param {string} $action Action to be used
     * @return {string} Resulting link
     */
    public function Link($action=null) {
        $link = Controller::join_links(
            $this->stat('url_base', true),
            $this->stat('url_segment', true), // in case we want to change the segment
            '/', // trailing slash needed if $action is null!
            "$action"
        );
        
        $this->extend('updateLink', $link);
        return $link;
    }
    
    /**
     * Generates the link with search params
     * @param {string} Link to
     * @return {string} Link with search params
     */
    protected function LinkWithSearch($link) {
        // Whitelist to avoid side effects
        $params=array(
                    'q'=>(array)$this->request->getVar('q'),
                    'ParentID'=>$this->request->getVar('ParentID')
                );
        
        $link=Controller::join_links(
                                    $link,
                                    (array_filter(array_values($params)) ? '?'.http_build_query($params):null)
                                );
        
        $this->extend('updateLinkWithSearch', $link);
        return $link;
    }
    
    /**
     * Gets the main tab link
     * @return {string} URL to the main tab
     */
    public function getLinkMain() {
        if($this->currentPageID()!=0 && $this->class=='CodeBankEditSnippet') {
            return $this->LinkWithSearch(Controller::join_links($this->Link('show'), $this->currentPageID()));
        }else if($this->currentPageID()!=0 && $this->class=='CodeBank') {
            $otherID=null;
            if(!empty($this->urlParams['OtherID']) && is_numeric($this->urlParams['OtherID'])) {
                $otherID=intval($this->urlParams['OtherID']);
            }
            
            return $this->LinkWithSearch(Controller::join_links($this->Link('show'), $this->currentPageID(), $otherID));
        }
        
        return $this->LinkWithSearch(singleton('CodeBank')->Link());
    }
    
    /**
     * Gets the form used for viewing snippets
     * @param {int} $id ID of the record to fetch
     * @param {FieldList} $fields Fields to use
     * @return {Form} Form to be used
     */
    public function getEditForm($id=null, $fields=null) {
        if(!$id) {
            $id=$this->currentPageID();
        }
        
        
        $form=parent::getEditForm($id);
        
        
        $record=$this->getRecord($id);
        if($record && !$record->canView()) {
            return Security::permissionFailure($this);
        }
        
        
        if(!$fields) {
            $fields=$form->Fields();
        }
        
        
        $actions=$form->Actions();
        
        
        if($record) {
            $fields->push($idField=new HiddenField("ID", false, $id));
            $actions=new FieldList(
                                    new FormAction('doCopy', _t('CodeBank.COPY', '_Copy')),
                                    new FormAction('doEditRedirect', _t('CodeBank.EDIT', '_Edit')),
                                    new FormAction('doExport', _t('CodeBank.EXPORT', '_Export')),
                                    new FormAction('doPrint', _t('CodeBank.PRINT', '_Print')),
                                    new LabelField('Revision', _t('CodeBank.REVISION', '_Revision').': '),
                                    DropdownField::create('RevisionID', '', $record->Versions()->where('ID<>'.$record->CurrentVersionID)->Map('ID', 'Created'), $this->urlParams['OtherID'], null, '{'._t('CodeBank.CURRENT_REVISION', '_Current Revision').'}')->setDisabled($record->Versions()->Count()<=1)->addExtraClass('no-change-track'),
                                    FormAction::create('compareRevision', _t('CodeBank.COMPARE_WITH_CURRENT', '_Compare with Current'))->setDisabled($record->Versions()->Count()<=1 || empty($this->urlParams['OtherID']) || !is_numeric($this->urlParams['OtherID']))
                                );
            
            
            // Use <button> to allow full jQuery UI styling
            $actionsFlattened=$actions->dataFields();
            if($actionsFlattened) {
                foreach($actionsFlattened as $action) {
                    if($action instanceof FormAction) {
                        $action->setUseButtonTag(true);
                    }
                }
            }
            
            
            if($record->hasMethod('getCMSValidator')) {
                $validator=$record->getCMSValidator();
            }else {
                $validator=new RequiredFields();
            }
            
            
            if($record->Package() && $record->Package()!==false && $record->Package()->ID!=0) {
                $package=new ArrayList(array($record->Package()));
            }else {
                $package=null;
            }
            
            $fields->replaceField('PackageID', new PackageViewField('PackageID', _t('Snippet.PACKAGE', '_Package'), $package, $record->ID));
            $fields->replaceField('Text', HighlightedContentField::create('SnippetText', _t('Snippet.CODE', '_Code'), $record->Language()->HighlightCode)->setForm($form));
            $fields->addFieldToTab('Root.Main', ReadonlyField::create('CreatorName', _t('CodeBank.CREATOR', '_Creator'), ($record->Creator() ? $record->Creator()->Name:null))->setForm($form));
            $fields->addFieldToTab('Root.Main', ReadonlyField::create('LanguageName', _t('CodeBank.LANGUAGE', '_Language'), $record->Language()->Name)->setForm($form));
            $fields->addFieldToTab('Root.Main', DatetimeField_Readonly::create('LastModified', _t('CodeBank.LAST_MODIFIED', '_Last Modified'), $record->CurrentVersion->LastEdited)->setForm($form));
{'fraction_non_alphanumeric': 0.14926991009373206, 'fraction_numerical': 0.0008289230376841165, 'mean_word_length': 1.9049824041489165, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 159, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 38, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4593274', 'n_tokens_mistral': 4092, 'n_tokens_neox': 3999, 'n_words': 737}