Handles exporting of snippets
@param {SS_HTTPRequest} $request HTTP Request Data
540800
public function export_snippet(SS_HTTPRequest $request) {
        if($request->getVar('s')) {
            //Use the session id in the request
            Session::start($request->getVar('s'));
        }
        
        
        if(!Permission::check('CODE_BANK_ACCESS')) {
            header("HTTP/1.1 401 Unauthorized");
            
            
            //Save session and exit
            Session::save();
            exit;
        }
        
        
        try {
            $snippet=Snippet::get()->byID(intval($request->getVar('id')));
            if(empty($snippet) || $snippet===false || $snippet->ID==0) {
                header("HTTP/1.1 404 Not Found");
                
                
                //Save session and exit
                Session::save();
                exit;
            }
            
            
            $urlFilter=URLSegmentFilter::create();
            $fileID=$urlFilter->filter($snippet->Title);
            
            
            //If the temp dir doesn't exist create it
            if(!file_exists(ASSETS_PATH.'/.codeBankTemp')) {
                mkdir(ASSETS_PATH.'/.codeBankTemp', Config::inst()->get('Filesystem', 'folder_create_mask'));
            }
            
            
            if($snippet->Language()->Name=='ActionScript 3') {
                $zip=new ZipArchive();
                
                $res=$zip->open(ASSETS_PATH.'/.codeBankTemp/'.$fileID.'.zip', ZIPARCHIVE::CREATE);
                
                if($res===true) {
                    $path='';
                    $text=preg_split("/[\n\r]/", $snippet->getSnippetText());
                    $folder=str_replace('.', '/', trim(preg_replace('/^package (.*?)((\s*)\{)?$/i', '\\1', $text[0])));
                    
                    $className=array_values(preg_grep('/(\s*|\t*)public(\s+)class(\s+)(.*?)(\s*)((extends|implements)(.*?)(\s*))*\{/i', $text));
                    
                    if(count($className)==0) {
                        throw new Exception('Class definition could not be found');
                    }
                    
                    $className=trim(preg_replace('/(\s*|\t*)public(\s+)class(\s+)(.*?)(\s*)((extends|implements)(.*?)(\s*))*\{/i','\\4', $className[0]));
                    
                    if($className=="") {
                        throw new Exception('Class definition could not be found');
                    }
                    
                    $zip->addFromString($folder.'/'.$className.'.'.$snippet->Language()->FileExtension, $snippet->getSnippetText());
                    
                    if($zip->Close()!==false) {
                        chmod(ASSETS_PATH.'/.codeBankTemp/'.$fileID.'.zip',0600);
                        
                        
                        //Send File
                        SS_HTTPRequest::send_file(file_get_contents(ASSETS_PATH.'/.codeBankTemp/'.$fileID.'.zip'), $fileID.'.zip', 'application/octet-stream')->output();
                        unlink(ASSETS_PATH.'/.codeBankTemp/'.$fileID.'.zip');
                    }else {
                        header("HTTP/1.1 500 Internal Server Error");
                    }
                }else {
                    header("HTTP/1.1 500 Internal Server Error");
                }
            }else {
                SS_HTTPRequest::send_file($snippet->getSnippetText(), $fileID.'.'.$snippet->Language()->FileExtension, 'text/plain')->output();
            }
        }catch (Exception $e) {
            header("HTTP/1.1 500 Internal Server Error");
        }
        
        
        //Save session and exit
        Session::save();
        exit;
    }
820970
public function upload(SS_HTTPRequest $request)
    {
        $field = $this->getUploadField();
        $uploadResponse = $field->upload($request);
        //decode response body. ugly hack ;o
        $body = Convert::json2array($uploadResponse->getBody());
        $body = array_shift($body);
        //add extra data
        $body['import_url'] = Controller::join_links(
           $this->Link('preview'), $body['id'],
           // Also pull the back URL from the current request so we can persist this particular URL through the following pages.
           "?BackURL=" . $this->getBackURL($request)
        );
        //don't return buttons at all
        unset($body['buttons']);
        //re-encode
        $response = new SS_HTTPResponse(Convert::raw2json(array($body)));

        return $response;
    }
