diff --git a/application/config/lsconfig.php b/application/config/lsconfig.php index e5acbacd12b..46ea1358db6 100644 --- a/application/config/lsconfig.php +++ b/application/config/lsconfig.php @@ -528,7 +528,7 @@ $config['publicdir'] = $config['rootdir']; // The directory path of the public scripts -$config['homedir'] = $config['rootdir'].DIRECTORY_SEPARATOR."admin"; // The directory path of the admin scripts +$config['homedir'] = $config['rootdir']; // The directory path of the admin scripts $config['tempdir'] = $config['rootdir'].DIRECTORY_SEPARATOR."tmp"; // The directory path where LimeSurvey can store temporary files $config['imagedir'] = $config['rootdir'].DIRECTORY_SEPARATOR."images"; // The directory path of the image directory $config['uploaddir'] = $config['rootdir'].DIRECTORY_SEPARATOR."upload"; diff --git a/application/controllers/admin/database.php b/application/controllers/admin/database.php index c6f73efdc4f..b99409def7c 100644 --- a/application/controllers/admin/database.php +++ b/application/controllers/admin/database.php @@ -22,18 +22,12 @@ * @version $Id: database.php 11349 2011-11-09 21:49:00Z tpartner $ * @access public */ -class Database extends Admin_Controller { - - - /** - * Database::__construct() - * Constructor - * @return - */ - function __construct() - { - parent::__construct(); - } +class database extends Survey_Common_Action +{ + public function run($sa = null) + { + $this->route('index', array('sa')); + } /** * Database::index() @@ -43,20 +37,19 @@ function __construct() */ function index($action=null) { - - $clang = $this->limesurvey_lang; + $clang = $this->controller->lang; $postsid=returnglobal('sid'); $postgid=returnglobal('gid'); $postqid=returnglobal('qid'); $postqaid=returnglobal('qaid'); $databaseoutput = ''; - $surveyid = $this->input->post("sid"); - $gid = $this->input->post("gid"); - $qid = $this->input->post("qid"); + $surveyid = returnglobal('sid'); + $gid = returnglobal('gid'); + $qid = returnglobal('qid'); // if $action is not passed, check post data. if (!$action) { - $action = $this->input->post("action"); + $action = $_POST['action']; } if ($action == "updatedefaultvalues" && bHasSurveyPermission($surveyid, 'surveycontent','update')) @@ -381,7 +374,6 @@ function index($action=null) if ($action == "insertquestion" && bHasSurveyPermission($surveyid, 'surveycontent','create')) { - $_POST = $this->input->post(); $baselang = GetBaseLanguageFromSurveyID($surveyid); if (strlen($_POST['title']) < 1) { @@ -391,8 +383,6 @@ function index($action=null) } else { - $this->load->helper('database'); - if (!isset($_POST['lid']) || $_POST['lid'] == '') {$_POST['lid']="0";} if (!isset($_POST['lid1']) || $_POST['lid1'] == '') {$_POST['lid1']="0";} if(!empty($_POST['questionposition']) || $_POST['questionposition'] == '0') @@ -400,53 +390,54 @@ function index($action=null) //Bug Fix: remove +1 -> $question_order=(sanitize_int($_POST['questionposition'])+1); $question_order=(sanitize_int($_POST['questionposition'])); //Need to renumber all questions on or after this - $cdquery = "UPDATE ".$this->db->dbprefix."questions SET question_order=question_order+1 WHERE gid=".$gid." AND question_order >= ".$question_order; - $cdresult=db_execute_assoc($cdquery); // or safe_die($connect->ErrorMsg()); // Checked) + $cdquery = "UPDATE {{questions}} SET question_order=question_order+1 WHERE gid=".$gid." AND question_order >= ".$question_order; + $cdresult=Yii::app()->db->createCommand($cdquery)->execute(); // or safe_die($connect->ErrorMsg()); // Checked) } else { $question_order=(getMaxquestionorder($gid,$surveyid)); $question_order++; } - if ($this->config->item('filterxsshtml')) - { - $_POST['title']=$this->security->xss_clean($_POST['title']); - $_POST['question_'.$baselang]=$this->security->xss_clean($_POST['question_'.$baselang]); - $_POST['help_'.$baselang]=$this->security->xss_clean($_POST['help_'.$baselang]); - } - else - { - $_POST['title'] = html_entity_decode($_POST['title'], ENT_QUOTES, "UTF-8"); - $_POST['question_'.$baselang] = html_entity_decode($_POST['question_'.$baselang], ENT_QUOTES, "UTF-8"); - $_POST['help_'.$baselang] = html_entity_decode($_POST['help_'.$baselang], ENT_QUOTES, "UTF-8"); - } + $_POST['title'] = html_entity_decode($_POST['title'], ENT_QUOTES, "UTF-8"); + $_POST['question_'.$baselang] = html_entity_decode($_POST['question_'.$baselang], ENT_QUOTES, "UTF-8"); + $_POST['help_'.$baselang] = html_entity_decode($_POST['help_'.$baselang], ENT_QUOTES, "UTF-8"); - // Fix bug with FCKEditor saving strange BR types - $_POST['title']=fix_FCKeditor_text($_POST['title']); - $_POST['question_'.$baselang]=fix_FCKeditor_text($_POST['question_'.$baselang]); - $_POST['help_'.$baselang]=fix_FCKeditor_text($_POST['help_'.$baselang]); + $purifier = new CHtmlPurifier(); + // Fix bug with FCKEditor saving strange BR types + if (Yii::app()->getConfig('filterxsshtml')) + { + $_POST['title']=$purifier->purify($_POST['title']); + $_POST['question_'.$baselang]=$purifier->purify($_POST['question_'.$baselang]); + $_POST['help_'.$baselang]=$purifier->purify($_POST['help_'.$baselang]); + } + else + { + $_POST['title']=fix_FCKeditor_text($_POST['title']); + $_POST['question_'.$baselang]=fix_FCKeditor_text($_POST['question_'.$baselang]); + $_POST['help_'.$baselang]=fix_FCKeditor_text($_POST['help_'.$baselang]); + } //$_POST = array_map('db_quote', $_POST); $data = array(); $data = array( - 'sid' => $surveyid, - 'gid' => $gid, - 'type' => $_POST['type'], - 'title' => $_POST['title'], - 'question' => $_POST['question_'.$baselang], - 'preg' => $_POST['preg'], - 'help' => $_POST['help_'.$baselang], - 'other' => $_POST['other'], - 'mandatory' => $_POST['mandatory'], - 'question_order' => $question_order, - 'language' => $baselang - - - + 'sid' => $surveyid, + 'gid' => $gid, + 'type' => $_POST['type'], + 'title' => $_POST['title'], + 'question' => $_POST['question_'.$baselang], + 'preg' => $_POST['preg'], + 'help' => $_POST['help_'.$baselang], + 'other' => $_POST['other'], + 'mandatory' => $_POST['mandatory'], + 'question_order' => $question_order, + 'language' => $baselang ); - $this->load->model("questions_model"); - $result = $this->questions_model->insertRecords($data); + $question = new Questions; + foreach ($data as $k => $v) + $question->$k = $v; + $result = $question->save(); + /** $query = "INSERT INTO ".db_table_name('questions')." (sid, gid, type, title, question, preg, help, other, mandatory, question_order, language)" ." VALUES ('{$postsid}', '{$postgid}', '{$_POST['type']}', '{$_POST['title']}'," @@ -454,7 +445,7 @@ function index($action=null) */ //$result = $connect->Execute($query); // Checked // Get the last inserted questionid for other languages - $qid=$this->db->insert_id(); //$connect->Insert_ID(db_table_name_nq('questions'),"qid"); + $qid=Yii::app()->db->getLastInsertID(); //$connect->Insert_ID(db_table_name_nq('questions'),"qid"); // Add other languages if ($result) @@ -464,28 +455,25 @@ function index($action=null) { if ($alang != "") { - db_switchIDInsert('questions',true); - $data = array( - 'qid' => $qid, - 'sid' => $surveyid, - 'gid' => $gid, - 'type' => $_POST['type'], - 'title' => $_POST['title'], - 'question' => $_POST['question_'.$alang], - 'preg' => $_POST['preg'], - 'help' => $_POST['help_'.$alang], - 'other' => $_POST['other'], - 'mandatory' => $_POST['mandatory'], - 'question_order' => $question_order, - 'language' => $alang - - - + 'qid' => $qid, + 'sid' => $surveyid, + 'gid' => $gid, + 'type' => $_POST['type'], + 'title' => $_POST['title'], + 'question' => $_POST['question_'.$alang], + 'preg' => $_POST['preg'], + 'help' => $_POST['help_'.$alang], + 'other' => $_POST['other'], + 'mandatory' => $_POST['mandatory'], + 'question_order' => $question_order, + 'language' => $alang ); + $ques = new Questions; + foreach ($data as $k => $v) + $ques->$k = $v; + $result2 = $ques->save(); - $this->load->model("questions_model"); - $result2 = $this->questions_model->insertRecords($data); /** $query = "INSERT INTO ".db_table_name('questions')." (qid, sid, gid, type, title, question, preg, help, other, mandatory, question_order, language)" ." VALUES ('$qid','{$postsid}', '{$postgid}', '{$_POST['type']}', '{$_POST['title']}'," @@ -496,7 +484,6 @@ function index($action=null) $databaseoutput .= "\n"; } - db_switchIDInsert('questions',false); } } } @@ -516,15 +503,15 @@ function index($action=null) { $data = array(); $data = array( - 'qid' => $qid, - 'value' => $_POST[$validAttribute['name']], - 'attribute' => $validAttribute['name'] - + 'qid' => $qid, + 'value' => $_POST[$validAttribute['name']], + 'attribute' => $validAttribute['name'] ); - - $this->load->model("question_attributes_model"); - $result = $this->question_attributes_model->insertRecords($data); + $attr = new Question_attributes; + foreach ($data as $k => $v) + $attr->$k = $v; + $result = $attr->save(); /**$query = "INSERT into ".db_table_name('question_attributes')." (qid, value, attribute) values ($qid,'".db_quote($_POST[$validAttribute['name']])."','{$validAttribute['name']}')"; $result = $connect->Execute($query) or safe_die("Error updating attribute value
".$query."
".$connect->ErrorMsg()); // Checked */ @@ -533,7 +520,7 @@ function index($action=null) } fixsortorderQuestions($gid, $surveyid); - $this->session->set_userdata('flashmessage', $clang->gT("Question was successfully added.")); + Yii::app()->session['flashmessage'] = $clang->gT("Question was successfully added."); //include("surveytable_functions.php"); //surveyFixColumns($surveyid); @@ -545,25 +532,22 @@ function index($action=null) } else { - redirect(site_url('admin/survey/view/'.$surveyid.'/'.$gid.'/'.$qid)); + $this->controller->redirect($this->controller->createUrl('admin/survey/sa/view/surveyid/'.$surveyid.'/gid/'.$gid.'/qid/'.$qid)); } } if ($action == "updatequestion" && bHasSurveyPermission($surveyid, 'surveycontent','update')) { - $_POST = $this->input->post(); - $this->load->helper('database'); - - - $cqquery = "SELECT type, gid FROM ".$this->db->dbprefix."questions WHERE qid={$qid}"; - $cqresult=db_execute_assoc($cqquery); // or safe_die ("Couldn't get question type to check for change
".$cqquery."
".$connect->ErrorMsg()); // Checked - $cqr=$cqresult->row_array(); + Yii::app()->loadHelper('expressions/em_manager'); + $cqquery = "SELECT type, gid FROM {{questions}} WHERE qid={$qid}"; + $cqresult=Yii::app()->db->createCommand($cqquery)->query(); // or safe_die ("Couldn't get question type to check for change
".$cqquery."
".$connect->ErrorMsg()); // Checked + $cqr=$cqresult->read(); $oldtype=$cqr['type']; $oldgid=$cqr['gid']; // Remove invalid question attributes on saving $qattributes=questionAttributes(); - $attsql="delete from ".$this->db->dbprefix."question_attributes where qid='{$qid}' and "; + $attsql="delete from {{question_attributes}} where qid='{$qid}' and "; if (isset($qattributes[$_POST['type']])){ $validAttributes=$qattributes[$_POST['type']]; foreach ($validAttributes as $validAttribute) @@ -573,7 +557,7 @@ function index($action=null) } } $attsql.='1=1'; - db_execute_assoc($attsql); // or safe_die ("Couldn't delete obsolete question attributes
".$attsql."
".$connect->ErrorMsg()); // Checked + Yii::app()->db->createCommand($attsql)->execute(); // or safe_die ("Couldn't delete obsolete question attributes
".$attsql."
".$connect->ErrorMsg()); // Checked $aLanguages=array_merge(array(GetBaseLanguageFromSurveyID($surveyid)),GetAdditionalLanguagesFromSurveyID($surveyid)); @@ -593,21 +577,21 @@ function index($action=null) { if (isset($_POST[$validAttribute['name'].'_'.$sLanguage])) { - $value=$this->db->escape($_POST[$validAttribute['name'].'_'.$sLanguage]); - $query = "select qaid from ".$this->db->dbprefix."question_attributes + $value=sanatize_paranoid_string($_POST[$validAttribute['name'].'_'.$sLanguage]); + $query = "select qaid from {{question_attributes}} WHERE attribute='".$validAttribute['name']."' AND qid={$qid} AND language='{$sLanguage}'"; - $result = db_execute_assoc($query); // or safe_die("Error updating attribute value
".$query."
".$connect->ErrorMsg()); // Checked - if ($result->num_rows()>0) + $result = Yii::app()->db->createCommand($query)->query(); // or safe_die("Error updating attribute value
".$query."
".$connect->ErrorMsg()); // Checked + if ($result->getRowCount()>0) { - $query = "UPDATE ".$this->db->dbprefix."question_attributes + $query = "UPDATE {{question_attributes}} SET value=".$value." WHERE attribute='".$validAttribute['name']."' AND qid={$qid} AND language='{$sLanguage}'"; - $result = db_execute_assoc($query) ; // or safe_die("Error updating attribute value
".$query."
".$connect->ErrorMsg()); // Checked + $result = Yii::app()->db->createCommand($query)->execute() ; // or safe_die("Error updating attribute value
".$query."
".$connect->ErrorMsg()); // Checked } else { - $query = "INSERT into ".$this->db->dbprefix."question_attributes + $query = "INSERT into {{question_attributes}} (qid, value, attribute, language) values ({$qid},{$value},'{$validAttribute['name']}','{$sLanguage}')"; - $result = db_execute_assoc($query); // or safe_die("Error updating attribute value
".$query."
".$connect->ErrorMsg()); // Checked + $result = Yii::app()->db->createCommand($query)->execute(); // or safe_die("Error updating attribute value
".$query."
".$connect->ErrorMsg()); // Checked } } } @@ -616,21 +600,21 @@ function index($action=null) { if (isset($_POST[$validAttribute['name']])) { - $query = "select qaid from ".$this->db->dbprefix."question_attributes + $query = "select qaid from {{question_attributes}} WHERE attribute='".$validAttribute['name']."' AND qid=".$qid; - $result = db_execute_assoc($query); // or safe_die("Error updating attribute value
".$query."
".$connect->ErrorMsg()); // Checked - $value = $this->db->escape($_POST[$validAttribute['name']]); - if ($result->num_rows()>0) + $result = Yii::app()->db->createCommand($query)->query(); // or safe_die("Error updating attribute value
".$query."
".$connect->ErrorMsg()); // Checked + $value = sanitize_string_paranoid($_POST[$validAttribute['name']]); + if ($result->getRowCount()>0) { - $query = "UPDATE ".$this->db->dbprefix."question_attributes + $query = "UPDATE {{question_attributes}} SET value=".$value.",language=NULL WHERE attribute='".$validAttribute['name']."' AND qid=".$qid; - $result = db_execute_assoc($query) ; // or safe_die("Error updating attribute value
".$query."
".$connect->ErrorMsg()); // Checked + $result = Yii::app()->db->createCommand($query)->execute() ; // or safe_die("Error updating attribute value
".$query."
".$connect->ErrorMsg()); // Checked } else { - $query = "INSERT into ".$this->db->dbprefix."question_attributes + $query = "INSERT into {{question_attributes}} (qid, value, attribute) values ($qid,$value,'{$validAttribute['name']}')"; - $result = db_execute_assoc($query); // or safe_die("Error updating attribute value
".$query."
".$connect->ErrorMsg()); // Checked + $result = Yii::app()->db->createCommand($query)->execute(); // or safe_die("Error updating attribute value
".$query."
".$connect->ErrorMsg()); // Checked } } } @@ -694,29 +678,26 @@ function index($action=null) $questlangs = GetAdditionalLanguagesFromSurveyID($surveyid); $baselang = GetBaseLanguageFromSurveyID($surveyid); array_push($questlangs,$baselang); - if ($this->config->item('filterxsshtml')) - { - $_POST['title']=$this->security->xss_clean($_POST['title']); - } - else - { - $_POST['title'] = html_entity_decode($_POST['title'], ENT_QUOTES, "UTF-8"); - } + $p = new CHtmlPurifier(); + if (Yii::app()->getConfig('filterxsshtml')) + $_POST['title'] = $p->purify($_POST['title']); + else + $_POST['title'] = html_entity_decode($_POST['title'], ENT_QUOTES, "UTF-8"); + // Fix bug with FCKEditor saving strange BR types $_POST['title']=fix_FCKeditor_text($_POST['title']); - $this->load->model('questions_model'); foreach ($questlangs as $qlang) { - if ($this->config->item('filterxsshtml')) - { - $_POST['question_'.$qlang]=$this->security->xss_clean($_POST['question_'.$qlang]); - $_POST['help_'.$qlang]=$this->security->xss_clean($_POST['help_'.$qlang]); - } - else - { - $_POST['question_'.$qlang] = html_entity_decode($_POST['question_'.$qlang], ENT_QUOTES, "UTF-8"); - $_POST['help_'.$qlang] = html_entity_decode($_POST['help_'.$qlang], ENT_QUOTES, "UTF-8"); - } + if (Yii::app()->getConfig('filterxsshtml')) + { + $_POST['question_'.$qlang] = $p->purify($_POST['question_'.$qlang]); + $_POST['help_'.$qlang] = $p->purify($_POST['help_'.$qlang]); + } + else + { + $_POST['question_'.$qlang] = html_entity_decode($_POST['question_'.$qlang], ENT_QUOTES, "UTF-8"); + $_POST['help_'.$qlang] = html_entity_decode($_POST['help_'.$qlang], ENT_QUOTES, "UTF-8"); + } // Fix bug with FCKEditor saving strange BR types $_POST['question_'.$qlang]=fix_FCKeditor_text($_POST['question_'.$qlang]); @@ -726,15 +707,15 @@ function index($action=null) { // ToDo: Sanitize the POST variables ! $udata = array( - 'type' => $_POST['type'], - 'title' => $_POST['title'], - 'question' => $_POST['question_'.$qlang], - 'preg' => $_POST['preg'], - 'help' => $_POST['help_'.$qlang], - 'gid' => $gid, - 'other' => $_POST['other'], - 'mandatory' => $_POST['mandatory'], - 'relevance' => $_POST['relevance'], + 'type' => $_POST['type'], + 'title' => $_POST['title'], + 'question' => $_POST['question_'.$qlang], + 'preg' => $_POST['preg'], + 'help' => $_POST['help_'.$qlang], + 'gid' => $gid, + 'other' => $_POST['other'], + 'mandatory' => $_POST['mandatory'], + 'relevance' => $_POST['relevance'], ); if ($oldgid!=$gid) @@ -759,7 +740,11 @@ function index($action=null) } } $condn = array('sid' => $surveyid, 'qid' => $qid, 'language' => $qlang); - $uqresult = $this->questions_model->update($udata,$condn); //($uqquery); // or safe_die ("Error Update Question: ".$uqquery."
".$connect->ErrorMsg()); // Checked) + $question = Questions::model()->findByAttributes($condn); + foreach ($udata as $k => $v) + $question->$k = $v; + + $uqresult = $question->save();//($uqquery); // or safe_die ("Error Update Question: ".$uqquery."
".$connect->ErrorMsg()); // Checked) if (!$uqresult) { $databaseoutput .= "\n"; @@ -771,8 +756,8 @@ function index($action=null) // Update the group ID on subquestions, too if ($oldgid!=$gid) { - $sQuery="UPDATE ".$this->db->dbprefix."questions set gid={$gid} where gid={$oldgid} and parent_qid>0"; - $oResult = db_execute_assoc($sQuery); // or safe_die ("Error updating question group ID: ".$uqquery."
".$connect->ErrorMsg()); // Checked + $sQuery="UPDATE {{questions}} set gid={$gid} where gid={$oldgid} and parent_qid>0"; + $oResult = Yii::app()->db->createCommand($sQuery)->execute(); // or safe_die ("Error updating question group ID: ".$uqquery."
".$connect->ErrorMsg()); // Checked // if the group has changed then fix the sortorder of old and new group fixsortorderQuestions($oldgid, $surveyid); fixsortorderQuestions($gid, $surveyid); @@ -782,18 +767,16 @@ function index($action=null) } if ($oldtype != $_POST['type']) { - $sQuery="UPDATE ".$this->db->dbprefix."questions set type=".$this->db->escape($_POST['type'])." where parent_qid={$qid}"; - $oResult = db_execute_assoc($sQuery); // or safe_die ("Error updating question group ID: ".$uqquery."
".$connect->ErrorMsg()); // Checked + $sQuery="UPDATE {{questions}} set type=".sanitize_paranoid_string($_POST['type'])." where parent_qid={$qid}"; + $oResult = Yii::app()->db->createCommand($sQuery)->execute(); // or safe_die ("Error updating question group ID: ".$uqquery."
".$connect->ErrorMsg()); // Checked } - $query = "DELETE FROM ".$this->db->dbprefix."answers WHERE qid= {$qid} and scale_id>={$iAnswerScales}"; - $result = db_execute_assoc($query); // or safe_die("Error: ".$connect->ErrorMsg()); // Checked + $query = "DELETE FROM {{answers}} WHERE qid= {$qid} and scale_id>={$iAnswerScales}"; + $result = Yii::app()->db->createCommand($query)->execute(); // or safe_die("Error: ".$connect->ErrorMsg()); // Checked // Remove old subquestion scales - $query = "DELETE FROM ".$this->db->dbprefix."questions WHERE parent_qid={$qid} and scale_id>={$iSubquestionScales}"; - $result = db_execute_assoc($query) ; //or safe_die("Error: ".$connect->ErrorMsg()); // Checked - $this->session->set_userdata('flashmessage',$clang->gT("Question was successfully saved.")); - + $query = "DELETE FROM {{questions}} WHERE parent_qid={$qid} and scale_id>={$iSubquestionScales}"; + $result = Yii::app()->db->createCommand($query)->execute() ; //or safe_die("Error: ".$connect->ErrorMsg()); // Checked } else @@ -842,7 +825,7 @@ function index($action=null) } else { - redirect(site_url('admin/survey/view/'.$surveyid.'/'.$gid.'/'.$qid)); + $this->controller->redirect($this->controller->createUrl('admin/survey/view/surveyid/'.$surveyid.'/gid/'.$gid.'/qid/'.$qid)); } } diff --git a/application/controllers/admin/export.php b/application/controllers/admin/export.php index c3e1998d30b..fb68167c15e 100644 --- a/application/controllers/admin/export.php +++ b/application/controllers/admin/export.php @@ -48,6 +48,8 @@ public function run($sa) $this->route('showquexmlsurvey', array('surveyid', 'lang')); elseif ($sa == 'exportspss') $this->route('exportspss', array('sid', 'lang')); + elseif ($sa == 'dumplabel') + $this->route('dumplabel', array('lid')); elseif ($sa == 'exportr') $this->route('exportr', array('sid', 'subaction')); } @@ -1264,13 +1266,12 @@ function dumplabel($lid=null) $xml->startDocument('1.0', 'UTF-8'); $xml->startElement('document'); $xml->writeElement('LimeSurveyDocType','Label set'); - $xml->writeElement('DBVersion',$this->config->item("dbversionnumber")); + $xml->writeElement('DBVersion',getGlobalSetting("DBVersion")); // Label sets table - $dbprefix = $this->db->dbprefix; - $lsquery = "SELECT * FROM {$dbprefix}labelsets WHERE lid=".implode(' or lid=',$lids); + $lsquery = "SELECT * FROM {{labelsets}} WHERE lid=".implode(' or lid=',$lids); BuildXMLFromQuery($xml,$lsquery,'labelsets'); // Labels - $lquery = "SELECT lid, code, title, sortorder, language, assessment_value FROM {$dbprefix}labels WHERE lid=".implode(' or lid=',$lids); + $lquery = "SELECT lid, code, title, sortorder, language, assessment_value FROM {{labels}} WHERE lid=".implode(' or lid=',$lids); BuildXMLFromQuery($xml,$lquery,'labels'); $xml->endElement(); // close columns $xml->endDocument(); diff --git a/application/controllers/admin/question.php b/application/controllers/admin/question.php index ea2b74c8957..b51f8a04635 100644 --- a/application/controllers/admin/question.php +++ b/application/controllers/admin/question.php @@ -22,17 +22,22 @@ * @version $Id: question.php 11260 2011-10-25 18:34:55Z tmswhite $ * @access public */ - class question extends Survey_Common_Controller { + class question extends Survey_Common_Action + { /** - * question::__construct() - * Constructor - * @return + * Routes to the correct sub-action + * + * @access public + * @return void */ - function __construct() - { - parent::__construct(); - } + public function run($sa) + { + if ($sa == 'addquestion' || $sa == 'index' || $sa == 'editquestion') + $this->route('index', array('sa', 'surveyid', 'gid', 'qid')); + elseif ($sa == 'import') + $this->route('import', array()); + } /** * question::import() @@ -41,20 +46,20 @@ function __construct() */ function import() { - $action = $this->input->post('action'); - $surveyid = $this->input->post('sid'); - $gid = $this->input->post('gid'); - $clang = $this->limesurvey_lang; + $action = returnglobal('action'); + $surveyid = returnglobal('sid'); + $gid = returnglobal('gid'); + $clang = $this->controller->lang; - $css_admin_includes[] = $this->config->item('styleurl')."admin/default/superfish.css"; - $this->config->set_item("css_admin_includes", $css_admin_includes); + $css_admin_includes[] = Yii::app()->getConfig('styleurl')."/admin/default/superfish.css"; + Yii::app()->setConfig("css_admin_includes", $css_admin_includes); - self::_getAdminHeader(); - self::_showadminmenu($surveyid); - self::_surveybar($surveyid,$gid); - self::_surveysummary($surveyid,"viewquestion"); - self::_questiongroupbar($surveyid,$gid,NULL,"viewgroup"); + $this->controller->_getAdminHeader(); + $this->controller->_showadminmenu($surveyid); + $this->_surveybar($surveyid,$gid); + $this->_surveysummary($surveyid,"viewquestion"); + $this->_questiongroupbar($surveyid,$gid,NULL,"viewgroup"); if ($action == 'importquestion') { @@ -62,7 +67,7 @@ function import() $importquestion = "
".$clang->gT("Import Question")."
\n"; $importquestion .= "
\n"; - $sFullFilepath = $this->config->item('tempdir'). DIRECTORY_SEPARATOR . $_FILES['the_file']['name']; + $sFullFilepath = Yii::app()->getConfig('tempdir'). DIRECTORY_SEPARATOR . $_FILES['the_file']['name']; $aPathInfo = pathinfo($sFullFilepath); $sExtension = $aPathInfo['extension']; @@ -106,7 +111,7 @@ function import() $importquestion .= "
".$clang->gT("Success")."
 
