本文整理汇总了PHP中randomChars函数的典型用法代码示例。如果您正苦于以下问题:PHP randomChars函数的具体用法?PHP randomChars怎么用?PHP randomChars使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了randomChars函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: init
/**
* An initialization method that implementing classes can override to gain access
* to any information about the survey, language, or formatting options they
* may need for setup.
*
* @param Survey $oSurvey
* @param mixed $sLanguageCode
* @param FormattingOptions $oOptions
*/
public function init(SurveyObj $oSurvey, $sLanguageCode, FormattingOptions $oOptions)
{
$this->languageCode = $sLanguageCode;
$this->translator = new Translator();
$this->filename = Yii::app()->getConfig("tempdir") . DIRECTORY_SEPARATOR . randomChars(40);
$this->webfilename = 'results-survey' . $oSurvey->id;
}
示例2: init
/**
* An initialization method that implementing classes can override to gain access
* to any information about the survey, language, or formatting options they
* may need for setup.
*
* @param Survey $oSurvey
* @param mixed $sLanguageCode
* @param FormattingOptions $oOptions
*/
public function init(SurveyObj $oSurvey, $sLanguageCode, FormattingOptions $oOptions)
{
$this->languageCode = $sLanguageCode;
$this->translator = new Translator();
if ($oOptions->output == 'file') {
$sRandomFileName = Yii::app()->getConfig("tempdir") . DIRECTORY_SEPARATOR . randomChars(40);
$this->filename = $sRandomFileName;
}
}
示例3: import
/**
* 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);
}
}
示例4: generateToken
public function generateToken()
{
$length = $this->survey->tokenlength;
$this->token = randomChars($length);
$counter = 0;
while (!$this->validate('token')) {
$this->token = randomChars($length);
$counter++;
// This is extremely unlikely.
if ($counter > 10) {
throw new CHttpException(500, 'Failed to create unique token in 10 attempts.');
}
}
}
示例5: import
/**
* Function responsible to import a question.
*
* @access public
* @return void
*/
public function import()
{
$action = returnGlobal('action');
$surveyid = returnGlobal('sid');
$gid = returnGlobal('gid');
$clang = $this->getController()->lang;
$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);
if (!@move_uploaded_file($_FILES['the_file']['tmp_name'], $sFullFilepath)) {
$fatalerror = sprintf($clang->gT("An error occurred uploading your file. This may be caused by incorrect permissions in your %s folder."), Yii::app()->getConfig('tempdir'));
}
// validate that we have a SID and GID
if (!$surveyid) {
$fatalerror .= $clang->gT("No SID (Survey) has been provided. Cannot import question.");
}
if (!$gid) {
$fatalerror .= $clang->gT("No GID (Group) has been provided. Cannot import question");
}
if (isset($fatalerror)) {
unlink($sFullFilepath);
$this->getController()->error($fatalerror);
}
// IF WE GOT THIS FAR, THEN THE FILE HAS BEEN UPLOADED SUCCESFULLY
Yii::app()->loadHelper('admin/import');
if (strtolower($sExtension) == 'csv') {
$aImportResults = CSVImportQuestion($sFullFilepath, $surveyid, $gid);
} elseif (strtolower($sExtension) == 'lsq') {
$aImportResults = XMLImportQuestion($sFullFilepath, $surveyid, $gid);
} else {
$this->getController()->error($clang->gT('Unknown file extension'));
}
fixLanguageConsistency($surveyid);
if (isset($aImportResults['fatalerror'])) {
unlink($sFullFilepath);
$this->getController()->error($aImportResults['fatalerror']);
}
unlink($sFullFilepath);
$aData['aImportResults'] = $aImportResults;
$aData['surveyid'] = $surveyid;
$aData['gid'] = $gid;
$aData['sExtension'] = $sExtension;
$aViewUrls[] = 'import_view';
}
$this->_renderWrappedTemplate('survey/Question', $aViewUrls, $aData);
}
示例6: PrepareEditorScript
function PrepareEditorScript($load = false, $controller = null)
{
$clang = Yii::app()->lang;
$data['clang'] = $clang;
$data['sKCFinderCSRFToken'] = $_SESSION['kcfinder_csrftoken'] = randomChars(128);
App()->getClientScript()->registerCoreScript('ckeditor');
if ($controller == null) {
$controller = Yii::app()->getController();
}
if ($load == false) {
echo $controller->renderPartial('/admin/survey/prepareEditorScript_view', $data, true);
} else {
return $controller->renderPartial('/admin/survey/prepareEditorScript_view', $data);
}
}
示例7: import
/**
* questiongroup::import()
* Function responsible to import a question group.
*
* @access public
* @return void
*/
function import()
{
$action = $_POST['action'];
$surveyid = $_POST['sid'];
$clang = $this->getController()->lang;
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 (!@move_uploaded_file($_FILES['the_file']['tmp_name'], $sFullFilepath)) {
$fatalerror = sprintf($clang->gT("An error occurred uploading your file. This may be caused by incorrect permissions in your %s folder."), $this->config->item('tempdir'));
}
// validate that we have a SID
if (!returnGlobal('sid')) {
$fatalerror .= $clang->gT("No SID (Survey) has been provided. Cannot import question.");
}
if (isset($fatalerror)) {
@unlink($sFullFilepath);
$this->getController()->error($fatalerror);
}
Yii::app()->loadHelper('admin/import');
// IF WE GOT THIS FAR, THEN THE FILE HAS BEEN UPLOADED SUCCESFULLY
if (strtolower($sExtension) == 'csv') {
$aImportResults = CSVImportGroup($sFullFilepath, $surveyid);
} elseif (strtolower($sExtension) == 'lsg') {
$aImportResults = XMLImportGroup($sFullFilepath, $surveyid);
} else {
$this->getController()->error('Unknown file extension');
}
LimeExpressionManager::SetDirtyFlag();
// so refreshes syntax highlighting
fixLanguageConsistency($surveyid);
if (isset($aImportResults['fatalerror'])) {
unlink($sFullFilepath);
$this->getController()->error($aImportResults['fatalerror']);
}
unlink($sFullFilepath);
$aData['display'] = $importgroup;
$aData['surveyid'] = $surveyid;
$aData['aImportResults'] = $aImportResults;
$aData['sExtension'] = $sExtension;
//$aData['display']['menu_bars']['surveysummary'] = 'importgroup';
$this->_renderWrappedTemplate('survey/QuestionGroups', 'import_view', $aData);
// TMSW Condition->Relevance: call LEM->ConvertConditionsToRelevance() after import
}
}
示例8: addPrimaryKey
/**
* @param string $sTablename
*/
function addPrimaryKey($sTablename, $aColumns)
{
return Yii::app()->db->createCommand()->addPrimaryKey('PK_' . $sTablename . '_' . randomChars(12, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'), '{{' . $sTablename . '}}', $aColumns);
}
示例9: actionIndex
/**
* register::index()
* Process register form data and take appropriate action
* @return
*/
function actionIndex($surveyid = null)
{
Yii::app()->loadHelper('database');
Yii::app()->loadHelper('replacements');
$postlang = Yii::app()->request->getPost('lang');
if ($surveyid == null) {
$surveyid = Yii::app()->request->getPost('sid');
}
if (!$surveyid) {
Yii::app()->request->redirect(Yii::app()->baseUrl);
}
// Get passed language from form, so that we dont loose this!
if (!isset($postlang) || $postlang == "" || !$postlang) {
$baselang = Survey::model()->findByPk($surveyid)->language;
Yii::import('application.libraries.Limesurvey_lang');
Yii::app()->lang = new Limesurvey_lang($baselang);
$clang = Yii::app()->lang;
} else {
Yii::import('application.libraries.Limesurvey_lang');
Yii::app()->lang = new Limesurvey_lang($postlang);
$clang = Yii::app()->lang;
$baselang = $postlang;
}
$thissurvey = getSurveyInfo($surveyid, $baselang);
$register_errormsg = "";
// Check the security question's answer
if (function_exists("ImageCreate") && isCaptchaEnabled('registrationscreen', $thissurvey['usecaptcha'])) {
if (!isset($_POST['loadsecurity']) || !isset($_SESSION['survey_' . $surveyid]['secanswer']) || Yii::app()->request->getPost('loadsecurity') != $_SESSION['survey_' . $surveyid]['secanswer']) {
$register_errormsg .= $clang->gT("The answer to the security question is incorrect.") . "<br />\n";
}
}
//Check that the email is a valid style address
if (!validateEmailAddress(Yii::app()->request->getPost('register_email'))) {
$register_errormsg .= $clang->gT("The email you used is not valid. Please try again.");
}
// Check for additional fields
$attributeinsertdata = array();
foreach (GetParticipantAttributes($surveyid) as $field => $data) {
if (empty($data['show_register']) || $data['show_register'] != 'Y') {
continue;
}
$value = sanitize_xss_string(Yii::app()->request->getPost('register_' . $field));
if (trim($value) == '' && $data['mandatory'] == 'Y') {
$register_errormsg .= sprintf($clang->gT("%s cannot be left empty"), $thissurvey['attributecaptions'][$field]);
}
$attributeinsertdata[$field] = $value;
}
if ($register_errormsg != "") {
$_SESSION['survey_' . $surveyid]['register_errormsg'] = $register_errormsg;
Yii::app()->request->redirect(Yii::app()->createUrl('survey/index/sid/' . $surveyid));
}
//Check if this email already exists in token database
$query = "SELECT email FROM {{tokens_{$surveyid}}}\n" . "WHERE email = '" . sanitize_email(Yii::app()->request->getPost('register_email')) . "'";
$usrow = Yii::app()->db->createCommand($query)->queryRow();
if ($usrow) {
$register_errormsg = $clang->gT("The email you used has already been registered.");
$_SESSION['survey_' . $surveyid]['register_errormsg'] = $register_errormsg;
Yii::app()->request->redirect(Yii::app()->createUrl('survey/index/sid/' . $surveyid));
//include "index.php";
//exit;
}
$mayinsert = false;
// Get the survey settings for token length
//$this->load->model("surveys_model");
$tlresult = Survey::model()->findAllByAttributes(array("sid" => $surveyid));
if (isset($tlresult[0])) {
$tlrow = $tlresult[0];
} else {
$tlrow = $tlresult;
}
$tokenlength = $tlrow['tokenlength'];
//if tokenlength is not set or there are other problems use the default value (15)
if (!isset($tokenlength) || $tokenlength == '') {
$tokenlength = 15;
}
while ($mayinsert != true) {
$newtoken = randomChars($tokenlength);
$ntquery = "SELECT * FROM {{tokens_{$surveyid}}} WHERE token='{$newtoken}'";
$usrow = Yii::app()->db->createCommand($ntquery)->queryRow();
if (!$usrow) {
$mayinsert = true;
}
}
$postfirstname = sanitize_xss_string(strip_tags(Yii::app()->request->getPost('register_firstname')));
$postlastname = sanitize_xss_string(strip_tags(Yii::app()->request->getPost('register_lastname')));
$starttime = sanitize_xss_string(Yii::app()->request->getPost('startdate'));
$endtime = sanitize_xss_string(Yii::app()->request->getPost('enddate'));
/*$postattribute1=sanitize_xss_string(strip_tags(returnGlobal('register_attribute1')));
$postattribute2=sanitize_xss_string(strip_tags(returnGlobal('register_attribute2'))); */
// Insert new entry into tokens db
Tokens_dynamic::sid($thissurvey['sid']);
$token = new Tokens_dynamic();
$token->firstname = $postfirstname;
$token->lastname = $postlastname;
$token->email = Yii::app()->request->getPost('register_email');
//.........这里部分代码省略.........
示例10: attributeMapCSV
function attributeMapCSV()
{
$clang = $this->getController()->lang;
$sRandomFileName = randomChars(20);
$sFilePath = Yii::app()->getConfig('tempdir') . DIRECTORY_SEPARATOR . $sRandomFileName;
$aPathinfo = pathinfo($_FILES['the_file']['name']);
$sExtension = $aPathinfo['extension'];
if (strtolower($sExtension) == 'csv') {
$bMoveFileResult = @move_uploaded_file($_FILES['the_file']['tmp_name'], $sFilePath);
$errorinupload = '';
$filterblankemails = Yii::app()->request->getPost('filterbea');
} else {
$templateData['error_msg'] = sprintf($clang->gT("This is not a .csv file."), Yii::app()->getConfig('tempdir'));
$errorinupload = array('error' => $this->upload->display_errors());
Yii::app()->session['summary'] = array('errorinupload' => $errorinupload);
$this->_renderWrappedTemplate('participants', array('participantsPanel', 'uploadSummary'), array('aAttributes' => ParticipantAttributeName::model()->getAllAttributes()));
}
if (!$bMoveFileResult) {
$templateData['error_msg'] = sprintf($clang->gT("An error occurred uploading your file. This may be caused by incorrect permissions in your %s folder."), Yii::app()->getConfig('tempdir'));
$errorinupload = array('error' => $this->upload->display_errors());
Yii::app()->session['summary'] = array('errorinupload' => $errorinupload);
$this->_renderWrappedTemplate('participants', array('participantsPanel', 'uploadSummary'), array('aAttributes' => ParticipantAttributeName::model()->getAllAttributes()));
} else {
$aData = array('upload_data' => $_FILES['the_file']);
$sFileName = $_FILES['the_file']['name'];
$regularfields = array('firstname', 'participant_id', 'lastname', 'email', 'language', 'blacklisted', 'owner_uid');
$csvread = fopen($sFilePath, 'r');
$separator = Yii::app()->request->getPost('separatorused');
$firstline = fgetcsv($csvread, 1000, ',');
$selectedcsvfields = 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;
}
$linecount = count(file($sFilePath));
$attributes = ParticipantAttributeName::model()->model()->getCPDBAttributes();
$aData = array('attributes' => $attributes, 'firstline' => $selectedcsvfields, 'fullfilepath' => $sRandomFileName, 'linecount' => $linecount - 1, 'filterbea' => $filterblankemails, 'participant_id_exists' => in_array('participant_id', $fieldlist));
App()->getClientScript()->registerCssFile(Yii::app()->getConfig('adminstyleurl') . "attributeMapCSV.css");
App()->getClientScript()->registerPackage('qTip2');
App()->getClientScript()->registerPackage('jquery-nestedSortable');
App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . "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 = '" . $clang->gT("OK") . "';\n" . "var processed = '" . $clang->gT("Summary") . "';\n" . "var summary = '" . $clang->gT("Upload summary") . "';\n" . "var notPairedErrorTxt = '" . $clang->gT("You have to pair this field with an existing attribute.") . "';\n" . "var onlyOnePairedErrorTxt = '" . $clang->gT("Only one CSV attribute is mapped with central attribute.") . "';\n" . "var cannotAcceptErrorTxt='" . $clang->gT("This list cannot accept token attributes.") . "';\n" . "var separator = '" . sanitize_paranoid_string($_POST['separatorused']) . "';\n" . "var thefilepath = '" . $sRandomFileName . "';\n" . "var filterblankemails = '" . $filterblankemails . "';\n";
App()->getClientScript()->registerScript("sAttributeMapJS", $sAttributeMapJS, CClientScript::POS_BEGIN);
$this->_renderWrappedTemplate('participants', 'attributeMapCSV', $aData);
}
}
示例11: createTokens
/**
* Creates tokens for all token records that have empty token fields and returns the number
* of tokens created
*
* @param int $iSurveyID
* @return array ( int number of created tokens, int number to be created tokens)
*/
function createTokens($iSurveyID)
{
$tkresult = $this->selectEmptyTokens($iSurveyID);
//Exit early if there are not empty tokens
if (count($tkresult) === 0) {
return array(0, 0);
}
//get token length from survey settings
$tlrow = Survey::model()->findByAttributes(array("sid" => $iSurveyID));
$iTokenLength = $tlrow->tokenlength;
//if tokenlength is not set or there are other problems use the default value (15)
if (empty($iTokenLength)) {
$iTokenLength = 15;
}
//Add some criteria to select only the token field
$criteria = $this->getDbCriteria();
$criteria->select = 'token';
$ntresult = $this->findAllAsArray($criteria);
//Use AsArray to skip active record creation
// select all existing tokens
foreach ($ntresult as $tkrow) {
$existingtokens[$tkrow['token']] = true;
}
$newtokencount = 0;
$invalidtokencount = 0;
foreach ($tkresult as $tkrow) {
$bIsValidToken = false;
while ($bIsValidToken == false && $invalidtokencount < 50) {
$newtoken = randomChars($iTokenLength);
if (!isset($existingtokens[$newtoken])) {
$existingtokens[$newtoken] = true;
$bIsValidToken = true;
$invalidtokencount = 0;
} else {
$invalidtokencount++;
}
}
if ($bIsValidToken) {
$itresult = $this->updateToken($tkrow['tid'], $newtoken);
$newtokencount++;
} else {
break;
}
}
return array($newtokencount, count($tkresult));
}
示例12: step3
function step3()
{
$clang = $this->getController()->lang;
$buildnumber = Yii::app()->getConfig("buildnumber");
$tempdir = Yii::app()->getConfig("tempdir");
$updatebuild = getGlobalSetting("updatebuild");
//$_POST=$this->input->post();
$rootdir = Yii::app()->getConfig("rootdir");
$publicdir = Yii::app()->getConfig("publicdir");
$tempdir = Yii::app()->getConfig("tempdir");
$aDatabasetype = Yii::app()->db->getDriverName();
$aData = array('clang' => $clang);
// Request the list with changed files from the server
if (!isset(Yii::app()->session['updateinfo'])) {
if ($updateinfo['error'] == 1) {
}
} else {
$updateinfo = Yii::app()->session['updateinfo'];
}
$aData['updateinfo'] = $updateinfo;
// okay, updateinfo now contains all necessary updateinformation
// Create DB and file backups now
$basefilename = dateShift(date("Y-m-d H:i:s"), "Y-m-d", Yii::app()->getConfig('timeadjust')) . '_' . md5(uniqid(rand(), true));
//Now create a backup of the files to be delete or modified
$filestozip = array();
foreach ($updateinfo['files'] as $file) {
if (is_file($publicdir . $file['file']) === true) {
$filestozip[] = $publicdir . $file['file'];
}
}
Yii::app()->loadLibrary("admin/pclzip");
$archive = new PclZip($tempdir . DIRECTORY_SEPARATOR . 'LimeSurvey_files_backup_' . $basefilename . '.zip');
$v_list = $archive->add($filestozip, PCLZIP_OPT_REMOVE_PATH, $publicdir);
if ($v_list == 0) {
$aFileBackup = array('class' => 'error', 'text' => sprintf($clang->gT("Error on file backup: %s"), $archive->errorInfo(true)));
} else {
$aFileBackup = array('class' => 'success', 'text' => sprintf($clang->gT("File backup created: %s"), $tempdir . DIRECTORY_SEPARATOR . 'LimeSurvey_files_backup_' . $basefilename . '.zip'));
}
$aData['aFileBackup'] = $aFileBackup;
$aData['databasetype'] = $aDatabasetype;
//TODO: Yii provides no function to backup the database. To be done after dumpdb is ported
if (in_array($aDatabasetype, array('mysql', 'mysqli'))) {
if (in_array($aDatabasetype, array('mysql', 'mysqli')) && Yii::app()->getConfig('demoMode') != true) {
Yii::app()->loadHelper("admin/backupdb");
$sfilename = $tempdir . DIRECTORY_SEPARATOR . "backup_db_" . randomChars(20) . "_" . dateShift(date("Y-m-d H:i:s"), "Y-m-d", Yii::app()->getConfig('timeadjust')) . ".sql";
$dfilename = $tempdir . DIRECTORY_SEPARATOR . "LimeSurvey_database_backup_" . $basefilename . ".zip";
outputDatabase('', false, $sfilename);
// Before try to zip: test size of file
if (is_file($sfilename) && filesize($sfilename)) {
$archive = new PclZip($dfilename);
$v_list = $archive->add(array($sfilename), PCLZIP_OPT_REMOVE_PATH, $tempdir, PCLZIP_OPT_ADD_TEMP_FILE_ON);
unlink($sfilename);
if ($v_list == 0) {
// Unknow reason because backup of DB work ?
$aSQLBackup = array('class' => 'warning', 'text' => $clang->gT("Unable to backup your database for unknow reason. Before proceeding please backup your database using a backup tool!"));
} else {
$aSQLBackup = array('class' => 'success', 'text' => sprintf($clang->gT('DB backup created: %s'), htmlspecialchars($dfilename)));
}
} else {
$aSQLBackup = array('class' => 'warning', 'text' => $clang->gT("Unable to backup your database for unknow reason. Before proceeding please backup your database using a backup tool!"));
}
}
} else {
$aSQLBackup = array('class' => 'warning', 'text' => $clang->gT('Database backup functionality is currently not available for your database type. Before proceeding please backup your database using a backup tool!'));
}
$aData['aSQLBackup'] = $aSQLBackup;
if ($aFileBackup['class'] == "success" && $aSQLBackup['class'] == "success") {
$aData['result'] = "success";
} elseif ($aFileBackup['class'] == "error" || $aSQLBackup['class'] == "error") {
$aData['result'] = "error";
} else {
$aData['result'] = "warning";
}
$this->_renderWrappedTemplate('update', 'step3', $aData);
}
示例13: attributeMapCSV
function attributeMapCSV()
{
$clang = $this->getController()->lang;
$sRandomFileName = randomChars(20);
$sFilePath = Yii::app()->getConfig('tempdir') . DIRECTORY_SEPARATOR . $sRandomFileName;
$aPathinfo = pathinfo($_FILES['the_file']['name']);
$sExtension = $aPathinfo['extension'];
if (strtolower($sExtension) == 'csv') {
$bMoveFileResult = @move_uploaded_file($_FILES['the_file']['tmp_name'], $sFilePath);
$errorinupload = '';
$filterblankemails = Yii::app()->request->getPost('filterbea');
} else {
$templateData['error_msg'] = sprintf($clang->gT("This is not a .csv file."), Yii::app()->getConfig('tempdir'));
$errorinupload = array('error' => $this->upload->display_errors());
Yii::app()->session['summary'] = array('errorinupload' => $errorinupload);
$this->_renderWrappedTemplate('participants', array('participantsPanel', 'uploadSummary'));
}
if (!$bMoveFileResult) {
$templateData['error_msg'] = sprintf($clang->gT("An error occurred uploading your file. This may be caused by incorrect permissions in your %s folder."), Yii::app()->getConfig('tempdir'));
$errorinupload = array('error' => $this->upload->display_errors());
Yii::app()->session['summary'] = array('errorinupload' => $errorinupload);
$this->_renderWrappedTemplate('participants', array('participantsPanel', 'uploadSummary'));
} else {
$aData = array('upload_data' => $_FILES['the_file']);
$sFileName = $_FILES['the_file']['name'];
$regularfields = array('firstname', 'participant_id', 'lastname', 'email', 'language', 'blacklisted', 'owner_uid');
$csvread = fopen($sFilePath, 'r');
$seperator = Yii::app()->request->getPost('seperatorused');
$firstline = fgetcsv($csvread, 1000, ',');
$selectedcsvfields = 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;
}
$linecount = count(file($sFilePath));
$attributes = ParticipantAttributeNames::model()->model()->getAttributes();
$aData = array('attributes' => $attributes, 'firstline' => $selectedcsvfields, 'fullfilepath' => $sRandomFileName, 'linecount' => $linecount - 1, 'filterbea' => $filterblankemails, 'participant_id_exists' => in_array('participant_id', $fieldlist));
$this->_renderWrappedTemplate('participants', 'attributeMapCSV', $aData);
}
}
示例14: GetNewSurveyID
/**
* This function returns a new random sid if the existing one is taken,
* otherwise it returns the old one.
*
* @param mixed $iOldSID
*/
function GetNewSurveyID($iOldSID)
{
Yii::app()->loadHelper('database');
$query = "SELECT sid FROM {{surveys}} WHERE sid={$iOldSID}";
$aRow = Yii::app()->db->createCommand($query)->queryRow();
//if (!is_null($isresult))
if ($aRow !== false) {
// Get new random ids until one is found that is not used
do {
$iNewSID = randomChars(5, '123456789');
$query = "SELECT sid FROM {{surveys}} WHERE sid={$iNewSID}";
$aRow = Yii::app()->db->createCommand($query)->queryRow();
} while ($aRow !== false);
return $iNewSID;
} else {
return $iOldSID;
}
}
示例15: run
//.........这里部分代码省略.........
}
//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) {