173660
public function getsubtree($request) {
        if(strpos($request->getVar('ID'), 'folder-')!==false) {
            $folderID=(strpos($request->getVar('ID'), 'folder-')!==false ? intval(str_replace('folder-', '', $request->getVar('ID'))):null);
            $html=$this->getSiteTreeFor('SnippetFolder', $folderID, 'Children', null, array($this, 'hasSnippets'));
        }else {
            $languageID=(strpos($request->getVar('ID'), 'language-')!==false ? intval(str_replace('language-', '', $request->getVar('ID'))):null);
            $html=$this->getSiteTreeFor($this->stat('tree_class'), $languageID, 'Children', null, array($this, 'hasSnippets'));
        }

        // Trim off the outer tag
        $html=preg_replace('/^[\s\t\r\n]*<ul[^>]*>/','', $html);
        $html=preg_replace('/<\/ul[^>]*>[\s\t\r\n]*$/','', $html);
        
        return $html;
    }
201965
public function handleDelete(SS_HTTPRequest $request)
    {
        parse_str($request->getBody(), $vars);
        $count = 0;
        if ($vars['ids']) {
            foreach (explode(',', $vars['ids']) as $id) {
                if ($file = File::get()->byID($id)) {
                    if ($file->canDelete()) {
                        $file->delete();
                        $count++;
                    }
                }
            }
        }

        $result = array(
            'deleted' => $count
        );

        $response = new SS_HTTPResponse(
            Convert::array2json($result), 200
        );

        return $response->addHeader('Content-Type', 'application/json');
    }
175469
protected function getResultsTemplate($request)
    {
        $templates = [
            Page::class . '_results',
            Page::class
        ];

        if ($request->getVar('format') == 'rss') {
            array_unshift($templates, Page::class . '_results_rss');
        }

        if ($request->getVar('format') == 'atom') {
            array_unshift($templates, Page::class . '_results_atom');
        }

        return $templates;
    }