\n" .$clang->gT("File upload succeeded.")."

\n" .$clang->gT("Reading file..")."

\n"; - $this->load->helper('admin/import'); + Yii::app()->loadHelper('admin/import'); if (strtolower($sExtension)=='csv') { $aImportResults=CSVImportQuestion($sFullFilepath, $surveyid, $gid); @@ -142,19 +147,19 @@ function import() ."\n"; $importquestion .= "".$clang->gT("Question import is complete.")."
 \n"; - $importquestion .= "\n"; + $importquestion .= "controller->createUrl('admin/survey/view/surveyid/'.$surveyid.'/gid/'.$gid.'/qid/'.$aImportResults['newqid'])."', '_top')\" />\n"; $importquestion .= "

\n"; unlink($sFullFilepath); $data['display'] = $importquestion; - $this->load->view('survey_view',$data); + $this->controller->render('/survey_view',$data); } - self::_loadEndScripts(); + $this->controller->_loadEndScripts(); - self::_getAdminFooter("http://docs.limesurvey.org", $this->limesurvey_lang->gT("LimeSurvey online manual")); + $this->controller->_getAdminFooter("http://docs.limesurvey.org", $this->controller->lang->gT("LimeSurvey online manual")); } @@ -663,40 +668,39 @@ function _editsubquestion($surveyid,$gid,$qid) */ function index($action,$surveyid,$gid,$qid=null) { - $surveyid = sanitize_int($surveyid); if(isset($qid)) $qid = sanitize_int($qid); $gid = sanitize_int($gid); - self::_js_admin_includes(base_url().'scripts/jquery/jquery.dd.js'); - $css_admin_includes[] = base_url().'scripts/jquery/dd.css'; + $this->getController()->_js_admin_includes(Yii::app()->baseUrl.'scripts/jquery/jquery.dd.js'); + $css_admin_includes[] = Yii::app()->baseUrl.'scripts/jquery/dd.css'; - $css_admin_includes[] = $this->config->item('styleurl')."admin/default/superfish.css"; - $this->config->set_item("css_admin_includes", $css_admin_includes); + $css_admin_includes[] = Yii::app()->getConfig('styleurl')."admin/default/superfish.css"; + Yii::app()->setConfig("css_admin_includes", $css_admin_includes); - self::_getAdminHeader(); - self::_showadminmenu($surveyid);; - self::_surveybar($surveyid,$gid); - self::_surveysummary($surveyid,"viewgroup"); - self::_questiongroupbar($surveyid,$gid,$qid,"addquestion"); + $this->controller->_getAdminHeader(); + $this->controller->_showadminmenu($surveyid);; + $this->_surveybar($surveyid,$gid); + $this->_surveysummary($surveyid,"viewgroup"); + $this->_questiongroupbar($surveyid,$gid,$qid,"addquestion"); if ($action != "addquestion") { - self::_questionbar($surveyid,$gid,$qid,"editquestion"); + $this->_questionbar($surveyid,$gid,$qid,"editquestion"); } - if(bHasSurveyPermission($surveyid,'surveycontent','read')) + if (bHasSurveyPermission($surveyid,'surveycontent','read')) { - $this->session->set_userdata('FileManagerContext',"edit:question:".$surveyid); - $_POST = $this->input->post(); - $clang = $this->limesurvey_lang; - $this->load->helper('admin/htmleditor'); - $this->load->helper('surveytranslator'); - $this->load->helper('database'); + Yii::app()->session['FileManagerContext'] = "edit:question:".$surveyid; + + $clang = $this->controller->lang; + Yii::app()->loadHelper('admin/htmleditor'); + Yii::app()->loadHelper('surveytranslator'); + if (isset($_POST['sortorder'])) {$postsortorder=sanitize_int($_POST['sortorder']);} - $data['adding'] = $adding =($action=="addquestion"); + $data['adding'] = $adding = $action == "addquestion"; $questlangs = GetAdditionalLanguagesFromSurveyID($surveyid); $baselang = GetBaseLanguageFromSurveyID($surveyid); $questlangs[] = $baselang; @@ -705,14 +709,14 @@ function index($action,$surveyid,$gid,$qid=null) if (!$adding) { - $egquery = "SELECT * FROM ".$this->db->dbprefix."questions WHERE sid=$surveyid AND gid=$gid AND qid=$qid"; - $egresult = db_execute_assoc($egquery); - foreach ($egresult->result_array() as $esrow) + $egquery = "SELECT * FROM {{questions}} WHERE sid=$surveyid AND gid=$gid AND qid=$qid"; + $egresult = Yii::app()->db->createCommand($egquery)->query(); + foreach ($egresult->readAll() as $esrow) { if(!array_key_exists($esrow['language'], $questlangs)) // Language Exists, BUT ITS NOT ON THE SURVEY ANYMORE. { - $egquery = "DELETE FROM ".$this->db->dbprefix."questions WHERE sid='{$surveyid}' AND gid='{$gid}' AND qid='{$qid}' AND language='".$esrow['language']."'"; - $egresultD = db_execute_assoc($egquery); + $egquery = "DELETE FROM {{questions}} WHERE sid='{$surveyid}' AND gid='{$gid}' AND qid='{$qid}' AND language='".$esrow['language']."'"; + $egresultD = Yii::app()->db->createCommand($egquery)->query(); } else { $questlangs[$esrow['language']] = 99; } @@ -728,7 +732,7 @@ function index($action,$surveyid,$gid,$qid=null) 'help' => $esrow['help']); } } - if ($egresult==false or $egresult->num_rows()==0) + if ($egresult==false or $egresult->getRowCount()==0) { safe_die('Invalid question id'); } @@ -738,18 +742,16 @@ function index($action,$surveyid,$gid,$qid=null) { if ($value != 99) { - db_switchIDInsert('questions',true); - $egquery = "INSERT INTO ".$this->db->dbprefix."questions (qid, sid, gid, type, title, question, preg, help, other, mandatory, question_order, language)" + $egquery = "INSERT INTO {{questions}} (qid, sid, gid, type, title, question, preg, help, other, mandatory, question_order, language)" ." VALUES ('{$qid}','{$surveyid}', '{$gid}', '{$basesettings['type']}', '{$basesettings['title']}'," ." '{$basesettings['question']}', '{$basesettings['preg']}', '{$basesettings['help']}', '{$basesettings['other']}', '{$basesettings['mandatory']}', '{$basesettings['question_order']}','{$key}')"; - $egresult = db_execute_assoc($egquery); - db_switchIDInsert('questions',false); + $egresult = Yii::app()->createCommand($egquery)->execute(); } } - $eqquery = "SELECT ".$this->db->dbprefix."questions.*, group_name FROM ".$this->db->dbprefix."questions - join ".$this->db->dbprefix."groups on ".$this->db->dbprefix."groups.gid=".$this->db->dbprefix."questions.gid WHERE ".$this->db->dbprefix."questions.sid=$surveyid AND ".$this->db->dbprefix."questions.gid=$gid AND qid=$qid AND ".$this->db->dbprefix."questions.language='{$baselang}'"; - $eqresult = db_execute_assoc($eqquery); + $eqquery = "SELECT {{questions}}.*, group_name FROM {{questions}} + join {{groups}} on {{groups}}.gid={{questions}}.gid WHERE {{questions}}.sid=$surveyid AND {{questions}}.gid=$gid AND qid=$qid AND {{questions}}.language='{$baselang}'"; + $eqresult = Yii::app()->db->createCommand($eqquery)->query(); } $qtypelist=getqtypelist('','array'); @@ -764,7 +766,7 @@ function index($action,$surveyid,$gid,$qid=null) if (!$adding) { - $eqrow = $eqresult->row_array(); // there should be only one datarow, therefore we don't need a 'while' construct here. + $eqrow = $eqresult->read(); // there should be only one datarow, therefore we don't need a 'while' construct here. // Todo: handler in case that record is not found } else @@ -781,6 +783,7 @@ function index($action,$surveyid,$gid,$qid=null) $eqrow['mandatory']='N'; $eqrow['preg']=''; $eqrow['relevance']=1; + $eqrow['group_name'] = ''; } $data['eqrow'] = $eqrow; $data['surveyid'] = $surveyid; @@ -789,17 +792,17 @@ function index($action,$surveyid,$gid,$qid=null) if (!$adding) { - $aqquery = "SELECT * FROM ".$this->db->dbprefix."questions WHERE sid=$surveyid AND gid=$gid AND qid=$qid AND language != '{$baselang}'"; - $aqresult = db_execute_assoc($aqquery); + $aqquery = "SELECT * FROM {{questions}} WHERE sid=$surveyid AND gid=$gid AND qid=$qid AND language != '{$baselang}'"; + $aqresult = Yii::app()->db->createCommand($aqquery)->query(); $data['aqresult'] = $aqresult; } $data['clang'] = $clang; $data['action'] = $action; - $this->load->model('surveys_model'); - $sumresult1 = $this->surveys_model->getDataOnSurvey($surveyid); //$sumquery1, 1) ; //Checked - if ($sumresult1->num_rows()==0){die('Invalid survey id');} // if surveyid is invalid then die to prevent errors at a later time - $surveyinfo = $sumresult1->row_array(); + $sumresult1 = Survey::model()->findByPk($surveyid); //$sumquery1, 1) ; //Checked + if (is_null($sumresult1)) + die('Invalid survey id'); // if surveyid is invalid then die to prevent errors at a later time + $surveyinfo = $sumresult1->attributes; $surveyinfo = array_map('FlattenText', $surveyinfo); $data['activated'] = $activated = $surveyinfo['active']; @@ -808,7 +811,7 @@ function index($action,$surveyid,$gid,$qid=null) { // Prepare selector Class for javascript function : TODO with or without picture $selectormodeclass='full'; // default - if ($this->session->userdata('questionselectormode')=='none'){$selectormodeclass='none';} + if (Yii::app()->session['questionselectormode']=='none'){$selectormodeclass='none';} $data['selectormodeclass'] = $selectormodeclass; } @@ -820,18 +823,17 @@ function index($action,$surveyid,$gid,$qid=null) if ($adding) { - //Get the questions for this group $baselang = GetBaseLanguageFromSurveyID($surveyid); - $oqquery = "SELECT * FROM ".$this->db->dbprefix."questions WHERE sid=$surveyid AND gid=$gid AND language='".$baselang."' order by question_order" ; - $oqresult = db_execute_assoc($oqquery); + $oqquery = "SELECT * FROM {{questions}} WHERE sid=$surveyid AND gid=$gid AND language='".$baselang."' order by question_order" ; + $oqresult = Yii::app()->db->createCommand($oqquery)->query(); $data['oqresult'] = $oqresult; } $data['qid'] = $qid; - $this->load->view("admin/survey/Question/editQuestion_view",$data); - self::_questionJavascript($eqrow['type']); + $this->controller->render("/admin/survey/Question/editQuestion_view",$data); + $this->_questionJavascript($eqrow['type']); } @@ -840,10 +842,10 @@ function index($action,$surveyid,$gid,$qid=null) include('access_denied.php'); } - self::_loadEndScripts(); + $this->controller->_loadEndScripts(); - self::_getAdminFooter("http://docs.limesurvey.org", $this->limesurvey_lang->gT("LimeSurvey online manual")); + $this->controller->_getAdminFooter("http://docs.limesurvey.org", $this->controller->lang->gT("LimeSurvey online manual")); } @@ -856,7 +858,7 @@ function index($action,$surveyid,$gid,$qid=null) */ function _questionjavascript($type) { - $this->load->view('admin/survey/Question/questionJavascript_view',array('type' => $type)); + $this->controller->render('/admin/survey/Question/questionJavascript_view',array('type' => $type)); } /** diff --git a/application/controllers/admin/tokens.php b/application/controllers/admin/tokens.php index 04a3222ddc6..390ed05c709 100644 --- a/application/controllers/admin/tokens.php +++ b/application/controllers/admin/tokens.php @@ -31,9 +31,21 @@ public function run($sa) elseif ($sa == 'addnew') $this->route('addnew', array('surveyid')); elseif ($sa == 'browse') - { $this->route('browse', array('surveyid', 'limit', 'start', 'order', 'searchstring')); - } + elseif ($sa == 'remind') + $this->route('remind', array('surveyid')); + elseif ($sa == 'email') + $this->route('email', array('surveyid')); + elseif ($sa == 'bounceprocessing') + $this->route('bounceprocessing', array('surveyid')); + elseif ($sa == 'bouncesettings') + $this->route('bouncesettings', array('surveyid')); + elseif ($sa == 'exportdialog') + $this->route('exportdialog', array('surveyid')); + elseif ($sa == 'import') + $this->route('import', array('surveyid')); + elseif ($sa == 'importldap') + $this->route('importldap', array('surveyid')); } /** @@ -94,8 +106,9 @@ function bounceprocessing($surveyid) { $surveyid = sanitize_int($surveyid); - $clang = $this->limesurvey_lang; - $this->load->helper('globalsettings'); + $clang = $this->controller->lang; + + Tokens_dynamic::sid($surveyid); $thissurvey=getSurveyInfo($surveyid); if ($thissurvey['bounceprocessing']!='N' && !($thissurvey['bounceprocessing']=='G' && getGlobalSetting('bounceaccounttype')=='off') && bHasSurveyPermission($surveyid, 'tokens','update')) @@ -195,16 +208,17 @@ function bounceprocessing($surveyid) $tokenBounce=explode(": ",$item); if($surveyid == $surveyidBounce[1]) { - $bouncequery = "UPDATE ".db_table_name("tokens_$surveyid")." SET emailstatus='bounced' WHERE token='$tokenBounce[1]';"; + $bouncequery = "UPDATE {{tokens_$surveyid}} SET emailstatus='bounced' WHERE token='$tokenBounce[1]';"; $data = array( 'emailstatus'=> 'bounced' ); $condn = array('token' => $tokenBounce[1]); - $this->load->model('tokens_dynamic_model'); - - $anish= $this->tokens_dynamic_model->updateRecords($surveyid,$data,$condn); //$connect->Execute($bouncequery);) + $record = Tokens_dynamic::model()->findByAttributes($condn); + foreach ($data as $k => $v) + $record->$k = $v; + $record->save(); $readbounce=imap_body($mbox,$count); // Put read if (isset($thissurvey['bounceremove']) && $thissurvey['bounceremove']) // TODO Y or just true, and a imap_delete @@ -222,12 +236,13 @@ function bounceprocessing($surveyid) $checktotal++; @imap_close($mbox); } - $entertimestamp = "update ".db_table_name("surveys")." set bouncetime='$datelastbounce' where sid='$surveyid'"; + $entertimestamp = "update {{surveys}} set bouncetime='$datelastbounce' where sid='$surveyid'"; $data = array('bouncetime' => $datelastbounce); $condn = array('sid' => $surveyid); - $this->load->model('surveys_model'); + $survey = Survey::model()->findByAttributes($condn); + $survey->bouncetime = $datelistbounce; + $executetimestamp = $survey->save(); - $executetimestamp = $this->surveys_model->updateSurvey($data,$condn); //'$connect->Execute($entertimestamp);) if($bouncetotal>0) { echo sprintf($clang->gT("%s messages were scanned out of which %s were marked as bounce by the system."), $checktotal,$bouncetotal); @@ -846,14 +861,14 @@ function updatetokenattributedescriptions($surveyid) function email($surveyid,$tokenids=null) { $surveyid = sanitize_int($surveyid); - $clang=$this->limesurvey_lang; + $clang=$this->controller->lang; if(!bHasSurveyPermission($surveyid, 'tokens', 'update')) { show_error("no permissions"); // TODO Replace } if(isset($tokenids) && $tokenids=="tids") { - $tokenids=$this->input->post("tokenids"); + $tokenids=$_POST['tokenids']; $tokenidsarray=explode("|", substr($tokenids, 1)); //Make the tokenids string into an array, and exclude the first character unset($tokenids); foreach($tokenidsarray as $tokenitem) { @@ -861,13 +876,12 @@ function email($surveyid,$tokenids=null) } } - $this->load->model("tokens_dynamic_model"); - $tkcount=$this->tokens_dynamic_model->totalRecords($surveyid); - $this->load->helper("surveytranslator"); + Tokens_dynamic::sid($surveyid); + $tkcount=count(Tokens_dynamic::model()->findAll()); + Yii::app()->loadHelper("surveytranslator"); - $this->load->model("surveys_model"); - $query = $this->tokens_dynamic_model->getAllRecords($surveyid,FALSE,1); - $examplerow = $query->row_array(); + $query = Tokens_dynamic::model()->find($surveyid); + $examplerow = !is_null($query) ? $query->attributes : array(); $tokenfields=GetTokenFieldsAndNames($surveyid,true); $nrofattributes=0; @@ -875,14 +889,14 @@ function email($surveyid,$tokenids=null) $data['clang']=$clang; $thissurvey=getSurveyInfo($surveyid); $data['thissurvey']=$thissurvey; - $data['imageurl'] = $this->config->item('imageurl'); + $data['imageurl'] = Yii::app()->getConfig('imageurl'); $data['surveyid']=$surveyid; $data['tokenfields']=$tokenfields; $data['nrofattributes']=$nrofattributes; $data['examplerow']=$examplerow; - $this->load->helper("admin/htmleditor_helper"); - + Yii::app()->loadHelper("admin/htmleditor"); + Yii::app()->loadHelper('replacements'); if (getEmailFormat($surveyid) == 'html') { $ishtml=true; @@ -893,19 +907,18 @@ function email($surveyid,$tokenids=null) } $data['ishtml']=$ishtml; - if (!$this->input->post('ok')) + if (empty($_POST['ok'])) { - self::_getAdminHeader(); - $this->load->view("admin/token/tokenbar",$data); - $this->load->view("admin/token/email",$data); - self::_getAdminFooter("http://docs.limesurvey.org", $this->limesurvey_lang->gT("LimeSurvey online manual")); + $this->controller->_getAdminHeader(); + $this->controller->render("/admin/token/tokenbar",$data); + $this->controller->render("/admin/token/email",$data); + $this->controller->_getAdminFooter("http://docs.limesurvey.org", $clang->gT("LimeSurvey online manual")); } else { - $_POST=$this->input->post(); - $tokenid=$this->input->post("tokenid"); - $tokenids=$this->input->post("tokenids"); - $maxemails=$this->config->item("maxemails"); + $tokenid=returnglobal('tokenid'); + $tokenids=returnglobal('tokenids'); + $maxemails=Yii::app()->getConfig("maxemails"); $data['tokenid']=$tokenid; $data['tokenids']=$tokenids; @@ -920,22 +933,32 @@ function email($surveyid,$tokenids=null) } //$ctfieldcount = $ctresult->FieldCount(); - $ctresult=$this->tokens_dynamic_model->ctquery($surveyid,$SQLemailstatuscondition,$tokenid,$tokenids); - $ctcount = $ctresult->num_rows(); + $ctquery = "SELECT * FROM {{tokens_$surveyid}} WHERE ((completed ='N') or (completed='')) AND ((sent ='N') or (sent='')) AND token !='' AND email != '' $SQLemailstatuscondition"; + + if ($tokenid) {$ctquery .= " AND tid='{$tokenid}'";} + if ($tokenids) {$ctquery .= " AND tid IN ('".implode("', '", $tokenids)."')";} - $emresult = $this->tokens_dynamic_model->emquery($surveyid,$SQLemailstatuscondition,$maxemails,$tokenid,$tokenids); - $emcount = $emresult->num_rows(); + $ctresult = Yii::app()->db->createCommand($ctquery)->query(); + $ctcount = $ctresult->getRowCount(); + + $emquery = "SELECT * FROM {{tokens_$surveyid}} WHERE ((completed ='N') or (completed='')) AND ((sent ='N') or (sent='')) AND token !='' AND email != '' $SQLemailstatuscondition"; + + if ($tokenid) {$emquery .= " and tid='{$tokenid}'";} + if ($tokenids) {$emquery .= " AND tid IN ('".implode("', '", $tokenids)."')";} + + $emresult = Yii::app()->db->createCommand($emquery)->limit($maxemails)->query(); + $emcount = $emresult->getRowCount(); $surveylangs = GetAdditionalLanguagesFromSurveyID($surveyid); $baselanguage = GetBaseLanguageFromSurveyID($surveyid); array_unshift($surveylangs,$baselanguage); - $this->load->config("email"); + Yii::app()->loadConfig('email'); foreach ($surveylangs as $language) { $_POST['message_'.$language]=auto_unescape($_POST['message_'.$language]); $_POST['subject_'.$language]=auto_unescape($_POST['subject_'.$language]); - if ($ishtml) $_POST['message_'.$language] = html_entity_decode($_POST['message_'.$language], ENT_QUOTES, $this->config->item("emailcharset")); + if ($ishtml) $_POST['message_'.$language] = html_entity_decode($_POST['message_'.$language], ENT_QUOTES, Yii::app()->getConfig("emailcharset")); } $attributes=GetTokenFieldsAndNames($surveyid); @@ -943,7 +966,7 @@ function email($surveyid,$tokenids=null) if ($emcount > 0) { - foreach ($emresult->result_array() as $emrow) + foreach ($emresult->readAll() as $emrow) { unset($fieldsarray); $to=array(); @@ -970,8 +993,8 @@ function email($surveyid,$tokenids=null) $from = $_POST['from_'.$emrow['language']]; - $publicurl=site_url(); - $modrewrite=$this->config->item("modrewrite"); + $publicurl=Yii::app()->baseUrl; + $modrewrite=Yii::app()->getConfig("modrewrite"); if ($ishtml === false) { $fieldsarray["{OPTOUTURL}"]="$publicurl/optout/local/".trim($emrow['language'])."/$surveyid/{$emrow['token']}"; @@ -1016,16 +1039,16 @@ function email($surveyid,$tokenids=null) { $tokenoutput .= $emrow['tid'] ." ".ReplaceFields($clang->gT("Email to {FIRSTNAME} {LASTNAME} ({EMAIL}) skipped: Token is not valid anymore.")."
", $fieldsarray); } - elseif (SendEmailMessage($modmessage, $modsubject, $to , $from, $this->config->item("sitename"), $ishtml, getBounceEmail($surveyid),null,$customheaders)) + elseif (SendEmailMessage($modmessage, $modsubject, $to , $from, Yii::app()->getConfig("sitename"), $ishtml, getBounceEmail($surveyid),null,$customheaders)) { // Put date into sent - $today = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i", $this->config->item("timeadjust")); - $udequery = "UPDATE ".$this->db->dbprefix("tokens_{$surveyid}")."\n" + $today = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig("timeadjust")); + $udequery = "UPDATE {{tokens_$surveyid}}\n" ."SET sent='$today' WHERE tid={$emrow['tid']}"; // - $uderesult = db_execute_assoc($udequery); + $uderesult = Yii::app()->db->createCommand($udequery)->query(); $tokenoutput .= $clang->gT("Invitation sent to:")." {$emrow['firstname']} {$emrow['lastname']} ($to)
\n"; - if ($this->config->item("emailsmtpdebug")==2) + if (Yii::app()->getConfig("emailsmtpdebug")==2) { $tokenoutput .=$maildebug; } @@ -1075,31 +1098,31 @@ function email($surveyid,$tokenids=null) } $tokenoutput .="\n"; } - $data['clang']=$this->limesurvey_lang; + $data['clang']=$this->controller->lang; $data['thissurvey']=getSurveyInfo($surveyid); - $data['imageurl'] = $this->config->item('imageurl'); + $data['imageurl'] = Yii::app()->getConfig('imageurl'); $data['surveyid']=$surveyid; $data['tokenoutput']=$tokenoutput; - self::_getAdminHeader(); - $this->load->view("admin/token/tokenbar",$data); - $this->load->view("admin/token/emailpost",$data); - self::_getAdminFooter("http://docs.limesurvey.org", $this->limesurvey_lang->gT("LimeSurvey online manual")); + $this->controller->_getAdminHeader(); + $this->controller->render("/admin/token/tokenbar",$data); + $this->controller->render("/admin/token/emailpost",$data); + $this->controller->_getAdminFooter("http://docs.limesurvey.org", $clang->gT("LimeSurvey online manual")); } else { - $data['clang']=$this->limesurvey_lang; + $data['clang']=$this->controller->lang; $data['thissurvey']=getSurveyInfo($surveyid); - $data['imageurl'] = $this->config->item('imageurl'); + $data['imageurl'] = Yii::app()->getConfig('imageurl'); $data['surveyid']=$surveyid; - self::_getAdminHeader(); - $this->load->view("admin/token/tokenbar",$data); - self::_showMessageBox($clang->gT("Warning"), + $this->controller->_getAdminHeader(); + $this->controller->render("/admin/token/tokenbar",$data); + $this->controller->_showMessageBox($clang->gT("Warning"), $clang->gT("There were no eligible emails to send. This will be because none satisfied the criteria of:") ."
 "); - self::_getAdminFooter("http://docs.limesurvey.org", $this->limesurvey_lang->gT("LimeSurvey online manual")); + $this->controller->_getAdminFooter("http://docs.limesurvey.org", $clang->gT("LimeSurvey online manual")); } } } @@ -1110,19 +1133,20 @@ function email($surveyid,$tokenids=null) function remind($surveyid) { $surveyid = sanitize_int($surveyid); - $clang=$this->limesurvey_lang; + $clang=$this->controller->lang; if(!bHasSurveyPermission($surveyid, 'tokens', 'update')) { show_error("no permissions"); // TODO Replace } - $this->load->model("tokens_dynamic_model"); - $tkcount=$this->tokens_dynamic_model->totalRecords($surveyid); - $this->load->helper("surveytranslator"); + Tokens_dynamic::sid($surveyid); - $this->load->model("surveys_model"); - $query = $this->tokens_dynamic_model->getAllRecords($surveyid,FALSE,1); - $examplerow = $query->row_array(); + $tkcount=count(Tokens_dynamic::model()->findAll()); + + Yii::app()->loadHelper("surveytranslator"); + + $query = Tokens_dynamic::model()->find(); + $examplerow = is_null($query) ? array() : $query->attributes; $tokenfields=GetTokenFieldsAndNames($surveyid,true); $nrofattributes=0; @@ -1131,13 +1155,14 @@ function remind($surveyid) $data['clang']=$clang; $thissurvey=getSurveyInfo($surveyid); $data['thissurvey']=$thissurvey; - $data['imageurl'] = $this->config->item('imageurl'); + $data['imageurl'] = Yii::app()->getConfig('imageurl'); $data['surveyid']=$surveyid; $data['tokenfields']=$tokenfields; $data['nrofattributes']=$nrofattributes; $data['examplerow']=$examplerow; - - $this->load->helper("admin/htmleditor_helper"); + $data['surveyid'] = $surveyid; + Yii::app()->loadHelper("admin/htmleditor"); + Yii::app()->loadHelper('replacements'); if (getEmailFormat($surveyid) == 'html') { @@ -1149,20 +1174,18 @@ function remind($surveyid) } $data['ishtml']=$ishtml; - if (!$this->input->post('ok')) + if (empty($_POST['ok'])) { - self::_getAdminHeader(); - $this->load->view("admin/token/tokenbar",$data); - $this->load->view("admin/token/remind",$data); - self::_getAdminFooter("http://docs.limesurvey.org", $this->limesurvey_lang->gT("LimeSurvey online manual")); + $this->controller->_getAdminHeader(); + $this->controller->render("/admin/token/tokenbar",$data); + $this->controller->render("/admin/token/remind",$data); + $this->controller->_getAdminFooter("http://docs.limesurvey.org", $this->controller->lang->gT("LimeSurvey online manual")); } else { //Views don't work properly when sending emails: The user will only receive feedback after the script is executed. $tokenoutput=""; - $_POST=$this->input->post(); - $this->load->helper("database"); //$tokenoutput .= $clang->gT("Sending Reminders") $surveylangs = GetAdditionalLanguagesFromSurveyID($surveyid); @@ -1219,24 +1242,23 @@ function remind($surveyid) $SQLreminderdelaycondition = ""; } - $ctquery = "SELECT * FROM ".$this->db->dbprefix("tokens_{$surveyid}")." WHERE (completed ='N' or completed ='') AND sent<>'' AND sent<>'N' AND token <>'' AND email <> '' $SQLemailstatuscondition $SQLremindercountcondition $SQLreminderdelaycondition"; + $ctquery = "SELECT * FROM {{tokens_$surveyid}} WHERE (completed ='N' or completed ='') AND sent<>'' AND sent<>'N' AND token <>'' AND email <> '' $SQLemailstatuscondition $SQLremindercountcondition $SQLreminderdelaycondition"; if (isset($starttokenid)) {$ctquery .= " AND tid > '{$starttokenid}'";} if (isset($tokenid) && $tokenid) {$ctquery .= " AND tid = '{$tokenid}'";} if (isset($tokenids)) {$ctquery .= " AND tid IN (".implode(", ", $tokenids).")";} $tokenoutput .= "\n"; - $ctresult = db_execute_assoc($ctquery) or safe_die ("Database error!
