/** * questiongroup::import() * Function responsible to import a question group. * * @access public * @return void */ function import() { $action = $_POST['action']; $iSurveyID = $surveyid = $aData['surveyid'] = (int) $_POST['sid']; if (!Permission::model()->hasSurveyPermission($surveyid, 'surveycontent', 'import')) { Yii::app()->user->setFlash('error', gT("Access denied")); $this->getController()->redirect(array('admin/survey/sa/listquestiongroups/surveyid/' . $surveyid)); } if ($action == 'importgroup') { $importgroup = "\n"; $importgroup .= "\n"; $sFullFilepath = Yii::app()->getConfig('tempdir') . DIRECTORY_SEPARATOR . randomChars(20); $aPathInfo = pathinfo($_FILES['the_file']['name']); $sExtension = $aPathInfo['extension']; if ($_FILES['the_file']['error'] == 1 || $_FILES['the_file']['error'] == 2) { $fatalerror = sprintf(gT("Sorry, this file is too large. Only files up to %01.2f MB are allowed."), getMaximumFileUploadSize() / 1024 / 1024) . '<br>'; } elseif (!@move_uploaded_file($_FILES['the_file']['tmp_name'], $sFullFilepath)) { $fatalerror = gT("An error occurred uploading your file. This may be caused by incorrect permissions for the application /tmp folder."); } // validate that we have a SID if (!returnGlobal('sid')) { $fatalerror .= gT("No SID (Survey) has been provided. Cannot import question."); } if (isset($fatalerror)) { @unlink($sFullFilepath); Yii::app()->user->setFlash('error', $fatalerror); $this->getController()->redirect(array('admin/questiongroups/sa/importview/surveyid/' . $surveyid)); } Yii::app()->loadHelper('admin/import'); // IF WE GOT THIS FAR, THEN THE FILE HAS BEEN UPLOADED SUCCESFULLY if (strtolower($sExtension) == 'lsg') { $aImportResults = XMLImportGroup($sFullFilepath, $iSurveyID); } else { Yii::app()->user->setFlash('error', gT("Unknown file extension")); $this->getController()->redirect(array('admin/questiongroups/sa/importview/surveyid/' . $surveyid)); } LimeExpressionManager::SetDirtyFlag(); // so refreshes syntax highlighting fixLanguageConsistency($iSurveyID); if (isset($aImportResults['fatalerror'])) { unlink($sFullFilepath); Yii::app()->user->setFlash('error', $aImportResults['fatalerror']); $this->getController()->redirect(array('admin/questiongroups/sa/importview/surveyid/' . $surveyid)); } unlink($sFullFilepath); $aData['display'] = $importgroup; $aData['surveyid'] = $iSurveyID; $aData['aImportResults'] = $aImportResults; $aData['sExtension'] = $sExtension; //$aData['display']['menu_bars']['surveysummary'] = 'importgroup'; $aData['sidemenu']['state'] = false; $surveyinfo = Survey::model()->findByPk($iSurveyID)->surveyinfo; $aData['title_bar']['title'] = $surveyinfo['surveyls_title'] . "(" . gT("ID") . ":" . $iSurveyID . ")"; $this->_renderWrappedTemplate('survey/QuestionGroups', 'import_view', $aData); } }
$iValue = substr($sSize, 0, -1); switch (strtoupper($sSuffix)) { case 'P': $iValue *= 1024; case 'T': $iValue *= 1024; case 'G': $iValue *= 1024; case 'M': $iValue *= 1024; case 'K': $iValue *= 1024; break; } return $iValue; } function getMaximumFileUploadSize() { return min(convertPHPSizeToBytes(ini_get('post_max_size')), convertPHPSizeToBytes(ini_get('upload_max_filesize'))); } var_dump(getMaximumFileUploadSize()); } ################################################################################ ## FORMA 03 - SIMPLES ################################################################################ if (false) { echo '<hr />'; $maxUpload = (int) ini_get('upload_max_filesize'); $maxPost = (int) ini_get('post_max_size'); var_dump($maxUpload, $maxPost); }
echo getSideBodyClass(false); ?> '> <h3><?php eT("Import a question"); ?> </h3> <div class="row"> <div class="col-lg-12"> <?php echo CHtml::form(array("admin/questions/sa/import"), 'post', array('id' => 'importquestion', 'class' => 'form-horizontal', 'name' => 'importquestion', 'enctype' => 'multipart/form-data', 'onsubmit' => "return validatefilename(this, '" . gT("Please select a file to import!", 'js') . "');")); ?> <div class="form-group"> <label class="col-sm-2 control-label" for='the_file'><?php eT("Select question file (*.lsq):"); echo '<br>' . sprintf(gT("(Maximum file size: %01.2f MB)"), getMaximumFileUploadSize() / 1024 / 1024); ?> </label> <div class="col-sm-3"> <input name='the_file' id='the_file' type="file" required="required" accept=".lsq" /> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label" for='the_file'><?php eT("Destination question group:"); ?> </label> <div class="col-sm-3"> <select name='gid' id='gid' class="form-control"> <?php echo getGroupList3($groupid, $surveyid);
echo htmlspecialchars($editfile); ?> ' /> <input type='hidden' name='action' value='templatefiledelete' /> </form> </div> <div style='margin-top:1em;'> <?php if (Permission::model()->hasGlobalPermission('templates', 'update')) { ?> <?php echo CHtml::form(array('admin/templates/sa/uploadfile'), 'post', array('id' => 'importtemplatefile', 'name' => 'importtemplatefile', 'enctype' => 'multipart/form-data')); ?> <?php printf(gT("Upload a file (maximum size: %d MB):"), getMaximumFileUploadSize() / 1024 / 1024); ?> <br> <input name='upload_file' id="upload_file" type="file" required="required"/> <input type='submit' value='<?php eT("Upload"); ?> ' class='btn btn-default' <?php if (!is_template_editable($templatename)) { ?> disabled='disabled' <?php } ?> />
/** * Show the drag-n-drop form for CSV attributes */ public function attributeMapCSV() { if (!Permission::model()->hasGlobalPermission('participantpanel', 'import')) { die('No permission'); } if ($_FILES['the_file']['name'] == '') { Yii::app()->setFlashMessage(gT('Please select a file to import!'), 'error'); Yii::app()->getController()->redirect(array('admin/participants/sa/importCSV')); } $sRandomFileName = randomChars(20); $sFilePath = Yii::app()->getConfig('tempdir') . DIRECTORY_SEPARATOR . $sRandomFileName; $aPathinfo = pathinfo($_FILES['the_file']['name']); $sExtension = $aPathinfo['extension']; if ($_FILES['the_file']['error'] == 1 || $_FILES['the_file']['error'] == 2) { Yii::app()->setFlashMessage(sprintf(gT("Sorry, this file is too large. Only files up to %01.2f MB are allowed."), getMaximumFileUploadSize() / 1024 / 1024), 'error'); Yii::app()->getController()->redirect(array('admin/participants/sa/importCSV')); exit; } elseif (strtolower($sExtension) == 'csv') { $bMoveFileResult = @move_uploaded_file($_FILES['the_file']['tmp_name'], $sFilePath); $filterblankemails = Yii::app()->request->getPost('filterbea'); } else { Yii::app()->setFlashMessage(gT("This is not a .csv file."), 'error'); Yii::app()->getController()->redirect(array('admin/participants/sa/importCSV')); exit; } if (!$bMoveFileResult) { Yii::app()->setFlashMessage(sprintf(gT("An error occurred uploading your file. This may be caused by incorrect permissions in your %s folder."), Yii::app()->getConfig('tempdir')), 'error'); Yii::app()->getController()->redirect(array('admin/participants/sa/importCSV')); exit; } else { $regularfields = array('firstname', 'participant_id', 'lastname', 'email', 'language', 'blacklisted', 'owner_uid'); $oCSVFile = fopen($sFilePath, 'r'); $aFirstLine = fgets($oCSVFile); rewind($oCSVFile); $sSeparator = Yii::app()->request->getPost('separatorused'); if ($sSeparator == 'auto') { $aCount = array(); $aCount[','] = substr_count($aFirstLine, ','); $aCount[';'] = substr_count($aFirstLine, ';'); $aCount['|'] = substr_count($aFirstLine, '|'); $aResult = array_keys($aCount, max($aCount)); $sSeparator = $aResult[0]; } $firstline = fgetcsv($oCSVFile, 1000, $sSeparator[0]); $selectedcsvfields = array(); $fieldlist = array(); foreach ($firstline as $key => $value) { $testvalue = preg_replace('/[^(\\x20-\\x7F)]*/', '', $value); //Remove invalid characters from string if (!in_array(strtolower($testvalue), $regularfields)) { array_push($selectedcsvfields, $value); } $fieldlist[] = $value; } $iLineCount = count(array_filter(array_filter(file($sFilePath), 'trim'))); $attributes = ParticipantAttributeName::model()->model()->getCPDBAttributes(); $aData = array('attributes' => $attributes, 'firstline' => $selectedcsvfields, 'fullfilepath' => $sRandomFileName, 'linecount' => $iLineCount - 1, 'filterbea' => $filterblankemails, 'participant_id_exists' => in_array('participant_id', $fieldlist)); App()->getClientScript()->registerPackage('qTip2'); App()->getClientScript()->registerPackage('jquery-nestedSortable'); $this->registerScriptFile('ADMIN_SCRIPT_PATH', 'attributeMapCSV.js'); $sAttributeMapJS = "var copyUrl = '" . App()->createUrl("admin/participants/sa/uploadCSV") . "';\n" . "var displayParticipants = '" . App()->createUrl("admin/participants/sa/displayParticipants") . "';\n" . "var mapCSVcancelled = '" . App()->createUrl("admin/participants/sa/mapCSVcancelled") . "';\n" . "var characterset = '" . sanitize_paranoid_string($_POST['characterset']) . "';\n" . "var okBtn = '" . gT("OK") . "';\n" . "var processed = '" . gT("Summary") . "';\n" . "var summary = '" . gT("Upload summary") . "';\n" . "var notPairedErrorTxt = '" . gT("You have to pair this field with an existing attribute.") . "';\n" . "var onlyOnePairedErrorTxt = '" . gT("Only one CSV attribute is mapped with central attribute.") . "';\n" . "var cannotAcceptErrorTxt='" . gT("This list cannot accept token attributes.") . "';\n" . "var separator = '" . sanitize_paranoid_string($_POST['separatorused']) . "';\n" . "var thefilepath = '" . $sRandomFileName . "';\n" . "var filterblankemails = '" . sanitize_paranoid_string($filterblankemails) . "';\n"; App()->getClientScript()->registerScript("sAttributeMapJS", $sAttributeMapJS, CClientScript::POS_BEGIN); $this->_renderWrappedTemplate('participants', 'attributeMapCSV', $aData); } }
function run($actionID) { $surveyid = Yii::app()->session['LEMsid']; $oSurvey = Survey::model()->findByPk($surveyid); if (!$oSurvey) { throw new CHttpException(400); } // See for debug > 1 $sLanguage = isset(Yii::app()->session['survey_' . $surveyid]['s_lang']) ? Yii::app()->session['survey_' . $surveyid]['s_lang'] : ""; $uploaddir = Yii::app()->getConfig("uploaddir"); $tempdir = Yii::app()->getConfig("tempdir"); Yii::app()->loadHelper("database"); // Fill needed var $sFileGetContent = Yii::app()->request->getParam('filegetcontents', ''); // The file to view fu_ or fu_tmp $bDelete = Yii::app()->request->getParam('delete'); $sFieldName = Yii::app()->request->getParam('fieldname'); $sFileName = Yii::app()->request->getParam('filename', ''); // The file to delete fu_ or fu_tmp $sOriginalFileName = Yii::app()->request->getParam('name', ''); // Used for javascript return only $sMode = Yii::app()->request->getParam('mode'); $sPreview = Yii::app()->request->getParam('preview', 0); // Validate and filter and throw error if problems // Using 'futmp_'.randomChars(15).'_'.$pathinfo['extension'] for filename, then remove all other characters $sFileGetContentFiltered = preg_replace('/[^a-zA-Z0-9_]/', '', $sFileGetContent); $sFileNameFiltered = preg_replace('/[^a-zA-Z0-9_]/', '', $sFileName); $sFieldNameFiltered = preg_replace('/[^X0-9]/', '', $sFieldName); if ($sFileGetContent != $sFileGetContentFiltered || $sFileName != $sFileNameFiltered || $sFieldName != $sFieldNameFiltered) { // If one seems to be a hack: Bad request throw new CHttpException(400); // See for debug > 1 } if ($sFileGetContent) { if (substr($sFileGetContent, 0, 6) == 'futmp_') { $sFileDir = $tempdir . '/upload/'; } elseif (substr($sFileGetContent, 0, 3) == 'fu_') { // Need to validate $_SESSION['srid'], and this file is from this srid ! $sFileDir = "{$uploaddir}/surveys/{$surveyid}/files/"; } else { throw new CHttpException(400); // See for debug > 1 } if (is_file($sFileDir . $sFileGetContent)) { header('Content-Type: ' . CFileHelper::getMimeType($sFileDir . $sFileGetContent)); readfile($sFileDir . $sFileGetContent); Yii::app()->end(); } else { Yii::app()->end(); } } elseif ($bDelete) { if (substr($sFileName, 0, 6) == 'futmp_') { $sFileDir = $tempdir . '/upload/'; } elseif (substr($sFileName, 0, 3) == 'fu_') { // Need to validate $_SESSION['srid'], and this file is from this srid ! $sFileDir = "{$uploaddir}/surveys/{$surveyid}/files/"; } else { throw new CHttpException(400); // See for debug > 1 } if (isset($_SESSION[$sFieldName])) { // We already have $sFieldName ? $sJSON = $_SESSION[$sFieldName]; $aFiles = json_decode(stripslashes($sJSON), true); if (substr($sFileName, 0, 3) == 'fu_') { $iFileIndex = 0; $found = false; foreach ($aFiles as $aFile) { if ($aFile['filename'] == $sFileName) { $found = true; break; } $iFileIndex++; } if ($found == true) { unset($aFiles[$iFileIndex]); } $_SESSION[$sFieldName] = ls_json_encode($aFiles); } } //var_dump($sFileDir.$sFilename); // Return some json to do a beautiful text if (@unlink($sFileDir . $sFileName)) { echo sprintf(gT('File %s deleted'), $sOriginalFileName); } else { echo gT('Oops, There was an error deleting the file'); } Yii::app()->end(); } if ($sMode == "upload") { $sTempUploadDir = $tempdir . '/upload/'; // Check if exists and is writable if (!file_exists($sTempUploadDir)) { // Try to create mkdir($sTempUploadDir); } $filename = $_FILES['uploadfile']['name']; // Do we filter file name ? It's used on displaying only , but not save like that. //$filename = sanitize_filename($_FILES['uploadfile']['name']);// This remove all non alpha numeric characters and replaced by _ . Leave only one dot . $size = 0.001 * $_FILES['uploadfile']['size']; $preview = Yii::app()->session['preview']; $aFieldMap = createFieldMap($surveyid, 'short', false, false, $sLanguage); if (!isset($aFieldMap[$sFieldName])) { throw new CHttpException(400); // See for debug > 1 } $aAttributes = getQuestionAttributeValues($aFieldMap[$sFieldName]['qid']); $maxfilesize = (int) $aAttributes['max_filesize']; $valid_extensions_array = explode(",", $aAttributes['allowed_filetypes']); $valid_extensions_array = array_map('trim', $valid_extensions_array); $pathinfo = pathinfo($_FILES['uploadfile']['name']); $ext = strtolower($pathinfo['extension']); $randfilename = 'futmp_' . randomChars(15) . '_' . $pathinfo['extension']; $randfileloc = $sTempUploadDir . $randfilename; // check to see that this file type is allowed // it is also checked at the client side, but jst double checking if (!in_array($ext, $valid_extensions_array)) { $return = array("success" => false, "msg" => sprintf(gT("Sorry, this file extension (%s) is not allowed!"), $ext)); //header('Content-Type: application/json'); echo ls_json_encode($return); Yii::app()->end(); } // If this is just a preview, don't save the file if ($preview) { if ($size > $maxfilesize) { $return = array("success" => false, "msg" => sprintf(gT("Sorry, this file is too large. Only files upto %s KB are allowed."), $maxfilesize)); //header('Content-Type: application/json'); echo ls_json_encode($return); Yii::app()->end(); } else { if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $randfileloc)) { $return = array("success" => true, "file_index" => $filecount, "size" => $size, "name" => rawurlencode(basename($filename)), "ext" => $ext, "filename" => $randfilename, "msg" => gT("The file has been successfuly uploaded.")); // TODO : unlink this file since this is just a preview. But we can do it only if it's not needed, and still needed to have the file content // Maybe use a javascript 'onunload' on preview question/group // unlink($randfileloc) //header('Content-Type: application/json'); echo ls_json_encode($return); Yii::app()->end(); } } } else { // if everything went fine and the file was uploaded successfuly, // send the file related info back to the client $iFileUploadTotalSpaceMB = Yii::app()->getConfig("iFileUploadTotalSpaceMB"); if ($size > $maxfilesize) { $return = array("success" => false, "msg" => sprintf(gT("Sorry, this file is too large. Only files up to %s KB are allowed.", 'unescaped'), $maxfilesize)); //header('Content-Type: application/json'); echo ls_json_encode($return); Yii::app()->end(); } elseif ($iFileUploadTotalSpaceMB > 0 && calculateTotalFileUploadUsage() + $size / 1024 / 1024 > $iFileUploadTotalSpaceMB) { $return = array("success" => false, "msg" => gT("We are sorry but there was a system error and your file was not saved. An email has been dispatched to notify the survey administrator.", 'unescaped')); //header('Content-Type: application/json'); echo ls_json_encode($return); Yii::app()->end(); } elseif (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $randfileloc)) { $return = array("success" => true, "size" => $size, "name" => rawurlencode(basename($filename)), "ext" => $ext, "filename" => $randfilename, "msg" => gT("The file has been successfuly uploaded.")); //header('Content-Type: application/json'); echo ls_json_encode($return); Yii::app()->end(); } else { // check for upload error if ($_FILES['uploadfile']['error'] > 2) { $return = array("success" => false, "msg" => gT("Sorry, there was an error uploading your file")); //header('Content-Type: application/json'); echo ls_json_encode($return); Yii::app()->end(); } else { if ($_FILES['uploadfile']['error'] == 1 || $_FILES['uploadfile']['error'] == 2 || $size > $maxfilesize) { $return = array("success" => false, "msg" => sprintf(gT("Sorry, this file is too large. Only files upto %s KB are allowed."), $maxfilesize)); //header('Content-Type: application/json'); echo ls_json_encode($return); Yii::app()->end(); } else { $return = array("success" => false, "msg" => gT("Unknown error")); //header('Content-Type: application/json'); echo ls_json_encode($return); Yii::app()->end(); } } } } return; } $meta = ''; App()->getClientScript()->registerPackage('jqueryui'); App()->getClientScript()->registerPackage('jquery-superfish'); $sNeededScriptVar = ' var uploadurl = "' . $this->createUrl('/uploader/index/mode/upload/') . '"; var imageurl = "' . Yii::app()->getConfig('imageurl') . '/"; var surveyid = "' . $surveyid . '"; var fieldname = "' . $sFieldName . '"; var questgrppreview = ' . $sPreview . '; csrfToken = ' . ls_json_encode(Yii::app()->request->csrfToken) . '; showpopups="' . Yii::app()->getConfig("showpopups") . '"; '; $sLangScriptVar = "\n uploadLang = {\n titleFld: '" . gT('Title', 'js') . "',\n commentFld: '" . gT('Comment', 'js') . "',\n errorNoMoreFiles: '" . gT('Sorry, no more files can be uploaded!', 'js') . "',\n errorOnlyAllowed: '" . gT('Sorry, only %s files can be uploaded for this question!', 'js') . "',\n uploading: '" . gT('Uploading', 'js') . "',\n selectfile: '" . gT('Select file', 'js') . "',\n errorNeedMore: '" . gT('Please upload %s more file(s).', 'js') . "',\n errorMoreAllowed: '" . gT('If you wish, you may upload %s more file(s); else you may return back to survey.', 'js') . "',\n errorMaxReached: '" . gT('The maximum number of files has been uploaded. You may return back to survey.', 'js') . "',\n errorTooMuch: '" . gT('The maximum number of files has been uploaded. You may return back to survey.', 'js') . "',\n errorNeedMoreConfirm: '" . gT("You need to upload %s more files for this question.\nAre you sure you want to exit?", 'js') . "',\n deleteFile : '" . gt('Delete', 'js') . "',\n editFile : '" . gt('Edit', 'js') . "',\n };\n "; $aSurveyInfo = getSurveyInfo($surveyid, $sLanguage); $oEvent = new PluginEvent('beforeSurveyPage'); $oEvent->set('surveyId', $surveyid); App()->getPluginManager()->dispatchEvent($oEvent); if (!is_null($oEvent->get('template'))) { $aSurveyInfo['templatedir'] = $event->get('template'); } $sTemplateDir = getTemplatePath($aSurveyInfo['template']); $sTemplateUrl = getTemplateURL($aSurveyInfo['template']) . "/"; App()->clientScript->registerScript('sNeededScriptVar', $sNeededScriptVar, CClientScript::POS_HEAD); App()->clientScript->registerScript('sLangScriptVar', $sLangScriptVar, CClientScript::POS_HEAD); App()->getClientScript()->registerScriptFile(Yii::app()->getConfig("generalscripts") . 'ajaxupload.js'); App()->getClientScript()->registerScriptFile(Yii::app()->getConfig("generalscripts") . 'uploader.js'); App()->getClientScript()->registerScriptFile("{$sTemplateUrl}template.js"); App()->clientScript->registerCssFile(Yii::app()->getConfig("publicstyleurl") . "uploader.css"); App()->getClientScript()->registerCssFile(Yii::app()->getConfig('publicstyleurl') . "uploader-files.css"); if (file_exists($sTemplateDir . DIRECTORY_SEPARATOR . 'jquery-ui-custom.css')) { Yii::app()->getClientScript()->registerCssFile("{$sTemplateUrl}jquery-ui-custom.css"); } elseif (file_exists($sTemplateDir . DIRECTORY_SEPARATOR . 'jquery-ui.css')) { Yii::app()->getClientScript()->registerCssFile("{$sTemplateUrl}jquery-ui.css"); } else { Yii::app()->getClientScript()->registerCssFile(Yii::app()->getConfig('publicstyleurl') . "jquery-ui.css"); } App()->clientScript->registerCssFile("{$sTemplateUrl}template.css"); $header = getHeader($meta); echo $header; $fn = $sFieldName; $qid = (int) Yii::app()->request->getParam('qid'); $minfiles = (int) Yii::app()->request->getParam('minfiles'); $maxfiles = (int) Yii::app()->request->getParam('maxfiles'); $qidattributes = getQuestionAttributeValues($qid); $qidattributes['max_filesize'] = floor(min($qidattributes['max_filesize'] * 1024, getMaximumFileUploadSize()) / 1024); $body = '</head><body class="uploader"> <div id="notice"></div> <input type="hidden" id="ia" value="' . $fn . '" /> <input type="hidden" id="' . $fn . '_minfiles" value="' . $minfiles . '" /> <input type="hidden" id="' . $fn . '_maxfiles" value="' . $maxfiles . '" /> <input type="hidden" id="' . $fn . '_maxfilesize" value="' . $qidattributes['max_filesize'] . '" /> <input type="hidden" id="' . $fn . '_allowed_filetypes" value="' . $qidattributes['allowed_filetypes'] . '" /> <input type="hidden" id="preview" value="' . Yii::app()->session['preview'] . '" /> <input type="hidden" id="' . $fn . '_show_comment" value="' . $qidattributes['show_comment'] . '" /> <input type="hidden" id="' . $fn . '_show_title" value="' . $qidattributes['show_title'] . '" /> <input type="hidden" id="' . $fn . '_licount" value="0" /> <input type="hidden" id="' . $fn . '_filecount" value="0" /> <!-- The upload button --> <div class="upload-div"> <button id="button1" class="button upload-button" type="button" >' . gT("Select file") . '</button> </div> <p class="uploadmsg">' . sprintf(gT("You can upload %s under %s KB each."), $qidattributes['allowed_filetypes'], $qidattributes['max_filesize']) . '</p> <div class="uploadstatus" id="uploadstatus"></div> <!-- The list of uploaded files --> </body> </html>'; App()->getClientScript()->render($body); echo $body; }
/** * import from csv */ public function import($iSurveyId) { $aData = array(); $iSurveyId = (int) $iSurveyId; if (!Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'import')) { Yii::app()->session['flashmessage'] = gT("You do not have permission to access this page."); $this->getController()->redirect(array("/admin/survey/sa/view/surveyid/{$iSurveyId}")); } // CHECK TO SEE IF A TOKEN TABLE EXISTS FOR THIS SURVEY $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}'); if (!$bTokenExists) { self::_newtokentable($iSurveyId); } $surveyinfo = Survey::model()->findByPk($iSurveyId)->surveyinfo; $aData['sidemenu']['state'] = false; $aData["surveyinfo"] = $surveyinfo; $aData['title_bar']['title'] = $surveyinfo['surveyls_title'] . "(" . gT("ID") . ":" . $iSurveyId . ")"; $aData['sidemenu']["token_menu"] = TRUE; $aData['token_bar']['closebutton']['url'] = 'admin/tokens/sa/index/surveyid/' . $iSurveyId; $this->registerScriptFile('ADMIN_SCRIPT_PATH', 'tokensimport.js'); $aEncodings = aEncodingsArray(); if (Yii::app()->request->isPostRequest) { $sUploadCharset = Yii::app()->request->getPost('csvcharset'); if (!array_key_exists($sUploadCharset, $aEncodings)) { $sUploadCharset = 'auto'; } $bFilterDuplicateToken = Yii::app()->request->getPost('filterduplicatetoken'); $bFilterBlankEmail = Yii::app()->request->getPost('filterblankemail'); $bAllowInvalidEmail = Yii::app()->request->getPost('allowinvalidemail'); $aAttrFieldNames = getAttributeFieldNames($iSurveyId); $aDuplicateList = array(); $aInvalidTokenList = array(); $aInvalidEmailList = array(); $aInvalidFormatList = array(); $aModelErrorList = array(); $aFirstLine = array(); $oFile = CUploadedFile::getInstanceByName("the_file"); $sPath = Yii::app()->getConfig('tempdir'); $sFileName = $sPath . '/' . randomChars(20); if ($_FILES['the_file']['error'] == 1 || $_FILES['the_file']['error'] == 2) { Yii::app()->setFlashMessage(sprintf(gT("Sorry, this file is too large. Only files up to %01.2f MB are allowed."), getMaximumFileUploadSize() / 1024 / 1024), 'error'); } elseif (strtolower($oFile->getExtensionName()) != 'csv') { Yii::app()->setFlashMessage(gT("Only CSV files are allowed."), 'error'); } elseif (!@$oFile->saveAs($sFileName)) { Yii::app()->setFlashMessage(sprintf(gT("Upload file not found. Check your permissions and path (%s) for the upload directory"), $sPath), 'error'); } else { $iRecordImported = 0; $iRecordCount = 0; $iRecordOk = 0; $iInvalidEmailCount = 0; // Count invalid email imported // This allows to read file with MAC line endings too @ini_set('auto_detect_line_endings', true); // open it and trim the ednings $aTokenListArray = file($sFileName); $sBaseLanguage = Survey::model()->findByPk($iSurveyId)->language; if (!Yii::app()->request->getPost('filterduplicatefields') || Yii::app()->request->getPost('filterduplicatefields') && count(Yii::app()->request->getPost('filterduplicatefields')) == 0) { $aFilterDuplicateFields = array('firstname', 'lastname', 'email'); } else { $aFilterDuplicateFields = Yii::app()->request->getPost('filterduplicatefields'); } $sSeparator = Yii::app()->request->getPost('separator'); $aMissingAttrFieldName = $aInvalideAttrFieldName = array(); foreach ($aTokenListArray as $buffer) { $buffer = @mb_convert_encoding($buffer, "UTF-8", $sUploadCharset); if ($iRecordCount == 0) { // Parse first line (header) from CSV $buffer = removeBOM($buffer); // We alow all field except tid because this one is really not needed. $aAllowedFieldNames = Token::model($iSurveyId)->tableSchema->getColumnNames(); if (($kTid = array_search('tid', $aAllowedFieldNames)) !== false) { unset($aAllowedFieldNames[$kTid]); } // Some header don't have same column name $aReplacedFields = array('invited' => 'sent', 'reminded' => 'remindersent'); switch ($sSeparator) { case 'comma': $sSeparator = ','; break; case 'semicolon': $sSeparator = ';'; break; default: $comma = substr_count($buffer, ','); $semicolon = substr_count($buffer, ';'); if ($semicolon > $comma) { $sSeparator = ';'; } else { $sSeparator = ','; } } $aFirstLine = str_getcsv($buffer, $sSeparator, '"'); $aFirstLine = array_map('trim', $aFirstLine); $aIgnoredColumns = array(); // Now check the first line for invalid fields foreach ($aFirstLine as $index => $sFieldname) { $aFirstLine[$index] = preg_replace("/(.*) <[^,]*>\$/", "\$1", $sFieldname); $sFieldname = $aFirstLine[$index]; if (!in_array($sFieldname, $aAllowedFieldNames)) { $aIgnoredColumns[] = $sFieldname; } if (array_key_exists($sFieldname, $aReplacedFields)) { $aFirstLine[$index] = $aReplacedFields[$sFieldname]; } // Attribute not in list if (strpos($aFirstLine[$index], 'attribute_') !== false and !in_array($aFirstLine[$index], $aAttrFieldNames) and Yii::app()->request->getPost('showwarningtoken')) { $aInvalideAttrFieldName[] = $aFirstLine[$index]; } } //compare attributes with source csv if (Yii::app()->request->getPost('showwarningtoken')) { $aMissingAttrFieldName = array_diff($aAttrFieldNames, $aFirstLine); // get list of mandatory attributes $allAttrFieldNames = GetParticipantAttributes($iSurveyId); //if it isn't mandantory field we don't need to show in warning if (!empty($aAttrFieldNames)) { if (!empty($aMissingAttrFieldName)) { foreach ($aMissingAttrFieldName as $index => $AttrFieldName) { if (isset($allAttrFieldNames[$AttrFieldName]) and strtolower($allAttrFieldNames[$AttrFieldName]["mandatory"]) != "y") { unset($aMissingAttrFieldName[$index]); } } } if (isset($aInvalideAttrFieldName) and !empty($aInvalideAttrFieldName)) { foreach ($aInvalideAttrFieldName as $index => $AttrFieldName) { if (isset($allAttrFieldNames[$AttrFieldName]) and strtolower($allAttrFieldNames[$AttrFieldName]["mandatory"]) != "y") { unset($aInvalideAttrFieldName[$index]); } } } } } } else { $line = str_getcsv($buffer, $sSeparator, '"'); if (count($aFirstLine) != count($line)) { $aInvalidFormatList[] = sprintf(gT("Line %s"), $iRecordCount); $iRecordCount++; continue; } $aWriteArray = array_combine($aFirstLine, $line); //kick out ignored columns foreach ($aIgnoredColumns as $column) { unset($aWriteArray[$column]); } $bDuplicateFound = false; $bInvalidEmail = false; $bInvalidToken = false; $aWriteArray['email'] = isset($aWriteArray['email']) ? trim($aWriteArray['email']) : ""; $aWriteArray['firstname'] = isset($aWriteArray['firstname']) ? $aWriteArray['firstname'] : ""; $aWriteArray['lastname'] = isset($aWriteArray['lastname']) ? $aWriteArray['lastname'] : ""; $aWriteArray['language'] = isset($aWriteArray['language']) ? $aWriteArray['language'] : $sBaseLanguage; if ($bFilterDuplicateToken) { $aParams = array(); $oCriteria = new CDbCriteria(); $oCriteria->condition = ""; foreach ($aFilterDuplicateFields as $field) { if (isset($aWriteArray[$field])) { $oCriteria->addCondition("{$field} = :{$field}"); $aParams[":{$field}"] = $aWriteArray[$field]; } } if (!empty($aParams)) { $oCriteria->params = $aParams; } $dupresult = TokenDynamic::model($iSurveyId)->count($oCriteria); if ($dupresult > 0) { $bDuplicateFound = true; $aDuplicateList[] = sprintf(gT("Line %s : %s %s (%s)"), $iRecordCount, $aWriteArray['firstname'], $aWriteArray['lastname'], $aWriteArray['email']); } } //treat blank emails if (!$bDuplicateFound && $bFilterBlankEmail && $aWriteArray['email'] == '') { $bInvalidEmail = true; $aInvalidEmailList[] = sprintf(gT("Line %s : %s %s"), $iRecordCount, CHtml::encode($aWriteArray['firstname']), CHtml::encode($aWriteArray['lastname'])); } if (!$bDuplicateFound && $aWriteArray['email'] != '') { $aEmailAddresses = preg_split("/(,|;)/", $aWriteArray['email']); foreach ($aEmailAddresses as $sEmailaddress) { if (!validateEmailAddress($sEmailaddress)) { if ($bAllowInvalidEmail) { $iInvalidEmailCount++; if (empty($aWriteArray['emailstatus']) || strtoupper($aWriteArray['emailstatus'] == "OK")) { $aWriteArray['emailstatus'] = "invalid"; } } else { $bInvalidEmail = true; $aInvalidEmailList[] = sprintf(gT("Line %s : %s %s (%s)"), $iRecordCount, CHtml::encode($aWriteArray['firstname']), CHtml::encode($aWriteArray['lastname']), CHtml::encode($aWriteArray['email'])); } } } } if (!$bDuplicateFound && !$bInvalidEmail && isset($aWriteArray['token']) && trim($aWriteArray['token']) != '') { if (trim($aWriteArray['token']) != sanitize_token($aWriteArray['token'])) { $aInvalidTokenList[] = sprintf(gT("Line %s : %s %s (%s) - token : %s"), $iRecordCount, CHtml::encode($aWriteArray['firstname']), CHtml::encode($aWriteArray['lastname']), CHtml::encode($aWriteArray['email']), CHtml::encode($aWriteArray['token'])); $bInvalidToken = true; } // We allways search for duplicate token (it's in model. Allow to reset or update token ? if (Token::model($iSurveyId)->count("token=:token", array(":token" => $aWriteArray['token']))) { $bDuplicateFound = true; $aDuplicateList[] = sprintf(gT("Line %s : %s %s (%s) - token : %s"), $iRecordCount, CHtml::encode($aWriteArray['firstname']), CHtml::encode($aWriteArray['lastname']), CHtml::encode($aWriteArray['email']), CHtml::encode($aWriteArray['token'])); } } if (!$bDuplicateFound && !$bInvalidEmail && !$bInvalidToken) { // unset all empty value foreach ($aWriteArray as $key => $value) { if ($aWriteArray[$key] == "") { unset($aWriteArray[$key]); } if (substr($value, 0, 1) == '"' && substr($value, -1) == '"') { // Fix CSV quote $value = substr($value, 1, -1); } } // Some default value : to be moved to Token model rules in future release ? // But think we have to accept invalid email etc ... then use specific scenario $oToken = Token::create($iSurveyId); if ($bAllowInvalidEmail) { $oToken->scenario = 'allowinvalidemail'; } foreach ($aWriteArray as $key => $value) { $oToken->{$key} = $value; } if (!$oToken->save()) { $errors = $oToken->getErrors(); $aModelErrorList[] = sprintf(gT("Line %s : %s"), $iRecordCount, print_r($errors, true)); } else { $iRecordImported++; } } $iRecordOk++; } $iRecordCount++; } $iRecordCount = $iRecordCount - 1; unlink($sFileName); $aData['aTokenListArray'] = $aTokenListArray; // Big array in memory, just for success ? $aData['iRecordImported'] = $iRecordImported; $aData['iRecordOk'] = $iRecordOk; $aData['iRecordCount'] = $iRecordCount; $aData['aFirstLine'] = $aFirstLine; // Seem not needed $aData['aDuplicateList'] = $aDuplicateList; $aData['aInvalidTokenList'] = $aInvalidTokenList; $aData['aInvalidFormatList'] = $aInvalidFormatList; $aData['aInvalidEmailList'] = $aInvalidEmailList; $aData['aModelErrorList'] = $aModelErrorList; $aData['iInvalidEmailCount'] = $iInvalidEmailCount; $aData['thissurvey'] = getSurveyInfo($iSurveyId); $aData['iSurveyId'] = $aData['surveyid'] = $iSurveyId; $aData['aInvalideAttrFieldName'] = $aInvalideAttrFieldName; $aData['aMissingAttrFieldName'] = $aMissingAttrFieldName; $this->_renderWrappedTemplate('token', array('csvimportresult'), $aData); Yii::app()->end(); } } // If there are error with file : show the form $aData['aEncodings'] = $aEncodings; asort($aData['aEncodings']); $aData['iSurveyId'] = $iSurveyId; $aData['thissurvey'] = getSurveyInfo($iSurveyId); $aData['surveyid'] = $iSurveyId; $aTokenTableFields = getTokenFieldsAndNames($iSurveyId); unset($aTokenTableFields['sent']); unset($aTokenTableFields['remindersent']); unset($aTokenTableFields['remindercount']); unset($aTokenTableFields['usesleft']); foreach ($aTokenTableFields as $sKey => $sValue) { if ($sValue['description'] != $sKey) { $sValue['description'] .= ' - ' . $sKey; } $aNewTokenTableFields[$sKey] = $sValue['description']; } $aData['aTokenTableFields'] = $aNewTokenTableFields; // Get default character set from global settings $thischaracterset = getGlobalSetting('characterset'); // If no encoding was set yet, use the old "auto" default if ($thischaracterset == "") { $thischaracterset = "auto"; } $aData['thischaracterset'] = $thischaracterset; $this->_renderWrappedTemplate('token', array('csvupload'), $aData); }
</form> </div> <!-- Import --> <?php if ($action == "newlabelset" && Permission::model()->hasGlobalPermission('labelsets', 'import')) { ?> <div id='neweditlblset1' class="tab-pane fade in" > <?php echo CHtml::form(array("admin/labels/sa/import"), 'post', array('enctype' => 'multipart/form-data', 'class' => 'form-horizontal', 'id' => 'importlabels', 'name' => "importlabels")); ?> <div class="form-group"> <label class="col-sm-3 control-label" for='the_file'> <?php echo gT("Select label set file (*.lsl):") . '<br>' . sprintf(gT("(Maximum file size: %01.2f MB)"), getMaximumFileUploadSize() / 1024 / 1024); ?> </label> <input id='the_file' name='the_file' type='file'/> </div> <div class="form-group"> <label class="col-sm-3 control-label" for='checkforduplicates'> <?php eT("Don't import if label set already exists:"); ?> </label> <?php $this->widget('yiiwheels.widgets.switch.WhSwitch', array('name' => 'checkforduplicates', 'id' => 'checkforduplicates', 'value' => 1, 'onLabel' => gT('On'), 'offLabel' => gT('Off'))); ?> </div>
/** * Function responsible to import a question. * * @access public * @return void */ public function import() { $action = returnGlobal('action'); $surveyid = $iSurveyID = returnGlobal('sid'); $gid = returnGlobal('gid'); $aViewUrls = array(); $aData['display']['menu_bars']['surveysummary'] = 'viewquestion'; $aData['display']['menu_bars']['gid_action'] = 'viewgroup'; if ($action == 'importquestion') { $sFullFilepath = Yii::app()->getConfig('tempdir') . DIRECTORY_SEPARATOR . randomChars(20); $sExtension = pathinfo($_FILES['the_file']['name'], PATHINFO_EXTENSION); $fatalerror = ''; if ($_FILES['the_file']['error'] == 1 || $_FILES['the_file']['error'] == 2) { $fatalerror = sprintf(gT("Sorry, this file is too large. Only files up to %01.2f MB are allowed."), getMaximumFileUploadSize() / 1024 / 1024) . '<br>'; } elseif (!@move_uploaded_file($_FILES['the_file']['tmp_name'], $sFullFilepath)) { $fatalerror = sprintf(gT("An error occurred uploading your file. This may be caused by incorrect permissions in your %s folder."), Yii::app()->getConfig('tempdir')) . '<br>'; } // validate that we have a SID and GID if (!$surveyid) { $fatalerror .= gT("No SID (Survey) has been provided. Cannot import question."); } if (!$gid) { $fatalerror .= gT("No GID (Group) has been provided. Cannot import question"); } if ($fatalerror != '') { unlink($sFullFilepath); $message = '<p>' . $fatalerror . '</p> <a class="btn btn-default btn-lg" href="' . $this->getController()->createUrl('admin/survey/sa/listquestions/surveyid/') . '/' . $surveyid . '">' . gT("Return to question list") . '</a></p>'; $this->_renderWrappedTemplate('super', 'messagebox', array('title' => gT('Error'), 'message' => $message)); die; } // IF WE GOT THIS FAR, THEN THE FILE HAS BEEN UPLOADED SUCCESFULLY Yii::app()->loadHelper('admin/import'); if (strtolower($sExtension) == 'lsq') { $aImportResults = XMLImportQuestion($sFullFilepath, $surveyid, $gid); } else { $this->getController()->error(gT('Unknown file extension')); } fixLanguageConsistency($surveyid); if (isset($aImportResults['fatalerror'])) { //echo htmlentities($aImportResults['fatalerror']); die(); $message = $aImportResults['fatalerror']; $message .= '<p> <a class="btn btn-default btn-lg" href="' . $this->getController()->createUrl('admin/survey/sa/listquestions/surveyid/') . '/' . $surveyid . '">' . gT("Return to question list") . '</a></p>'; $this->_renderWrappedTemplate('super', 'messagebox', array('title' => gT('Error'), 'message' => $message)); die; } unlink($sFullFilepath); $aData['aImportResults'] = $aImportResults; $aData['surveyid'] = $surveyid; $aData['gid'] = $gid; $aData['sExtension'] = $sExtension; $aViewUrls[] = 'import_view'; } ///// $aData['sidemenu']['state'] = false; $aData['surveyid'] = $iSurveyID; $surveyinfo = Survey::model()->findByPk($iSurveyID)->surveyinfo; $aData['title_bar']['title'] = $surveyinfo['surveyls_title'] . "(" . gT("ID") . ":" . $iSurveyID . ")"; $this->_renderWrappedTemplate('survey/Question', $aViewUrls, $aData); }
/** * Function to import a label set * * @access public * @return void */ public function import() { if (!Permission::model()->hasGlobalPermission('labelsets', 'import')) { Yii::app()->session['flashmessage'] = gT('Access denied!'); $this->getController()->redirect(App()->createUrl("/admin")); } $action = returnGlobal('action'); $aViewUrls = array(); if ($action == 'importlabels') { Yii::app()->loadHelper('admin/import'); $sFullFilepath = Yii::app()->getConfig('tempdir') . DIRECTORY_SEPARATOR . randomChars(20); $aPathInfo = pathinfo($_FILES['the_file']['name']); $sExtension = !empty($aPathInfo['extension']) ? $aPathInfo['extension'] : ''; if ($_FILES['the_file']['error'] == 1 || $_FILES['the_file']['error'] == 2) { Yii::app()->setFlashMessage(sprintf(gT("Sorry, this file is too large. Only files up to %01.2f MB are allowed."), getMaximumFileUploadSize() / 1024 / 1024), 'error'); $this->getController()->redirect(App()->createUrl("/admin/labels/sa/newlabelset")); } if (!@move_uploaded_file($_FILES['the_file']['tmp_name'], $sFullFilepath)) { Yii::app()->setFlashMessage(gT("An error occurred uploading your file. This may be caused by incorrect permissions for the application /tmp folder."), 'error'); $this->getController()->redirect(App()->createUrl("/admin/labels/sa/newlabelset")); } $options['checkforduplicates'] = 'off'; if ($_POST['checkforduplicates'] == 1) { $options['checkforduplicates'] = 'on'; } if (strtolower($sExtension) == 'lsl') { $aImportResults = XMLImportLabelsets($sFullFilepath, $options); } else { $this->getController()->error(gT("Uploaded label set file needs to have an .lsl extension.")); } unlink($sFullFilepath); $aViewUrls['import_view'][] = array('aImportResults' => $aImportResults); } $this->_renderWrappedTemplate('labels', $aViewUrls); }
/** * Import survey */ ?> <!-- tab import survey --> <!-- import form --> <?php echo CHtml::form(array('admin/survey/sa/copy'), 'post', array('id' => 'importsurvey', 'name' => 'importsurvey', 'class' => 'form-horizontal', 'enctype' => 'multipart/form-data', 'onsubmit' => 'return validatefilename(this,"' . gT('Please select a file to import!', 'js') . '");')); ?> <div class="row"> <!-- Select file --> <div class='form-group '> <label class='control-label col-sm-3' for='the_file'> <?php printf(gT("Select survey structure file (*.lss, *.txt) or survey archive (*.lsa) (maximum file size: %01.2f MB)"), getMaximumFileUploadSize() / 1024 / 1024); ?> </label> <div class='col-sm-4'> <input id='the_file' name="the_file" type="file" accept='.lss,.lsa,.tsv,.txt'/> </div> </div> <!-- Convert resource links and INSERTANS fields? --> <div class='form-group'> <label class='control-label col-sm-3' for='translinksfields'><?php eT("Convert resource links and expression fields?"); ?> </label> <div class='col-sm-4'> <?php
/** * Responsible to import a template archive. * * @access public * @return void */ public function upload() { if (!Permission::model()->hasGlobalPermission('templates', 'import')) { die('No permission'); } Yii::app()->loadHelper('admin/template'); $lid = returnGlobal('lid'); $action = returnGlobal('action'); if ($action == 'templateupload') { if (Yii::app()->getConfig('demoMode')) { Yii::app()->user->setFlash('error', gT("Demo mode: Uploading templates is disabled.")); $this->getController()->redirect(array("admin/templates/sa/upload")); } Yii::app()->loadLibrary('admin.pclzip'); if ($_FILES['the_file']['error'] == 1 || $_FILES['the_file']['error'] == 2) { Yii::app()->setFlashMessage(sprintf(gT("Sorry, this file is too large. Only files up to %01.2f MB are allowed."), getMaximumFileUploadSize() / 1024 / 1024), 'error'); $this->getController()->redirect(array("admin/templates/sa/upload")); } $zip = new PclZip($_FILES['the_file']['tmp_name']); $sNewDirectoryName = sanitize_dirname(pathinfo($_FILES['the_file']['name'], PATHINFO_FILENAME)); $destdir = Yii::app()->getConfig('usertemplaterootdir') . DIRECTORY_SEPARATOR . $sNewDirectoryName; if (!is_writeable(dirname($destdir))) { Yii::app()->user->setFlash('error', sprintf(gT("Incorrect permissions in your %s folder."), dirname($destdir))); $this->getController()->redirect(array("admin/templates/sa/upload")); } if (!is_dir($destdir)) { mkdir($destdir); } else { Yii::app()->user->setFlash('error', sprintf(gT("Template '%s' does already exist."), $sNewDirectoryName)); $this->getController()->redirect(array("admin/templates/sa/upload")); } $aImportedFilesInfo = array(); $aErrorFilesInfo = array(); if (is_file($_FILES['the_file']['tmp_name'])) { $aExtractResult = $zip->extract(PCLZIP_OPT_PATH, $destdir, PCLZIP_CB_PRE_EXTRACT, 'templateExtractFilter'); if ($aExtractResult === 0) { Yii::app()->user->setFlash('error', gT("This file is not a valid ZIP file archive. Import failed.")); rmdirr($destdir); $this->getController()->redirect(array("admin/templates/sa/upload")); } else { // Successfully unpacked foreach ($aExtractResult as $sFile) { if ($sFile['status'] == 'skipped') { $aErrorFilesInfo[] = array("filename" => $sFile['stored_filename']); } else { $aImportedFilesInfo[] = array("filename" => $sFile['stored_filename'], "status" => gT("OK"), 'is_folder' => $sFile['folder']); } } if (!Template::checkIfTemplateExists($sNewDirectoryName)) { Yii::app()->user->setFlash('error', gT("This ZIP archive did not contain a template. Import failed.")); rmdirr($destdir); $this->getController()->redirect(array("admin/templates/sa/upload")); } } if (count($aImportedFilesInfo) == 0) { Yii::app()->user->setFlash('error', gT("This ZIP archive contains no valid template files. Import failed.")); $this->getController()->redirect(array("admin/templates/sa/upload")); } } else { Yii::app()->user->setFlash('error', sprintf(gT("An error occurred uploading your file. This may be caused by incorrect permissions in your %s folder."), Yii::app()->getConfig('usertemplaterootdir'))); rmdirr($destdir); $this->getController()->redirect(array("admin/templates/sa/upload")); } if (count($aImportedFilesInfo) > 0) { // Not working with 2.5 templates... //$templateFixes= $this->_templateFixes($sNewDirectoryName); $templateFixes = array(); } else { $templateFixes = array(); } $aViewUrls = 'importuploaded_view'; $aData = array('aImportedFilesInfo' => $aImportedFilesInfo, 'aErrorFilesInfo' => $aErrorFilesInfo, 'lid' => $lid, 'newdir' => $sNewDirectoryName, 'templateFixes' => $templateFixes); } else { $aViewUrls = 'importform_view'; $aData = array('lid' => $lid); } $this->_renderWrappedTemplate('templates', $aViewUrls, $aData); }
</h4> </div> <?php echo CHtml::form(array('admin/templates/sa/upload'), 'post', array('id' => 'importtemplate', 'name' => 'importtemplate', 'enctype' => 'multipart/form-data', 'onsubmit' => 'return validatefilename(this,"' . gT('Please select a file to import!', 'js') . '");')); ?> <div class="modal-body"> <input type='hidden' name='lid' value='$lid' /> <input type='hidden' name='action' value='templateupload' /> <div class="form-group"> <label for='the_file'><?php eT("Select template ZIP file:"); ?> </label> <input id='the_file' name='the_file' type="file" accept='.zip' /> <?php printf(gT('(Maximum file size: %01.2f MB)'), getMaximumFileUploadSize() / 1024 / 1024); ?> </div> </div> <div class="modal-footer"> <?php if (!function_exists("zip_open")) { ?> <?php eT("The ZIP library is not activated in your PHP configuration thus importing ZIP files is currently disabled.", "js"); ?> <?php } else { ?> <input class="btn btn-success" type='button' value='<?php eT("Import");
if ($_POST['format'] == 'pdf' && isset($_FILES['pdf'])) { if (strlen($_FILES['pdf']['name']) == 0) { Print_Message('Error', 'You forgot to include the PDF File to print...', 'center'); } else { if (mime_content_type($_FILES['pdf']['tmp_name']) == 'application/pdf') { $file = $_FILES['pdf']['tmp_name']; include 'res/printer.php'; } else { Print_Message('Error', html($_FILES['pdf']['name']) . ' does not look like a PDF', 'center'); } } } } } } $upLimit = getMaximumFileUploadSize(); ?> <form name="Printer" action="index.php?page=Printer" method="post" enctype="multipart/form-data" onsubmit="return submitPrint(this,<?php echo $upLimit; ?> ,false);"> <input type="hidden" name="format"/> <input type="hidden" name="options"/> <div id="sidebar" style="min-height:100px;"> <div class="side_box"> <h2>Printer Configuration</h2> <div id="p_config"> <script type="text/javascript"> var printers=<?php $f = file_get_contents('config/printers.json'); echo $f === false ? '\'Printers have not been configured, please <a href="index.php?page=Config&action=Search-For-Printers">search for printers</a> on the <a href="index.php?page=Config">Configure</a> page.\'' : $f;
/** * Function responsible to import/copy a survey based on $action. * * @access public * @return void */ public function copy() { $importsurvey = ""; $action = Yii::app()->request->getParam('action'); $iSurveyID = sanitize_int(Yii::app()->request->getParam('sid')); if ($action == "importsurvey" || $action == "copysurvey") { // Start the HTML if ($action == 'importsurvey') { $aData['sHeader'] = gT("Import survey data"); $aData['sSummaryHeader'] = gT("Survey structure import summary"); $importingfrom = "http"; $aPathInfo = pathinfo($_FILES['the_file']['name']); if (isset($aPathInfo['extension'])) { $sExtension = $aPathInfo['extension']; } else { $sExtension = ""; } } elseif ($action == 'copysurvey') { $aData['sHeader'] = gT("Copy survey"); $aData['sSummaryHeader'] = gT("Survey copy summary"); } // Start traitment and messagebox $aData['bFailed'] = false; // Put a var for continue if ($action == 'importsurvey') { $sFullFilepath = Yii::app()->getConfig('tempdir') . DIRECTORY_SEPARATOR . randomChars(30) . '.' . $sExtension; if ($_FILES['the_file']['error'] == 1 || $_FILES['the_file']['error'] == 2) { $aData['sErrorMessage'] = sprintf(gT("Sorry, this file is too large. Only files up to %01.2f MB are allowed."), getMaximumFileUploadSize() / 1024 / 1024) . '<br>'; $aData['bFailed'] = true; } elseif (!in_array(strtolower($sExtension), array('lss', 'txt', 'tsv', 'lsa'))) { $aData['sErrorMessage'] = sprintf(gT("Import failed. You specified an invalid file type '%s'."), $sExtension); $aData['bFailed'] = true; } elseif ($aData['bFailed'] || !@move_uploaded_file($_FILES['the_file']['tmp_name'], $sFullFilepath)) { $aData['sErrorMessage'] = sprintf(gT("An error occurred uploading your file. This may be caused by incorrect permissions in your %s folder."), Yii::app()->getConfig('tempdir')); $aData['bFailed'] = true; } } elseif ($action == 'copysurvey') { $iSurveyID = sanitize_int(Yii::app()->request->getParam('copysurveylist')); $aExcludes = array(); $sNewSurveyName = Yii::app()->request->getPost('copysurveyname'); if (Yii::app()->request->getPost('copysurveyexcludequotas') == "1") { $aExcludes['quotas'] = true; } if (Yii::app()->request->getPost('copysurveyexcludepermissions') == "1") { $aExcludes['permissions'] = true; } if (Yii::app()->request->getPost('copysurveyexcludeanswers') == "1") { $aExcludes['answers'] = true; } if (Yii::app()->request->getPost('copysurveyresetconditions') == "1") { $aExcludes['conditions'] = true; } if (Yii::app()->request->getPost('copysurveyresetstartenddate') == "1") { $aExcludes['dates'] = true; } if (!$iSurveyID) { $aData['sErrorMessage'] = gT("No survey ID has been provided. Cannot copy survey"); $aData['bFailed'] = true; } elseif (!Survey::model()->findByPk($iSurveyID)) { $aData['sErrorMessage'] = gT("Invalid survey ID"); $aData['bFailed'] = true; } elseif (!Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'export') && !Permission::model()->hasSurveyPermission($iSurveyID, 'surveycontent', 'export')) { $aData['sErrorMessage'] = gT("We are sorry but you don't have permissions to do this."); $aData['bFailed'] = true; } else { Yii::app()->loadHelper('export'); $copysurveydata = surveyGetXMLData($iSurveyID, $aExcludes); } } // Now, we have the survey : start importing Yii::app()->loadHelper('admin/import'); if ($action == 'importsurvey' && !$aData['bFailed']) { $aImportResults = importSurveyFile($sFullFilepath, $_POST['translinksfields'] == '1'); if (is_null($aImportResults) || !empty($aImportResults['error'])) { $aData['sErrorMessage'] = isset($aImportResults['error']) ? $aImportResults['error'] : gT("Unknown error."); $aData['bFailed'] = true; } } elseif ($action == 'copysurvey' && !$aData['bFailed']) { $aImportResults = XMLImportSurvey('', $copysurveydata, $sNewSurveyName, sanitize_int(App()->request->getParam('copysurveyid')), $_POST['copysurveytranslinksfields'] == '1'); if (isset($aExcludes['conditions'])) { Question::model()->updateAll(array('relevance' => '1'), 'sid=' . $aImportResults['newsid']); QuestionGroup::model()->updateAll(array('grelevance' => '1'), 'sid=' . $aImportResults['newsid']); } if (!isset($aExcludes['permissions'])) { Permission::model()->copySurveyPermissions($iSurveyID, $aImportResults['newsid']); } } else { $aData['bFailed'] = true; } if ($action == 'importsurvey' && isset($sFullFilepath) && file_exists($sFullFilepath)) { unlink($sFullFilepath); } if (!$aData['bFailed']) { $aData['action'] = $action; $aData['sLink'] = $this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $aImportResults['newsid']); $aData['aImportResults'] = $aImportResults; } } $this->_renderWrappedTemplate('survey', 'importSurvey_view', $aData); }
echo "</h2>"; echo "<ul>"; echo "<h3 display:inline;>"; echo getTranslation("Select a HF XML file to import into your HIS Library.", $settings); echo "</h3>"; echo "<form style='display:inline;' action='?action=import-function&v=import&step=1' method='POST' enctype='multipart/form-data'>"; echo "<input type='file' name='import_file' style='background-color:" . rcolor() . ";display:inline;font-size:24px;'>"; echo "<input type='submit' name='btnSubmit' value='"; echo getTranslation("Submit", $settings); echo "' style='background-color:" . rcolor() . ";display:inline;'/>"; echo "</form>"; echo "<br/>"; echo "<br/>"; echo getTranslation("Max File Upload Size", $settings); echo ": "; echo getMaximumFileUploadSize(); echo "</ul>"; echo "<br/>"; echo "<br/>"; echo "<br/>"; echo "<br/>"; echo "<br/>"; echo "<!--"; echo "<h2>"; echo getTranslation("Add System Kind (Linux, Windows, Mac, ...)", $settings); echo "</h2>"; echo "<form action='?action=add-system-kind' method='post'>"; echo "<table>"; echo "<tr><td valign='top'>"; echo getTranslation("Name", $settings); echo "</td><td><textarea name='name' style='width:500;' rows='5'></textarea></td></tr>";