840730
public function run($request) {
        //Check for tables
        $tables=DB::tableList();
        if(!array_key_exists('languages', $tables) || !array_key_exists('snippits', $tables) || !array_key_exists('snippit_history', $tables) || !array_key_exists('preferences', $tables) || !array_key_exists('settings', $tables) || !array_key_exists('snippit_search', $tables) || !array_key_exists('users', $tables)) {
            echo '<b>'._t('CodeBankLegacyMigrate.TABLES_NOT_FOUND', '_Could not find Code Bank 2.2 database tables, cannot migrate').'</b>';
            exit;
        }
        
        
        //Ensure Empty
        if(Snippet::get()->Count()>0) {
            echo '<b>'._t('CodeBankLegacyMigrate.SNIPPETS_PRESENT', '_Already appears to be snippets present in the database, please start with a clean database, cannot migrate.').'</b>';
            exit;
        }
        
        
        //Increase Timeout, since 30s probably won't be enough in huge databases
        increase_time_limit_to(600);
        
        
        //Find Other language
        $plainTextID=SnippetLanguage::get()->filter('Name', 'Other')->first();
        if(empty($plainTextID) || $plainTextID==false || $plainTextID->ID==0) {
            echo _t('CodeBankLegacyMigrate.OTHER_NOT_FOUND', '_Could not find the Other Language, cannot migrate, please run dev/build first');
            exit;
        }else {
            $plainTextID=$plainTextID->ID;
        }
        
        
        //Check for users group
        $usersGroup=Group::get()->filter('Code', 'code-bank-api')->first();
        if(empty($usersGroup) || $usersGroup==false || $usersGroup->ID==0) {
            //Rollback Transaction
            if(DB::getConn()->supportsTransactions()) {
                DB::getConn()->transactionRollback();
            }
            
            echo _t('CodeBankLegacyMigrate.GROUP_NOT_FOUND', '_Could not find users group, cannot migrate, please run dev/build first');
            exit;
        }
        
        
        //Start Transaction
        if(DB::getConn()->supportsTransactions()) {
            DB::getConn()->transactionStart();
        }
        
        
        //Migrate Languages
        echo '<b>'._t('CodeBankLegacyMigrate.MIGRATE_USER_LANGUAGES', '_Migrating User Languages').'</b>... ';
        $results=DB::query('SELECT * FROM "languages" WHERE "user_language"=1');
        if($results->numRecords()>0) {
            foreach($results as $row) {
                DB::query('INSERT INTO "SnippetLanguage" ("ClassName","Created", "LastEdited", "Name", "FileExtension", "HighlightCode", "UserLanguage") '.
                        "VALUES('SnippetLanguage','".date('Y-m-d H:i:s')."','".date('Y-m-d H:i:s')."','".Convert::raw2sql($row['language'])."','".Convert::raw2sql($row['file_extension'])."','".Convert::raw2sql($row['sjhs_code'])."',1)");
            }
            
            echo _t('CodeBankLegacyMigrate.DONE', '_Done').'<br/>';
        }else {
            echo _t('CodeBankLegacyMigrate.NOT_FOUND', '_None Found').'<br/>';
        }
        
        
        //Migrate Users
        echo '<b>'._t('CodeBankLegacyMigrate.MIGRATE_USERS', '_Migrating Users').'</b>...';
        
        $results=DB::query('SELECT * FROM "users"');
        if($results->numRecords()>0) {
            foreach($results as $row) {
                if($row['deleted']==true) {
                    echo '<br/><i>'._t('CodeBankLegacyMigrate.DELETED_MEMBER_SKIP', '_WARNING: Skipping deleted member {username}, deleted members in Code Bank 3 are not supported', array('username'=>$row['username'])).'</i><br/>';
                    continue;
                }
                
                //Get user heartbeat preference
                $useHeartbeat=DB::query('SELECT "value" FROM "preferences" WHERE "code"=\'heartbeat\' AND "fkUser"='.$row['id'])->value();
                
                
                //Insert User
                $member=Member::get()->filter('Email', Convert::raw2sql($row['username']))->first();
                if(empty($member) || $member===false || $member->ID==0) {
                    $member=new Member();
                    $member->FirstName=$row['username'];
                    $member->Email=$row['username'];
                    $member->Password=$row['password'];
                    $member->PasswordEncryption='sha1';
                    $member->Locale='en_US';
                    $member->DateFormat='MMM d, yyyy';
                    $member->TimeFormat='h:mm:ss a';
                    $member->UseHeartbeat=intval($useHeartbeat);
                    $member->write();
                    
                    
                    DB::query('UPDATE "Member" '.
                            'SET "Password"=\''.substr(base_convert($row['password'], 16, 36), 0, 64).'\', '.
                            '"Salt"=NULL '.
                            'WHERE "ID"='.$member->ID);
                    
                    
                    //Add to security group
                    if($row['username']=='admin') {
                        //For admin add to administrators group
                        $member->addToGroupByCode('administrators');
                    }else {
                        //For all others add to code-bank-api
                        $member->addToGroupByCode('code-bank-api');
                    }
                }else {
                    //Add to code-bank-api if not admin
                    if($row['username']!='admin') {
                        $member->addToGroupByCode('code-bank-api');
                    }
                    
                    $member->UseHeartbeat=intval($useHeartbeat);
                    $member->write();
                    
                    echo '<br/><i>'._t('CodeBankLegacyMigrate.MEMBER_EXISTS', '_WARNING: Member {username} already exists in the database, no changes have been made to this member. If you are unsure of the password please ask an administrator to have it reset or use the forgot password link', array('username'=>$row['username'])).'</i><br/>';
                }
            }
            
            echo _t('CodeBankLegacyMigrate.DONE', '_Done').'<br/>';
        }else {
            //Rollback Transaction
            if(DB::getConn()->supportsTransactions()) {
                DB::getConn()->transactionRollback();
            }
            
            echo _t('CodeBankLegacyMigrate.NO_USERS_FOUND', '_No users found, Code Bank 2.2 appears to have not been properly setup cannot continue with migration');
            exit;
        }
        
        
        //Migrate IP Message
        echo '<b>Migrating IP Message</b>...';
        $ipMessage=DB::query('SELECT "value" FROM "settings" WHERE "code"=\'ipMessage\'')->value();
        $config=CodeBankConfig::CurrentConfig();
        $config->IPMessage=$ipMessage;
        $config->write();
        echo _t('CodeBankLegacyMigrate.DONE', '_Done').'<br/>';
        
        
        //Migrate Snippets
        echo '<b>'._t('CodeBankLegacyMigrate.MIGRATE_SNIPPETS', '_Migrating Snippets').'</b>...';
        $results=DB::query('SELECT "snippits".*, "languages"."language", "creator"."username" AS "creatorUsername", "lastEditor"."username" AS "lastEditorUsername" '.
                            'FROM "snippits" '.
                                'INNER JOIN "languages" ON "snippits"."fkLanguage"="languages"."id" '.
                                'LEFT JOIN "users" "creator" ON "snippits"."fkCreatorUser"="creator"."id" '.
                                'LEFT JOIN "users" "lastEditor" ON "snippits"."fkLastEditUser"="lastEditor"."id"');
        if($results->numRecords()>0) {
            foreach($results as $row) {
                //Get Creator ID
                $creator=Member::get()->filter('Email', Convert::raw2sql($row['creatorUsername']))->first();
                if(!empty($creator) && $creator!==false && $creator->ID!=0) {
                    $creatorID=$creator->ID;
                }else {
                    $creatorID=0;
                }
                
                
                //Get Last Editor ID
                $lastEditor=Member::get()->filter('Email', Convert::raw2sql($row['lastEditorUsername']))->first();
                if(!empty($lastEditor) && $lastEditor!==false && $lastEditor->ID!=0) {
                    $lastEditorID=$lastEditor->ID;
                }else {
                    $lastEditorID=0;
                }
                
                
                //Get Language ID
                $language=SnippetLanguage::get()->filter('Name', Convert::raw2sql($row['language']))->first();
                if(!empty($language) && $language!==false && $language->ID!=0) {
                    $languageID=$language->ID;
                }else {
                    $languageID=$plainTextID;
                }
                
                
                //Insert Snippet Info
                DB::query('INSERT INTO "Snippet" ("ID", "ClassName", "Created", "LastEdited", "Title", "Description", "Tags", "LanguageID", "CreatorID", "LastEditorID") '.
                        "VALUES(".$row['id'].",'Snippet','".date('Y-m-d H:i:s')."','".date('Y-m-d H:i:s')."','".Convert::raw2sql($row['title'])."','".Convert::raw2sql($row['description'])."','".Convert::raw2sql($row['tags'])."',".$languageID.",".$creatorID.",".$lastEditorID.")");
                
                
                //Get History
                $versions=DB::query('SELECT * FROM "snippit_history" WHERE "fkSnippit"='.$row['id']);
                foreach($versions as $version) {
                    DB::query('INSERT INTO "SnippetVersion" ("ClassName", "Created", "LastEdited", "Text", "ParentID") '.
                            "VALUES('SnippetVersion','".date('Y-m-d H:i:s', strtotime($version['date']))."','".date('Y-m-d H:i:s', strtotime($version['date']))."','".Convert::raw2sql($version['text'])."',".$row['id'].")");
                                
                }
            }
            
            
            echo _t('CodeBankLegacyMigrate.DONE', '_Done').'<br/>';
        }else {
            echo _t('CodeBankLegacyMigrate.NO_SNIPPETS_FOUND', '_No snippets found').'<br/>';
        }
        
        
        //Rename tables
        DB::getConn()->renameTable('snippits', '_obsolete_snippits');
        DB::getConn()->renameTable('snippit_search', '_obsolete_snippit_search');
        DB::getConn()->renameTable('snippit_history', '_obsolete_snippit_history');
        DB::getConn()->renameTable('languages', '_obsolete_languages');
        DB::getConn()->renameTable('settings', '_obsolete_settings');
        DB::getConn()->renameTable('preferences', '_obsolete_preferences');
        DB::getConn()->renameTable('users', '_obsolete_users');
        
        //Complete Transaction
        if(DB::getConn()->supportsTransactions()) {
            DB::getConn()->transactionEnd();
        }
        
        
        //Mark Migrated
        touch(ASSETS_PATH.'/.codeBankMigrated');
        
        echo '<br/><h4>'._t('CodeBankLegacyMigrate.MIGRATION_COMPLETE', '_Migration Completed').'</h4>';
        exit;
    }