\n" . $connect->ErrorMsg()); - $ctcount = $ctresult->num_rows(); + $ctresult = Yii::app()->db->createCommand($ctquery)->query(); + $ctcount = $ctresult->getRowCount(); //$ctfieldcount = $ctresult->FieldCount(); - $emquery = "SELECT * FROM ".$this->db->dbprefix("tokens_{$surveyid}")." WHERE (completed = 'N' or completed = '') AND sent <> 'N' and sent <>'' AND token <>'' AND EMAIL <>'' $SQLemailstatuscondition $SQLremindercountcondition $SQLreminderdelaycondition"; + $emquery = "SELECT * FROM {{tokens_$surveyid}} WHERE (completed = 'N' or completed = '') AND sent <> 'N' and sent <>'' AND token <>'' AND EMAIL <>'' $SQLemailstatuscondition $SQLremindercountcondition $SQLreminderdelaycondition"; if (isset($starttokenid)) {$emquery .= " AND tid > '{$starttokenid}'";} if (isset($tokenid) && $tokenid) {$emquery .= " AND tid = '{$tokenid}'";} if (isset($tokenids)) {$emquery .= " AND tid IN (".implode(", ", $tokenids).")";} $emquery .= " ORDER BY tid "; - $emresult = db_select_limit_assoc($emquery, $this->config->item("maxemails")) or safe_die ("Couldn't do query.
$emquery
".$connect->ErrorMsg()); - $emcount = $emresult->num_rows(); - + $emresult = Yii::app()->db->createCommand($emquery)->limit(Yii::app()->getConfig("maxemails"))->query(); + $emcount = $emresult->getRowCount(); $attributes=GetTokenFieldsAndNames($surveyid); if ($emcount > 0) @@ -1244,7 +1266,7 @@ function remind($surveyid) $tokenoutput .= "\n" ."\t\n" ."\n" + ."\t\n"; if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && captcha_enabled('saveandloadscreen', $thissurvey['usecaptcha'])) { - $_saveform .="\n"; + $_saveform .="\n"; } $_saveform .= "\n" . "\n" @@ -522,7 +520,7 @@ function templatereplace($line, $replacements=array(),&$redata=array(), $debugSr $_loadform .= "' />\n"; if (isset($thissurvey['usecaptcha']) && function_exists("ImageCreate") && captcha_enabled('saveandloadscreen', $thissurvey['usecaptcha'])) { - $_loadform .="\n"; + $_loadform .="\n"; } $_loadform .="\n" . "
\n"; - while ($emrow = $emresult->FetchRow()) + while ($emrow = $emresult-read()) { unset($fieldsarray); $to=array(); @@ -1323,15 +1345,15 @@ function remind($surveyid) { $tokenoutput .= $emrow['tid'] ." ".ReplaceFields($clang->gT("Email to {FIRSTNAME} {LASTNAME} ({EMAIL}) skipped: Token is not valid anymore.")."
", $fieldsarray); } - elseif (SendEmailMessage($sendmessage, $msgsubject, $to, $from, $sitename,$ishtml,getBounceEmail($surveyid),null,$customheaders)) + elseif (SendEmailMessage($sendmessage, $msgsubject, $to, $from, Yii::app()->getConfig('sitename'),$ishtml,getBounceEmail($surveyid),null,$customheaders)) { // Put date into remindersent $today = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i", $timeadjust); - $udequery = "UPDATE ".db_table_name("tokens_{$surveyid}")."\n" + $udequery = "UPDATE {{tokens_$surveyid}}\n" ."SET remindersent='$today',remindercount = remindercount+1 WHERE tid={$emrow['tid']}"; // - $uderesult = $connect->Execute($udequery) or safe_die ("Could not update tokens
$udequery
".$connect->ErrorMsg()); + $uderesult = Yii::app()->db->createCommand($udequery)->execute(); //orig: $tokenoutput .= "({$emrow['tid']})[".$clang->gT("Reminder sent to:")." {$emrow['firstname']} {$emrow['lastname']}]
\n"; $tokenoutput .= "({$emrow['tid']}) [".$clang->gT("Reminder sent to:")." {$emrow['firstname']} {$emrow['lastname']} ($to)]
\n"; } @@ -1402,8 +1424,11 @@ function remind($surveyid) ."
\n"; } //$tokenoutput .= "\n"; - echo $tokenoutput; - } + $this->controller->_getAdminHeader(); + $this->controller->render('/admin/token/tokenbar', $data); + echo $tokenoutput; + $this->controller->_getAdminFooter("http://docs.limesurvey.org", $this->controller->lang->gT("LimeSurvey online manual")); + } } /** @@ -1411,33 +1436,704 @@ function remind($surveyid) */ function exportdialog($surveyid) { + $clang = $this->controller->lang; $surveyid = sanitize_int($surveyid); if (bHasSurveyPermission($surveyid, 'tokens','export') )//EXPORT FEATURE SUBMITTED BY PIETERJAN HEYSE { - $this->load->helper("database"); - if ($this->input->post('submit')) + if (!empty($_POST['submit'])) { - $this->load->helper("export"); + Yii::app()->loadHelper("export"); tokens_export($surveyid); } - $langquery = "SELECT language FROM ".$this->db->dbprefix("tokens_$surveyid")." group by language"; - $langresult = db_execute_assoc($langquery); - $data['resultr'] = $langresult->row_array(); + $langquery = "SELECT language FROM {{tokens_$surveyid}} group by language"; + $langresult = Yii::app()->db->createCommand($langquery)->query(); + $data['resultr'] = $langresult->read(); - $data['clang']=$this->limesurvey_lang; + $data['clang']=$this->controller->lang; $thissurvey=getSurveyInfo($surveyid); $data['thissurvey']=$thissurvey; - $data['imageurl'] = $this->config->item('imageurl'); + $data['imageurl'] = Yii::app()->getConfig('imageurl'); $data['surveyid']=$surveyid; - self::_getAdminHeader(); - $this->load->view("admin/token/tokenbar",$data); - $this->load->view("admin/token/exportdialog",$data); - self::_getAdminFooter("http://docs.limesurvey.org", $this->limesurvey_lang->gT("LimeSurvey online manual")); + $this->controller->_getAdminHeader(); + $this->controller->render("/admin/token/tokenbar",$data); + $this->controller->render("/admin/token/exportdialog",$data); + $this->controller->_getAdminFooter("http://docs.limesurvey.org", $clang->gT("LimeSurvey online manual")); } } + /** + * Performs a ldap import + * + * @access public + * @param int $surveyid + * @return void + */ + public function importldap($surveyid) + { + $surveyid = (int) $surveyid; + $clang = $this->controller->lang; + + Yii::app()->loadConfig('ldap'); + Yii::app()->loadHelper('ldap'); + + $tokenoutput = ''; + if (!bHasSurveyPermission($surveyid, 'tokens', 'create')) + show_error('access denied'); + + if (empty($_POST['submit'])) + { + $tokenoutput .= "\t
".$clang->gT("Upload LDAP entries")."
\n"; + $tokenoutput .= self::formldap(null, $surveyid); + $tokenoutput .= "
\n" + ."\t
".$clang->gT("Note:")."

\n" + .$clang->gT("LDAP queries are defined by the administrator in the config-ldap.php file")."\n" + ."
\n"; + } + else + { + $ldap_queries = Yii::app()->getConfig('ldap_queries'); + $ldap_server = Yii::app()->getConfig('ldap_server'); + + $duplicatelist=array(); + $invalidemaillist=array(); + $tokenoutput .= "\t
" + .$clang->gT("Uploading LDAP Query")."
\n"; + $ldapq=$_POST['ldapQueries']; // the ldap query id + + $ldap_server_id=$ldap_queries[$ldapq]['ldapServerId']; + $ldapserver=$ldap_server[$ldap_server_id]['server']; + $ldapport=$ldap_server[$ldap_server_id]['port']; + if (isset($ldap_server[$ldap_server_id]['encoding']) && + $ldap_server[$ldap_server_id]['encoding'] != 'utf-8' && + $ldap_server[$ldap_server_id]['encoding'] != 'UTF-8') + { + $ldapencoding=$ldap_server[$ldap_server_id]['encoding']; + } + else + { + $ldapencoding=''; + } + + // define $attrlist: list of attributes to read from users' entries + $attrparams = array('firstname_attr','lastname_attr', + 'email_attr','token_attr', 'language'); + + $aTokenAttr=GetAttributeFieldNames($surveyid); + foreach ($aTokenAttr as $thisattrfieldname) + { + $attridx=substr($thisattrfieldname,10); // the 'attribute_' prefix is 10 chars long + $attrparams[] = "attr".$attridx; + } + + foreach ($attrparams as $id => $attr) { + if (array_key_exists($attr,$ldap_queries[$ldapq]) && + $ldap_queries[$ldapq][$attr] != '') { + $attrlist[]=$ldap_queries[$ldapq][$attr]; + } + } + + // Open connection to server + $ds = ldap_getCnx($ldap_server_id); + + if ($ds) { + // bind to server + $resbind=ldap_bindCnx($ds, $ldap_server_id); + + if ($resbind) { + $ResArray=array(); + $resultnum=ldap_doTokenSearch($ds, $ldapq, $ResArray, $surveyid); + $xz = 0; // imported token count + $xv = 0; // meet minim requirement count + $xy = 0; // check for duplicates + $duplicatecount = 0; // duplicate tokens skipped count + $invalidemailcount = 0; + + if ($resultnum >= 1) { + foreach ($ResArray as $responseGroupId => $responseGroup) { + for($j = 0;$j < $responseGroup['count']; $j++) { + // first let's initialize everything to '' + $myfirstname=''; + $mylastname=''; + $myemail=''; + $mylanguage=''; + $mytoken=''; + $myattrArray=array(); + + // The first 3 attrs MUST exist in the ldap answer + // ==> send PHP notice msg to apache logs otherwise + $meetminirequirements=true; + if (isset($responseGroup[$j][$ldap_queries[$ldapq]['firstname_attr']]) && + isset($responseGroup[$j][$ldap_queries[$ldapq]['lastname_attr']]) + ) + { + // minimum requirement for ldap + // * at least a firstanme + // * at least a lastname + // * if filterblankemail is set (default): at least an email address + $myfirstname = ldap_readattr($responseGroup[$j][$ldap_queries[$ldapq]['firstname_attr']]); + $mylastname = ldap_readattr($responseGroup[$j][$ldap_queries[$ldapq]['lastname_attr']]); + if (isset($responseGroup[$j][$ldap_queries[$ldapq]['email_attr']])) + { + $myemail = ldap_readattr($responseGroup[$j][$ldap_queries[$ldapq]['email_attr']]); + $myemail= sanitize_email($myemail); + ++$xv; + } + elseif ($filterblankemail !==true) + { + $myemail = ''; + ++$xv; + } + else + { + $meetminirequirements=false; + } + } + else + { + $meetminirequirements=false; + } + + // The following attrs are optionnal + if ( isset($responseGroup[$j][$ldap_queries[$ldapq]['token_attr']]) ) $mytoken = ldap_readattr($responseGroup[$j][$ldap_queries[$ldapq]['token_attr']]); + + foreach ($aTokenAttr as $thisattrfieldname) + { + $attridx=substr($thisattrfieldname,10); // the 'attribute_' prefix is 10 chars long + if ( isset($ldap_queries[$ldapq]['attr'.$attridx]) && + isset($responseGroup[$j][$ldap_queries[$ldapq]['attr'.$attridx]]) ) $myattrArray[$attridx] = ldap_readattr($responseGroup[$j][$ldap_queries[$ldapq]['attr'.$attridx]]); + } + + if ( isset($responseGroup[$j][$ldap_queries[$ldapq]['language']]) ) $mylanguage = ldap_readattr($responseGroup[$j][$ldap_queries[$ldapq]['language']]); + + // In case Ldap Server encoding isn't UTF-8, let's translate + // the strings to UTF-8 + if ($ldapencoding != '') + { + $myfirstname = @mb_convert_encoding($myfirstname,"UTF-8",$ldapencoding); + $mylastname = @mb_convert_encoding($mylastname,"UTF-8",$ldapencoding); + foreach ($aTokenAttr as $thisattrfieldname) + { + $attridx=substr($thisattrfieldname,10); // the 'attribute_' prefix is 10 chars long + @mb_convert_encoding($myattrArray[$attridx],"UTF-8",$ldapencoding); + } + + } + + // Now check for duplicates or bad formatted email addresses + $dupfound=false; + $invalidemail=false; + if ($filterduplicatetoken) + { + $dupquery = "SELECT firstname, lastname from {{tokens_$surveyid}} where email=".db_quoteall($myemail)." and firstname=".db_quoteall($myfirstname)." and lastname=".db_quoteall($mylastname); + $dupresult = Yii::app()->db->createCommand($dupquery)->query(); + if ( $dupresult->getRowCount() > 0) + { + $dupfound = true; + $duplicatelist[]=$myfirstname." ".$mylastname." (".$myemail.")"; + $xy++; + + } + } + if ($filterblankemail && $myemail=='') + { + $invalidemail=true; + $invalidemaillist[]=$myfirstname." ".$mylastname." ( )"; + } + elseif ($myemail!='' && !validate_email($myemail)) + { + $invalidemail=true; + $invalidemaillist[]=$myfirstname." ".$mylastname." (".$myemail.")"; + } + + if ($invalidemail) + { + ++$invalidemailcount; + } + elseif ($dupfound) + { + ++$duplicatecount; + } + elseif ($meetminirequirements===true) + { + // No issue, let's import + $iq = "INSERT INTO {{tokens_$surveyid}} \n" + . "(firstname, lastname, email, emailstatus, token, language"; + + foreach ($aTokenAttr as $thisattrfieldname) + { + $attridx=substr($thisattrfieldname,10); // the 'attribute_' prefix is 10 chars long + if (!empty($myattrArray[$attridx])) {$iq .= ", $thisattrfieldname";} + } + $iq .=") \n" + . "VALUES (".db_quoteall($myfirstname).", ".db_quoteall($mylastname).", ".db_quoteall($myemail).", 'OK', ".db_quoteall($mytoken).", ".db_quoteall($mylanguage).""; + + foreach ($aTokenAttr as $thisattrfieldname) + { + $attridx=substr($thisattrfieldname,10); // the 'attribute_' prefix is 10 chars long + if (!empty($myattrArray[$attridx])) {$iq .= ", ".db_quoteall($myattrArray[$attridx]).""; }// dbquote_all encloses str with quotes + } + $iq .= ")"; + $ir = Yii::app()->db->createCommand($iq)->execute(); + if (!$ir) $duplicatecount++; + $xz++; + // or safe_die ("Couldn't insert line
\n$buffer
\n".htmlspecialchars($connect->ErrorMsg())."
$iq
\n"); + } + } // End for each entry + } // End foreach responseGroup + } // End of if resnum >= 1 + + if ($xz != 0) + { + $tokenoutput .= "".$clang->gT("Success")."