137761
protected function saveElements(\Illuminate\Http\Request $request)
    {
        $this->getElements()->onlyActive()->each(function ($element) use ($request) {
            $element = $this->getElementContainer($element);

            if ($element instanceof FormElementInterface) {
                $element->save($request);
            }
        });
    }
1287335
public static function dump($val, HTTPRequest $request = null)
    {
        echo self::create_debug_view($request)
            ->renderVariable($val, self::caller());
    }
1333765
function (request) {
            var transport;
            if (request.jsonp) {
                transport = this.__jsonp;
            } else if (ariaUtilsType.isHTMLElement(request.form)) {
                transport = this.__iframe;
            } else {
                transport = this._getTransport(request.url, Aria.$frameworkWindow
                        ? Aria.$frameworkWindow.location
                        : null);
            }

            var instance = Aria.getClassRef(transport);
            var args = {
                req : request,
                transport : {
                    classpath : transport,
                    instance : instance
                }
            };

            if (!instance) {
                Aria.load({
                    classes : [transport],
                    oncomplete : {
                        fn : this._asyncRequest,
                        args : args,
                        scope : this
                    }
                });
            } else {
                this._asyncRequest(args);
            }
        }
36227
public function exportArchiveAction()
    {
        $params = $this->_processParameters($this->showParameters);

        $this->addSnippets($this->exportSnippets, $params);

        $this->html->h2($this->_('Export respondent archive'));

        //Now show the export form
        $export = $this->loader->getRespondentExport();
        $form   = $export->getForm();
        $div    = $this->html->div(array('id' => 'mainform'));
        $div[]  = $form;

        $request = $this->getRequest();

        $form->populate($request->getParams());

        if ($request->isPost()) {
            $respondent = $this->getRespondent();
            $patients   = array(
                array(
                    'gr2o_id_organization' => $respondent->getOrganizationId(),
                    'gr2o_patient_nr'      => $respondent->getPatientNumber()
                    )
                );
            $export->render($patients, $request->getParam('group'), $request->getParam('format'));
        }
    }