\n"; + } + else + { + $tokenoutput .= "".$clang->gT("Failed")."

\n"; + } + $message = "$resultnum ".$clang->gT("Results from LDAP Query").".
\n"; + $message .= "$xv ".$clang->gT("Records met minumum requirements").".
\n"; + $message .= "$xz ".$clang->gT("Records imported").".
\n"; + $message .= "$xy ".$clang->gT("Duplicate records removed"); + $message .= " [".$clang->gT("List")."]"; + $message .= ""; + $message .= "
\n"; + $message .= sprintf($clang->gT("%s records with invalid email address removed"),$invalidemailcount); + $message .= " [".$clang->gT("List")."]"; + $message .= ""; + $message .= "
\n"; + $tokenoutput .= "$message
\n"; + } + else { + $errormessage="".$clang->gT("Error").": ".$clang->gT("Can't bind to the LDAP directory")."\n"; + $tokenoutput .= self::formldap($errormessage, $surveyid); + } + @ldap_close($ds); + } + else { + $errormessage="".$clang->gT("Error").": ".$clang->gT("Can't connect to the LDAP directory")."\n"; + $tokenoutput .= self::formldap($errormessage, $surveyid); + } + } + + $this->controller->_getAdminHeader(); + $this->controller->render('/admin/token/tokenbar', array('thissurvey' => getSurveyInfo($surveyid), 'imageurl' => Yii::app()->getConfig('imageurl'), 'clang' => $clang, 'surveyid' => $surveyid)); + echo $tokenoutput; + $this->controller->_getAdminFooter("http://docs.limesurvey.org", $clang->gT("LimeSurvey online manual")); + } + + /** + * Ldap submission form + */ + function formldap($error=null, $surveyid) + { + $ldap_queries = Yii::app()->getConfig('ldap_queries'); + $clang = $this->controller->lang; + + $tokenoutput = ''; + if ($error) {$tokenoutput .= $error . "

\n";} + + if (!function_exists('ldap_connect')) + { + $tokenoutput .= '

'; + $tokenoutput .= $clang->gT('Sorry, but the LDAP module is missing in your PHP configuration.'); + $tokenoutput .= '
'; + } + + elseif (! isset($ldap_queries) || ! is_array($ldap_queries) || count($ldap_queries) == 0) { + $tokenoutput .= '
'; + $tokenoutput .= $clang->gT('LDAP is disabled or no LDAP query defined.'); + $tokenoutput .= '


'; + } + else { + $tokenoutput .= "

"; + $tokenoutput .= '

'; + $tokenoutput .= $clang->gT("Select the LDAP query you want to run:")."
"; + $tokenoutput .= "
"; + $tokenoutput .= '

'; + $tokenoutput .= "

\n" + . "

\n"; + $tokenoutput .= ""; + $tokenoutput .= ""; + $tokenoutput .= "

"; + $tokenoutput .= '
'; + } + + return $tokenoutput; + } + + /** + * import from csv + */ + function import($surveyid) + { + $surveyid = (int) $surveyid; + + if (!bHasSurveyPermission($surveyid, 'tokens', 'create')) + show_error('access denied'); + + $this->controller->_js_admin_includes('scripts/tokens.js'); + + $clang = $this->controller->lang; + + $encodingsarray = array( + "armscii8"=>$clang->gT("ARMSCII-8 Armenian") + ,"ascii"=>$clang->gT("US ASCII") + ,"auto"=>$clang->gT("Automatic") + ,"big5"=>$clang->gT("Big5 Traditional Chinese") + ,"binary"=>$clang->gT("Binary pseudo charset") + ,"cp1250"=>$clang->gT("Windows Central European") + ,"cp1251"=>$clang->gT("Windows Cyrillic") + ,"cp1256"=>$clang->gT("Windows Arabic") + ,"cp1257"=>$clang->gT("Windows Baltic") + ,"cp850"=>$clang->gT("DOS West European") + ,"cp852"=>$clang->gT("DOS Central European") + ,"cp866"=>$clang->gT("DOS Russian") + ,"cp932"=>$clang->gT("SJIS for Windows Japanese") + ,"dec8"=>$clang->gT("DEC West European") + ,"eucjpms"=>$clang->gT("UJIS for Windows Japanese") + ,"euckr"=>$clang->gT("EUC-KR Korean") + ,"gb2312"=>$clang->gT("GB2312 Simplified Chinese") + ,"gbk"=>$clang->gT("GBK Simplified Chinese") + ,"geostd8"=>$clang->gT("GEOSTD8 Georgian") + ,"greek"=>$clang->gT("ISO 8859-7 Greek") + ,"hebrew"=>$clang->gT("ISO 8859-8 Hebrew") + ,"hp8"=>$clang->gT("HP West European") + ,"keybcs2"=>$clang->gT("DOS Kamenicky Czech-Slovak") + ,"koi8r"=>$clang->gT("KOI8-R Relcom Russian") + ,"koi8u"=>$clang->gT("KOI8-U Ukrainian") + ,"latin1"=>$clang->gT("cp1252 West European") + ,"latin2"=>$clang->gT("ISO 8859-2 Central European") + ,"latin5"=>$clang->gT("ISO 8859-9 Turkish") + ,"latin7"=>$clang->gT("ISO 8859-13 Baltic") + ,"macce"=>$clang->gT("Mac Central European") + ,"macroman"=>$clang->gT("Mac West European") + ,"sjis"=>$clang->gT("Shift-JIS Japanese") + ,"swe7"=>$clang->gT("7bit Swedish") + ,"tis620"=>$clang->gT("TIS620 Thai") + ,"ucs2"=>$clang->gT("UCS-2 Unicode") + ,"ujis"=>$clang->gT("EUC-JP Japanese") + ,"utf8"=>$clang->gT("UTF-8 Unicode")); + + $tokenoutput = ''; + + if (!empty($_POST['submit'])) + { + if (isset($_POST['csvcharset']) && $_POST['csvcharset']) //sanitize charset - if encoding is not found sanitize to 'auto' + { + $uploadcharset=$_POST['csvcharset']; + if (!array_key_exists($uploadcharset,$encodingsarray)) {$uploadcharset='auto';} + $filterduplicatetoken=(isset($_POST['filterduplicatetoken']) && $_POST['filterduplicatetoken']=='on'); + $filterblankemail=(isset($_POST['filterblankemail']) && $_POST['filterblankemail']=='on'); + } + $attrfieldnames=GetAttributeFieldnames($surveyid); + $duplicatelist=array(); + $invalidemaillist=array(); + $invalidformatlist=array(); + $tokenoutput .= "\t
".$clang->gT("Token file upload")."
\n" + ."\t
\n"; + + $the_path = Yii::app()->getConfig('tempdir'); + + $the_file_name = $_FILES['the_file']['name']; + $the_file = $_FILES['the_file']['tmp_name']; + $the_full_file_path = $the_path."/".$the_file_name; + + if (!@move_uploaded_file($the_file, $the_full_file_path)) + { + $errormessage="
".$clang->gT("Error")."

".$clang->gT("Upload file not found. Check your permissions and path ({$the_full_file_path}) for the upload directory")."

\n"; + $tokenoutput .= self::form_upload_csv(null, $encodingsarray, $clang, $surveyid); + } + else + { + $tokenoutput .= "
".$clang->gT("Uploaded CSV file successfully")."

\n"; + $xz = 0; $recordcount = 0; $xv = 0; + // This allows to read file with MAC line endings too + @ini_set('auto_detect_line_endings', true); + // open it and trim the ednings + $tokenlistarray = file($the_full_file_path); + $baselanguage=GetBaseLanguageFromSurveyID($surveyid); + if (!isset($tokenlistarray)) + { + $tokenoutput .= "
".$clang->gT("Failed to open the uploaded file!")."

\n"; + } + if (!isset($_POST['filterduplicatefields']) || (isset($_POST['filterduplicatefields']) && count($_POST['filterduplicatefields'])==0)) + { + $filterduplicatefields=array('firstname','lastname','email'); + } else { + $filterduplicatefields=$_POST['filterduplicatefields']; + } + $separator = returnglobal('separator'); + foreach ($tokenlistarray as $buffer) + { + $buffer=@mb_convert_encoding($buffer,"UTF-8",$uploadcharset); + $firstname = ""; $lastname = ""; $email = ""; $emailstatus="OK"; $token = ""; $language=""; $attribute1=""; $attribute2=""; //Clear out values from the last path, in case the next line is missing a value + if ($recordcount==0) + { + // Pick apart the first line + $buffer=removeBOM($buffer); + $allowedfieldnames=array('firstname','lastname','email','emailstatus','token','language', 'validfrom', 'validuntil', 'usesleft'); + $allowedfieldnames=array_merge($attrfieldnames,$allowedfieldnames); + + switch ($separator) { + case 'comma': + $separator = ','; + break; + case 'semicolon': + $separator = ';'; + break; + default: + $comma = substr_count($buffer,','); + $semicolon = substr_count($buffer,';'); + if ($semicolon>$comma) $separator = ';'; else $separator = ','; + } + $firstline = convertCSVRowToArray($buffer,$separator,'"'); + $firstline=array_map('trim',$firstline); + $ignoredcolumns=array(); + //now check the first line for invalid fields + foreach ($firstline as $index=>$fieldname) + { + $firstline[$index] = preg_replace("/(.*) <[^,]*>$/","$1",$fieldname); + $fieldname = $firstline[$index]; + if (!in_array($fieldname,$allowedfieldnames)) + { + $ignoredcolumns[]=$fieldname; + } + } + if (!in_array('firstname',$firstline) || !in_array('lastname',$firstline) || !in_array('email',$firstline)) + { + $tokenoutput .= "
".$clang->gT("Error: Your uploaded file is missing one or more of the mandatory columns: 'firstname', 'lastname' or 'email'")."