195997
public function handleFolderContents(SS_HTTPRequest $request)
    {
        if (!$request->param('FolderID')) {
            $folder = Injector::inst()->get('Folder');
            $folder->Filename = ASSETS_DIR;
        } else {
            $folder = Folder::get()->byID($request->param('FolderID'));
        }

        if (!$folder) {
            return $this->httpError(404, 'That folder does not exist');
        }

        $cursor = (int)$request->getVar('cursor');
        $result = array(
            'folder' => $this->createFolderJson($folder),
            'breadcrumbs' => $this->createBreadcrumbJson($folder),
            'children' => array()
        );

        $files = File::get()
            ->filter(array(
                'ParentID' => $folder->ID
            ))
            ->sort($this->getSortClause($request->getVar('sort')));

        $totalFiles = (int)$files->count();
        $files = $files->limit($this->config()->folder_items_limit, $cursor);

        foreach ($files as $file) {
            if (!$file->canView()) {
                continue;
            }

            $result['children'][] = ($file instanceof Folder) ?
                $this->createFolderJson($file) :
                $this->createFileJson($file, $folder);
        }

        $cursor += $files->count();
        $result['cursor'] = $cursor;
        $result['has_more'] = ($cursor < $totalFiles);
        $result['total_items'] = $totalFiles;

        $response = new SS_HTTPResponse(
            Convert::array2json($result), 200
        );

        return $response->addHeader('Content-Type', 'application/json');
    }
660292
protected function doRequestInProcess($request)
    {
        $deprecationsFile = tempnam(sys_get_temp_dir(), 'deprec');
        putenv('SYMFONY_DEPRECATIONS_SERIALIZE='.$deprecationsFile);
        $_ENV['SYMFONY_DEPRECATIONS_SERIALIZE'] = $deprecationsFile;
        $process = new PhpProcess($this->getScript($request), null, null);
        $process->run();

        if (file_exists($deprecationsFile)) {
            $deprecations = file_get_contents($deprecationsFile);
            unlink($deprecationsFile);
            foreach ($deprecations ? unserialize($deprecations) : [] as $deprecation) {
                if ($deprecation[0]) {
                    @trigger_error($deprecation[1], E_USER_DEPRECATED);
                } else {
                    @trigger_error($deprecation[1], E_USER_DEPRECATED);
                }
            }
        }

        if (!$process->isSuccessful() || !preg_match('/^O\:\d+\:/', $process->getOutput())) {
            throw new \RuntimeException(sprintf('OUTPUT: %s ERROR OUTPUT: %s', $process->getOutput(), $process->getErrorOutput()));
        }

        return unserialize($process->getOutput());
    }
771820
public function restoresnapshot($request) {
		$dataArchive = DNDataArchive::get()->byId($request->param('DataArchiveID'));

		if(!$dataArchive) {
			throw new SS_HTTPResponse_Exception('Archive not found', 404);
		}

		// We check for canDownload because that implies access to the data.
		// canRestore is later checked on the actual restore action per environment.
		if(!$dataArchive->canDownload()) {
			throw new SS_HTTPResponse_Exception('Not allowed to access archive', 403);
		}

		$form = $this->getDataTransferRestoreForm($this->request, $dataArchive);

		// View currently only available via ajax
		return $form->forTemplate();
	}
933915
public function postAction(Request $request)
    {
        $document = $this->documentManager->create(Structure::TYPE_SNIPPET);
        $form = $this->processForm($request, $document);

        return $this->handleView($form->getData());
    }
1168197
public function exportAction($cf_group_id, Request $request)
    {
        $em = $this->getDoctrine()->getManager();

        $cFGroup = $em->getRepository('ChillCustomFieldsBundle:CustomFieldsGroup')->find($cf_group_id);
        $reports = $em->getRepository('ChillReportBundle:Report')->findByCFGroup($cFGroup);


        $response = $this->render('ChillReportBundle:Report:export.csv.twig', array(
            'reports' => $reports,
            'cf_group' => $cFGroup
        ));

        $response->headers->set('Content-Type', 'text/csv; charset=utf-8');
        $response->headers->set('Content-Disposition', 'attachment; filename="export.csv"');
        return $response;
    }
308933
public function handleCreateFolder(SS_HTTPRequest $request)
    {

        if (!Injector::inst()->get('Folder')->canCreate()) {
            return $this->httpError(403);
        }

        $parentID = (int)$request->postVar('parentID');

        /** @var Folder $parentRecord */
        $parentRecord = Folder::get()->byID($parentID);

        $name = $request->postVar('title') ? $request->postVar('title') : _t('AssetAdmin.NEWFOLDER', "NewFolder");
        if ($parentRecord && $parentRecord->ID) {
            $filename = Controller::join_links($parentRecord->FullPath, $name);
        } else {
            $filename = Controller::join_links(ASSETS_PATH, $name);
        }

        /** @var Folder $record */
        $record = Folder::create(array(
            'ParentID' => $parentID,
            'Name' => basename($filename),
            'Title' => basename($filename),
            'Filename' => $filename
        ));

        // Ensure uniqueness
        $i = 2;
        if (substr($record->Filename, -1) == "/") {
            $baseFilename = substr($record->Filename, 0, -1);
        } else {
            $baseFilename = $record->Filename;
        }
        $baseFilename .= "-";
        while (file_exists($record->FullPath)) {
            $record->Filename = $baseFilename . $i . '/';
            $i++;
        }

        $record->Name = $record->Title = basename($record->Filename);

        mkdir($record->FullPath);
        @chmod($record->FullPath, (int)Config::inst()->get('Filesystem', 'file_create_mask'));

        $record->write();

        $response = new SS_HTTPResponse(
            Convert::array2json($this->createFolderJson($record)), 200
        );

        return $response->addHeader('Content-Type', 'application/json');
    }
835973
public function fileEditorLinkForm($request = null)
    {
        // Get ID either from posted back value, or url parameter
        if (!$request) {
            $this->jsonError(400);
            return null;
        }
        $id = $request->param('ID');
        if (!$id) {
            $this->jsonError(400);
            return null;
        }
        return $this->getFileInsertForm($id);
    }