"; + $recordcount=count($tokenlistarray); + break; + } + + } + else + { + + $line = convertCSVRowToArray($buffer,$separator,'"'); + + if (count($firstline)!=count($line)) + { + $invalidformatlist[]=$recordcount; + $recordcount++; + continue; + } + $writearray=array_combine($firstline,$line); + + //kick out ignored columns + foreach ($ignoredcolumns as $column) + { + unset($writearray[$column]); + } + $dupfound=false; + $invalidemail=false; + + if ($filterduplicatetoken!=false) + { + $dupquery = "SELECT tid from {{tokens_$surveyid}} where 1=1"; + foreach($filterduplicatefields as $field) + { + if (isset($writearray[$field])) { + $dupquery.=' and '.db_quote_id($field).' = '.db_quoteall($writearray[$field]); + } + } + $dupresult = Yii::app()->db->createCommand($dupquery)->query(); + if ( $dupresult->getRowCount() > 0) + { + $dupfound = true; + $duplicatelist[]=$writearray['firstname']." ".$writearray['lastname']." (".$writearray['email'].")"; + } + } + + + $writearray['email'] = trim($writearray['email']); + + //treat blank emails + if ($filterblankemail && $writearray['email']=='') + { + $invalidemail=true; + $invalidemaillist[]=$line[0]." ".$line[1]." ( )"; + } + if ($writearray['email']!='') + { + $aEmailAddresses=explode(';',$writearray['email']); + foreach ($aEmailAddresses as $sEmailaddress) + { + if (!validate_email($sEmailaddress)) + { + $invalidemail=true; + $invalidemaillist[]=$line[0]." ".$line[1]." (".$line[2].")"; + } + } + } + + if (!isset($writearray['token'])) { + $writearray['token'] = ''; + } else { + $writearray['token'] = sanitize_token($writearray['token']); + } + + if (!$dupfound && !$invalidemail) + { + if (!isset($writearray['emailstatus']) || $writearray['emailstatus']=='') $writearray['emailstatus'] = "OK"; + if (!isset($writearray['language']) || $writearray['language'] == "") $writearray['language'] = $baselanguage; + if (isset($writearray['validfrom']) && trim($writearray['validfrom']=='')){ unset($writearray['validfrom']);} + if (isset($writearray['validuntil']) && trim($writearray['validuntil']=='')){ unset($writearray['validuntil']);} + + // sanitize it before writing into table + $sanitizedArray = array_map('db_quoteall',array_values($writearray)); + + $iq = "INSERT INTO {{tokens_$surveyid}} \n" + . "(".implode(',',array_keys($writearray)).") \n" + . "VALUES (".implode(",",$sanitizedArray).")"; + $ir = Yii::app()->db->createCommand($iq)->execute(); + + if (!$ir) + { + $duplicatelist[]=$writearray['firstname']." ".$writearray['lastname']." (".$writearray['email'].")"; + } else { + $xz++; + } + } + $xv++; + } + $recordcount++; + } + $recordcount = $recordcount-1; + if ($xz != 0) + { + $tokenoutput .= "
".$clang->gT("Successfully created token entries")."

\n"; + } else { + $tokenoutput .= "
".$clang->gT("Failed to create token entries")."
\n"; + } + $message = '
  • '.sprintf($clang->gT("%s records in CSV"),$recordcount)."
  • \n"; + $message .= '
  • '.sprintf($clang->gT("%s records met minumum requirements"),$xv)."
  • \n"; + $message .= '
  • '.sprintf($clang->gT("%s records imported"),$xz)."
\n"; + + + if (count($duplicatelist)>0 || count($invalidformatlist)>0 || count($invalidemaillist)>0) + { + + $message .="
".$clang->gT('Warnings')."
    "; + if (count($duplicatelist)>0) + { + $message .= '
  • '.sprintf($clang->gT("%s duplicate records removed"),count($duplicatelist)); + $message .= " [".$clang->gT("List")."]"; + $message .= ""; + $message .= "
  • \n"; + } + + if (count($invalidformatlist)>0) + { + $message .= '
  • '.sprintf($clang->gT("%s lines had a mismatching number of fields."),count($invalidformatlist)); + $message .= " [".$clang->gT("List")."]"; + $message .= "\n"; + } + else + { + $tokenoutput = self::form_upload_csv(null, $encodingsarray, $clang, $surveyid); + $tokenoutput .= "
    \n" + ."
    ".$clang->gT("CSV input format")."
    \n" + ."

    ".$clang->gT("File should be a standard CSV (comma delimited) file with optional double quotes around values (default for OpenOffice and Excel). The first line must contain the field names. The fields can be in any order.").'

    '.$clang->gT("Mandatory fields:")." firstname,lastname,email
    " + .''.$clang->gT('Optional fields:')." emailstatus, token, language, validfrom, validuntil, attribute_1, attribute_2, attribute_3, usesleft, ... ." + ."
    \n"; + } + + $this->controller->_getAdminHeader(); + $this->controller->render('/admin/token/tokenbar', array('thissurvey' => getSurveyInfo($surveyid), 'imageurl' => Yii::app()->getConfig('imageurl'), 'clang' => $clang, 'surveyid' => $surveyid)); + echo $tokenoutput; + $this->controller->_getAdminFooter("http://docs.limesurvey.org", $clang->gT("LimeSurvey online manual")); + } + + function form_upload_csv($error = null, $encodingsarray = array(), $clang = null, $surveyid) + { + $tokenoutput = ''; + if ($error) {$tokenoutput .= $error . "

    \n";} + asort($encodingsarray); + $charsetsout=''; + foreach ($encodingsarray as $charset=>$title) + { + $charsetsout.=""; + if ($separator == 'comma') $selected = " selected = 'selected'"; else $selected = ''; + $separatorout .= ""; + if ($separator == 'semicolon') $selected = " selected = 'selected'"; else $selected = ''; + $separatorout .= ""; + $tokenoutput .= "
      \n" + . "
    • \n" + . "
    • \n" + . "
    • \n" + . "
    • \n" + . "
    • " + . "
    • " + . " " + . "
    \n" + . "

    \n" + . "\n" + . "\n" + . "

    \n\n"; + return $tokenoutput; + } /** * Generate tokens */ @@ -1549,15 +2245,14 @@ function kill($surveyid) function bouncesettings($surveyid) { $surveyid = sanitize_int($surveyid); - $clang = $this->limesurvey_lang; - $data['clang']=$this->limesurvey_lang; + $clang = $this->controller->lang; + $data['clang']=$clang; $data['thissurvey'] = $data['settings']=getSurveyInfo($surveyid); - $data['imageurl'] = $this->config->item('imageurl'); + $data['imageurl'] = Yii::app()->getConfig('imageurl'); $data['surveyid']=$surveyid; - if($this->input->post()) + if(!empty($_POST)) { - $_POST = $this->input->post(); @$fieldvalue = array("bounceprocessing"=>$_POST['bounceprocessing'], "bounce_email"=>$_POST['bounce_email'], ); @@ -1571,21 +2266,23 @@ function bouncesettings($surveyid) $fieldvalue['bounceaccounthost']=$_POST['bounceaccounthost']; } - $where = "sid = $surveyid"; - $this->load->helper("database"); - db_execute_assoc($this->db->update_string('surveys', $fieldvalue, $where)); + $survey = Survey::model()->findByAttributes(array('sid' => $surveyid)); + foreach ($fieldvalue as $k => $v) + $survey->$k = $v; + $survey->save(); + //$connect->AutoExecute("{$dbprefix}surveys", $fieldvalue, 2,"sid=$surveyid",get_magic_quotes_gpc()); - self::_getAdminHeader(); - $this->load->view("admin/token/tokenbar",$data); - self::_showMessageBox($clang->gT("Bounce settings"),$clang->gT("Bounce settings have been saved."),"successheader"); - self::_getAdminFooter("http://docs.limesurvey.org", $this->limesurvey_lang->gT("LimeSurvey online manual")); + $this->controller->_getAdminHeader(); + $this->controller->render("/admin/token/tokenbar",$data); + $this->controller->_showMessageBox($clang->gT("Bounce settings"),$clang->gT("Bounce settings have been saved."),"successheader"); + $this->controller->_getAdminFooter("http://docs.limesurvey.org", $clang->gT("LimeSurvey online manual")); } else { - self::_getAdminHeader(); - $this->load->view("admin/token/tokenbar",$data); - $this->load->view("admin/token/bounce",$data); - self::_getAdminFooter("http://docs.limesurvey.org", $this->limesurvey_lang->gT("LimeSurvey online manual")); + $this->controller->_getAdminHeader(); + $this->controller->render("/admin/token/tokenbar",$data); + $this->controller->render("/admin/token/bounce",$data); + $this->controller->_getAdminFooter("http://docs.limesurvey.org", $clang->gT("LimeSurvey online manual")); } } diff --git a/application/helpers/admin/import_helper.php b/application/helpers/admin/import_helper.php index 109641c8be4..13c5d8674c2 100644 --- a/application/helpers/admin/import_helper.php +++ b/application/helpers/admin/import_helper.php @@ -307,7 +307,7 @@ function CSVImportGroup($sFullFilepath, $newsid) $lsiresult=Yii::app()->db->createCommand($lsainsert)->query(); $results['labelsets']++; // Get the new insert id for the labels inside this labelset - $newlid=Yii::app()->db->getgetLastInsertID(); //$connect->Insert_ID("{$dbprefix}labelsets",'lid'); + $newlid=Yii::app()->db->getgetLastInsertID(); //$connect->Insert_ID("{{labelsets}}",'lid'); if ($labelsarray) { $count=0; @@ -444,7 +444,7 @@ function CSVImportGroup($sFullFilepath, $newsid) //GET NEW GID .... if is not done before and we count a group if a new gid is required if ($newgid == 0) { - $newgid = Yii::apps()->db->getgetLastInsertID(); //$connect->Insert_ID("{$dbprefix}groups",'gid'); + $newgid = Yii::apps()->db->getgetLastInsertID(); //$connect->Insert_ID("{{groups}}",'gid'); $countgroups++; } } @@ -535,7 +535,7 @@ function CSVImportGroup($sFullFilepath, $newsid) } else { - $aQIDReplacements[$oldqid]=Yii::app()->db->getLastInsertID(); //$connect->Insert_ID("{$dbprefix}questions",'qid'); + $aQIDReplacements[$oldqid]=Yii::app()->db->getLastInsertID(); //$connect->Insert_ID("{{questions}}",'qid'); $saveqid=$aQIDReplacements[$oldqid]; } $qtypes = getqtypelist("" ,"array"); @@ -574,7 +574,7 @@ function CSVImportGroup($sFullFilepath, $newsid) $qres = Yii::app()->db->createCommand($qinsert)->query() or safe_die ($clang->gT("Error").": Failed to insert question
    \n$qinsert
    \n"); if ($fieldname=='') { - $aSQIDReplacements[$labelrow['code'].'_'.$saveqid]=$CI->db->insert_id(); //$connect->Insert_ID("{$dbprefix}questions","qid"); + $aSQIDReplacements[$labelrow['code'].'_'.$saveqid]=$CI->db->insert_id(); //$connect->Insert_ID("{{questions}}","qid"); } } } @@ -661,7 +661,7 @@ function CSVImportGroup($sFullFilepath, $newsid) $qres = Yii::app()->db->createCommand()->insert('{{questions}}', $questionrowdata); if (!isset($questionrowdata['qid'])) { - $aSQIDReplacements[$answerrowdata['code'].$answerrowdata['qid']]=Yii::app()->db->getLastInsertID(); //$connect->Insert_ID("{$dbprefix}questions","qid"); + $aSQIDReplacements[$answerrowdata['code'].$answerrowdata['qid']]=Yii::app()->db->getLastInsertID(); //$connect->Insert_ID("{{questions}}","qid"); } $results['subquestions']++; @@ -723,7 +723,7 @@ function CSVImportGroup($sFullFilepath, $newsid) unset($qarowdata["qaid"]); - //$tablename="{$dbprefix}question_attributes"; + //$tablename="{{question_attributes}}"; //$qainsert=$connect->GetInsertSQL($tablename,$qarowdata); $result = Yii::app()->db->createCommand()->insert('{{question_attributes}}', $qarowdata); if ($result!==false) $results['question_attributes']++; @@ -1123,10 +1123,8 @@ function XMLImportGroup($sFullFilepath, $newsid) */ function CSVImportQuestion($sFullFilepath, $newsid, $newgid) { - $CI =& get_instance(); - $CI->load->helper('database'); - $clang = $CI->limesurvey_lang; - $dbprefix = $CI->db->dbprefix; + $clang = Yii::app()->lang; + $aLIDReplacements=array(); $aQIDReplacements=array(); // this array will have the "new qid" for the questions, the key will be the "old qid" $aSQIDReplacements=array(); @@ -1347,11 +1345,11 @@ function CSVImportQuestion($sFullFilepath, $newsid, $newgid) unset($labelsetrowdata['lid']); $newvalues=array_values($labelsetrowdata); //$newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly - $lsainsert = "INSERT INTO {$dbprefix}labelsets (".implode(',',array_keys($labelsetrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix + $lsainsert = "INSERT INTO {{labelsets}} (".implode(',',array_keys($labelsetrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix $lsiresult=Yii::app()->db->createCommand($lsainsert)->query(); // Get the new insert id for the labels inside this labelset - $newlid=$CI->db->insert_id(); //$connect->Insert_ID("{$dbprefix}labelsets",'lid'); + $newlid=Yii::app()->db->getLastInsertID(); //$connect->Insert_ID("{{labelsets}}",'lid'); if ($labelsarray) { $count=0; @@ -1376,7 +1374,7 @@ function CSVImportQuestion($sFullFilepath, $newsid, $newgid) $newvalues=array_values($labelrowdata); //$newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly - $lainsert = "INSERT INTO {$dbprefix}labels (".implode(',',array_keys($labelrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix + $lainsert = "INSERT INTO {{labels}} (".implode(',',array_keys($labelrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix $liresult=Yii::app()->db->createCommand($lainsert)->query(); $results['labels']++; } @@ -1386,7 +1384,7 @@ function CSVImportQuestion($sFullFilepath, $newsid, $newgid) //CHECK FOR DUPLICATE LABELSETS $thisset=""; $query2 = "SELECT code, title, sortorder, language, assessment_value - FROM {$dbprefix}labels + FROM {{labels}} WHERE lid=".$newlid." ORDER BY language, sortorder, code"; $result2 = Yii::app()->db->createCommand($query2)->query() or safe_die("Died querying labelset $lid
    $query2
    "); @@ -1412,9 +1410,9 @@ function CSVImportQuestion($sFullFilepath, $newsid, $newgid) { //There is a matching labelset. So, we will delete this one and refer //to the matched one. - $query = "DELETE FROM {$dbprefix}labels WHERE lid=$newlid"; + $query = "DELETE FROM {{labels}} WHERE lid=$newlid"; $result=Yii::app()->db->createCommand($query)->query() or safe_die("Couldn't delete labels
    $query
    "); - $query = "DELETE FROM {$dbprefix}labelsets WHERE lid=$newlid"; + $query = "DELETE FROM {{labelsets}} WHERE lid=$newlid"; $result=Yii::app()->db->createCommand($query)->query() or safe_die("Couldn't delete labelset
    $query
    "); $newlid=$lsmatch; } @@ -1471,7 +1469,6 @@ function CSVImportQuestion($sFullFilepath, $newsid, $newgid) } else { - db_switchIDInsert('questions',true); $questionrowdata['qid'] = $newqid; } @@ -1511,19 +1508,14 @@ function CSVImportQuestion($sFullFilepath, $newsid, $newgid) $newvalues=array_values($questionrowdata); $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly - $qinsert = "INSERT INTO {$dbprefix}questions (".implode(',',array_keys($questionrowdata)).") VALUES (".implode(',',$newvalues).")"; + $qinsert = "INSERT INTO {{questions}} (".implode(',',array_keys($questionrowdata)).") VALUES (".implode(',',$newvalues).")"; $qres = Yii::app()->db->createCommand($qinsert)->query() or safe_die("Error: Failed to insert question
    \n$qinsert
    \n"); // set the newqid only if is not set if (!isset($newqid)) { - $newqid=$CI->db->insert_id(); //$connect->Insert_ID("{$dbprefix}questions","qid"); + $newqid=Yii::app()->db->getLastInsertID(); //$connect->Insert_ID("{{questions}}","qid"); } - else - { - db_switchIDInsert('questions',false); - } - } $qtypes = getqtypelist("" ,"array"); $results['answers']=0; @@ -1551,7 +1543,6 @@ function CSVImportQuestion($sFullFilepath, $newsid, $newgid) if (isset($aSQIDReplacements[$labelrow['code']])){ $fieldname='qid,'; $data=$aSQIDReplacements[$labelrow['code']].','; - db_switchIDInsert('questions',true); } else{ $fieldname='' ; @@ -1563,11 +1554,7 @@ function CSVImportQuestion($sFullFilepath, $newsid, $newgid) $qres = Yii::app()->db->createCommand($qinsert)->query() or safe_die ("Error: Failed to insert subquestion
    \n$qinsert
    \n".$connect->ErrorMsg()); if ($fieldname=='') { - $aSQIDReplacements[$labelrow['code']]=$CI->db->insert_id(); //$connect->Insert_ID("{$dbprefix}questions","qid"); - } - else - { - db_switchIDInsert('questions',false); + $aSQIDReplacements[$labelrow['code']]=$CI->db->insert_id(); //$connect->Insert_ID("{{questions}}","qid"); } } @@ -1624,7 +1611,10 @@ function CSVImportQuestion($sFullFilepath, $newsid, $newgid) //$query=$connect->GetInsertSQL($dbprefix.'defaultvalues',$insertdata); - $qres = $CI->defaultvalues_model->insertRecords($insertdata) or safe_die("Error: Failed to insert defaultvalue
    \n"); + $dvalue = new Defaultvalues; + foreach ($insertdata as $k => $v) + $dvalue->$k = $v; + $qres = $dvalue->save(); } // translate internal links @@ -1637,7 +1627,6 @@ function CSVImportQuestion($sFullFilepath, $newsid, $newgid) $questionrowdata=array(); if (isset($aSQIDReplacements[$answerrowdata['code'].$answerrowdata['qid']])){ $questionrowdata['qid']=$aSQIDReplacements[$answerrowdata['code'].$answerrowdata['qid']]; - db_switchIDInsert('questions',true); } $questionrowdata['parent_qid']=$answerrowdata['qid']; $questionrowdata['sid']=$newsid; @@ -1651,14 +1640,13 @@ function CSVImportQuestion($sFullFilepath, $newsid, $newgid) //$tablename=$dbprefix.'questions'; //$query=$connect->GetInsertSQL($tablename,$questionrowdata); - $qres = $CI->questions_model->insertRecords($questionrowdata) or safe_die("Error: Failed to insert question
    \n"); + $question = new Questions; + foreach ($questionrowdata as $k => $v) + $question->$k = $v; + $qres = $question->save(); if (!isset($questionrowdata['qid'])) { - $aSQIDReplacements[$answerrowdata['code'].$answerrowdata['qid']]=$CI->db->insert_id(); //$connect->Insert_ID("{$dbprefix}questions","qid"); - } - else - { - db_switchIDInsert('questions',false); + $aSQIDReplacements[$answerrowdata['code'].$answerrowdata['qid']]=$CI->db->insert_id(); //$connect->Insert_ID("{{questions}}","qid"); } $results['subquestions']++; // also convert default values subquestions for multiple choice @@ -1682,7 +1670,10 @@ function CSVImportQuestion($sFullFilepath, $newsid, $newgid) //$tablename=$dbprefix.'answers'; //$query=$connect->GetInsertSQL($tablename,$answerrowdata); - $ares = $CI->answers_model->insertRecords($answerrowdata) or safe_die("Error: Failed to insert answer
    \n"); + $answer = new Answers; + foreach ($answerrowdata as $k => $v) + $answer->$k = $v; + $ares = $answer->save(); $results['answers']++; } } @@ -1700,10 +1691,13 @@ function CSVImportQuestion($sFullFilepath, $newsid, $newgid) $qarowdata["qid"]=$newqid; unset($qarowdata["qaid"]); - //$tablename="{$dbprefix}question_attributes"; + //$tablename="{{question_attributes}}"; //$qainsert=$connect->GetInsertSQL($tablename,$qarowdata); - $result=$CI->question_attributes_model->insertRecords($qarowdata) or safe_die ("Couldn't insert question_attribute
    "); + $attr = new Question_attributes; + foreach ($qarowdata as $k => $v) + $attr->$k = $v; + $result = $attr->save(); $results['question_attributes']++; } @@ -1727,11 +1721,7 @@ function CSVImportQuestion($sFullFilepath, $newsid, $newgid) */ function XMLImportQuestion($sFullFilepath, $newsid, $newgid) { - $CI =& get_instance(); - $CI->load->helper('database'); - $clang = $CI->limesurvey_lang; - $dbprefix = $CI->db->dbprefix; - + $clang = Yii::app()->lang; $aLanguagesSupported = array(); // this array will keep all the languages supported for the survey $sBaseLanguage = GetBaseLanguageFromSurveyID($newsid); @@ -1809,19 +1799,18 @@ function XMLImportQuestion($sFullFilepath, $newsid, $newgid) if (isset($aQIDReplacements[$oldqid])) { $insertdata['qid']=$aQIDReplacements[$oldqid]; - db_switchIDInsert('questions',true); } //$query=$connect->GetInsertSQL($tablename,$insertdata); - $result = $CI->questions_model->insertRecords($insertdata) or safe_die($clang->gT("Error").": Failed to insert data
    \n"); + + $ques = new Questions; + foreach ($insertdata as $k => $v) + $ques->$k = $v; + $result = $ques->save(); if (!isset($aQIDReplacements[$oldqid])) { - $newqid=$CI->db->insert_id(); //$connect->Insert_ID($tablename,"qid"); // save this for later + $newqid=Yii::app()->db->getLastInsertID(); //$connect->Insert_ID($tablename,"qid"); // save this for later $aQIDReplacements[$oldqid]=$newqid; // add old and new qid to the mapping array } - else - { - db_switchIDInsert('questions',false); - } } // Import subquestions -------------------------------------------------------------- @@ -1848,20 +1837,18 @@ function XMLImportQuestion($sFullFilepath, $newsid, $newgid) } if (isset($aQIDReplacements[$oldsqid])){ $insertdata['qid']=$aQIDReplacements[$oldsqid]; - db_switchIDInsert('questions',true); } //$query=$connect->GetInsertSQL($tablename,$insertdata); - $result = $CI->questions_model->insertRecords($insertdata) or safe_die($clang->gT("Error").": Failed to insert data
    \n"); - $newsqid=$CI->db->insert_id(); //$connect->Insert_ID($tablename,"qid"); // save this for later + $ques = new Questions; + foreach ($insertdata as $k => $v) + $ques->$k = $v; + $result = $ques->save(); + $newsqid=Yii::app()->db->getLastInsertID(); //$connect->Insert_ID($tablename,"qid"); // save this for later if (!isset($insertdata['qid'])) { $aQIDReplacements[$oldsqid]=$newsqid; // add old and new qid to the mapping array } - else - { - db_switchIDInsert('questions',false); - } $results['subquestions']++; } } @@ -1882,7 +1869,10 @@ function XMLImportQuestion($sFullFilepath, $newsid, $newgid) // now translate any links //$query=$connect->GetInsertSQL($tablename,$insertdata); - $result=$CI->answers_model->insertRecords($insertdata) or safe_die ($clang->gT("Error").": Failed to insert data
    \n"); + $answers = new Answers; + foreach ($insertdata as $k => $v) + $answers->$k = $v; + $result = $answers->save(); $results['answers']++; } } @@ -1909,12 +1899,18 @@ function XMLImportQuestion($sFullFilepath, $newsid, $newgid) foreach ($importlanguages as $sLanguage) { $insertdata['language']=$sLanguage; - $result=$CI->question_attributes_model->insertRecords($insertdata) or safe_die($clang->gT("Error").": Failed to insert question_attributes
    "); + $attributes = new Question_attributes; + foreach ($insertdata as $k => $v) + $attributes->$k = $v; + $result = $attributes->save(); } } else { - $result=$CI->question_attributes_model->insertRecords($insertdata) or safe_die($clang->gT("Error").": Failed to insert question_attributes
    \n"); + $attributes = new Question_attributes; + foreach ($insertdata as $k => $v) + $attributes->$k = $v; + $result = $attributes->save(); } $results['question_attributes']++; } @@ -1939,7 +1935,10 @@ function XMLImportQuestion($sFullFilepath, $newsid, $newgid) // now translate any links //$query=$connect->GetInsertSQL($tablename,$insertdata); - $result=$CI->defaultvalues_model->insertRecords($insertdata) or safe_die($clang->gT("Error").": Failed to insert data
    \n"); + $default = new Defaultvalues; + foreach ($insertdata as $k => $v) + $default->$k = $v; + $result = $default->save(); $results['defaultvalues']++; } } @@ -2053,7 +2052,7 @@ function CSVImportLabelset($sFullFilepath, $options) $results['labelsets']++; // Get the new insert id for the labels inside this labelset - $newlid=$CI->db->insert_id(); //$connect->Insert_ID("{$dbprefix}labelsets",'lid'); + $newlid=$CI->db->insert_id(); //$connect->Insert_ID("{{labelsets}}",'lid'); if ($labelsarray) { $count=0; @@ -2145,9 +2144,7 @@ function CSVImportLabelset($sFullFilepath, $options) */ function XMLImportLabelsets($sFullFilepath, $options) { - $CI =& get_instance(); - $CI->load->helper('database'); - $clang = $CI->limesurvey_lang; + $clang = Yii::app()->lang; $xml = simplexml_load_file($sFullFilepath); if ($xml->LimeSurveyDocType!='Label set') safe_die('This is not a valid LimeSurvey label set structure XML file.'); $iDBVersion = (int) $xml->DBVersion; @@ -2156,7 +2153,6 @@ function XMLImportLabelsets($sFullFilepath, $options) $results['labelsets']=0; $results['labels']=0; $results['warnings']=array(); - $dbprefix = $CI->db->dbprefix; // Import labels table =================================================================================== @@ -2176,10 +2172,10 @@ function XMLImportLabelsets($sFullFilepath, $options) // Insert the new question //$query=$connect->GetInsertSQL($tablename,$insertdata); - $result = $CI->labelsets_model->insertRecords($insertdata) or safe_die($clang->gT("Error").": Failed to insert data
    "); + $result = Yii::app()->db->createCommand()->insert('{{labelsets}}', $insertdata); $results['labelsets']++; - $newlsid=$CI->db->insert_id(); //$connect->Insert_ID($tablename,"lid"); // save this for later + $newlsid=Yii::app()->db->getLastInsertID(); //$connect->Insert_ID($tablename,"lid"); // save this for later $aLSIDReplacements[$oldlsid]=$newlsid; // add old and new lsid to the mapping array } @@ -2198,7 +2194,7 @@ function XMLImportLabelsets($sFullFilepath, $options) //$query=$connect->GetInsertSQL($tablename,$insertdata); - $result = $CI->labels_model->insertRecords($insertdata) or safe_die($clang->gT("Error").": Failed to insert data
    "); + $result = Yii::app()->db->createCommand()->insert('{{labels}}', $insertdata); $results['labels']++; } @@ -2213,7 +2209,7 @@ function XMLImportLabelsets($sFullFilepath, $options) FROM {{labels}} WHERE lid=".$newlid." ORDER BY language, sortorder, code"; - $result2 = Yii::app()->db->createCommand($query2)->query() or safe_die("Died querying labelset $lid
    "); + $result2 = Yii::app()->db->createCommand($query2)->query(); foreach($result2->readAll() as $row2) { $row2 = array_values($row2); @@ -2237,10 +2233,11 @@ function XMLImportLabelsets($sFullFilepath, $options) //There is a matching labelset. So, we will delete this one and refer //to the matched one. $query = "DELETE FROM {{labels}} WHERE lid=$newlid"; - $result=Yii::app()->db->createCommand($query)->query() or safe_die("Couldn't delete labels
    $query
    "); - $results['labels']=$results['labels']-$CI->db->affected_rows(); + $result=Yii::app()->db->createCommand($query)->execute(); + $results['labels']=$results['labels']-$result; $query = "DELETE FROM {{labelsets}} WHERE lid=$newlid"; - $result=Yii::app()->db->createCommand($query)->query() or safe_die("Couldn't delete labelset
    $query
    "); + $result=Yii::app()->db->createCommand($query)->query(); + $results['labelsets']--; $newlid=$lsmatch; $results['warnings'][]=$clang->gT("Label set was not imported because the same label set already exists.")." ".sprintf($clang->gT("Existing LID: %s"),$newlid); @@ -2794,7 +2791,7 @@ function CSVImportSurvey($sFullFilepath,$iDesiredSurveyId=NULL,$bTranslateLinks= WHERE lid=".$newlid." ORDER BY language, sortorder, code"; $result2 = Yii::app()->db->createCommand($query2)->query() or safe_die("Died querying labelset $lid
    $query2
    ".$connect->ErrorMsg()); - + foreach($result2->readAll() as $row2) { $row2 = array_values($row2); @@ -2879,12 +2876,11 @@ function CSVImportSurvey($sFullFilepath,$iDesiredSurveyId=NULL,$bTranslateLinks= $gres = Groups::model()->insertRecords($grouprowdata) or safe_die($clang->gT('Error').": Failed to insert group
    \
    \n"); if (isset($grouprowdata['gid'])) db_switchIDInsert('groups',false); - //GET NEW GID if (!isset($grouprowdata['gid'])) { $aGIDReplacements[$oldgid]=Yii::app()->db->createCommand('Select LAST_INSERT_ID()')->query()->read(); //$connect->Insert_ID("{$dbprefix}groups",'gid'); $aGIDReplacements[$oldgid]=$aGIDReplacements[$oldgid]['LAST_INSERT_ID()']; - } + } } // Fix sortorder of the groups - if users removed groups manually from the csv file there would be gaps fixSortOrderGroups($newsid); @@ -2973,7 +2969,7 @@ function CSVImportSurvey($sFullFilepath,$iDesiredSurveyId=NULL,$bTranslateLinks= // Now we will fix up old label sets where they are used as answers if (((isset($oldlid1) && isset($aLIDReplacements[$oldlid1])) || (isset($oldlid2) && isset($aLIDReplacements[$oldlid2]))) && ($qtypes[$questionrowdata['type']]['answerscales']>0 || $qtypes[$questionrowdata['type']]['subquestions']>1)) { - + $query="select * from {{labels}} where lid={$aLIDReplacements[$oldlid1]} and language='{$questionrowdata['language']}'"; $oldlabelsresult=Yii::app()->db->createCommand($query)->query(); foreach($oldlabelsresult->readAll() as $labelrow) @@ -3003,7 +2999,7 @@ function CSVImportSurvey($sFullFilepath,$iDesiredSurveyId=NULL,$bTranslateLinks= $qres = Yii::app()->db->createCommand($qinsert)->query() or safe_die ($clang->gT("Error").": Failed to insert question
    \n$qinsert
    \n"); if ($fieldname=='') { - $aSQIDReplacements[$labelrow['code'].'_'.$saveqid]=$CI->db->insert_id(); //$connect->Insert_ID("{$dbprefix}questions","qid"); + $aSQIDReplacements[$labelrow['code'].'_'.$saveqid]=$CI->db->insert_id(); //$connect->Insert_ID("{{questions}}","qid"); } } } @@ -3061,10 +3057,10 @@ function CSVImportSurvey($sFullFilepath,$iDesiredSurveyId=NULL,$bTranslateLinks= } // Convert default values for single select questions $query1 = 'select type,gid from {{questions}} where qid='.$answerrowdata["qid"]; - + $resultquery1 = Yii::app()->db->createCommand($query1)->query(); $questiontemp=$resultquery1->read(); //$connect->GetRow('select type,gid from '.$CI->db->dbprefix.'questions where qid='.$answerrowdata["qid"]);) - + $oldquestion['newtype']=$questiontemp['type']; $oldquestion['gid']=$questiontemp['gid']; if ($answerrowdata['default_value']=='Y' && ($oldquestion['newtype']=='L' || $oldquestion['newtype']=='O' || $oldquestion['newtype']=='!')) @@ -3159,7 +3155,7 @@ function CSVImportSurvey($sFullFilepath,$iDesiredSurveyId=NULL,$bTranslateLinks= $newvalues=array_values($qarowdata); $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly - + $qainsert = "INSERT INTO {{question_attributes}} (".implode(',',array_keys($qarowdata)).") VALUES (".implode(',',$newvalues).")"; $result=Yii::app()->db->createCommand($qainsert)->execute(); // no safe_die since some LimeSurvey version export duplicate question attributes - these are just ignored if ($result>0) {$importresults['question_attributes']++;} @@ -3563,7 +3559,7 @@ function XMLImportSurvey($sFullFilepath,$sXMLdata=NULL,$sNewSurveyName=NULL,$iDe db_switchIDInsert('questions',true); } - + $result = Questions::model()->insertRecords($insertdata) or safe_die($clang->gT("Error").": Failed to insert data
    "); if (!isset($aQIDReplacements[$oldqid])) { @@ -3913,7 +3909,7 @@ function GetNewSurveyID($oldsid) $query = "SELECT sid FROM {{surveys}} WHERE sid=$oldsid"; $res = Yii::app()->db->createCommand($query)->query(); - $isresult = $res->read(); //$connect->GetOne("SELECT sid FROM {$dbprefix}surveys WHERE sid=$oldsid");) + $isresult = $res->read(); //$connect->GetOne("SELECT sid FROM {{surveys}} WHERE sid=$oldsid");) //if (!is_null($isresult)) if($res->count() > 0) diff --git a/application/helpers/common_helper.php b/application/helpers/common_helper.php index 61c230cd23c..5da85f2271d 100644 --- a/application/helpers/common_helper.php +++ b/application/helpers/common_helper.php @@ -2992,7 +2992,10 @@ function GetBaseLanguageFromSurveyID($surveyid) if (!isset($cache[$surveyid])) { $condition = array('sid' => $surveyid);//"sid=$surveyid"; + $surveylanguage = Survey::model()->findByPk($surveyid);//("SELECT language FROM ".db_table_name('surveys')." WHERE sid=$surveyid";) + if (is_null($surveylanguage)) + die(var_dump(debug_backtrace())); $surveylanguage = $surveylanguage->attributes; //Checked) if (!isset($surveylanguage['language']) || is_null($surveylanguage)) @@ -5853,8 +5856,6 @@ function getTokenData($surveyid, $token) */ function sGetTemplatePath($sTemplateName) { - $CI = &get_instance(); - if (isStandardTemplate($sTemplateName)) { return Yii::app()->getConfig("standardtemplaterootdir").'/'.$sTemplateName; @@ -7918,14 +7919,12 @@ function getlabelsets($languages=null) // Returns a list with label sets // if the $languages paramter is provided then only labelset containing all of the languages in the paramter are provided { - $CI =& get_instance(); - $CI->load->helper('database'); - $clang = $CI->limesurvey_lang; + $clang = Yii::app()->lang; if ($languages){ $languages=sanitize_languagecodeS($languages); $languagesarray=explode(' ',trim($languages)); } - $query = "SELECT ".$CI->db->dbprefix."labelsets.lid as lid, label_name FROM ".$CI->db->dbprefix."labelsets"; + $query = "SELECT {{labelsets}}.lid as lid, label_name FROM {{labelsets}}"; if ($languages){ $query .=" where "; foreach ($languagesarray as $item) @@ -7935,9 +7934,9 @@ function getlabelsets($languages=null) $query .=" 1=1 "; } $query .=" order by label_name"; - $result = db_execute_assoc($query) or safe_die ("Couldn't get list of label sets
    $query
    "); //Checked + $result = Yii::app()->db->createCommand($query)->query(); //Checked $labelsets=array(); - foreach ($result->result_array() as $row) + foreach ($result->readAll() as $row) { $labelsets[] = array($row['lid'], $row['label_name']); } @@ -7948,14 +7947,13 @@ function getHeader($meta = false) { global $embedded; - $CI =& get_instance(); $surveyid = Yii::app()->getConfig('sid'); - $CI->load->helper('surveytranslator'); + Yii::app()->loadHelper('surveytranslator'); $clang = $CI->limesurvey_lang; - if ($CI->session->userdata('s_lang')) + if (!empty(Yii::app()->session['s_lang'])) { - $surveylanguage= $CI->session->userdata('s_lang'); + $surveylanguage= Yii::app()->session['s_lang']; } elseif (isset($surveyid) && $surveyid) { @@ -7974,14 +7972,14 @@ function getHeader($meta = false) if (substr($jsinclude,0,4) == 'http') $js_header .= "\n"; else - $js_header .= "\n"; + $js_header .= "\n"; } } if(Yii::app()->getConfig("css_admin_includes")) { foreach (Yii::app()->getConfig("css_admin_includes") as $cssinclude) { - $css_header .= "\n"; + $css_header .= "baseUrl.$cssinclude."\" />\n"; } } @@ -8531,4 +8529,29 @@ function checkgroupfordisplay($gid,$anonymized,$surveyid) } } +function db_quote_id($id) +{ + // WE DONT HAVE nor USE other thing that alfanumeric characters in the field names + // $quote = $connect->nameQuote; + // return $quote.str_replace($quote,$quote.$quote,$id).$quote; + + switch (Yii::app()->db->createCommand($id)) + { + case "mysqli" : + case "mysql" : + return "`".$id."`"; + break; + case "mssql_n" : + case "mssql" : + case "mssqlnative" : + case "odbc_mssql" : + return "[".$id."]"; + break; + case "postgre": + return "\"".$id."\""; + break; + default: + return "`".$id."`"; + } +} // Closing PHP tag intentionally omitted - yes, it is okay diff --git a/application/helpers/database_helper.php b/application/helpers/database_helper.php index ee4c1c7784b..ba63f1a7208 100644 --- a/application/helpers/database_helper.php +++ b/application/helpers/database_helper.php @@ -117,32 +117,6 @@ function &db_select_column($sql) * @param mixed $id Fieldname to be quoted */ -function db_quote_id($id) -{ - // WE DONT HAVE nor USE other thing that alfanumeric characters in the field names - // $quote = $connect->nameQuote; - // return $quote.str_replace($quote,$quote.$quote,$id).$quote; - - switch (get_instance()->db->platform()) - { - case "mysqli" : - case "mysql" : - return "`".$id."`"; - break; - case "mssql_n" : - case "mssql" : - case "mssqlnative" : - case "odbc_mssql" : - return "[".$id."]"; - break; - case "postgre": - return "\"".$id."\""; - break; - default: - return "`".$id."`"; - } -} - function db_random() { $CI = &get_instance(); diff --git a/application/helpers/export_helper.php b/application/helpers/export_helper.php index 3df8049224b..ed1b19e1d34 100644 --- a/application/helpers/export_helper.php +++ b/application/helpers/export_helper.php @@ -1830,11 +1830,8 @@ function tokens_export($surveyid) header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Pragma: cache"); - $CI =& get_instance(); - $dbprefix = $CI->db->dbprefix; - $_POST = $CI->input->post(); - - $bquery = "SELECT * FROM ".$CI->db->dbprefix("tokens_$surveyid").' where 1=1'; + $bquery = "SELECT * FROM {{tokens_$surveyid}} where 1=1"; + $databasetype = Yii::app()->db->getDriverName(); if (trim($_POST['filteremail'])!='') { if ($databasetype=='odbc_mssql' || $databasetype=='odbtp' || $databasetype=='mssql_n' || $connect->databaseType == 'mssqlnative') @@ -1855,12 +1852,12 @@ function tokens_export($surveyid) $bquery .= " and completed='N'"; if ($thissurvey['anonymized']=='N') { - $bquery .=" and token not in (select token from ".db_table_name("survey_$surveyid")." group by token)"; + $bquery .=" and token not in (select token from {{survey_$surveyid}} group by token)"; } } if ($_POST['tokenstatus']==3 && $thissurvey['anonymized']=='N') { - $bquery .= " and completed='N' and token in (select token from ".db_table_name("survey_$surveyid")." group by token)"; + $bquery .= " and completed='N' and token in (select token from {{survey_$surveyid}} group by token)"; } if ($_POST['invitationstatus']==1) @@ -1887,8 +1884,8 @@ function tokens_export($surveyid) } $bquery .= " ORDER BY tid"; - $bresult = db_execute_assoc($bquery) or die ("$bquery
    ".htmlspecialchars($connect->ErrorMsg())); - $bfieldcount=$bresult->num_rows(); + $bresult = Yii::app()->db->createCommand($bquery)->query(); + $bfieldcount=$bresult->getRowCount(); // Export UTF8 WITH BOM $tokenoutput = chr(hexdec('EF')).chr(hexdec('BB')).chr(hexdec('BF')); $tokenoutput .= "tid,firstname,lastname,email,emailstatus,token,language,validfrom,validuntil,invited,reminded,remindercount,completed,usesleft"; @@ -1901,7 +1898,10 @@ function tokens_export($surveyid) $tokenoutput .=" <".str_replace(","," ",$attrfielddescr[$attr_name]).">"; } $tokenoutput .="\n"; - foreach($bresult->result_array() as $brow) + + Yii::import('application.libraries.Date_Time_Converter', true); + + foreach($bresult->readAll() as $brow) { if (trim($brow['validfrom']!='')) diff --git a/application/helpers/replacements_helper.php b/application/helpers/replacements_helper.php index 465ac545ac2..a9d5a1be029 100644 --- a/application/helpers/replacements_helper.php +++ b/application/helpers/replacements_helper.php @@ -15,8 +15,6 @@ */ function templatereplace($line, $replacements=array(),&$redata=array(), $debugSrc='Unspecified', $anonymized=false, $questionNum=NULL, $registerdata=array()) { - $CI =& get_instance(); - /* global $clienttoken,$token,$sitename,$move,$showXquestions,$showqnumcode,$questioncode,$register_errormsg; global $s_lang,$errormsg,$saved_id, $totalBoilerplatequestions, $relativeurl, $languagechanger,$captchapath,$loadname; @@ -62,7 +60,7 @@ function templatereplace($line, $replacements=array(),&$redata=array(), $debugSr 'totalBoilerplatequestions', 'totalquestions', ); - + $varsPassed = array(); foreach($allowedvars as $var) @@ -81,12 +79,12 @@ function templatereplace($line, $replacements=array(),&$redata=array(), $debugSr // extract($redata); // creates variables for each of the keys in the array // Local over-rides in case not set above - if (!isset($showgroupinfo)) { $showgroupinfo = $CI->config->config['showgroupinfo']; } - if (!isset($showqnumcode)) { $showqnumcode = $CI->config->config['showqnumcode']; } + if (!isset($showgroupinfo)) { $showgroupinfo = Yii::app()->getConfig('showgroupinfo'); } + if (!isset($showqnumcode)) { $showqnumcode = Yii::app()->getConfig('showqnumcode'); } $_surveyid = (isset($surveyid) ? $surveyid : 0); if (!isset($totalBoilerplatequestions)) { $totalBoilerplatequestions = 0; } - if (!isset($showXquestions)) { $showXquestions = $CI->config->config['showXquestions']; } - if (!isset($relativeurl)) { $relativeurl = $CI->config->item("relativeurl"); } + if (!isset($showXquestions)) { $showXquestions = Yii::app()->getConfig('showXquestions'); } + if (!isset($relativeurl)) { $relativeurl = Yii::app()->getConfig("relativeurl"); } if (!isset($s_lang)) { $s_lang = (isset($_SESSION['s_lang']) ? $_SESSION['s_lang'] : 'en'); } if (!isset($captchapath)) { $captchapath = ''; } @@ -94,11 +92,11 @@ function templatereplace($line, $replacements=array(),&$redata=array(), $debugSr { $line = file_get_contents($line); } - - $clang = ($CI->limesurvey_lang) ? $CI->limesurvey_lang : $registerdata['clang']; - - $CI->load->helper('surveytranslator'); + + $clang = Yii::app()->lang; + + Yii::app()->loadHelper('surveytranslator'); $questiondetails = array('sid' => 0, 'gid' => 0, 'qid' => 0, 'aid' =>0); if(isset($question) && isset($question['sgq'])) $questiondetails=getsidgidqidaidtype($question['sgq']); //Gets an array containing SID, GID, QID, AID and Question Type) @@ -113,7 +111,7 @@ function templatereplace($line, $replacements=array(),&$redata=array(), $debugSr } else { - $templatename=$CI->config->item('defaulttemplate'); + $templatename=Yii::app()->getConfig('defaulttemplate'); } $templatename=validate_templatedir($templatename); if(!isset($templatedir)) $templatedir = sGetTemplatePath($templatename); @@ -122,7 +120,7 @@ function templatereplace($line, $replacements=array(),&$redata=array(), $debugSr if (stripos ($line,"")) { $line=str_ireplace("", - "\n" + "\n" .use_firebug() ."\t", $line); } @@ -140,7 +138,7 @@ function templatereplace($line, $replacements=array(),&$redata=array(), $debugSr { $surveyformat .= " page-odd"; } - + if (isset($thissurvey['allowjumps']) && $thissurvey['allowjumps']=="Y" && $surveyformat!="allinone" && (isset($_SESSION['step']) && $_SESSION['step']>0)){ $surveyformat .= " withindex"; } @@ -301,8 +299,8 @@ function templatereplace($line, $replacements=array(),&$redata=array(), $debugSr { $dateformatdetails=getDateFormatData($thissurvey['surveyls_dateformat']); $items = array($thissurvey['expiry'],"Y-m-d"); - $CI->load->library('Date_Time_Converter',$items); - $datetimeobj = $CI->date_time_converter ; + Yii::import('application.libraries.Date_Time_Converter', true); + $datetimeobj = new Date_Time_Converter($items) ; $_dateoutput=$datetimeobj->convert($dateformatdetails['phpdate']); } else @@ -412,7 +410,7 @@ function templatereplace($line, $replacements=array(),&$redata=array(), $debugSr } else { - $helpicon=$CI->config->item('imageurl')."/help.gif"; + $helpicon=Yii::app()->getConfig('imageurl')."/help.gif"; } } $_questionhelp = "Help".$help; @@ -433,7 +431,7 @@ function templatereplace($line, $replacements=array(),&$redata=array(), $debugSr if (isset($thissurvey['active']) and $thissurvey['active'] == "N") { - $_restart= "createUrl("survey/sid/$surveyid/newtest/Y"); if (isset($s_lang) && $s_lang!='') $_restart.="/lang/".$s_lang; $_restart.="'>".$clang->gT("Restart this Survey").""; } @@ -444,7 +442,7 @@ function templatereplace($line, $replacements=array(),&$redata=array(), $debugSr if (!empty($restart_token)) $restart_extra .= "/token/".urlencode($restart_token); else $restart_extra = "/newtest/Y"; if (!empty($_GET['lang'])) $restart_extra .= "/lang/".returnglobal('lang'); - $_restart = "".$clang->gT("Restart this Survey").""; + $_restart = "".$clang->gT("Restart this Survey").""; } else { @@ -501,7 +499,7 @@ function templatereplace($line, $replacements=array(),&$redata=array(), $debugSr $_saveform .= "' />
" . $clang->gT("Security Question") . ":
" . $clang->gT("Security Question") . ":
" . $clang->gT("Security Question") . ":
" . $clang->gT("Security Question") . ":
\n"; @@ -534,7 +532,7 @@ function templatereplace($line, $replacements=array(),&$redata=array(), $debugSr $tokensid = $surveyid; else $tokensid = $registerdata['sid']; - + $_registerform = "
\n"; if (!isset($_REQUEST['lang'])) { @@ -544,7 +542,7 @@ function templatereplace($line, $replacements=array(),&$redata=array(), $debugSr { $_reglang = returnglobal('lang'); } - + $_registerform .= "\n"; $_registerform .= "\n"; @@ -571,7 +569,7 @@ function templatereplace($line, $replacements=array(),&$redata=array(), $debugSr $_registerform .= " value='" . htmlentities(returnglobal('register_email'), ENT_QUOTES, 'UTF-8') . "'"; } $_registerform .= " />\n"; - + if ((count($registerdata) > 1 || isset($thissurvey['usecaptcha'])) && function_exists("ImageCreate") && captcha_enabled('registrationscreen', $thissurvey['usecaptcha'])) { $_registerform .="" . $clang->gT("Security Question") . ":
\n"; @@ -579,14 +577,14 @@ function templatereplace($line, $replacements=array(),&$redata=array(), $debugSr $_registerform .= "" . "\n" . "\n"; - + if (count($registerdata) > 1 && $registerdata['sid'] != NULL && $debugSrc == 'register.php') { $_registerform .= ""; $_registerform .= ""; - } - - + } + + $_registerform .= "
\n"; } else diff --git a/application/views/admin/survey/Question/editQuestion_view.php b/application/views/admin/survey/Question/editQuestion_view.php index d48afe0b617..f0a48c9b9c8 100644 --- a/application/views/admin/survey/Question/editQuestion_view.php +++ b/application/views/admin/survey/Question/editQuestion_view.php @@ -1,8 +1,8 @@ - + @@ -31,7 +31,7 @@ -
');"> + ');">