Esempio n. 1
0
 /**
  * @covers rvilbrandt\gamebook\Model\Gamebook\Conditions::setFromArray
  */
 public function testSetFromArray()
 {
     $this->object->setFromObject(json_decode(file_get_contents(__DIR__ . "/../../../data/conditions_valid.json")));
     $this->assertEquals("Hodor", $this->object->states->eq['name']);
     $this->assertEquals(1, $this->object->states->gt['test']);
     $this->assertContains("key", $this->object->inventory->has);
 }
Esempio n. 2
0
 function listEvents($opts = array())
 {
     $cond = new Conditions();
     $per_page = 10;
     $cond->setPaging(10000, $per_page);
     $where = array(1);
     if (isset($opts['where'])) {
         foreach ($opts['where'] as $f => $v) {
             $where[] = $f . '=' . Database::escape($v);
         }
     }
     $events = Database::sql2array('SELECT SQL_CALC_FOUND_ROWS * FROM `lib_events` WHERE ' . implode(' AND ', $where) . ' ORDER BY age_start_days,age_end_days  LIMIT ' . $cond->getLimit());
     $cond->setPaging(Database::sql2single('SELECT FOUND_ROWS()'), $per_page);
     $template_ids = array();
     foreach ($events as $event) {
         $template_ids[$event['template_id']] = 1;
     }
     if (count($template_ids)) {
         $templates = Database::sql2array('SELECT * FROM lib_event_templates T WHERE id IN(' . implode(',', array_keys($template_ids)) . ')', 'id');
         foreach ($events as &$event) {
             $event['template'] = isset($templates[$event['template_id']]) ? $templates[$event['template_id']]['title'] : false;
         }
     }
     $data['events'] = $events;
     if (!isset($opts['cond']) || $opts['cond'] == true) {
         $data['conditions'] = $cond->getConditions();
     }
     return $data;
 }
Esempio n. 3
0
 function getRightholders()
 {
     $cond = new Conditions();
     $per_page = 0;
     if (isset($this->params['per_page'])) {
         $per_page = (int) $this->params['per_page'];
     }
     $per_page = $per_page > 0 ? $per_page : 1;
     $pagingName = isset($this->params['paging_parameter_name']) ? $this->params['paging_parameter_name'] : 'p';
     $where = '';
     $order = 'ORDER BY `id` DESC ';
     $group_by = '';
     $query = 'SELECT COUNT(1) FROM `rightholders` ' . $where . ' ' . $group_by . '';
     $count = Database::sql2single($query);
     $cond->setPaging($count, $per_page, $pagingName);
     $limit = $cond->getLimit();
     $limit = ' LIMIT ' . $limit;
     $query = 'SELECT * FROM `rightholders`' . $where . ' ' . $group_by . ' ' . $order . ' ' . $limit;
     $data = Database::sql2array($query);
     foreach ($data as &$row) {
         $row['path'] = Config::need('www_path') . '/admin/rightholders/' . $row['id'];
     }
     $this->data['rightholders'] = $data;
     $this->data['rightholders']['title'] = 'Правообладатели';
     $this->data['rightholders']['count'] = $count;
     $this->data['conditions'] = $cond->getConditions();
 }
Esempio n. 4
0
 function getSearch()
 {
     $query_string = isset(Request::$get_normal['q']) ? trim(Request::$get_normal['q']) : false;
     $search = Search::getInstance();
     /* @var $search Search */
     $cond = new Conditions();
     $per_page = 0;
     if (isset($this->params['per_page'])) {
         $per_page = (int) $this->params['per_page'];
     }
     $per_page = $per_page > 0 ? $per_page : 5;
     $cond->setPaging(1000, $per_page);
     $offset = $cond->getMongoLimit();
     list($sids, $count, $hl) = $search->searchMagazinesByString($query_string, $offset, $per_page);
     $cond = new Conditions();
     $cond->setPaging($count, $per_page);
     if ($count) {
         $query = 'SELECT * FROM `magazines` WHERE `id` IN(' . implode(',', $sids) . ')';
         $series = Database::sql2array($query);
         $this->data['magazines'] = $series;
     } else {
         $this->data['magazines'] = array();
     }
     $this->data['conditions'] = $cond->getConditions();
     foreach ($this->data['magazines'] as &$m) {
         if (isset($hl[$m['id']])) {
             $m['path'] = Config::need('www_path') . '/m/' . $m['id'] . '#hl=' . implode(' ', $hl[$m['id']]);
         } else {
             $m['path'] = Config::need('www_path') . '/m/' . $m['id'] . '#hl=' . Request::$get_normal['q'];
         }
     }
     $this->data['magazines']['title'] = 'Журналы по запросу «' . $query_string . '»';
     $this->data['magazines']['count'] = $count;
 }
Esempio n. 5
0
 function getOne($for_editing = false)
 {
     if ($this->genre_id) {
         $query = 'SELECT * FROM `genre` WHERE `id`=' . Database::escape($this->genre_id);
     } else {
         $query = 'SELECT * FROM `genre` WHERE `name`=' . Database::escape($this->genre_name);
     }
     $data = Database::sql2row($query);
     if (!isset($data['name'])) {
         return;
     }
     $this->data['genre'] = array('name' => $data['name'], 'id' => $data['id'], 'id_parent' => $data['id_parent'], 'title' => $data['title'], 'description' => $data['description'], 'books_count' => $data['books_count'], 'path' => Config::need('www_path') . '/genres/' . $data['id'], 'path_edit' => Config::need('www_path') . '/genres/' . $data['id'] . '/edit');
     Request::pass('genre-title', $data['title']);
     if (!$data['id_parent']) {
         $this->data['genre']['subgenres'] = $this->getAll($data['id']);
         return;
     }
     if (!$for_editing) {
         $query = 'SELECT COUNT(1) FROM `book_genre` BG JOIN `book` B ON B.id = BG.id_book WHERE BG.id_genre = ' . $data['id'] . '';
         $count = Database::sql2single($query);
         $cond = new Conditions();
         $cond->setPaging($count, 20);
         $limit = $cond->getLimit();
         $this->data['conditions'] = $cond->getConditions();
         $query = 'SELECT `id_book` FROM `book_genre` BG JOIN `book` B ON B.id = BG.id_book WHERE BG.id_genre = ' . $data['id'] . ' ORDER BY B.mark DESC LIMIT ' . $limit;
         $bids = Database::sql2array($query, 'id_book');
         $books = Books::getInstance()->getByIdsLoaded(array_keys($bids));
         Books::getInstance()->LoadBookPersons(array_keys($bids));
         $aids = array();
         foreach ($books as $book) {
             $book = Books::getInstance()->getById($book->id);
             list($aid, $aname) = $book->getAuthor(1, 1, 1);
             // именно наш автор, если их там много
             $this->data['genre']['books'][$book->id] = $book->getListData();
             $aids[$aid] = $aid;
         }
         if (count($aids)) {
             $persons = Persons::getInstance()->getByIdsLoaded($aids);
             foreach ($persons as $person) {
                 $this->data['genre']['authors'][] = $person->getListData();
             }
         }
         $this->data['parent'] = array();
         if ($data['id_parent']) {
             $data = Database::sql2row('SELECT * FROM `genre` WHERE `id`=' . Database::escape($data['id_parent']));
             $this->data['genre']['parent'][] = array('name' => $data['name'], 'id' => $data['id'], 'id_parent' => $data['id_parent'], 'title' => $data['title'], 'description' => $data['description'], 'books_count' => $data['books_count'], 'path' => Config::need('www_path') . '/genres/' . $data['id'], 'path_edit' => Config::need('www_path') . '/genres/' . $data['id'] . '/edit');
         }
     }
 }
Esempio n. 6
0
	/**
	 * устанавливает $this->data[items_name]
	 * @param type $where
	 * @param type $sortings
	 * @param type $return 
	 */
	function _list($where, $sortings = false, $return = false) {
		$limit = false;
		$order = false;
		$sorting_order = false;
		$cond = new Conditions();
		if ($this->ConditionsEnabled) {
			// пейджинг, сортировка
			if ($sortings) {
				$cond->setSorting($sortings);
				$order = $cond->getSortingField();
				$sorting_order = $cond->getSortingOrderSQL();
			}
			$per_page = isset($this->params['per_page']) ? $this->params['per_page'] : 0;
			$pagingName = isset($this->params['paging_parameter_name']) ? $this->params['paging_parameter_name'] : 'p';
			if ($per_page) {
				$cond->setPaging($this->getCountBySQL($where), $per_page, $pagingName);
				$limit = $cond->getLimit();
			}
		}
		$query = $this->prepareSelect('id', $where, $order ? ($order . ' ' . $sorting_order) : '', $limit);
		$ids = Database::sql2array($query, 'id'); // нашли объекты, которые хотим вывести
		if ($return)
			return $this->_idsToData(array_keys($ids)); // отдаем массив
		else
			$this->data = $this->_idsToData(array_keys($ids)); // отдаем массив
		$this->data['conditions'] = $cond->getConditions();
		return true;
	}
Esempio n. 7
0
 function getSynthesis($mode = 'synthesis')
 {
     $min_update_time = time() - 48 * 60 * 60;
     $query = 'SELECT COUNT(1) FROM `posts` WHERE `update_time`>' . $min_update_time;
     $count = min(200, Database::sql2single($query));
     $cond = new Conditions();
     $per_page = 20;
     $cond->setPaging($count, $per_page, 'p');
     $this->data['conditions'] = $cond->getConditions();
     $limit = $cond->getLimit();
     switch ($mode) {
         case 'synthesis':
             $order = 'rating';
             break;
         case 'links':
             $order = 'rating_links';
             break;
         case 'visits':
             $order = 'rating_visits';
             break;
         case 'comments':
             $order = 'rating_comments';
             break;
     }
     $posts = Database::sql2array('SELECT * FROM `posts` ORDER BY ' . $order . ' DESC LIMIT ' . $limit);
     $i = 0;
     foreach ($posts as $data) {
         $post = new Post($data);
         $this->data['posts'][$i] = $post->getShort();
         $this->data['posts'][$i]['num'] = ($cond->currentPage - 1) * $per_page + $i + 1;
         $aids[$post->data['id_author']] = $post->data['id_author'];
         $i++;
     }
     if (count($aids)) {
         $authors = Database::sql2array('SELECT * FROM `authors` WHERE `id` IN(' . implode(',', $aids) . ')');
         foreach ($authors as $data) {
             $author = new Author($data);
             $this->data['authors'][] = $author->getShort();
         }
     }
 }
Esempio n. 8
0
 function getSettings()
 {
     $cond = new Conditions();
     $per_page = 0;
     if (isset($this->params['per_page'])) {
         $per_page = (int) $this->params['per_page'];
     }
     $per_page = $per_page > 0 ? $per_page : 1;
     $pagingName = isset($this->params['paging_parameter_name']) ? $this->params['paging_parameter_name'] : 'p';
     $where = '';
     $order = 'ORDER BY `id` DESC ';
     $group_by = '';
     $query = 'SELECT COUNT(1) FROM `settings` ' . $where . ' ' . $group_by . '';
     $count = Database::sql2single($query);
     $cond->setPaging($count, $per_page, $pagingName);
     $limit = $cond->getLimit();
     $limit = ' LIMIT ' . $limit;
     $query = 'SELECT * FROM `settings`' . $where . ' ' . $group_by . ' ' . $order . ' ' . $limit;
     $data = Database::sql2array($query);
     $this->data['settings'] = $data;
     $this->data['settings']['title'] = 'Настройки';
     $this->data['settings']['count'] = $count;
     $this->data['conditions'] = $cond->getConditions();
 }
Esempio n. 9
0
 public function getListDocuments(Vtiger_Request $request)
 {
     require_once 'modules/OSSDocumentControl/helpers/Conditions.php';
     $relatedModuleName = $request->get('rel_module');
     $moduleName = $request->getModule();
     $record = $request->get('record');
     $conditions = new Conditions();
     $documentList = $conditions->getListDocForModule($relatedModuleName);
     for ($i = 0; $i < count($documentList); $i++) {
         if (mb_strlen($documentList[$i]['doc_name']) > 20) {
             $documentList[$i]['doc_short_name'] = substr($documentList[$i]['doc_name'], 0, 15) . '...';
         } else {
             $documentList[$i]['doc_short_name'] = $documentList[$i]['doc_name'];
         }
     }
     for ($i = 0; $i < count($documentList); $i++) {
         $documentList[$i]['is_attach'] = $conditions->docIsAttachet($record, $documentList[$i]['doc_folder'], $documentList[$i]['doc_name']);
         $documentList[$i]['status'] = $conditions->docStatus($record, $documentList[$i]['doc_folder'], $documentList[$i]['doc_name']);
     }
     $viewer = $this->getViewer($request);
     $viewer->assign('MODULE', $moduleName);
     $viewer->assign('DOC_LIST', $documentList);
     return $viewer->view('GetListDocuments.tpl', $moduleName, 'true');
 }
Esempio n. 10
0
 public function process(Vtiger_Request $request)
 {
     require_once 'modules/OSSDocumentControl/helpers/Conditions.php';
     $moduleName = $request->getModule();
     $relModuleName = $request->get('rel_module');
     $record = $request->get('record');
     $form = $request->get('form');
     $conditions = new Conditions();
     $listDoc = $conditions->getListDocForModule($relModuleName, true);
     $notAttachDoc = array();
     $conditionCheckTab = array();
     for ($i = 0; $i < count($listDoc); $i++) {
         $conditionCheckTab[] = $conditions->checkConditionsForDoc($listDoc[$i]['doc_id'], $form);
     }
     $passCondition = true;
     for ($i = 0; $i < count($conditionCheckTab); $i++) {
         if (false == $conditionCheckTab[$i]['test']) {
             $passCondition = false;
         }
     }
     $passAttach = true;
     for ($i = 0; $i < count($conditionCheckTab); $i++) {
         if ($conditionCheckTab[$i]['test'] && '1' == $conditionCheckTab[$i]['doc_request']) {
             $isAttach = $conditions->docIsAttachet($record, $conditionCheckTab[$i]['folderid'], $conditionCheckTab[$i]['name']);
             if (!$isAttach) {
                 $passAttach = false;
                 $notAttachDoc[] = $conditionCheckTab[$i]['name'];
             }
         }
     }
     //var_dump($notAttachDoc, $pasCondition);
     $output = array('condition_allow' => $passAttach && $passCondition, 'not_attach_doc_list' => $notAttachDoc, 'tr' => array(vtranslate('NOT_ALLOW_TO_SAVE', $moduleName), vtranslate('LIST_REQ_DOC', $moduleName)), 'passAttach' => $passAttach, 'passCondition' => $passCondition);
     $response = new Vtiger_Response();
     $response->setResult($output);
     $response->emit();
 }
Esempio n. 11
0
    function _list($opts = array())
    {
        $has_paging = !isset($opts['no_paging']);
        $show_sortings = isset($opts['show_sortings']);
        $per_page = isset($opts['per_page']) ? $opts['per_page'] : 10;
        $per_page = min(100, max(1, (int) $per_page));
        $cond = new Conditions();
        $cond->setSorting(array('created' => array('order' => 'desc', 'title' => 'по дате')));
        $cond->setPaging(100000, $per_page);
        $where = array('1');
        if (isset($opts['where'])) {
            foreach ($opts['where'] as $w) {
                $where[] = $w;
            }
        }
        $order = $cond->getSortingField() . ' ' . $cond->getSortingOrderSQL();
        $limit = $cond->getLimit();
        $query = 'SELECT SQL_CALC_FOUND_ROWS P. * , GROUP_CONCAT( T.title ) AS tags, GROUP_CONCAT( PT.tag_id ) AS tags_indexes
FROM `publications` P
LEFT JOIN `publications_tags` PT ON PT.publication_id = P.id
LEFT JOIN `tags` T ON T.id = PT.tag_id
WHERE (' . implode(' AND ', $where) . ')
GROUP BY P.id
ORDER BY ' . $order . ' LIMIT ' . $limit . '';
        $publications = Database::sql2array($query, 'id');
        foreach ($publications as $publication) {
            $uids[$publication['user_id']] = $publication['user_id'];
        }
        $users = Users::getByIdsLoaded($uids);
        foreach ($publications as &$publication) {
            $publication['user'] = isset($users[$publication['user_id']]) ? $users[$publication['user_id']]->data : array();
        }
        $cond->setPaging(Database::sql2single('SELECT FOUND_ROWS()'), $per_page);
        $data['publications'] = $publications;
        $data['conditions'] = $cond->getConditions();
        if (!$show_sortings) {
            foreach ($data['conditions'] as $key => $group) {
                if ($group['mode'] == 'sorting') {
                    unset($data['conditions'][$key]);
                }
            }
        }
        return $data;
    }
Esempio n. 12
0
    function _list($opts)
    {
        $data = array();
        $has_paging = !isset($opts['no_paging']);
        $show_sortings = isset($opts['show_sortings']);
        $per_page = isset($opts['per_page']) ? $opts['per_page'] : 10;
        $per_page = min(100, max(1, (int) $per_page));
        $cond = new Conditions();
        $cond->setSorting(array('time' => array('order' => 'desc', 'title' => 'по дате')), array('time' => array('order' => 'desc', 'title' => 'по дате')));
        $cond->setPaging(100000, $per_page);
        $where = array('parent_id=0');
        if (isset($opts['where'])) {
            foreach ($opts['where'] as $w) {
                $where[] = $w;
            }
        }
        $order = $cond->getSortingField() . ' ' . $cond->getSortingOrderSQL();
        $limit = $cond->getLimit();
        $query = 'SELECT * FROM `comments`
WHERE (' . implode(' AND ', $where) . ')
ORDER BY ' . $order . ' LIMIT ' . $limit . '';
        $comments = Database::sql2array($query, 'id');
        $pids = array();
        $uids = array();
        foreach ($comments as $comment) {
            $pids[$comment['id']] = $comment['id'];
            $uids[$comment['user_id']] = $comment['user_id'];
        }
        if (count($pids)) {
            $query = 'SELECT * FROM `comments` WHERE `thread` IN (' . implode(',', $pids) . ') ORDER BY `thread`,`id`';
            $nextlevel = Database::sql2array($query, 'id');
            $comments += $nextlevel;
            foreach ($comments as $comment) {
                $uids[$comment['user_id']] = $comment['user_id'];
            }
            if (count($uids)) {
                $users = Users::getByIdsLoaded($uids);
            } else {
                $users = array();
            }
            foreach ($comments as &$comment) {
                if (!isset($users[$comment['user_id']])) {
                    continue;
                }
                $comment['user'] = $users[$comment['user_id']];
                $parents[$comment['parent_id']][$comment['id']] = $comment;
                uasort($parents[$comment['parent_id']], 'x_sort_comment');
            }
            $comments = $this->build_tree($parents, 0);
        }
        return $comments;
    }
Esempio n. 13
0
 public function process(Vtiger_Request $request)
 {
     $db = PearDatabase::getInstance();
     $id = $request->get('record');
     $newModuleId = $request->get('moduleid');
     $recordModel = $this->saveRecord($request);
     vimport('~~modules/OSSPdf/helpers/Conditions.php');
     Conditions::saveCondition($recordModel, $request);
     if ($request->get('relationOperation')) {
         $parentModuleName = $request->get('sourceModule');
         $parentRecordId = $request->get('sourceRecord');
         $parentRecordModel = Vtiger_Record_Model::getInstanceById($parentRecordId, $parentModuleName);
         //TODO : Url should load the related list instead of detail view of record
         $loadUrl = $parentRecordModel->getDetailViewUrl();
     } else {
         $loadUrl = $recordModel->getDetailViewUrl();
     }
     header("Location: {$loadUrl}");
 }
Esempio n. 14
0
 public function process(Vtiger_Request $request)
 {
     vimport('~~modules/OSSPdf/helpers/Conditions.php');
     $moduleSettingsName = $request->getModule(false);
     $moduleName = $request->getModule();
     $record = $request->get('record');
     $baseModule = Vtiger_Functions::getModuleName($request->get('base_module'));
     $num = $request->get('num');
     if ("" == $num) {
         $num = 0;
     }
     $viewer = $this->getViewer($request);
     $viewer->assign('NUM', ++$num);
     $viewer->assign('MODULE', $moduleName);
     $viewer->assign('BASE_MODULE', $baseModule);
     $viewer->assign('CONDITION_LIST', Conditions::getListBaseModuleField($baseModule));
     $viewer->assign('FIELD_LIST', Conditions::getListBaseModuleField($baseModule));
     echo $viewer->view('Condition.tpl', $moduleSettingsName, true);
 }
Esempio n. 15
0
 /**
  * Function responsible for deleting a question.
  *
  * @access public
  * @param string $action
  * @param int $surveyid
  * @param int $gid
  * @param int $qid
  * @return void
  */
 public function delete($surveyid, $gid, $qid)
 {
     $clang = $this->getController()->lang;
     $surveyid = sanitize_int($surveyid);
     $gid = sanitize_int($gid);
     $qid = sanitize_int($qid);
     if (hasSurveyPermission($surveyid, 'surveycontent', 'delete')) {
         if (!isset($qid)) {
             $qid = returnGlobal('qid');
         }
         LimeExpressionManager::RevertUpgradeConditionsToRelevance(NULL, $qid);
         // Check if any other questions have conditions which rely on this question. Don't delete if there are.
         // TMSW Conditions->Relevance:  Allow such deletes - can warn about missing relevance separately.
         $ccresult = Conditions::model()->findAllByAttributes(array('cqid' => $qid));
         $cccount = count($ccresult);
         // There are conditions dependent on this question
         if ($cccount) {
             foreach ($ccresult as $ccr) {
                 $qidarray[] = $ccr->qid;
             }
             if (isset($qidarray)) {
                 $qidlist = implode(", ", $qidarray);
             }
             $message = $clang->gT("Question could not be deleted. There are conditions for other questions that rely on this question. You cannot delete this question until those conditions are removed.");
             $message .= "<br /><a href='" . $this->getController()->createUrl("admin/expressions/sa/survey_logic_file/sid/{$surveyid}") . "' >" . $clang->gT("Look at survey logic files") . "</a>.";
             $this->getController()->error($message, $this->getController()->createUrl("admin/survey/sa/view/surveyid/{$surveyid}/gid/{$gid}/qid/{$qid}"));
         } else {
             $row = Questions::model()->findByAttributes(array('qid' => $qid))->attributes;
             $gid = $row['gid'];
             // See if there are any conditions/attributes/answers/defaultvalues for this question,
             // and delete them now as well
             Conditions::model()->deleteAllByAttributes(array('qid' => $qid));
             Question_attributes::model()->deleteAllByAttributes(array('qid' => $qid));
             Answers::model()->deleteAllByAttributes(array('qid' => $qid));
             $criteria = new CDbCriteria();
             $criteria->addCondition('qid = :qid1 or parent_qid = :qid2');
             $criteria->params[':qid1'] = $qid;
             $criteria->params[':qid2'] = $qid;
             Questions::model()->deleteAll($criteria);
             Defaultvalues::model()->deleteAllByAttributes(array('qid' => $qid));
             Quota_members::model()->deleteAllByAttributes(array('qid' => $qid));
             Questions::model()->updateQuestionOrder($gid, $surveyid);
             $qid = "";
             $postqid = "";
             $_GET['qid'] = "";
         }
         Yii::app()->session['flashmessage'] = $clang->gT("Question was successfully deleted.");
         $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $surveyid . '/gid/' . $gid));
     } else {
         Yii::app()->session['flashmessage'] = $clang->gT("You are not authorized to delete questions.");
         $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $surveyid . '/gid/' . $gid));
     }
 }
 /**
  * Shows admin menu for surveys
  * @param int Survey id
  */
 function _surveybar($iSurveyID, $gid = null)
 {
     //$this->load->helper('surveytranslator');
     $clang = $this->getController()->lang;
     //echo Yii::app()->getConfig('gid');
     $baselang = Survey::model()->findByPk($iSurveyID)->language;
     $condition = array('sid' => $iSurveyID, 'language' => $baselang);
     //$sumquery1 = "SELECT * FROM ".db_table_name('surveys')." inner join ".db_table_name('surveys_languagesettings')." on (surveyls_survey_id=sid and surveyls_language=language) WHERE sid=$iSurveyID"; //Getting data for this survey
     $sumresult1 = Survey::model()->with(array('languagesettings' => array('condition' => 'surveyls_language=language')))->findByPk($iSurveyID);
     //$sumquery1, 1) ; //Checked
     if (is_null($sumresult1)) {
         Yii::app()->session['flashmessage'] = $clang->gT("Invalid survey ID");
         $this->getController()->redirect($this->getController()->createUrl("admin/index"));
     }
     //  if surveyid is invalid then die to prevent errors at a later time
     $surveyinfo = $sumresult1->attributes;
     $surveyinfo = array_merge($surveyinfo, $sumresult1->languagesettings[0]->attributes);
     $surveyinfo = array_map('flattenText', $surveyinfo);
     //$surveyinfo = array_map('htmlspecialchars', $surveyinfo);
     $activated = $surveyinfo['active'] == 'Y';
     $js_admin_includes[] = Yii::app()->getConfig('generalscripts') . 'jquery/jquery.coookie.js';
     $js_admin_includes[] = Yii::app()->getConfig('generalscripts') . 'jquery/superfish.js';
     $js_admin_includes[] = Yii::app()->getConfig('generalscripts') . 'jquery/hoverIntent.js';
     $js_admin_includes[] = Yii::app()->getConfig('adminscripts') . 'surveytoolbar.js';
     $this->getController()->_js_admin_includes($js_admin_includes);
     //Parse data to send to view
     $aData['clang'] = $clang;
     $aData['surveyinfo'] = $surveyinfo;
     $aData['surveyid'] = $iSurveyID;
     // ACTIVATE SURVEY BUTTON
     $aData['activated'] = $activated;
     $condition = array('sid' => $iSurveyID, 'parent_qid' => 0, 'language' => $baselang);
     //$sumquery3 =  "SELECT * FROM ".db_table_name('questions')." WHERE sid={$iSurveyID} AND parent_qid=0 AND language='".$baselang."'"; //Getting a count of questions for this survey
     $sumresult3 = Questions::model()->findAllByAttributes($condition);
     //Checked
     $sumcount3 = count($sumresult3);
     $aData['canactivate'] = $sumcount3 > 0 && hasSurveyPermission($iSurveyID, 'surveyactivation', 'update');
     $aData['candeactivate'] = hasSurveyPermission($iSurveyID, 'surveyactivation', 'update');
     $aData['expired'] = $surveyinfo['expires'] != '' && $surveyinfo['expires'] < dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig('timeadjust'));
     $aData['notstarted'] = $surveyinfo['startdate'] != '' && $surveyinfo['startdate'] > dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig('timeadjust'));
     // Start of suckerfish menu
     // TEST BUTTON
     if (!$activated) {
         $aData['icontext'] = $clang->gT("Test this survey");
     } else {
         $aData['icontext'] = $clang->gT("Execute this survey");
     }
     $aData['baselang'] = Survey::model()->findByPk($iSurveyID)->language;
     $tmp_survlangs = Survey::model()->findByPk($iSurveyID)->getAdditionalLanguages();
     $aData['onelanguage'] = count($tmp_survlangs) == 0;
     $aData['additionallanguages'] = $tmp_survlangs;
     $tmp_survlangs[] = $aData['baselang'];
     rsort($tmp_survlangs);
     $aData['languagelist'] = $tmp_survlangs;
     $aData['hasadditionallanguages'] = count($aData['additionallanguages']) > 0;
     // EDIT SURVEY TEXT ELEMENTS BUTTON
     $aData['surveylocale'] = hasSurveyPermission($iSurveyID, 'surveylocale', 'read');
     // EDIT SURVEY SETTINGS BUTTON
     $aData['surveysettings'] = hasSurveyPermission($iSurveyID, 'surveysettings', 'read');
     // Survey permission item
     $aData['surveysecurity'] = Yii::app()->session['USER_RIGHT_SUPERADMIN'] == 1 || $surveyinfo['owner_id'] == Yii::app()->session['loginID'] || hasSurveyPermission($iSurveyID, 'surveysecurity', 'read');
     // CHANGE QUESTION GROUP ORDER BUTTON
     $aData['surveycontent'] = hasSurveyPermission($iSurveyID, 'surveycontent', 'read');
     $aData['groupsum'] = getGroupSum($iSurveyID, $surveyinfo['language']) > 1;
     // SET SURVEY QUOTAS BUTTON
     $aData['quotas'] = hasSurveyPermission($iSurveyID, 'quotas', 'read');
     // Assessment menu item
     $aData['assessments'] = hasSurveyPermission($iSurveyID, 'assessments', 'read');
     // EDIT SURVEY TEXT ELEMENTS BUTTON
     // End if survey properties
     // Tools menu item
     // Delete survey item
     $aData['surveydelete'] = hasSurveyPermission($iSurveyID, 'survey', 'delete');
     // Translate survey item
     $aData['surveytranslate'] = hasSurveyPermission($iSurveyID, 'translations', 'read');
     // RESET SURVEY LOGIC BUTTON
     //$sumquery6 = "SELECT count(*) FROM ".db_table_name('conditions')." as c, ".db_table_name('questions')." as q WHERE c.qid = q.qid AND q.sid=$iSurveyID"; //Getting a count of conditions for this survey
     // TMSW Conditions->Relevance:  How is conditionscount used?  Should Relevance do the same?
     $iConditionCount = Conditions::model()->with(array('questions' => array('condition' => 'sid =' . $iSurveyID)))->count();
     $aData['surveycontent'] = hasSurveyPermission($iSurveyID, 'surveycontent', 'update');
     $aData['conditionscount'] = $iConditionCount > 0;
     // Eport menu item
     $aData['surveyexport'] = hasSurveyPermission($iSurveyID, 'surveycontent', 'export');
     // PRINTABLE VERSION OF SURVEY BUTTON
     // SHOW PRINTABLE AND SCANNABLE VERSION OF SURVEY BUTTON
     //browse responses menu item
     $aData['respstatsread'] = hasSurveyPermission($iSurveyID, 'responses', 'read') || hasSurveyPermission($iSurveyID, 'statistics', 'read') || hasSurveyPermission($iSurveyID, 'responses', 'export');
     // Data entry screen menu item
     $aData['responsescreate'] = hasSurveyPermission($iSurveyID, 'responses', 'create');
     $aData['responsesread'] = hasSurveyPermission($iSurveyID, 'responses', 'read');
     // TOKEN MANAGEMENT BUTTON
     $aData['tokenmanagement'] = hasSurveyPermission($iSurveyID, 'surveysettings', 'update') || hasSurveyPermission($iSurveyID, 'tokens', 'read');
     $aData['gid'] = $gid;
     // = $this->input->post('gid');
     if (hasSurveyPermission($iSurveyID, 'surveycontent', 'read')) {
         $aData['permission'] = true;
     } else {
         $aData['gid'] = $gid = null;
         $qid = null;
         $aData['permission'] = false;
     }
     if (getGroupListLang($gid, $baselang, $iSurveyID)) {
         $aData['groups'] = getGroupListLang($gid, $baselang, $iSurveyID);
     } else {
         $aData['groups'] = "<option>" . $clang->gT("None") . "</option>";
     }
     $aData['GidPrev'] = $GidPrev = getGidPrevious($iSurveyID, $gid);
     $aData['GidNext'] = $GidNext = getGidNext($iSurveyID, $gid);
     $aData['iIconSize'] = Yii::app()->getConfig('adminthemeiconsize');
     $aData['sImageURL'] = Yii::app()->getConfig('adminimageurl');
     $this->getController()->render("/admin/survey/surveybar_view", $aData);
 }
Esempio n. 17
0
 function getLog()
 {
     if ($this->target_type == 'user') {
         $query = 'SELECT COUNT(DISTINCT(id_log)) FROM `biber_log_index` WHERE `id_user`=' . $this->id_target . ' ';
     } else {
         if ($this->target_type == 'all') {
             $query = 'SELECT COUNT(DISTINCT(id_log)) FROM `biber_log_index` WHERE `is_copy`=0';
         } else {
             $query = 'SELECT COUNT(1) FROM `biber_log_index` WHERE `target_type`=' . $this->target_type . ' AND `id_target`=' . $this->id_target . ' ';
         }
     }
     $count = min(1000, Database::sql2single($query));
     $cond = new Conditions();
     $cond->setPaging($count, 10);
     $this->data['conditions'] = $cond->getConditions();
     $limit = $cond->getLimit();
     if ($this->target_type == 'user') {
         $query = 'SELECT * FROM `biber_log_index` WHERE
         `id_user`=' . $this->id_target . ' GROUP BY id_log
         ORDER BY `time` DESC LIMIT ' . $limit;
     } else {
         if ($this->target_type == 'all') {
             $query = 'SELECT * FROM `biber_log_index` WHERE `is_copy`=0 GROUP BY id_log
         ORDER BY `time` DESC LIMIT ' . $limit;
         } else {
             $query = 'SELECT * FROM `biber_log_index` WHERE
         `target_type`=' . $this->target_type . ' AND
         `id_target`=' . $this->id_target . '
         ORDER BY `time` DESC LIMIT ' . $limit;
         }
     }
     $book_ids = array();
     $person_ids = array();
     $serie_ids = array();
     $magazine_ids = array();
     $uids = array();
     if ($this->target_type == BiberLog::TargetType_book) {
         $book_ids[$this->id_target] = $this->id_target;
     }
     if ($this->target_type == BiberLog::TargetType_person) {
         $person_ids[$this->id_target] = $this->id_target;
     }
     if ($this->target_type == 'user') {
         $uids[$this->id_target] = $this->id_target;
     }
     $arr = array();
     $arri = Database::sql2array($query, 'id_log');
     $to_fetch_log = array();
     foreach ($arri as $row) {
         $to_fetch_log[(int) $row['id_log']] = (int) $row['id_log'];
     }
     if (count($to_fetch_log)) {
         $query = 'SELECT * FROM `biber_log` WHERE `id` IN (' . implode(',', $to_fetch_log) . ') ORDER BY `time` DESC';
         $arr = Database::sql2array($query);
         foreach ($arr as &$rowx) {
             foreach ($arri[$rowx['id']] as $f => $v) {
                 $rowx[$f] = $v;
             }
         }
     }
     foreach ($arr as &$row) {
         $book_id_s = 0;
         $uids[$row['id_user']] = $row['id_user'];
         $vals = unserialize($row['data']);
         if (isset($vals['id1'])) {
             $book_ids[$vals['id1'][0]] = $vals['id1'][0];
             $book_ids[$vals['id1'][1]] = $vals['id1'][1];
         }
         if (isset($vals['id2'])) {
             $book_ids[$vals['id2'][0]] = $vals['id2'][0];
             $book_ids[$vals['id2'][1]] = $vals['id2'][1];
         }
         if (isset($vals['id_person'])) {
             if (isset($vals['id_person'][0])) {
                 $person_ids[$vals['id_person'][0]] = (int) $vals['id_person'][0];
             }
             if (isset($vals['id_person'][1])) {
                 $person_ids[$vals['id_person'][1]] = (int) $vals['id_person'][1];
             }
         }
         if (isset($vals['is_duplicate'])) {
             $book_ids[$vals['is_duplicate'][0]] = $vals['is_duplicate'][0];
             $book_ids[$vals['is_duplicate'][1]] = $vals['is_duplicate'][1];
         }
         $book_id = 0;
         $person_id = 0;
         $serie_id = 0;
         $values = array();
         foreach ($vals as $field => $v) {
             if (!is_array($v)) {
                 if ($field == 'id_book') {
                     $book_id = $v;
                     $book_ids[$v] = $v;
                 }
                 if ($field == 'id_person') {
                     $person_id = $v;
                     $person_ids[$v] = $v;
                 }
                 if ($field == 'id_serie') {
                     $serie_id = $v;
                     $serie_ids[$v] = $v;
                 }
                 if ($field == 'id_magazine') {
                     $serie_id = $v;
                     $magazine_ids[$v] = $v;
                 }
                 continue;
             }
             $tmp = array();
             if ($row['target_type'] == BiberLog::TargetType_book) {
                 if ($field == 'new_relations') {
                     foreach ($v[1] as $new_relation_id) {
                         $book_ids[$new_relation_id] = $new_relation_id;
                         $tmp[] = array('book_id' => $new_relation_id);
                     }
                     $values['new_relations'] = $tmp;
                 } else {
                     if ($field == 'old_relations') {
                         foreach ($v[1] as $new_relation_id) {
                             $book_ids[$new_relation_id] = $new_relation_id;
                             $tmp[] = array('book_id' => $new_relation_id);
                         }
                         $values['old_relations'] = $tmp;
                     } else {
                         if ($field == 'deleted_relations') {
                             foreach ($v[1] as $new_relation_id) {
                                 $book_ids[$new_relation_id] = $new_relation_id;
                                 $tmp[] = array('book_id' => $new_relation_id);
                             }
                             $values['deleted_relations'] = $tmp;
                         } else {
                             $values[] = array('name' => $field, 'old' => $v[0], 'new' => $v[1]);
                         }
                     }
                 }
             } else {
                 if ($row['target_type'] == BiberLog::TargetType_person) {
                     if ($field == 'new_relations') {
                         foreach ($v[1] as $new_relation_id) {
                             $person_ids[$new_relation_id] = (int) $new_relation_id;
                             $tmp[] = array('author_id' => $new_relation_id);
                         }
                         $values['new_relations'] = $tmp;
                     } else {
                         if ($field == 'old_relations') {
                             foreach ($v[1] as $new_relation_id) {
                                 $person_ids[$new_relation_id] = (int) $new_relation_id;
                                 $tmp[] = array('author_id' => $new_relation_id);
                             }
                             $values['old_relations'] = $tmp;
                         } else {
                             if ($field == 'deleted_relations') {
                                 foreach ($v[1] as $new_relation_id) {
                                     $person_ids[$new_relation_id] = (int) $new_relation_id;
                                     $tmp[] = array('author_id' => $new_relation_id);
                                 }
                                 $values['deleted_relations'] = $tmp;
                             } else {
                                 $values[] = array('name' => $field, 'old' => $v[0], 'new' => $v[1]);
                             }
                         }
                     }
                 } else {
                     if ($row['target_type'] == BiberLog::TargetType_magazine) {
                         $values[] = array('name' => $field, 'old' => $v[0], 'new' => $v[1]);
                     } else {
                         if ($row['target_type'] == BiberLog::TargetType_serie) {
                             if ($field == 'id_book') {
                                 $book_id_s = $v[0] ? $v[0] : $v[1];
                                 if ($book_id_s) {
                                     $book_ids[$book_id_s] = $book_id_s;
                                 }
                                 continue;
                             }
                             $values[] = array('name' => $field, 'old' => $v[0], 'new' => $v[1]);
                         }
                     }
                 }
             }
         }
         if (in_array($row['target_type'], array(BiberLog::TargetType_book))) {
             $book_ids[$row['id_target']] = $row['id_target'];
             $book_id = $row['id_target'];
         }
         if (in_array($row['target_type'], array(BiberLog::TargetType_person))) {
             $person_ids[(int) $row['id_target']] = (int) $row['id_target'];
             $person_id = $row['id_target'];
         }
         if (in_array($row['target_type'], array(BiberLog::TargetType_serie))) {
             $serie_id = $row['id_target'];
             $serie_ids[$row['id_target']] = $row['id_target'];
         }
         if (in_array($row['target_type'], array(BiberLog::TargetType_magazine))) {
             $magazine_id = $row['id_target'];
             $magazine_ids[$row['id_target']] = $row['id_target'];
         }
         $this->data['logs'][] = array('id' => $row['id'], 'book_id' => max($book_id, $book_id_s), 'author_id' => $person_id, 'serie_id' => $serie_id, 'time' => date('Y/m/d H:i:s', $row['time']), 'action' => BiberLog::$actionTypes[$row['action_type']], 'id_user' => $row['id_user'], 'values' => $values, 'applied' => $row['undo'] ? 0 : 1);
     }
     $users = Users::getByIdsLoaded($uids);
     foreach ($users as $user) {
         $this->data['users'][$user->id] = $user->getListData();
     }
     if (count($serie_ids)) {
         $query = 'SELECT id,name,title FROM `series` WHERE `id` IN(' . implode(',', $serie_ids) . ')';
         $out = Database::sql2array($query);
         foreach ($out as &$r) {
             $r['path'] = Config::need('www_path') . '/s/' . $r['id'];
         }
         $this->data['series'] = $out;
     }
     if (count($book_ids)) {
         $this->data['books'] = $this->getLogBooks($book_ids);
     }
     if (count($person_ids)) {
         $this->data['authors'] = $this->getLogPersons($person_ids);
     }
     foreach (Config::$langRus as $code => $title) {
         $this->data['lang_codes'][] = array('id' => Config::$langs[$code], 'code' => $code, 'title' => $title);
     }
 }
Esempio n. 18
0
 function getSearch()
 {
     $query_string = isset(Request::$get_normal['s']) ? Request::$get_normal['s'] : false;
     $query_string_prepared = '%' . mysql_escape_string($query_string) . '%';
     $cond = new Conditions();
     $per_page = 0;
     if (isset($this->params['per_page'])) {
         $per_page = (int) $this->params['per_page'];
     }
     $per_page = $per_page > 0 ? $per_page : 60;
     $pagingName = isset($this->params['paging_parameter_name']) ? $this->params['paging_parameter_name'] : 'p';
     $where = 'WHERE `nickname` LIKE \'' . $query_string_prepared . '\' OR `email` LIKE \'' . $query_string_prepared . '\' OR `id`=\'' . $query_string_prepared . '\'';
     $order = 'ORDER BY `regTime` DESC ';
     $group_by = '';
     $query = 'SELECT COUNT(1) FROM `users` ' . $where . ' ' . $group_by . '';
     $count = Database::sql2single($query);
     $cond->setPaging($count, $per_page, $pagingName);
     $limit = $cond->getLimit();
     $limit = ' LIMIT ' . $limit;
     $query = 'SELECT * FROM `users`' . $where . ' ' . $group_by . ' ' . $order . ' ' . $limit;
     $data = Database::sql2array($query);
     foreach ($data as $row) {
         $user = new User($row['id'], $row);
         Users::add($user);
         $this->data['users'][] = $user->getListData(true);
     }
     $this->data['users']['title'] = 'Пользователи';
     $this->data['users']['count'] = $count;
     $this->data['conditions'] = $cond->getConditions();
 }
Esempio n. 19
0
 public function process(Vtiger_Request $request)
 {
     $db = PearDatabase::getInstance();
     $viewer = $this->getViewer($request);
     $moduleName = $request->getModule();
     $record = $request->get('record');
     if (!empty($record) && $request->get('isDuplicate') == true) {
         $recordModel = Vtiger_Record_Model::getInstanceById($record, $moduleName);
         $viewer->assign('MODE', '');
     } else {
         if (!empty($record)) {
             $recordModel = Vtiger_Record_Model::getInstanceById($record, $moduleName);
             $viewer->assign('RECORD_ID', $record);
             $viewer->assign('MODE', 'edit');
         } else {
             $recordModel = Vtiger_Record_Model::getCleanInstance($moduleName);
             $viewer->assign('MODE', '');
         }
     }
     $moduleModel = $recordModel->getModule();
     $fieldList = $moduleModel->getFields();
     $requestFieldList = array_intersect_key($request->getAll(), $fieldList);
     foreach ($requestFieldList as $fieldName => $fieldValue) {
         $fieldModel = $fieldList[$fieldName];
         if ($fieldModel->isEditable()) {
             $recordModel->set($fieldName, $fieldValue);
         }
     }
     if ($request->get('record') != '') {
         $rid = $request->get('record');
         $mresult = $db->query("SELECT moduleid FROM vtiger_osspdf WHERE osspdfid = '{$rid}'", true);
         $moduleid = $db->query_result($mresult, 0, 'moduleid');
     } else {
         $moduleid = '2';
     }
     $pobierz = $db->query("select name from vtiger_tab where tabid = '{$moduleid}'", true);
     $modulename = $db->query_result($pobierz, 0, "name");
     $chosen_module = $modulename;
     $pobierz_bloki = $db->query("select blockid, blocklabel from vtiger_blocks where tabid = '{$moduleid}'", true);
     $field_list = array();
     for ($k = 0; $k < $db->num_rows($pobierz_bloki); $k++) {
         $blockid = $db->query_result($pobierz_bloki, $k, "blockid");
         $label = $db->query_result($pobierz_bloki, $k, "blocklabel");
         $pobierz_pola = $db->query("select fieldname, fieldlabel from vtiger_field where block = '{$blockid}' and tabid = '{$moduleid}'", true);
         for ($i = 0; $i < $db->num_rows($pobierz_pola); $i++) {
             $field_list[vtranslate($label, $modulename)][$i]['name'] = $db->query_result($pobierz_pola, $i, "fieldname");
             $field_list[vtranslate($label, $modulename)][$i]['label'] = vtranslate($db->query_result($pobierz_pola, $i, "fieldlabel"), $modulename);
         }
     }
     $recordStructureInstance = Vtiger_RecordStructure_Model::getInstanceFromRecordModel($recordModel, Vtiger_RecordStructure_Model::RECORD_STRUCTURE_MODE_EDIT);
     ///Conditions
     vimport('~~modules/OSSPdf/helpers/Conditions.php');
     $baseModule = Vtiger_Functions::getModuleName($moduleid);
     $Condition = Conditions::getConditionRelToRecordFieldInfo($request->get('record'), $baseModule);
     $viewer->assign('CONDITION_BY_TYPE', Conditions::getConditionByType());
     $viewer->assign('REQUIRED_CONDITIONS', $Condition['required_conditions']);
     $viewer->assign('OPTIONAL_CONDITIONS', $Condition['optional_conditions']);
     $viewer->assign('FIELD_LIST', Conditions::getListBaseModuleField($baseModule));
     $viewer->assign('BASE_MODULE', $baseModule);
     $viewer->assign('RECORD', $recordModel);
     ///Conditions
     $viewer->assign('DEFAULT_FIELDS', $field_list);
     $viewer->assign('RECORD_STRUCTURE_MODEL', $recordStructureInstance);
     $viewer->assign('RECORD_STRUCTURE', $recordStructureInstance->getStructure());
     $viewer->assign('MODULE', $moduleName);
     $viewer->assign('CURRENTDATE', date('Y-n-j'));
     $viewer->assign('USER_MODEL', Users_Record_Model::getCurrentUserModel());
     $mappingRelatedField = $moduleModel->getMappingRelatedField($moduleName);
     $viewer->assign('MAPPING_RELATED_FIELD', Zend_Json::encode($mappingRelatedField));
     $isRelationOperation = $request->get('relationOperation');
     //if it is relation edit
     $viewer->assign('IS_RELATION_OPERATION', $isRelationOperation);
     if ($isRelationOperation) {
         $viewer->assign('SOURCE_MODULE', $request->get('sourceModule'));
         $viewer->assign('SOURCE_RECORD', $request->get('sourceRecord'));
     }
     $viewer->assign('MAX_UPLOAD_LIMIT_MB', vglobal('upload_maxsize') / 1000000);
     $viewer->assign('MAX_UPLOAD_LIMIT', vglobal('upload_maxsize'));
     $viewer->view('EditView.tpl', $moduleName);
 }
Esempio n. 20
0
function fixMovedQuestionConditions($qid, $oldgid, $newgid)
{
    $surveyid = Yii::app()->getConfig('sid');
    $qid = sanitize_int($qid);
    $oldgid = sanitize_int($oldgid);
    $newgid = sanitize_int($newgid);
    Conditions::model()->updateCFieldName($surveyid, $qid, $oldgid, $newgid);
    // TMSW Conditions->Relevance:  Call LEM->ConvertConditionsToRelevance() when done
}
Esempio n. 21
0
 function getAllFriends()
 {
     $cond = new Conditions();
     $user = Users::getById($this->params['user_id']);
     $radiofilters = array('following' => array('title' => 'Мои друзья', 'default' => 1), 'followers' => array('title' => 'Я в друзьях', 'default' => 0), 'blacklisted' => array('title' => 'Чёрный список', 'default' => 0));
     $cond->setRadioFilters($radiofilters, 't');
     $type = $cond->getRadioFilterValue('t');
     switch ($type) {
         case 'following':
             $ids = $user->getFollowing();
             break;
         case 'followers':
             $ids = $user->getFollowers();
             break;
         case 'blacklisted':
             $ids = array();
             break;
     }
     $this->data['users'] = $this->_list($ids, array());
     $uids = array();
     foreach ($this->data['users'] as $uid => $data) {
         $uids[$data['id']] = $data['id'];
     }
     $sh = $rv = array();
     if (count($uids)) {
         $query = 'SELECT COUNT(1) as cnt, id_user FROM `users_bookshelf` WHERE `id_user` IN(' . implode(',', $uids) . ') GROUP BY id_user';
         $sh = Database::sql2array($query, 'id_user');
         $query = 'SELECT COUNT(1) as cnt, id_user FROM `book_review` WHERE `id_user` IN(' . implode(',', $uids) . ') GROUP BY id_user';
         $rv = Database::sql2array($query, 'id_user');
     }
     foreach ($this->data['users'] as &$f) {
         $f['books_count'] = isset($sh[$f['id']]) ? $sh[$f['id']]['cnt'] : 0;
         $f['reviews_count'] = isset($rv[$f['id']]) ? $rv[$f['id']]['cnt'] : 0;
         $f['books_path'] = Config::need('www_path') . '/user/' . $f['id'] . '/books';
         $f['contribution_path'] = Config::need('www_path') . '/user/' . $f['id'] . '/contribution';
     }
     $this->data['users']['user_id'] = $user->id;
     $this->data['conditions'] = $cond->getConditions();
 }
Esempio n. 22
0
 function index($subaction, $iSurveyID = null, $gid = null, $qid = null)
 {
     $iSurveyID = sanitize_int($iSurveyID);
     $gid = sanitize_int($gid);
     $qid = sanitize_int($qid);
     $clang = $this->getController()->lang;
     $imageurl = Yii::app()->getConfig("adminimageurl");
     Yii::app()->loadHelper("database");
     if (!empty($_POST['subaction'])) {
         $subaction = Yii::app()->request->getPost('subaction');
     }
     //BEGIN Sanitizing POSTed data
     if (!isset($iSurveyID)) {
         $iSurveyID = returnGlobal('sid');
     }
     if (!isset($qid)) {
         $qid = returnGlobal('qid');
     }
     if (!isset($gid)) {
         $gid = returnGlobal('gid');
     }
     if (!isset($p_scenario)) {
         $p_scenario = returnGlobal('scenario');
     }
     if (!isset($p_cqid)) {
         $p_cqid = returnGlobal('cqid');
         if ($p_cqid == '') {
             $p_cqid = 0;
         }
         // we are not using another question as source of condition
     }
     if (!isset($p_cid)) {
         $p_cid = returnGlobal('cid');
     }
     if (!isset($p_subaction)) {
         if (isset($_POST['subaction'])) {
             $p_subaction = $_POST['subaction'];
         } else {
             $p_subaction = $subaction;
         }
     }
     if (!isset($p_cquestions)) {
         $p_cquestions = returnGlobal('cquestions');
     }
     if (!isset($p_csrctoken)) {
         $p_csrctoken = returnGlobal('csrctoken');
     }
     if (!isset($p_prevquestionsgqa)) {
         $p_prevquestionsgqa = returnGlobal('prevQuestionSGQA');
     }
     if (!isset($p_canswers)) {
         if (isset($_POST['canswers']) && is_array($_POST['canswers'])) {
             foreach ($_POST['canswers'] as $key => $val) {
                 $p_canswers[$key] = preg_replace("/[^_.a-zA-Z0-9]@/", "", $val);
             }
         }
     }
     // this array will be used soon,
     // to explain wich conditions is used to evaluate the question
     if (Yii::app()->getConfig('stringcomparizonoperators') == 1) {
         $method = array("<" => $clang->gT("Less than"), "<=" => $clang->gT("Less than or equal to"), "==" => $clang->gT("equals"), "!=" => $clang->gT("Not equal to"), ">=" => $clang->gT("Greater than or equal to"), ">" => $clang->gT("Greater than"), "RX" => $clang->gT("Regular expression"), "a<b" => $clang->gT("Less than (Strings)"), "a<=b" => $clang->gT("Less than or equal to (Strings)"), "a>=b" => $clang->gT("Greater than or equal to (Strings)"), "a>b" => $clang->gT("Greater than (Strings)"));
     } else {
         $method = array("<" => $clang->gT("Less than"), "<=" => $clang->gT("Less than or equal to"), "==" => $clang->gT("equals"), "!=" => $clang->gT("Not equal to"), ">=" => $clang->gT("Greater than or equal to"), ">" => $clang->gT("Greater than"), "RX" => $clang->gT("Regular expression"));
     }
     if (isset($_POST['method'])) {
         if (!in_array($_POST['method'], array_keys($method))) {
             $p_method = "==";
         } else {
             $p_method = trim($_POST['method']);
         }
     }
     if (isset($_POST['newscenarionum'])) {
         $p_newscenarionum = sanitize_int($_POST['newscenarionum']);
     }
     //END Sanitizing POSTed data
     //include_once("login_check.php");
     include_once "database.php";
     // Caution (lemeur): database.php uses autoUnescape on all entries in $_POST
     // Take care to not use autoUnescape on $_POST variables after this
     $br = CHtml::openTag('br /');
     //MAKE SURE THAT THERE IS A SID
     if (!isset($iSurveyID) || !$iSurveyID) {
         $conditionsoutput = $clang->gT("You have not selected a survey") . str_repeat($br, 2);
         $conditionsoutput .= CHtml::submitButton($clang->gT("Main admin screen"), array('onclick' => "window.open('" . $this->getController()->createUrl("admin/") . "', '_top')")) . $br;
         safeDie($conditionsoutput);
         return;
     }
     if (isset($p_subaction) && $p_subaction == "resetsurveylogic") {
         $clang = $this->getController()->lang;
         $resetsurveylogicoutput = $br;
         $resetsurveylogicoutput .= CHtml::openTag('table', array('class' => 'alertbox'));
         $resetsurveylogicoutput .= CHtml::openTag('tr') . CHtml::openTag('td', array('colspan' => '2'));
         $resetsurveylogicoutput .= CHtml::tag('font', array('size' => '1'), CHtml::tag('strong', array(), $clang->gT("Reset Survey Logic")));
         $resetsurveylogicoutput .= CHtml::closeTag('td') . CHtml::closeTag('tr');
         if (!isset($_GET['ok'])) {
             $button_yes = CHtml::submitButton($clang->gT("Yes"), array('onclick' => "window.open('" . $this->getController()->createUrl("admin/conditions/sa/index/subaction/resetsurveylogic/surveyid/{$iSurveyID}") . "?ok=Y" . "', '_top')"));
             $button_cancel = CHtml::submitButton($clang->gT("Cancel"), array('onclick' => "window.open('" . $this->getController()->createUrl("admin/survey/sa/view/surveyid/{$iSurveyID}") . "', '_top')"));
             $messagebox_content = $clang->gT("You are about to delete all conditions on this survey's questions") . "({$iSurveyID})" . $br . $clang->gT("We recommend that before you proceed, you export the entire survey from the main administration screen.") . $br . $clang->gT("Continue?") . $br . $button_yes . $button_cancel;
             $this->_renderWrappedTemplate('conditions', array('message' => array('title' => $clang->gT("Warning"), 'message' => $messagebox_content)));
             exit;
         } else {
             LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyID);
             Conditions::model()->deleteRecords("qid in (select qid from {{questions}} where sid={$iSurveyID})");
             Yii::app()->session['flashmessage'] = $clang->gT("All conditions in this survey have been deleted.");
             $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $iSurveyID));
         }
     }
     // MAKE SURE THAT THERE IS A QID
     if (!isset($qid) || !$qid) {
         $conditionsoutput = $clang->gT("You have not selected a question") . str_repeat($br, 2);
         $conditionsoutput .= CHtml::submitButton($clang->gT("Main admin screen"), array('onclick' => "window.open('" . $this->getController()->createUrl("admin/") . "', '_top')")) . $br;
         safeDie($conditionsoutput);
         return;
     }
     // If we made it this far, then lets develop the menu items
     // add the conditions container table
     $extraGetParams = "";
     if (isset($qid) && isset($gid)) {
         $extraGetParams = "/gid/{$gid}/qid/{$qid}";
     }
     $conditionsoutput_action_error = "";
     // defined during the actions
     $markcidarray = array();
     if (isset($_GET['markcid'])) {
         $markcidarray = explode("-", $_GET['markcid']);
     }
     //BEGIN PROCESS ACTIONS
     // ADD NEW ENTRY IF THIS IS AN ADD
     if (isset($p_subaction) && $p_subaction == "insertcondition") {
         if (!isset($p_canswers) && !isset($_POST['ConditionConst']) && !isset($_POST['prevQuestionSGQA']) && !isset($_POST['tokenAttr']) && !isset($_POST['ConditionRegexp']) || !isset($p_cquestions) && !isset($p_csrctoken)) {
             $conditionsoutput_action_error .= CHtml::script("\n<!--\n alert(\"" . $clang->gT("Your condition could not be added! It did not include the question and/or answer upon which the condition was based. Please ensure you have selected a question and an answer.", "js") . "\")\n //-->\n");
         } else {
             if (isset($p_cquestions) && $p_cquestions != '') {
                 $conditionCfieldname = $p_cquestions;
             } elseif (isset($p_csrctoken) && $p_csrctoken != '') {
                 $conditionCfieldname = $p_csrctoken;
             }
             $condition_data = array('qid' => $qid, 'scenario' => $p_scenario, 'cqid' => $p_cqid, 'cfieldname' => $conditionCfieldname, 'method' => $p_method);
             if (isset($p_canswers)) {
                 foreach ($p_canswers as $ca) {
                     //First lets make sure there isn't already an exact replica of this condition
                     $condition_data['value'] = $ca;
                     $result = Conditions::model()->findAllByAttributes($condition_data);
                     $count_caseinsensitivedupes = count($result);
                     if ($count_caseinsensitivedupes == 0) {
                         $result = Conditions::model()->insertRecords($condition_data);
                     }
                 }
             }
             unset($posted_condition_value);
             // Please note that autoUnescape is already applied in database.php included above
             // so we only need to db_quote _POST variables
             if (isset($_POST['ConditionConst']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#CONST") {
                 $posted_condition_value = Yii::app()->request->getPost('ConditionConst');
             } elseif (isset($_POST['prevQuestionSGQA']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#PREVQUESTIONS") {
                 $posted_condition_value = Yii::app()->request->getPost('prevQuestionSGQA');
             } elseif (isset($_POST['tokenAttr']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#TOKENATTRS") {
                 $posted_condition_value = Yii::app()->request->getPost('tokenAttr');
             } elseif (isset($_POST['ConditionRegexp']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#REGEXP") {
                 $posted_condition_value = Yii::app()->request->getPost('ConditionRegexp');
             }
             if (isset($posted_condition_value)) {
                 $condition_data['value'] = $posted_condition_value;
                 $result = Conditions::model()->insertRecords($condition_data);
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
     }
     // UPDATE ENTRY IF THIS IS AN EDIT
     if (isset($p_subaction) && $p_subaction == "updatecondition") {
         if (!isset($p_canswers) && !isset($_POST['ConditionConst']) && !isset($_POST['prevQuestionSGQA']) && !isset($_POST['tokenAttr']) && !isset($_POST['ConditionRegexp']) || !isset($p_cquestions) && !isset($p_csrctoken)) {
             $conditionsoutput_action_error .= CHtml::script("\n<!--\n alert(\"" . $clang->gT("Your condition could not be added! It did not include the question and/or answer upon which the condition was based. Please ensure you have selected a question and an answer.", "js") . "\")\n //-->\n");
         } else {
             if (isset($p_cquestions) && $p_cquestions != '') {
                 $conditionCfieldname = $p_cquestions;
             } elseif (isset($p_csrctoken) && $p_csrctoken != '') {
                 $conditionCfieldname = $p_csrctoken;
             }
             if (isset($p_canswers)) {
                 foreach ($p_canswers as $ca) {
                     // This is an Edit, there will only be ONE VALUE
                     $updated_data = array('qid' => $qid, 'scenario' => $p_scenario, 'cqid' => $p_cqid, 'cfieldname' => $conditionCfieldname, 'method' => $p_method, 'value' => $ca);
                     $result = Conditions::model()->insertRecords($updated_data, TRUE, array('cid' => $p_cid));
                 }
             }
             unset($posted_condition_value);
             // Please note that autoUnescape is already applied in database.php included above
             // so we only need to db_quote _POST variables
             if (isset($_POST['ConditionConst']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#CONST") {
                 $posted_condition_value = Yii::app()->request->getPost('ConditionConst');
             } elseif (isset($_POST['prevQuestionSGQA']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#PREVQUESTIONS") {
                 $posted_condition_value = Yii::app()->request->getPost('prevQuestionSGQA');
             } elseif (isset($_POST['tokenAttr']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#TOKENATTRS") {
                 $posted_condition_value = Yii::app()->request->getPost('tokenAttr');
             } elseif (isset($_POST['ConditionRegexp']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#REGEXP") {
                 $posted_condition_value = Yii::app()->request->getPost('ConditionRegexp');
             }
             if (isset($posted_condition_value)) {
                 $updated_data = array('qid' => $qid, 'scenario' => $p_scenario, 'cqid' => $p_cqid, 'cfieldname' => $conditionCfieldname, 'method' => $p_method, 'value' => $posted_condition_value);
                 $result = Conditions::model()->insertRecords($updated_data, TRUE, array('cid' => $p_cid));
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
     }
     // DELETE ENTRY IF THIS IS DELETE
     if (isset($p_subaction) && $p_subaction == "delete") {
         LimeExpressionManager::RevertUpgradeConditionsToRelevance(NULL, $qid);
         // in case deleted the last condition
         $result = Conditions::model()->deleteRecords(array('cid' => $p_cid));
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
     }
     // DELETE ALL CONDITIONS IN THIS SCENARIO
     if (isset($p_subaction) && $p_subaction == "deletescenario") {
         LimeExpressionManager::RevertUpgradeConditionsToRelevance(NULL, $qid);
         // in case deleted the last condition
         $result = Conditions::model()->deleteRecords(array('qid' => $qid, 'scenario' => $p_scenario));
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
     }
     // UPDATE SCENARIO
     if (isset($p_subaction) && $p_subaction == "updatescenario" && isset($p_newscenarionum)) {
         $result = Conditions::model()->insertRecords(array('scenario' => $p_newscenarionum), TRUE, array('qid' => $qid, 'scenario' => $p_scenario));
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
     }
     // DELETE ALL CONDITIONS FOR THIS QUESTION
     if (isset($p_subaction) && $p_subaction == "deleteallconditions") {
         LimeExpressionManager::RevertUpgradeConditionsToRelevance(NULL, $qid);
         // in case deleted the last condition
         $result = Conditions::model()->deleteRecords(array('qid' => $qid));
     }
     // RENUMBER SCENARIOS
     if (isset($p_subaction) && $p_subaction == "renumberscenarios") {
         $query = "SELECT DISTINCT scenario FROM {{conditions}} WHERE qid=:qid ORDER BY scenario";
         $result = Yii::app()->db->createCommand($query)->bindParam(":qid", $qid, PDO::PARAM_INT)->query() or safeDie("Couldn't select scenario<br />{$query}<br />");
         $newindex = 1;
         foreach ($result->readAll() as $srow) {
             // new var $update_result == old var $result2
             $update_result = Conditions::model()->insertRecords(array('scenario' => $newindex), TRUE, array('qid' => $qid, 'scenario' => $srow['scenario']));
             $newindex++;
         }
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
         Yii::app()->session['flashmessage'] = $clang->gT("All conditions scenarios were renumbered.");
     }
     // COPY CONDITIONS IF THIS IS COPY
     if (isset($p_subaction) && $p_subaction == "copyconditions") {
         $qid = returnGlobal('qid');
         $copyconditionsfrom = returnGlobal('copyconditionsfrom');
         $copyconditionsto = returnGlobal('copyconditionsto');
         if (isset($copyconditionsto) && is_array($copyconditionsto) && isset($copyconditionsfrom) && is_array($copyconditionsfrom)) {
             //Get the conditions we are going to copy
             foreach ($copyconditionsfrom as &$entry) {
                 $entry = Yii::app()->db->quoteValue($entry);
             }
             $query = "SELECT * FROM {{conditions}}\n" . "WHERE cid in (";
             $query .= implode(", ", $copyconditionsfrom);
             $query .= ")";
             $result = Yii::app()->db->createCommand($query)->query() or safeDie("Couldn't get conditions for copy<br />{$query}<br />");
             foreach ($result->readAll() as $row) {
                 $proformaconditions[] = array("scenario" => $row['scenario'], "cqid" => $row['cqid'], "cfieldname" => $row['cfieldname'], "method" => $row['method'], "value" => $row['value']);
             }
             // while
             foreach ($copyconditionsto as $copyc) {
                 list($newsid, $newgid, $newqid) = explode("X", $copyc);
                 foreach ($proformaconditions as $pfc) {
                     //TIBO
                     //First lets make sure there isn't already an exact replica of this condition
                     $conditions_data = array('qid' => $newqid, 'scenario' => $pfc['scenario'], 'cqid' => $pfc['cqid'], 'cfieldname' => $pfc['cfieldname'], 'method' => $pfc['method'], 'value' => $pfc['value']);
                     $result = Conditions::model()->findAllByAttributes($conditions_data);
                     $count_caseinsensitivedupes = count($result);
                     $countduplicates = 0;
                     if ($count_caseinsensitivedupes != 0) {
                         foreach ($result as $ccrow) {
                             if ($ccrow['value'] == $pfc['value']) {
                                 $countduplicates++;
                             }
                         }
                     }
                     if ($countduplicates == 0) {
                         $result = Conditions::model()->insertRecords($conditions_data);
                         $conditionCopied = true;
                     } else {
                         $conditionDuplicated = true;
                     }
                 }
             }
             if (isset($conditionCopied) && $conditionCopied === true) {
                 if (isset($conditionDuplicated) && $conditionDuplicated == true) {
                     $CopyConditionsMessage = CHtml::tag('div', array('class' => 'partialheader'), '(' . $clang->gT("Conditions successfully copied (some were skipped because they were duplicates)") . ')');
                 } else {
                     $CopyConditionsMessage = CHtml::tag('div', array('class' => 'successheader'), '(' . $clang->gT("Conditions successfully copied") . ')');
                 }
             } else {
                 $CopyConditionsMessage = CHtml::tag('div', array('class' => 'warningheader'), '(' . $clang->gT("No conditions could be copied (due to duplicates)") . ')');
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyID);
         // do for whole survey, since don't know which questions affected.
     }
     //END PROCESS ACTIONS
     $cquestions = array();
     $canswers = array();
     //BEGIN: GATHER INFORMATION
     // 1: Get information for this question
     if (!isset($qid)) {
         $qid = returnGlobal('qid');
     }
     if (!isset($iSurveyID)) {
         $iSurveyID = returnGlobal('sid');
     }
     $thissurvey = getSurveyInfo($iSurveyID);
     $qresult = Questions::model()->with('groups')->findByAttributes(array('qid' => $qid, 'parent_qid' => 0, 'language' => Survey::model()->findByPk($iSurveyID)->language));
     $questiongroupname = $qresult->groups->group_name;
     $questiontitle = $qresult['title'];
     $questiontext = $qresult['question'];
     $questiontype = $qresult['type'];
     // 2: Get all other questions that occur before this question that are pre-determined answer types
     // To avoid natural sort order issues,
     // first get all questions in natural sort order
     // , and find out which number in that order this question is
     $qresult = Questions::model()->with(array('groups' => array('condition' => 'groups.language = :lang', 'params' => array(':lang' => Survey::model()->findByPk($iSurveyID)->language))))->findAllByAttributes(array('parent_qid' => 0, 'sid' => $iSurveyID, 'language' => Survey::model()->findByPk($iSurveyID)->language));
     $qrows = array();
     foreach ($qresult as $k => $v) {
         $qrows[$k] = array_merge($v->attributes, $v->groups->attributes);
     }
     // Perform a case insensitive natural sort on group name then question title (known as "code" in the form) of a multidimensional array
     usort($qrows, 'groupOrderThenQuestionOrder');
     $position = "before";
     // Go through each question until we reach the current one
     foreach ($qrows as $qrow) {
         if ($qrow["qid"] != $qid && $position == "before") {
             // remember all previous questions
             // all question types are supported.
             $questionlist[] = $qrow["qid"];
         } elseif ($qrow["qid"] == $qid) {
             break;
         }
     }
     // Now, using the same array which is now properly sorted by group then question
     // Create an array of all the questions that appear AFTER the current one
     $position = "before";
     foreach ($qrows as $qrow) {
         if ($qrow["qid"] == $qid) {
             $position = "after";
             //break;
         } elseif ($qrow["qid"] != $qid && $position == "after") {
             $postquestionlist[] = $qrow['qid'];
         }
     }
     $theserows = array();
     $postrows = array();
     if (isset($questionlist) && is_array($questionlist)) {
         foreach ($questionlist as $ql) {
             $result = Questions::model()->with(array('groups' => array('condition' => 'groups.language = :lang', 'params' => array(':lang' => Survey::model()->findByPk($iSurveyID)->language))))->findAllByAttributes(array('qid' => $ql, 'parent_qid' => 0, 'sid' => $iSurveyID, 'language' => Survey::model()->findByPk($iSurveyID)->language));
             $thiscount = count($result);
             // And store again these questions in this array...
             foreach ($result as $myrows) {
                 //key => value
                 $theserows[] = array("qid" => $myrows['qid'], "sid" => $myrows['sid'], "gid" => $myrows['gid'], "question" => $myrows['question'], "type" => $myrows['type'], "mandatory" => $myrows['mandatory'], "other" => $myrows['other'], "title" => $myrows['title']);
             }
         }
     }
     if (isset($postquestionlist) && is_array($postquestionlist)) {
         foreach ($postquestionlist as $pq) {
             $result = Questions::model()->with(array('groups' => array('condition' => 'groups.language = :lang', 'params' => array(':lang' => Survey::model()->findByPk($iSurveyID)->language))))->findAllByAttributes(array('qid' => $pq, 'parent_qid' => 0, 'sid' => $iSurveyID, 'language' => Survey::model()->findByPk($iSurveyID)->language));
             $postcount = count($result);
             foreach ($result as $myrows) {
                 $postrows[] = array("qid" => $myrows['qid'], "sid" => $myrows['sid'], "gid" => $myrows['gid'], "question" => $myrows['question'], "type" => $myrows['type'], "mandatory" => $myrows['mandatory'], "other" => $myrows['other'], "title" => $myrows['title']);
             }
             // while
         }
         $postquestionscount = count($postrows);
     }
     $questionscount = count($theserows);
     if (isset($postquestionscount) && $postquestionscount > 0) {
         //Build the array used for the questionNav and copyTo select boxes
         foreach ($postrows as $pr) {
             $pquestions[] = array("text" => $pr['title'] . ": " . substr(strip_tags($pr['question']), 0, 80), "fieldname" => $pr['sid'] . "X" . $pr['gid'] . "X" . $pr['qid']);
         }
     }
     // Previous question parsing ==> building cquestions[] and canswers[]
     if ($questionscount > 0) {
         $X = "X";
         foreach ($theserows as $rows) {
             $shortquestion = $rows['title'] . ": " . strip_tags($rows['question']);
             if ($rows['type'] == "A" || $rows['type'] == "B" || $rows['type'] == "C" || $rows['type'] == "E" || $rows['type'] == "F" || $rows['type'] == "H") {
                 $aresult = Questions::model()->findAllByAttributes(array('parent_qid' => $rows['qid'], 'language' => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'question_order ASC'));
                 foreach ($aresult as $arows) {
                     $shortanswer = "{$arows['title']}: [" . flattenText($arows['question']) . "]";
                     $shortquestion = $rows['title'] . ":{$shortanswer} " . flattenText($rows['question']);
                     $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title']);
                     switch ($rows['type']) {
                         case "A":
                             //Array 5 buttons
                             for ($i = 1; $i <= 5; $i++) {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], $i, $i);
                             }
                             break;
                         case "B":
                             //Array 10 buttons
                             for ($i = 1; $i <= 10; $i++) {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], $i, $i);
                             }
                             break;
                         case "C":
                             //Array Y/N/NA
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "Y", $clang->gT("Yes"));
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "U", $clang->gT("Uncertain"));
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "N", $clang->gT("No"));
                             break;
                         case "E":
                             //Array >/=/<
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "I", $clang->gT("Increase"));
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "S", $clang->gT("Same"));
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "D", $clang->gT("Decrease"));
                             break;
                         case "F":
                             //Array Flexible Row
                         //Array Flexible Row
                         case "H":
                             //Array Flexible Column
                             $fresult = Answers::model()->findAllByAttributes(array('qid' => $rows['qid'], "language" => Survey::model()->findByPk($iSurveyID)->language, 'scale_id' => 0), array('order' => 'sortorder, code'));
                             foreach ($fresult as $frow) {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], $frow['code'], $frow['answer']);
                             }
                             break;
                     }
                     // Only Show No-Answer if question is not mandatory
                     if ($rows['mandatory'] != 'Y') {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "", $clang->gT("No answer"));
                     }
                 }
                 //while
             } elseif ($rows['type'] == ":" || $rows['type'] == ";") {
                 // Multiflexi
                 //Get question attribute for $canswers
                 $qidattributes = getQuestionAttributeValues($rows['qid'], $rows['type']);
                 if (isset($qidattributes['multiflexible_max']) && trim($qidattributes['multiflexible_max']) != '') {
                     $maxvalue = floatval($qidattributes['multiflexible_max']);
                 } else {
                     $maxvalue = 10;
                 }
                 if (isset($qidattributes['multiflexible_min']) && trim($qidattributes['multiflexible_min']) != '') {
                     $minvalue = floatval($qidattributes['multiflexible_min']);
                 } else {
                     $minvalue = 1;
                 }
                 if (isset($qidattributes['multiflexible_step']) && trim($qidattributes['multiflexible_step']) != '') {
                     $stepvalue = floatval($qidattributes['multiflexible_step']);
                     if ($stepvalue == 0) {
                         $stepvalue = 1;
                     }
                 } else {
                     $stepvalue = 1;
                 }
                 if (isset($qidattributes['multiflexible_checkbox']) && $qidattributes['multiflexible_checkbox'] != 0) {
                     $minvalue = 0;
                     $maxvalue = 1;
                     $stepvalue = 1;
                 }
                 // Get the Y-Axis
                 $fquery = "SELECT sq.*, q.other" . " FROM {{questions sq}}, {{questions q}}" . " WHERE sq.sid={$iSurveyID} AND sq.parent_qid=q.qid " . "AND q.language=:lang" . " AND sq.language=:lang" . " AND q.qid=:qid\n                    AND sq.scale_id=0\n                    ORDER BY sq.question_order";
                 $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
                 $y_axis_db = Yii::app()->db->createCommand($fquery)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->bindParam(":qid", $rows['qid'], PDO::PARAM_INT)->query();
                 // Get the X-Axis
                 $aquery = "SELECT sq.*\n                    FROM {{questions q}}, {{questions sq}}\n                    WHERE q.sid={$iSurveyID}\n                    AND sq.parent_qid=q.qid\n                    AND q.language=:lang\n                    AND sq.language=:lang\n                    AND q.qid=:qid\n                    AND sq.scale_id=1\n                    ORDER BY sq.question_order";
                 $x_axis_db = Yii::app()->db->createCommand($aquery)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->bindParam(":qid", $rows['qid'], PDO::PARAM_INT)->query() or safeDie("Couldn't get answers to Array questions<br />{$aquery}<br />");
                 foreach ($x_axis_db->readAll() as $frow) {
                     $x_axis[$frow['title']] = $frow['question'];
                 }
                 foreach ($y_axis_db->readAll() as $yrow) {
                     foreach ($x_axis as $key => $val) {
                         $shortquestion = $rows['title'] . ":{$yrow['title']}:{$key}: [" . strip_tags($yrow['question']) . "][" . strip_tags($val) . "] " . flattenText($rows['question']);
                         $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $yrow['title'] . "_" . $key);
                         if ($rows['type'] == ":") {
                             for ($ii = $minvalue; $ii <= $maxvalue; $ii += $stepvalue) {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $yrow['title'] . "_" . $key, $ii, $ii);
                             }
                         }
                     }
                 }
                 unset($x_axis);
             } elseif ($rows['type'] == "1") {
                 $aresult = Questions::model()->findAllByAttributes(array('parent_qid' => $rows['qid'], 'language' => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'question_order desc'));
                 foreach ($aresult as $arows) {
                     $attr = getQuestionAttributeValues($rows['qid']);
                     $label1 = isset($attr['dualscale_headerA']) ? $attr['dualscale_headerA'] : 'Label1';
                     $label2 = isset($attr['dualscale_headerB']) ? $attr['dualscale_headerB'] : 'Label2';
                     $shortanswer = "{$arows['title']}: [" . strip_tags($arows['question']) . "][{$label1}]";
                     $shortquestion = $rows['title'] . ":{$shortanswer} " . strip_tags($rows['question']);
                     $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#0");
                     $shortanswer = "{$arows['title']}: [" . strip_tags($arows['question']) . "][{$label2}]";
                     $shortquestion = $rows['title'] . ":{$shortanswer} " . strip_tags($rows['question']);
                     $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#1");
                     // first label
                     $lresult = Answers::model()->findAllByAttributes(array('qid' => $rows['qid'], 'scale_id' => 0, 'language' => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'sortorder, answer'));
                     foreach ($lresult as $lrows) {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#0", "{$lrows['code']}", "{$lrows['code']}");
                     }
                     // second label
                     $lresult = Answers::model()->findAllByAttributes(array('qid' => $rows['qid'], 'scale_id' => 1, 'language' => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'sortorder, answer'));
                     foreach ($lresult as $lrows) {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#1", "{$lrows['code']}", "{$lrows['code']}");
                     }
                     // Only Show No-Answer if question is not mandatory
                     if ($rows['mandatory'] != 'Y') {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#0", "", $clang->gT("No answer"));
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#1", "", $clang->gT("No answer"));
                     }
                 }
                 //while
             } elseif ($rows['type'] == "K" || $rows['type'] == "Q") {
                 $aresult = Questions::model()->findAllByAttributes(array("parent_qid" => $rows['qid'], "language" => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'question_order desc'));
                 foreach ($aresult as $arows) {
                     $shortanswer = "{$arows['title']}: [" . strip_tags($arows['question']) . "]";
                     $shortquestion = $rows['title'] . ":{$shortanswer} " . strip_tags($rows['question']);
                     $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title']);
                     // Only Show No-Answer if question is not mandatory
                     if ($rows['mandatory'] != 'Y') {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "", $clang->gT("No answer"));
                     }
                 }
                 //while
             } elseif ($rows['type'] == "R") {
                 $aresult = Answers::model()->findAllByAttributes(array("qid" => $rows['qid'], "scale_id" => 0, "language" => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'sortorder, answer'));
                 $acount = count($aresult);
                 foreach ($aresult as $arow) {
                     $theanswer = addcslashes($arow['answer'], "'");
                     $quicky[] = array($arow['code'], $theanswer);
                 }
                 for ($i = 1; $i <= $acount; $i++) {
                     $cquestions[] = array("{$rows['title']}: [RANK {$i}] " . strip_tags($rows['question']), $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $i);
                     foreach ($quicky as $qck) {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $i, $qck[0], $qck[1]);
                     }
                     // Only Show No-Answer if question is not mandatory
                     if ($rows['mandatory'] != 'Y') {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $i, " ", $clang->gT("No answer"));
                     }
                 }
                 unset($quicky);
             } elseif ($rows['type'] == "M" || $rows['type'] == "P") {
                 $shortanswer = " [" . $clang->gT("Group of checkboxes") . "]";
                 $shortquestion = $rows['title'] . ":{$shortanswer} " . strip_tags($rows['question']);
                 $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid']);
                 $aresult = Questions::model()->findAllByAttributes(array("parent_qid" => $rows['qid'], "language" => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'question_order desc'));
                 foreach ($aresult as $arows) {
                     $theanswer = addcslashes($arows['question'], "'");
                     $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], $arows['title'], $theanswer);
                     $shortanswer = "{$arows['title']}: [" . strip_tags($arows['question']) . "]";
                     $shortanswer .= "[" . $clang->gT("Single checkbox") . "]";
                     $shortquestion = $rows['title'] . ":{$shortanswer} " . strip_tags($rows['question']);
                     $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], "+" . $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title']);
                     $canswers[] = array("+" . $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], 'Y', $clang->gT("checked"));
                     $canswers[] = array("+" . $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], '', $clang->gT("not checked"));
                 }
             } elseif ($rows['type'] == "X") {
                 //Just ignore this questiontype
             } else {
                 $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid']);
                 switch ($rows['type']) {
                     case "Y":
                         // Y/N/NA
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], "Y", $clang->gT("Yes"));
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], "N", $clang->gT("No"));
                         // Only Show No-Answer if question is not mandatory
                         if ($rows['mandatory'] != 'Y') {
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                         }
                         break;
                     case "G":
                         //Gender
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], "F", $clang->gT("Female"));
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], "M", $clang->gT("Male"));
                         // Only Show No-Answer if question is not mandatory
                         if ($rows['mandatory'] != 'Y') {
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                         }
                         break;
                     case "5":
                         // 5 choice
                         for ($i = 1; $i <= 5; $i++) {
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], $i, $i);
                         }
                         // Only Show No-Answer if question is not mandatory
                         if ($rows['mandatory'] != 'Y') {
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                         }
                         break;
                     case "N":
                         // Simple Numerical questions
                         // Only Show No-Answer if question is not mandatory
                         if ($rows['mandatory'] != 'Y') {
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                         }
                         break;
                     default:
                         $aresult = Answers::model()->findAllByAttributes(array('qid' => $rows['qid'], 'scale_id' => 0, 'language' => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'sortorder, answer'));
                         foreach ($aresult as $arows) {
                             $theanswer = addcslashes($arows['answer'], "'");
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], $arows['code'], $theanswer);
                         }
                         if ($rows['type'] == "D") {
                             // Only Show No-Answer if question is not mandatory
                             if ($rows['mandatory'] != 'Y') {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                             }
                         } elseif ($rows['type'] != "M" && $rows['type'] != "P" && $rows['type'] != "J" && $rows['type'] != "I") {
                             // For dropdown questions
                             // optinnaly add the 'Other' answer
                             if (($rows['type'] == "L" || $rows['type'] == "!") && $rows['other'] == "Y") {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], "-oth-", $clang->gT("Other"));
                             }
                             // Only Show No-Answer if question is not mandatory
                             if ($rows['mandatory'] != 'Y') {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                             }
                         }
                         break;
                 }
                 //switch row type
             }
             //else
         }
         //foreach theserows
     }
     //if questionscount > 0
     //END Gather Information for this question
     $questionNavOptions = CHtml::openTag('optgroup', array('class' => 'activesurveyselect', 'label' => $clang->gT("Before", "js")));
     foreach ($theserows as $row) {
         $question = $row['question'];
         $question = strip_tags($question);
         if (strlen($question) < 35) {
             $questionselecter = $question;
         } else {
             //$questionselecter = substr($question, 0, 35)."..";
             $questionselecter = htmlspecialchars(mb_strcut(html_entity_decode($question, ENT_QUOTES, 'UTF-8'), 0, 35, 'UTF-8')) . "...";
         }
         $questionNavOptions .= CHtml::tag('option', array('value' => $this->getController()->createUrl("/admin/conditions/sa/index/subaction/editconditionsform/surveyid/{$iSurveyID}/gid/{$row['gid']}/qid/{$row['qid']}")), $questionselecter);
     }
     $questionNavOptions .= CHtml::closeTag('optgroup');
     $questionNavOptions .= CHtml::openTag('optgroup', array('class' => 'activesurveyselect', 'label' => $clang->gT("Current", "js")));
     $question = strip_tags($questiontext);
     if (strlen($question) < 35) {
         $questiontextshort = $question;
     } else {
         //$questiontextshort = substr($question, 0, 35)."..";
         $questiontextshort = htmlspecialchars(mb_strcut(html_entity_decode($question, ENT_QUOTES, 'UTF-8'), 0, 35, 'UTF-8')) . "...";
     }
     $questionNavOptions .= CHtml::tag('option', array('value' => $this->getController()->createUrl("/admin/conditions/sa/index/subaction/editconditionsform/surveyid/{$iSurveyID}/gid/{$gid}/qid/{$qid}"), 'selected' => 'selected'), $questiontitle . ': ' . $questiontextshort);
     $questionNavOptions .= CHtml::closeTag('optgroup');
     $questionNavOptions .= CHtml::openTag('optgroup', array('class' => 'activesurveyselect', 'label' => $clang->gT("After", "js")));
     foreach ($postrows as $row) {
         $question = $row['question'];
         $question = strip_tags($question);
         if (strlen($question) < 35) {
             $questionselecter = $question;
         } else {
             //$questionselecter = substr($question, 0, 35)."..";
             $questionselecter = htmlspecialchars(mb_strcut(html_entity_decode($question, ENT_QUOTES, 'UTF-8'), 0, 35, 'UTF-8')) . "...";
         }
         $questionNavOptions .= CHtml::tag('option', array('value' => $this->getController()->createUrl("/admin/conditions/sa/index/subaction/editconditionsform/surveyid/{$iSurveyID}/gid/{$row['gid']}/qid/{$row['qid']}")), $row['title'] . ':' . $questionselecter);
     }
     $questionNavOptions .= CHtml::closeTag('optgroup');
     //Now display the information and forms
     //BEGIN: PREPARE JAVASCRIPT TO SHOW MATCHING ANSWERS TO SELECTED QUESTION
     $javascriptpre = CHtml::openTag('script', array('type' => 'text/javascript')) . "<!--\n" . "\tvar Fieldnames = new Array();\n" . "\tvar Codes = new Array();\n" . "\tvar Answers = new Array();\n" . "\tvar QFieldnames = new Array();\n" . "\tvar Qcqids = new Array();\n" . "\tvar Qtypes = new Array();\n";
     $jn = 0;
     if (isset($canswers)) {
         foreach ($canswers as $can) {
             $an = ls_json_encode(flattenText($can[2]));
             $javascriptpre .= "Fieldnames[{$jn}]='{$can['0']}';\n" . "Codes[{$jn}]='{$can['1']}';\n" . "Answers[{$jn}]={$an};\n";
             $jn++;
         }
     }
     $jn = 0;
     if (isset($cquestions)) {
         foreach ($cquestions as $cqn) {
             $javascriptpre .= "QFieldnames[{$jn}]='{$cqn['3']}';\n" . "Qcqids[{$jn}]='{$cqn['1']}';\n" . "Qtypes[{$jn}]='{$cqn['2']}';\n";
             $jn++;
         }
     }
     //  record a JS variable to let jQuery know if survey is Anonymous
     if ($thissurvey['anonymized'] == 'Y') {
         $javascriptpre .= "isAnonymousSurvey = true;";
     } else {
         $javascriptpre .= "isAnonymousSurvey = false;";
     }
     $javascriptpre .= "//-->\n" . CHtml::closeTag('script');
     //END: PREPARE JAVASCRIPT TO SHOW MATCHING ANSWERS TO SELECTED QUESTION
     $this->getController()->_css_admin_includes(Yii::app()->getConfig("publicstyleurl") . 'jquery.multiselect.css');
     $aViewUrls = array();
     $aData['clang'] = $clang;
     $aData['surveyid'] = $iSurveyID;
     $aData['qid'] = $qid;
     $aData['gid'] = $gid;
     $aData['imageurl'] = $imageurl;
     $aData['extraGetParams'] = $extraGetParams;
     $aData['quesitonNavOptions'] = $questionNavOptions;
     $aData['conditionsoutput_action_error'] = $conditionsoutput_action_error;
     $aData['javascriptpre'] = $javascriptpre;
     $aViewUrls['conditionshead_view'][] = $aData;
     //BEGIN DISPLAY CONDITIONS FOR THIS QUESTION
     if ($subaction == 'index' || $subaction == 'editconditionsform' || $subaction == 'insertcondition' || $subaction == "editthiscondition" || $subaction == "delete" || $subaction == "updatecondition" || $subaction == "deletescenario" || $subaction == "renumberscenarios" || $subaction == "deleteallconditions" || $subaction == "updatescenario" || $subaction == 'copyconditionsform' || $subaction == 'copyconditions' || $subaction == 'conditions') {
         //3: Get other conditions currently set for this question
         $conditionscount = 0;
         $s = 0;
         $criteria = new CDbCriteria();
         $criteria->select = 'scenario';
         // only select the 'scenario' column
         $criteria->condition = 'qid=:qid';
         $criteria->params = array(':qid' => $qid);
         $criteria->order = 'scenario';
         $criteria->group = 'scenario';
         $scenarioresult = Conditions::model()->findAll($criteria);
         $scenariocount = count($scenarioresult);
         $showreplace = "{$questiontitle}" . $this->_showSpeaker($questiontext);
         $onlyshow = sprintf($clang->gT("Only show question %s IF"), $showreplace);
         $aData['conditionsoutput'] = '';
         $aData['extraGetParams'] = $extraGetParams;
         $aData['quesitonNavOptions'] = $questionNavOptions;
         $aData['conditionsoutput_action_error'] = $conditionsoutput_action_error;
         $aData['javascriptpre'] = $javascriptpre;
         $aData['onlyshow'] = $onlyshow;
         $aData['subaction'] = $subaction;
         $aData['scenariocount'] = $scenariocount;
         $aViewUrls['conditionslist_view'][] = $aData;
         if ($scenariocount > 0) {
             //self::_js_admin_includes($this->config->item("generalscripts").'jquery/jquery.checkgroup.js');
             $this->getController()->_js_admin_includes(Yii::app()->getConfig("generalscripts") . 'jquery/jquery.checkgroup.js');
             foreach ($scenarioresult as $scenarionr) {
                 $scenariotext = "";
                 if ($s == 0 && $scenariocount > 1) {
                     $scenariotext = " -------- <i>Scenario {$scenarionr['scenario']}</i> --------";
                 }
                 if ($s > 0) {
                     $scenariotext = " -------- <i>" . $clang->gT("OR") . " Scenario {$scenarionr['scenario']}</i> --------";
                 }
                 if ($subaction == "copyconditionsform" || $subaction == "copyconditions") {
                     $initialCheckbox = "<td><input type='checkbox' id='scenarioCbx{$scenarionr['scenario']}' checked='checked'/>\n" . "<script type='text/javascript'>\$(document).ready(function () { \$('#scenarioCbx{$scenarionr['scenario']}').checkgroup({ groupName:'aConditionFromScenario{$scenarionr['scenario']}'}); });</script>" . "</td><td>&nbsp;</td>\n";
                 } else {
                     $initialCheckbox = "";
                 }
                 if ($scenariotext != "" && ($subaction == "editconditionsform" || $subaction == "insertcondition" || $subaction == "updatecondition" || $subaction == "editthiscondition" || $subaction == "renumberscenarios" || $subaction == "updatescenario" || $subaction == "deletescenario" || $subaction == "delete")) {
                     $img_tag = CHtml::image($imageurl . '/scenario_delete.png', $clang->gT("Delete this scenario"), array('name' => 'DeleteWholeGroup'));
                     $additional_main_content = CHtml::link($img_tag, '#', array('onclick' => "if ( confirm('" . $clang->gT("Are you sure you want to delete all conditions set in this scenario?", "js") . "')) { document.getElementById('deletescenario{$scenarionr['scenario']}').submit();}"));
                     $img_tag = CHtml::image($imageurl . '/scenario_edit.png', $clang->gT("Edit scenario"), array('name' => 'DeleteWholeGroup'));
                     $additional_main_content .= CHtml::link($img_tag, '#', array('id' => 'editscenariobtn' . $scenarionr['scenario'], 'onclick' => "\$('#editscenario{$scenarionr['scenario']}').toggle('slow');"));
                     $aData['additional_content'] = $additional_main_content;
                 }
                 $aData['initialCheckbox'] = $initialCheckbox;
                 $aData['scenariotext'] = $scenariotext;
                 $aData['scenarionr'] = $scenarionr;
                 if (!isset($aViewUrls['output'])) {
                     $aViewUrls['output'] = '';
                 }
                 $aViewUrls['output'] .= $this->getController()->render('/admin/conditions/includes/conditions_scenario', $aData, TRUE);
                 unset($currentfield);
                 $query = "SELECT count(*) as recordcount\n                    FROM {{conditions}} c, {{questions}} q, {{groups}} g\n                    WHERE c.cqid=q.qid " . "AND q.gid=g.gid " . "AND q.parent_qid=0 " . "AND q.language=:lang1 " . "AND g.language=:lang2 " . "AND c.qid=:qid " . "AND c.scenario=:scenario " . "AND c.cfieldname NOT LIKE '{%' ";
                 // avoid catching SRCtokenAttr conditions
                 $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
                 $result = Yii::app()->db->createCommand($query)->bindValue(":scenario", $scenarionr['scenario'])->bindValue(":qid", $qid, PDO::PARAM_INT)->bindValue(":lang1", $sLanguage, PDO::PARAM_STR)->bindValue(":lang2", $sLanguage, PDO::PARAM_STR)->queryRow();
                 $conditionscount = (int) $result['recordcount'];
                 $query = "SELECT c.cid, c.scenario, c.cqid, c.cfieldname, c.method, c.value, q.type\n                    FROM {{conditions}} c, {{questions}} q, {{groups}} g\n                    WHERE c.cqid=q.qid " . "AND q.gid=g.gid " . "AND q.parent_qid=0 " . "AND q.language=:lang1 " . "AND g.language=:lang2 " . "AND c.qid=:qid " . "AND c.scenario=:scenario " . "AND c.cfieldname NOT LIKE '{%' " . "ORDER BY g.group_order, q.question_order, c.cfieldname";
                 $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
                 $result = Yii::app()->db->createCommand($query)->bindValue(":scenario", $scenarionr['scenario'])->bindValue(":qid", $qid, PDO::PARAM_INT)->bindValue(":lang1", $sLanguage, PDO::PARAM_STR)->bindValue(":lang2", $sLanguage, PDO::PARAM_STR)->query() or safeDie("Couldn't get other conditions for question {$qid}<br />{$query}<br />");
                 $querytoken = "SELECT count(*) as recordcount " . "FROM {{conditions}} " . "WHERE " . " {{conditions}}.qid=:qid " . "AND {{conditions}}.scenario=:scenario " . "AND {{conditions}}.cfieldname LIKE '{%' ";
                 // only catching SRCtokenAttr conditions
                 $resulttoken = Yii::app()->db->createCommand($querytoken)->bindValue(":scenario", $scenarionr['scenario'], PDO::PARAM_INT)->bindValue(":qid", $qid, PDO::PARAM_INT)->queryRow() or safeDie("Couldn't get other conditions for question {$qid}<br />{$query}<br />");
                 $conditionscounttoken = (int) $resulttoken['recordcount'];
                 $querytoken = "SELECT {{conditions}}.cid, " . "{{conditions}}.scenario, " . "{{conditions}}.cqid, " . "{{conditions}}.cfieldname, " . "{{conditions}}.method, " . "{{conditions}}.value, " . "'' AS type " . "FROM {{conditions}} " . "WHERE " . " {{conditions}}.qid=:qid " . "AND {{conditions}}.scenario=:scenario " . "AND {{conditions}}.cfieldname LIKE '{%' " . "ORDER BY {{conditions}}.cfieldname";
                 $resulttoken = Yii::app()->db->createCommand($querytoken)->bindValue(":scenario", $scenarionr['scenario'], PDO::PARAM_INT)->bindValue(":qid", $qid, PDO::PARAM_INT)->query() or safeDie("Couldn't get other conditions for question {$qid}<br />{$query}<br />");
                 $conditionscount = $conditionscount + $conditionscounttoken;
                 if ($conditionscount > 0) {
                     $aConditionsMerged = array();
                     foreach ($resulttoken->readAll() as $arow) {
                         $aConditionsMerged[] = $arow;
                     }
                     foreach ($result->readAll() as $arow) {
                         $aConditionsMerged[] = $arow;
                     }
                     foreach ($aConditionsMerged as $rows) {
                         if ($rows['method'] == "") {
                             $rows['method'] = "==";
                         }
                         //Fill in the empty method from previous versions
                         $markcidstyle = "oddrow";
                         if (array_search($rows['cid'], $markcidarray) !== FALSE) {
                             // This is the style used when the condition editor is called
                             // in order to check which conditions prevent a question deletion
                             $markcidstyle = "markedrow";
                         }
                         if ($subaction == "editthiscondition" && isset($p_cid) && $rows['cid'] === $p_cid) {
                             // Style used when editing a condition
                             $markcidstyle = "editedrow";
                         }
                         if (isset($currentfield) && $currentfield != $rows['cfieldname']) {
                             $aViewUrls['output'] .= "<tr class='evenrow'>\n" . "\t<td colspan='2'>\n" . "<span><strong>" . $clang->gT("and") . "</strong></span></td></tr>";
                         } elseif (isset($currentfield)) {
                             $aViewUrls['output'] .= "<tr class='evenrow'>\n" . "\t<td colspan='2'>\n" . "<span><strong>" . $clang->gT("or") . "</strong></span></td></tr>";
                         }
                         $aViewUrls['output'] .= "\t<tr class='{$markcidstyle}'>\n" . "\t<td colspan='2'>" . CHtml::form(array("/admin/conditions/sa/index/subaction/{$subaction}/surveyid/{$iSurveyID}/gid/{$gid}/qid/{$qid}/"), 'post', array('id' => "conditionaction{$rows['cid']}", 'name' => "conditionaction{$rows['cid']}")) . "<table>\n" . "\t<tr>\n";
                         if ($subaction == "copyconditionsform" || $subaction == "copyconditions") {
                             $aViewUrls['output'] .= "<td>&nbsp;&nbsp;</td>" . "<td>\n" . "\t<input type='checkbox' name='aConditionFromScenario{$scenarionr['scenario']}' id='cbox{$rows['cid']}' value='{$rows['cid']}' checked='checked'/>\n" . "</td>\n";
                         }
                         $aViewUrls['output'] .= "" . "<td>\n" . "\t<span>\n";
                         $leftOperandType = 'unknown';
                         // prevquestion, tokenattr
                         if ($thissurvey['anonymized'] != 'Y' && preg_match('/^{TOKEN:([^}]*)}$/', $rows['cfieldname'], $extractedTokenAttr) > 0) {
                             $leftOperandType = 'tokenattr';
                             $aTokenAttrNames = getTokenFieldsAndNames($iSurveyID);
                             if (count($aTokenAttrNames) != 0) {
                                 $thisAttrName = HTMLEscape($aTokenAttrNames[strtolower($extractedTokenAttr[1])]['description']) . " [" . $clang->gT("From token table") . "]";
                             } else {
                                 $thisAttrName = HTMLEscape($extractedTokenAttr[1]) . " [" . $clang->gT("Inexistant token table") . "]";
                             }
                             $aViewUrls['output'] .= "\t{$thisAttrName}\n";
                             // TIBO not sure this is used anymore !!
                             $conditionsList[] = array("cid" => $rows['cid'], "text" => $thisAttrName);
                         } else {
                             $leftOperandType = 'prevquestion';
                             foreach ($cquestions as $cqn) {
                                 if ($cqn[3] == $rows['cfieldname']) {
                                     $aViewUrls['output'] .= "\t{$cqn['0']} (qid{$rows['cqid']})\n";
                                     $conditionsList[] = array("cid" => $rows['cid'], "text" => $cqn[0] . " ({$rows['value']})");
                                 } else {
                                     //$aViewUrls['output'] .= "\t<font color='red'>ERROR: Delete this condition. It is out of order.</font>\n";
                                 }
                             }
                         }
                         $aViewUrls['output'] .= "\t</span></td>\n" . "\t<td>\n" . "<span>\n" . $method[trim($rows['method'])] . "</span>\n" . "\t</td>\n" . "\n" . "\t<td>\n" . "<span>\n";
                         // let's read the condition's right operand
                         // determine its type and display it
                         $rightOperandType = 'unknown';
                         // predefinedAnsw,constantVal, prevQsgqa, tokenAttr, regexp
                         if ($rows['method'] == 'RX') {
                             $rightOperandType = 'regexp';
                             $aViewUrls['output'] .= "" . HTMLEscape($rows['value']) . "\n";
                         } elseif (preg_match('/^@([0-9]+X[0-9]+X[^@]*)@$/', $rows['value'], $matchedSGQA) > 0) {
                             // SGQA
                             $rightOperandType = 'prevQsgqa';
                             $textfound = false;
                             foreach ($cquestions as $cqn) {
                                 if ($cqn[3] == $matchedSGQA[1]) {
                                     $matchedSGQAText = $cqn[0];
                                     $textfound = true;
                                     break;
                                 }
                             }
                             if ($textfound === false) {
                                 $matchedSGQAText = $rows['value'] . ' (' . $clang->gT("Not found") . ')';
                             }
                             $aViewUrls['output'] .= "" . HTMLEscape($matchedSGQAText) . "\n";
                         } elseif ($thissurvey['anonymized'] != 'Y' && preg_match('/^{TOKEN:([^}]*)}$/', $rows['value'], $extractedTokenAttr) > 0) {
                             $rightOperandType = 'tokenAttr';
                             $aTokenAttrNames = getTokenFieldsAndNames($iSurveyID);
                             if (count($aTokenAttrNames) != 0) {
                                 $thisAttrName = HTMLEscape($aTokenAttrNames[strtolower($extractedTokenAttr[1])]['description']) . " [" . $clang->gT("From token table") . "]";
                             } else {
                                 $thisAttrName = HTMLEscape($extractedTokenAttr[1]) . " [" . $clang->gT("Inexistant token table") . "]";
                             }
                             $aViewUrls['output'] .= "\t{$thisAttrName}\n";
                         } elseif (isset($canswers)) {
                             foreach ($canswers as $can) {
                                 if ($can[0] == $rows['cfieldname'] && $can[1] == $rows['value']) {
                                     $aViewUrls['output'] .= "{$can['2']} ({$can['1']})\n";
                                     $rightOperandType = 'predefinedAnsw';
                                 }
                             }
                         }
                         // if $rightOperandType is still unkown then it is a simple constant
                         if ($rightOperandType == 'unknown') {
                             $rightOperandType = 'constantVal';
                             if ($rows['value'] == ' ' || $rows['value'] == '') {
                                 $aViewUrls['output'] .= "" . $clang->gT("No answer") . "\n";
                             } else {
                                 $aViewUrls['output'] .= "" . HTMLEscape($rows['value']) . "\n";
                             }
                         }
                         $aViewUrls['output'] .= "\t</span></td>\n" . "\t<td>\n";
                         if ($subaction == "editconditionsform" || $subaction == "insertcondition" || $subaction == "updatecondition" || $subaction == "editthiscondition" || $subaction == "renumberscenarios" || $subaction == "deleteallconditions" || $subaction == "updatescenario" || $subaction == "deletescenario" || $subaction == "delete") {
                             // show single condition action buttons in edit mode
                             $aData['rows'] = $rows;
                             $aData['sImageURL'] = Yii::app()->getConfig('adminimageurl');
                             //$aViewUrls['includes/conditions_edit'][] = $aData;
                             $aViewUrls['output'] .= $this->getController()->render('/admin/conditions/includes/conditions_edit', $aData, TRUE);
                             // now sets e corresponding hidden input field
                             // depending on the leftOperandType
                             if ($leftOperandType == 'tokenattr') {
                                 $aViewUrls['output'] .= CHtml::hiddenField('csrctoken', HTMLEscape($rows['cfieldname']), array('id' => 'csrctoken' . $rows['cid']));
                             } else {
                                 $aViewUrls['output'] .= CHtml::hiddenField('cquestions', HTMLEscape($rows['cfieldname']), array('id' => 'cquestions' . $rows['cid']));
                             }
                             // now set the corresponding hidden input field
                             // depending on the rightOperandType
                             // This is used when Editting a condition
                             if ($rightOperandType == 'predefinedAnsw') {
                                 $aViewUrls['output'] .= CHtml::hiddenField('EDITcanswers[]', HTMLEscape($rows['value']), array('id' => 'editModeTargetVal' . $rows['cid']));
                             } elseif ($rightOperandType == 'prevQsgqa') {
                                 $aViewUrls['output'] .= CHtml::hiddenField('EDITprevQuestionSGQA', HTMLEscape($rows['value']), array('id' => 'editModeTargetVal' . $rows['cid']));
                             } elseif ($rightOperandType == 'tokenAttr') {
                                 $aViewUrls['output'] .= CHtml::hiddenField('EDITtokenAttr', HTMLEscape($rows['value']), array('id' => 'editModeTargetVal' . $rows['cid']));
                             } elseif ($rightOperandType == 'regexp') {
                                 $aViewUrls['output'] .= CHtml::hiddenField('EDITConditionRegexp', HTMLEscape($rows['value']), array('id' => 'editModeTargetVal' . $rows['cid']));
                             } else {
                                 $aViewUrls['output'] .= CHtml::hiddenField('EDITConditionConst', HTMLEscape($rows['value']), array('id' => 'editModeTargetVal' . $rows['cid']));
                             }
                         }
                         $aViewUrls['output'] .= CHtml::closeTag('td') . CHtml::closeTag('tr') . CHtml::closeTag('table') . CHtml::closeTag('form') . CHtml::closeTag('td') . CHtml::closeTag('tr');
                         $currentfield = $rows['cfieldname'];
                     }
                 }
                 $s++;
             }
         } else {
             // no condition ==> disable delete all conditions button, and display a simple comment
             $aViewUrls['output'] = CHtml::openTag('tr') . CHtml::tag('td', array(), $clang->gT("This question is always shown.")) . CHtml::tag('td', array(), '&nbsp;') . CHtml::closeTag('tr');
         }
         $aViewUrls['output'] .= CHtml::closeTag('table');
     }
     //END DISPLAY CONDITIONS FOR THIS QUESTION
     // BEGIN: DISPLAY THE COPY CONDITIONS FORM
     if ($subaction == "copyconditionsform" || $subaction == "copyconditions") {
         $aViewUrls['output'] .= "<tr class=''><td colspan='3'>\n" . CHtml::form(array("/admin/conditions/sa/index/subaction/copyconditions/surveyid/{$iSurveyID}/gid/{$gid}/qid/{$qid}/"), 'post', array('id' => "copyconditions", 'name' => "copyconditions")) . "<div class='header ui-widget-header'>" . $clang->gT("Copy conditions") . "</div>\n";
         //CopyConditionsMessage
         if (isset($CopyConditionsMessage)) {
             $aViewUrls['output'] .= "<div class='messagebox ui-corner-all'>\n" . "{$CopyConditionsMessage}\n" . "</div>\n";
         }
         if (isset($conditionsList) && is_array($conditionsList)) {
             //TIBO
             $this->getController()->_js_admin_includes(Yii::app()->getConfig("generalscripts") . 'jquery/jquery.multiselect.min.js');
             // TODO
             $aViewUrls['output'] .= "<script type='text/javascript'>\$(document).ready(function () { \$('#copytomultiselect').multiselect( { autoOpen: true, noneSelectedText: '" . $clang->gT("No questions selected") . "', checkAllText: '" . $clang->gT("Check all") . "', uncheckAllText: '" . $clang->gT("Uncheck all") . "', selectedText: '# " . $clang->gT("selected") . "', beforeclose: function(){ return false;},height: 200 } ); });</script>";
             $aViewUrls['output'] .= "\t<div class='conditioncopy-tbl-row'>\n" . "\t<div class='condition-tbl-left'>" . $clang->gT("Copy the selected conditions to") . ":</div>\n" . "\t<div class='condition-tbl-right'>\n" . "\t\t<select name='copyconditionsto[]' id='copytomultiselect'  multiple='multiple' >\n";
             if (isset($pquestions) && count($pquestions) != 0) {
                 foreach ($pquestions as $pq) {
                     $aViewUrls['output'] .= "\t\t<option value='{$pq['fieldname']}'>" . $pq['text'] . "</option>\n";
                 }
             }
             $aViewUrls['output'] .= "\t\t</select>\n" . "\t</div>\n" . "\t</div>\n";
             if (!isset($pquestions) || count($pquestions) == 0) {
                 $disableCopyCondition = " disabled='disabled'";
             } else {
                 $disableCopyCondition = " ";
             }
             $aViewUrls['output'] .= "\t<div class='condition-tbl-full'>\n" . "\t\t<input type='submit' value='" . $clang->gT("Copy conditions") . "' onclick=\"prepareCopyconditions(); return true;\" {$disableCopyCondition}/>\n" . "<input type='hidden' name='subaction' value='copyconditions' />\n" . "<input type='hidden' name='sid' value='{$iSurveyID}' />\n" . "<input type='hidden' name='gid' value='{$gid}' />\n" . "<input type='hidden' name='qid' value='{$qid}' />\n" . "</div>\n";
             $aViewUrls['output'] .= "<script type=\"text/javascript\">\n" . "function prepareCopyconditions()\n" . "{\n" . "\t\$(\"input:checked[name^='aConditionFromScenario']\").each(function(i,val)\n" . "\t{\n" . "var thecid = val.value;\n" . "var theform = document.getElementById('copyconditions');\n" . "addHiddenElement(theform,'copyconditionsfrom[]',thecid);\n" . "return true;\n" . "\t});\n" . "}\n" . "</script>\n";
         } else {
             $aViewUrls['output'] .= "<div class='messagebox ui-corner-all'>\n" . "<div class='partialheader'>" . $clang->gT("There are no existing conditions in this survey.") . "</div><br />\n" . "</div>\n";
         }
         $aViewUrls['output'] .= "</form></td></tr>\n";
     }
     // END: DISPLAY THE COPY CONDITIONS FORM
     if (isset($cquestions)) {
         if (count($cquestions) > 0 && count($cquestions) <= 10) {
             $qcount = count($cquestions);
         } else {
             $qcount = 9;
         }
     } else {
         $qcount = 0;
     }
     //BEGIN: DISPLAY THE ADD or EDIT CONDITION FORM
     if ($subaction == "editconditionsform" || $subaction == "insertcondition" || $subaction == "updatecondition" || $subaction == "deletescenario" || $subaction == "renumberscenarios" || $subaction == "deleteallconditions" || $subaction == "updatescenario" || $subaction == "editthiscondition" || $subaction == "delete") {
         $aViewUrls['output'] .= CHtml::form(array("/admin/conditions/sa/index/subaction/{$subaction}/surveyid/{$iSurveyID}/gid/{$gid}/qid/{$qid}/"), 'post', array('id' => "editconditions", 'name' => "editconditions"));
         if ($subaction == "editthiscondition" && isset($p_cid)) {
             $mytitle = $clang->gT("Edit condition");
         } else {
             $mytitle = $clang->gT("Add condition");
         }
         $aViewUrls['output'] .= "<div class='header ui-widget-header'>" . $mytitle . "</div>\n";
         ///////////////////////////////////////////////////////////////////////////////////////////
         // Begin "Scenario" row
         if ($subaction != "editthiscondition" && isset($scenariocount) && ($scenariocount == 1 || $scenariocount == 0) || $subaction == "editthiscondition" && isset($scenario) && $scenario == 1) {
             $scenarioAddBtn = "\t<a id='scenarioaddbtn' href='#' onclick=\"\$('#scenarioaddbtn').hide();\$('#defaultscenariotxt').hide('slow');\$('#scenario').show('slow');\">" . "<img src='{$imageurl}/plus.png' alt='" . $clang->gT('Add scenario') . "' /></a>\n";
             $scenarioTxt = "<span id='defaultscenariotxt'>" . $clang->gT("Default scenario") . "</span>";
             $scenarioInputStyle = "style = 'display: none;'";
         } else {
             $scenarioAddBtn = "";
             $scenarioTxt = "";
             $scenarioInputStyle = "style = ''";
         }
         $aViewUrls['output'] .= "<div class='condition-tbl-row'>\n" . "<div class='condition-tbl-left'>{$scenarioAddBtn}&nbsp;" . $clang->gT("Scenario") . "</div>\n" . "<div class='condition-tbl-right'><input type='text' name='scenario' id='scenario' value='1' size='2' {$scenarioInputStyle}/>" . "{$scenarioTxt}\n" . "</div>\n" . "</div>\n";
         // Begin "Question" row
         $aViewUrls['output'] .= "<div class='condition-tbl-row'>\n" . "<div class='condition-tbl-left'>" . $clang->gT("Question") . "</div>\n" . "<div class='condition-tbl-right'>\n" . "\t<div id=\"conditionsource\" class=\"tabs-nav\">\n" . "\t<ul>\n" . "\t<li><a href=\"#SRCPREVQUEST\"><span>" . $clang->gT("Previous questions") . "</span></a></li>\n" . "\t<li><a href=\"#SRCTOKENATTRS\"><span>" . $clang->gT("Token fields") . "</span></a></li>\n" . "\t</ul>\n";
         // Previous question tab
         $aViewUrls['output'] .= "<div id='SRCPREVQUEST'><select name='cquestions' id='cquestions' size='" . ($qcount + 1) . "' >\n";
         if (isset($cquestions)) {
             $js_getAnswers_onload = "";
             foreach ($cquestions as $cqn) {
                 $aViewUrls['output'] .= "<option value='{$cqn['3']}' title=\"" . htmlspecialchars($cqn[0]) . "\"";
                 if (isset($p_cquestions) && $cqn[3] == $p_cquestions) {
                     $aViewUrls['output'] .= " selected";
                     if (isset($p_canswers)) {
                         $canswersToSelect = "";
                         foreach ($p_canswers as $checkval) {
                             $canswersToSelect .= ";{$checkval}";
                         }
                         $canswersToSelect = substr($canswersToSelect, 1);
                         $js_getAnswers_onload .= "\$('#canswersToSelect').val('{$canswersToSelect}');\n";
                     }
                 }
                 $aViewUrls['output'] .= ">{$cqn['0']}</option>\n";
             }
         }
         $aViewUrls['output'] .= "</select>\n" . "</div>\n";
         // Source token Tab
         $aViewUrls['output'] .= "<div id='SRCTOKENATTRS'><select name='csrctoken' id='csrctoken' size='" . ($qcount + 1) . "' >\n";
         foreach (getTokenFieldsAndNames($iSurveyID) as $tokenattr => $tokenattrName) {
             // Check to select
             if (isset($p_csrctoken) && $p_csrctoken == '{TOKEN:' . strtoupper($tokenattr) . '}') {
                 $selectThisSrcTokenAttr = "selected=\"selected\"";
             } else {
                 $selectThisSrcTokenAttr = "";
             }
             $aViewUrls['output'] .= "<option value='{TOKEN:" . strtoupper($tokenattr) . "}' {$selectThisSrcTokenAttr}>" . HTMLEscape($tokenattrName['description']) . "</option>\n";
         }
         $aViewUrls['output'] .= "</select>\n" . "</div>\n\n";
         $aViewUrls['output'] .= "\t</div>\n";
         // end conditionsource div
         $aViewUrls['output'] .= "</div>\n" . "</div>\n";
         // Begin "Comparison operator" row
         $aViewUrls['output'] .= "<div class='condition-tbl-row'>\n" . "<div class='condition-tbl-left'>" . $clang->gT("Comparison operator") . "</div>\n" . "<div class='condition-tbl-right'>\n" . "<select name='method' id='method'>\n";
         foreach ($method as $methodCode => $methodTxt) {
             $selected = $methodCode == "==" ? " selected='selected'" : "";
             $aViewUrls['output'] .= "\t<option value='" . $methodCode . "'{$selected}>" . $methodTxt . "</option>\n";
         }
         $aViewUrls['output'] .= "</select>\n" . "</div>\n" . "</div>\n";
         // Begin "Answer" row
         $aViewUrls['output'] .= "<div class='condition-tbl-row'>\n" . "<div class='condition-tbl-left'>" . $clang->gT("Answer") . "</div>\n";
         if ($subaction == "editthiscondition") {
             $multipletext = "";
             if (isset($_POST['EDITConditionConst']) && $_POST['EDITConditionConst'] != '') {
                 $EDITConditionConst = HTMLEscape($_POST['EDITConditionConst']);
             } else {
                 $EDITConditionConst = "";
             }
             if (isset($_POST['EDITConditionRegexp']) && $_POST['EDITConditionRegexp'] != '') {
                 $EDITConditionRegexp = HTMLEscape($_POST['EDITConditionRegexp']);
             } else {
                 $EDITConditionRegexp = "";
             }
         } else {
             $multipletext = "multiple";
             if (isset($_POST['ConditionConst']) && $_POST['ConditionConst'] != '') {
                 $EDITConditionConst = HTMLEscape($_POST['ConditionConst']);
             } else {
                 $EDITConditionConst = "";
             }
             if (isset($_POST['ConditionRegexp']) && $_POST['ConditionRegexp'] != '') {
                 $EDITConditionRegexp = HTMLEscape($_POST['ConditionRegexp']);
             } else {
                 $EDITConditionRegexp = "";
             }
         }
         $aViewUrls['output'] .= "" . "<div class='condition-tbl-right'>\n" . "<div id=\"conditiontarget\" class=\"tabs-nav\">\n" . "\t<ul>\n" . "\t\t<li><a href=\"#CANSWERSTAB\"><span>" . $clang->gT("Predefined") . "</span></a></li>\n" . "\t\t<li><a href=\"#CONST\"><span>" . $clang->gT("Constant") . "</span></a></li>\n" . "\t\t<li><a href=\"#PREVQUESTIONS\"><span>" . $clang->gT("Questions") . "</span></a></li>\n" . "\t\t<li><a href=\"#TOKENATTRS\"><span>" . $clang->gT("Token fields") . "</span></a></li>\n" . "\t\t<li><a href=\"#REGEXP\"><span>" . $clang->gT("RegExp") . "</span></a></li>\n" . "\t</ul>\n";
         // Predefined answers tab
         $aViewUrls['output'] .= "\t<div id='CANSWERSTAB'>\n" . "\t\t<select  name='canswers[]' {$multipletext} id='canswers' size='7'>\n" . "\t\t</select>\n" . "\t\t<br /><span id='canswersLabel'>" . $clang->gT("Predefined answer options for this question") . "</span>\n" . "\t</div>\n";
         // Constant tab
         $aViewUrls['output'] .= "\t<div id='CONST' style='display:block;' >\n" . "\t\t<textarea name='ConditionConst' id='ConditionConst' rows='5' cols='113'>{$EDITConditionConst}</textarea>\n" . "\t\t<br /><div id='ConditionConstLabel'>" . $clang->gT("Constant value") . "</div>\n" . "\t</div>\n";
         // Previous answers tab @SGQA@ placeholders
         $aViewUrls['output'] .= "\t<div id='PREVQUESTIONS'>\n" . "\t\t<select name='prevQuestionSGQA' id='prevQuestionSGQA' size='7'>\n";
         foreach ($cquestions as $cqn) {
             // building the @SGQA@ placeholders options
             if ($cqn[2] != 'M' && $cqn[2] != 'P') {
                 // Type M or P aren't real fieldnames and thus can't be used in @SGQA@ placehodlers
                 $aViewUrls['output'] .= "\t\t<option value='@{$cqn['3']}@' title=\"" . htmlspecialchars($cqn[0]) . "\"";
                 if (isset($p_prevquestionsgqa) && $p_prevquestionsgqa == "@" . $cqn[3] . "@") {
                     $aViewUrls['output'] .= " selected='selected'";
                 }
                 $aViewUrls['output'] .= ">{$cqn['0']}</option>\n";
             }
         }
         $aViewUrls['output'] .= "\t\t</select>\n" . "\t\t<br /><span id='prevQuestionSGQALabel'>" . $clang->gT("Answers from previous questions") . "</span>\n" . "\t</div>\n";
         // Token tab
         $aViewUrls['output'] .= "\t<div id='TOKENATTRS'>\n" . "\t\t<select name='tokenAttr' id='tokenAttr' size='7'>\n";
         foreach (getTokenFieldsAndNames($iSurveyID) as $tokenattr => $tokenattrName) {
             $aViewUrls['output'] .= "\t\t<option value='{TOKEN:" . strtoupper($tokenattr) . "}'>" . HTMLEscape($tokenattrName['description']) . "</option>\n";
         }
         $aViewUrls['output'] .= "\t\t</select>\n" . "\t\t<br /><span id='tokenAttrLabel'>" . $clang->gT("Attributes values from the participant's token") . "</span>\n" . "\t</div>\n";
         // Regexp Tab
         $aViewUrls['output'] .= "\t<div id='REGEXP' style='display:block;'>\n" . "\t\t<textarea name='ConditionRegexp' id='ConditionRegexp' rows='5' cols='113'>{$EDITConditionRegexp}</textarea>\n" . "\t\t<br /><div id='ConditionRegexpLabel'><a href=\"http://docs.limesurvey.org/tiki-index.php?page=Using+Regular+Expressions\" target=\"_blank\">" . $clang->gT("Regular expression") . "</a></div>\n" . "\t</div>\n";
         $aViewUrls['output'] .= "</div>\n";
         // end conditiontarget div
         $this->getController()->_js_admin_includes(Yii::app()->getConfig("adminscripts") . 'conditions.js');
         $this->getController()->_js_admin_includes(Yii::app()->getConfig("generalscripts") . 'jquery/lime-conditions-tabs.js');
         if ($subaction == "editthiscondition" && isset($p_cid)) {
             $submitLabel = $clang->gT("Update condition");
             $submitSubaction = "updatecondition";
             $submitcid = sanitize_int($p_cid);
         } else {
             $submitLabel = $clang->gT("Add condition");
             $submitSubaction = "insertcondition";
             $submitcid = "";
         }
         $aViewUrls['output'] .= "</div>\n" . "</div>\n";
         // Begin buttons row
         $aViewUrls['output'] .= "<div class='condition-tbl-full'>\n" . "\t<input type='reset' id='resetForm' value='" . $clang->gT("Clear") . "' />\n" . "\t<input type='submit' value='" . $submitLabel . "' />\n" . "<input type='hidden' name='sid' value='{$iSurveyID}' />\n" . "<input type='hidden' name='gid' value='{$gid}' />\n" . "<input type='hidden' name='qid' value='{$qid}' />\n" . "<input type='hidden' name='subaction' value='{$submitSubaction}' />\n" . "<input type='hidden' name='cqid' id='cqid' value='' />\n" . "<input type='hidden' name='cid' id='cid' value='" . $submitcid . "' />\n" . "<input type='hidden' name='editTargetTab' id='editTargetTab' value='' />\n" . "<input type='hidden' name='editSourceTab' id='editSourceTab' value='' />\n" . "<input type='hidden' name='canswersToSelect' id='canswersToSelect' value='' />\n" . "</div>\n" . "</form>\n";
         if (!isset($js_getAnswers_onload)) {
             $js_getAnswers_onload = '';
         }
         $aViewUrls['output'] .= "<script type='text/javascript'>\n" . "<!--\n" . "\t" . $js_getAnswers_onload . "\n";
         if (isset($p_method)) {
             $aViewUrls['output'] .= "\tdocument.getElementById('method').value='" . $p_method . "';\n";
         }
         if ($subaction == "editthiscondition") {
             // in edit mode we read previous values in order to dusplay them in the corresponding inputs
             if (isset($_POST['EDITConditionConst']) && $_POST['EDITConditionConst'] != '') {
                 // In order to avoid issues with backslash escaping, I don't use javascript to set the value
                 // Thus the value is directly set when creating the Textarea element
                 //$aViewUrls['output'] .= "\tdocument.getElementById('ConditionConst').value='".HTMLEscape($_POST['EDITConditionConst'])."';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#CONST';\n";
             } elseif (isset($_POST['EDITprevQuestionSGQA']) && $_POST['EDITprevQuestionSGQA'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('prevQuestionSGQA').value='" . HTMLEscape($_POST['EDITprevQuestionSGQA']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#PREVQUESTIONS';\n";
             } elseif (isset($_POST['EDITtokenAttr']) && $_POST['EDITtokenAttr'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('tokenAttr').value='" . HTMLEscape($_POST['EDITtokenAttr']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#TOKENATTRS';\n";
             } elseif (isset($_POST['EDITConditionRegexp']) && $_POST['EDITConditionRegexp'] != '') {
                 // In order to avoid issues with backslash escaping, I don't use javascript to set the value
                 // Thus the value is directly set when creating the Textarea element
                 //$aViewUrls['output'] .= "\tdocument.getElementById('ConditionRegexp').value='".HTMLEscape($_POST['EDITConditionRegexp'])."';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#REGEXP';\n";
             } elseif (isset($_POST['EDITcanswers']) && is_array($_POST['EDITcanswers'])) {
                 // was a predefined answers post
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#CANSWERSTAB';\n";
                 $aViewUrls['output'] .= "\t\$('#canswersToSelect').val('" . $_POST['EDITcanswers'][0] . "');\n";
             }
             if (isset($_POST['csrctoken']) && $_POST['csrctoken'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('csrctoken').value='" . HTMLEscape($_POST['csrctoken']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editSourceTab').value='#SRCTOKENATTRS';\n";
             } else {
                 if (isset($_POST['cquestions']) && $_POST['cquestions'] != '') {
                     $aViewUrls['output'] .= "\tdocument.getElementById('cquestions').value='" . HTMLEscape($_POST['cquestions']) . "';\n";
                     $aViewUrls['output'] .= "\tdocument.getElementById('editSourceTab').value='#SRCPREVQUEST';\n";
                 }
             }
         } else {
             // in other modes, for the moment we do the same as for edit mode
             if (isset($_POST['ConditionConst']) && $_POST['ConditionConst'] != '') {
                 // In order to avoid issues with backslash escaping, I don't use javascript to set the value
                 // Thus the value is directly set when creating the Textarea element
                 //$aViewUrls['output'] .= "\tdocument.getElementById('ConditionConst').value='".HTMLEscape($_POST['ConditionConst'])."';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#CONST';\n";
             } elseif (isset($_POST['prevQuestionSGQA']) && $_POST['prevQuestionSGQA'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('prevQuestionSGQA').value='" . HTMLEscape($_POST['prevQuestionSGQA']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#PREVQUESTIONS';\n";
             } elseif (isset($_POST['tokenAttr']) && $_POST['tokenAttr'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('tokenAttr').value='" . HTMLEscape($_POST['tokenAttr']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#TOKENATTRS';\n";
             } elseif (isset($_POST['ConditionRegexp']) && $_POST['ConditionRegexp'] != '') {
                 // In order to avoid issues with backslash escaping, I don't use javascript to set the value
                 // Thus the value is directly set when creating the Textarea element
                 //$aViewUrls['output'] .= "\tdocument.getElementById('ConditionRegexp').value='".HTMLEscape($_POST['ConditionRegexp'])."';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#REGEXP';\n";
             } else {
                 // was a predefined answers post
                 if (isset($_POST['cquestions'])) {
                     $aViewUrls['output'] .= "\tdocument.getElementById('cquestions').value='" . HTMLEscape($_POST['cquestions']) . "';\n";
                 }
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#CANSWERSTAB';\n";
             }
             if (isset($_POST['csrctoken']) && $_POST['csrctoken'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('csrctoken').value='" . HTMLEscape($_POST['csrctoken']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editSourceTab').value='#SRCTOKENATTRS';\n";
             } else {
                 if (isset($_POST['cquestions'])) {
                     $aViewUrls['output'] .= "\tdocument.getElementById('cquestions').value='" . javascriptEscape($_POST['cquestions']) . "';\n";
                 }
                 $aViewUrls['output'] .= "\tdocument.getElementById('editSourceTab').value='#SRCPREVQUEST';\n";
             }
         }
         if (isset($p_scenario)) {
             $aViewUrls['output'] .= "\tdocument.getElementById('scenario').value='" . $p_scenario . "';\n";
         }
         $aViewUrls['output'] .= "-->\n" . "</script>\n";
     }
     //END: DISPLAY THE ADD or EDIT CONDITION FORM
     $conditionsoutput = $aViewUrls['output'];
     $aData['conditionsoutput'] = $conditionsoutput;
     $this->_renderWrappedTemplate('conditions', $aViewUrls, $aData);
     // TMSW Conditions->Relevance:  Must call LEM->ConvertConditionsToRelevance() whenever Condition is added or updated - what is best location for that action?
 }
Esempio n. 23
0
 public function is_control_visible($control, $values = null)
 {
     if (null === $values) {
         $values = $this->get_settings();
     }
     // Repeater fields
     if (!empty($control['conditions'])) {
         return Conditions::check($control['conditions'], $values);
     }
     if (empty($control['condition'])) {
         return true;
     }
     foreach ($control['condition'] as $condition_key => $condition_value) {
         preg_match('/([a-z_0-9]+)(?:\\[([a-z_]+)])?(!?)$/i', $condition_key, $condition_key_parts);
         $pure_condition_key = $condition_key_parts[1];
         $condition_sub_key = $condition_key_parts[2];
         $is_negative_condition = !!$condition_key_parts[3];
         $instance_value = $values[$pure_condition_key];
         if (null === $instance_value) {
             return false;
         }
         if ($condition_sub_key) {
             if (!isset($instance_value[$condition_sub_key])) {
                 return false;
             }
             $instance_value = $instance_value[$condition_sub_key];
         }
         $is_contains = is_array($condition_value) ? in_array($instance_value, $condition_value) : $instance_value === $condition_value;
         if ($is_negative_condition && $is_contains || !$is_negative_condition && !$is_contains) {
             return false;
         }
     }
     return true;
 }
Esempio n. 24
0
 function getSearch()
 {
     $query_string = isset(Request::$get_normal['q']) ? trim(Request::$get_normal['q']) : false;
     $search = Search::getInstance();
     /* @var $search Search */
     $cond = new Conditions();
     $per_page = 0;
     if (isset($this->params['per_page'])) {
         $per_page = (int) $this->params['per_page'];
     }
     $per_page = $per_page > 0 ? $per_page : 5;
     $cond->setPaging(1000, $per_page);
     $offset = $cond->getMongoLimit();
     list($aids, $count, $hl) = $search->searchAuthorsByString($query_string, $offset, $per_page);
     $cond = new Conditions();
     $cond->setPaging($count, $per_page);
     $this->data = $this->_idsToData($aids);
     $this->data['conditions'] = $cond->getConditions();
     foreach ($this->data['authors'] as &$a) {
         if (isset($hl[$a['id']])) {
             $a['path'] .= '#hl=' . implode(' ', $hl[$a['id']]);
         } else {
             $a['path'] .= '#hl=' . Request::$get_normal['q'];
         }
     }
     $this->data['authors']['title'] = 'Авторы по запросу «' . $query_string . '»';
     $this->data['authors']['count'] = $count;
 }
Esempio n. 25
0
 /**
  * RPC Routine to delete a question of a survey .
  * Returns the id of the deleted question.
  *
  * @access public
  * @param string $sSessionKey Auth credentials
  * @param int iQuestionID Id of the question to delete 
  * @return array|int Id of the deleted Question or status
  */
 public function delete_question($sSessionKey, $iQuestionID)
 {
     if ($this->_checkSessionKey($sSessionKey)) {
         $oQuestion = Questions::model()->findByAttributes(array('qid' => $iQuestionID));
         if (!isset($oQuestion)) {
             return array('status' => 'Error: Invalid question ID');
         }
         $iSurveyID = $oQuestion['sid'];
         if (hasSurveyPermission($iSurveyID, 'surveycontent', 'delete')) {
             $oSurvey = Survey::model()->findByPk($iSurveyID);
             if ($oSurvey['active'] == 'Y') {
                 return array('status' => 'Survey is active and not editable');
             }
             $iGroupID = $oQuestion['gid'];
             $oCondition = Conditions::model()->findAllByAttributes(array('cqid' => $iQuestionID));
             if (count($oCondition) > 0) {
                 return array('status' => 'Cannot delete Question. Others rely on this question');
             }
             LimeExpressionManager::RevertUpgradeConditionsToRelevance(NULL, $iQuestionID);
             try {
                 Conditions::model()->deleteAllByAttributes(array('qid' => $iQuestionID));
                 Question_attributes::model()->deleteAllByAttributes(array('qid' => $iQuestionID));
                 Answers::model()->deleteAllByAttributes(array('qid' => $iQuestionID));
                 $sCriteria = new CDbCriteria();
                 $sCriteria->addCondition('qid = :qid or parent_qid = :qid');
                 $sCriteria->params[':qid'] = $iQuestionID;
                 Questions::model()->deleteAll($sCriteria);
                 Defaultvalues::model()->deleteAllByAttributes(array('qid' => $iQuestionID));
                 Quota_members::model()->deleteAllByAttributes(array('qid' => $iQuestionID));
                 Questions::updateSortOrder($iGroupID, $iSurveyID);
                 return (int) $iQuestionID;
             } catch (Exception $e) {
                 return array('status' => 'Error');
             }
         } else {
             return array('status' => 'No permission');
         }
     } else {
         return array('status' => 'Invalid session key');
     }
 }
Esempio n. 26
0
 function getStatistics($type, $id_target = false)
 {
     $id_target = $id_target ? max(0, (int) $id_target) : false;
     $cond = new Conditions();
     $per_page = 0;
     if (isset($this->params['per_page'])) {
         $per_page = (int) $this->params['per_page'];
     }
     $per_page = $per_page > 0 ? $per_page : 1;
     $pagingName = isset($this->params['paging_parameter_name']) ? $this->params['paging_parameter_name'] : 'p';
     $time_start = Request::get('from');
     $time_end = Request::get('to');
     $curtime = time();
     if (!$time_start) {
         $time_start = strtotime(date('Y-m-1 00:00:00'));
     } else {
         $time_start = strtotime(date('Y-m-d 00:00:00', strtotime($time_start)));
     }
     if (!$time_end) {
         $time_end = strtotime(date('Y-m-d 23:59:59'));
     } else {
         $time_end = strtotime(date('Y-m-d 23:59:59', strtotime($time_end)));
     }
     if ($time_end < $time_start) {
         $t = $time_end;
         $time_end = $time_start;
         $time_start = $t;
     }
     $where = 'WHERE (`time` >= ' . $time_start . ' AND `time` <= ' . $time_end . ')';
     if ($id_target) {
         $where .= ' AND `id_' . $type . '`=' . $id_target;
     }
     if ($type == 'user') {
         $order = 'ORDER BY COUNT(1) DESC ';
     } else {
         $order = 'ORDER BY `count` DESC ';
     }
     $group_by = 'GROUP BY `id_' . $type . '`';
     if ($id_target) {
         $group_by = 'GROUP BY `time`';
     }
     $query = 'SELECT COUNT(1) FROM (SELECT 1 FROM `stat_' . $type . '_download`' . $where . ' ' . $group_by . ') s ';
     $count = Database::sql2single($query);
     $cond->setPaging($count, $per_page, $pagingName);
     $limit = $cond->getLimit();
     $limit = ' LIMIT ' . $limit;
     if ($type == 'user') {
         $query = 'SELECT `id_' . $type . '`,COUNT(1) as `count` , `time` FROM `stat_' . $type . '_download`' . $where . ' ' . $group_by . ' ' . $order . ' ' . $limit;
     } else {
         $query = 'SELECT `id_' . $type . '`,sum(`count`) as `count` , `time` FROM `stat_' . $type . '_download`' . $where . ' ' . $group_by . ' ' . $order . ' ' . $limit;
     }
     $statistics = Database::sql2array($query);
     $gids = array();
     $aids = array();
     $bids = array();
     $uids = array();
     foreach ($statistics as &$stat) {
         if ($type == 'genre') {
             $gids[$stat['id_genre']] = $stat['id_genre'];
         }
         if ($type == 'author') {
             $aids[$stat['id_author']] = $stat['id_author'];
         }
         if ($type == 'book') {
             $bids[$stat['id_book']] = $stat['id_book'];
         }
         if ($type == 'user') {
             $uids[$stat['id_user']] = $stat['id_user'];
         }
         $stat['time'] = date('Y/m/d', $stat['time']);
         $stat['path'] = Config::need('www_path') . '/admin/' . $type . 's/' . $stat['id_' . $type];
     }
     $this->data['genres'] = $this->getStatGenres($gids);
     if (!count($aids)) {
         list($this->data['books'], $aids) = $this->getStatBooks($bids);
     }
     $this->data['authors'] = $this->getStatAuthors($aids);
     $this->data['users'] = $this->getStatUsers($uids);
     $this->data['statistics'] = $statistics;
     $this->data['statistics']['from'] = date('Y.m.d', $time_start);
     $this->data['statistics']['to'] = date('Y.m.d', $time_end);
     $title_part = '';
     if ($type == 'book') {
         $title_part = 'книг';
         $title_part_m = 'книги';
     }
     if ($type == 'author') {
         $title_part = 'книг авторов';
         $title_part_m = 'книг автора';
     }
     if ($type == 'genre') {
         $title_part = 'книг жанров';
         $title_part_m = 'книг жанра';
     }
     if ($type == 'user') {
         $title_part = ' книг пользователями';
         $title_part_m = ' книг пользователем ';
     }
     if (!$id_target) {
         $this->data['statistics']['title'] = 'Статистика по скачиванию ' . $title_part . ' за период с ' . $this->data['statistics']['from'] . ' по ' . $this->data['statistics']['to'];
     } else {
         $this->data['statistics']['title'] = 'Статистика по скачиванию ' . $title_part_m . ' за период с ' . $this->data['statistics']['from'] . ' по ' . $this->data['statistics']['to'];
     }
     $this->data['statistics']['count'] = $count;
     $this->data['conditions'] = $cond->getConditions();
     $this->data['statistics']['current_month_path'] = Request::$url . '?from=' . date('Y-m-01', strtotime(date('Y-m-1 00:00:00'))) . '&to=' . date('Y-m-d', strtotime(date('Y-m-d 23:59:59')) + 1);
     $this->data['statistics']['last_month_path'] = Request::$url . '?from=' . date('Y-m-01', strtotime(date('Y-m-1 00:00:00')) - 1) . '&to=' . date('Y-m-d', strtotime(date('Y-m-1 00:00:00')) - 1);
 }
Esempio n. 27
0
 function getUserContribution()
 {
     global $current_user;
     $uid = $this->params['user_id'];
     $user = new User($uid);
     $user->load();
     $count = Database::sql2single('SELECT COUNT(1) FROM  `users_points_history` WHERE `id_user`=' . $user->id);
     //по книгам, по дате, по типам действий
     $sortings = array('time' => array('title' => 'по дате'), 'id_target' => array('title' => 'по книге'), 'id_action' => array('title' => 'по типу действий'));
     $dsortings = array('time' => array('title' => 'по дате', 'order' => 'desc'));
     $cond = new Conditions();
     $cond->setPaging($count, isset($this->params['per_page']) ? (int) $this->params['per_page'] : 40);
     $cond->setSorting($sortings, $dsortings);
     $order = 'ORDER BY ' . $cond->getSortingField() . ' ' . $cond->getSortingOrderSQL();
     $limit = $cond->getLimit();
     $this->data['conditions'] = $cond->getConditions();
     $query = 'SELECT * FROM `users_points_history` WHERE `id_user`=' . $user->id . ' ' . $order . ' LIMIT ' . $limit;
     $contributions = Database::sql2array($query);
     $bids = array();
     $aids = array();
     $sids = array();
     $mids = array();
     $gids = array();
     $uids = array($user->id);
     $tmp = array();
     foreach (Config::$points as $name => $p) {
         $tmp[$p['id']] = $name;
     }
     foreach ($contributions as &$contribution) {
         switch ($contribution['target_type']) {
             case BiberLog::TargetType_book:
                 $contribution['id_book'] = $contribution['id_target'];
                 $bids[$contribution['id_target']] = $contribution['id_target'];
                 break;
             case BiberLog::TargetType_person:
                 $contribution['id_author'] = $contribution['id_target'];
                 $aids[$contribution['id_target']] = $contribution['id_target'];
                 break;
             case BiberLog::TargetType_magazine:
                 $contribution['id_magazine'] = $contribution['id_target'];
                 $mids[$contribution['id_target']] = $contribution['id_target'];
                 break;
             case BiberLog::TargetType_serie:
                 $contribution['id_serie'] = $contribution['id_target'];
                 $sids[$contribution['id_target']] = $contribution['id_target'];
                 break;
             case BiberLog::TargetType_genre:
                 $contribution['id_genre'] = $contribution['id_target'];
                 $gids[$contribution['id_target']] = $contribution['id_target'];
                 break;
             default:
                 throw new Exception('cant process type #' . $contribution['target_type'] . ' for contribution');
                 break;
         }
         $contribution['action'] = $tmp[$contribution['id_action']];
         unset($contribution['id_action']);
         unset($contribution['id_target']);
         unset($contribution['target_type']);
         if (!$current_user->can('logs_view')) {
             unset($contribution['points']);
         }
         $contribution['date'] = date('Y/m/d H:i:s', $contribution['time']);
         unset($contribution['time']);
     }
     $this->data['contributions'] = $contributions;
     $aaids = array();
     if (count($bids)) {
         list($this->data['books'], $aaids) = $this->getContributionBooks($bids);
     }
     if (count($aaids)) {
         foreach ($aaids as $aid) {
             $aids[$aid] = $aid;
         }
     }
     if (count($aids)) {
         $this->data['authors'] = $this->getContributionAuthors($aids);
     }
     if (count($mids)) {
         $this->data['magazines'] = $this->getContributionMagazines($mids);
     }
     if (count($sids)) {
         $this->data['series'] = $this->getContributionSeries($sids);
     }
     if (count($gids)) {
         $this->data['genres'] = $this->getContributionGenres($gids);
     }
     if (count($uids)) {
         $this->data['users'] = $this->getContributionUsers($uids);
     }
 }
Esempio n. 28
0
 function getBookContributionComments()
 {
     global $current_user;
     /* @var $current_user CurrentUser */
     $id_book = isset($this->params['book_id']) ? (int) $this->params['book_id'] : false;
     if (!$id_book) {
         return;
     }
     $book = Books::getInstance()->getByIdLoaded($id_book);
     /* @var $book Book */
     if (!$book->exists) {
         throw new Exception('book #' . $book->id . ' not exists');
     }
     $cond = new Conditions();
     $per_page = 0;
     if (isset($this->params['per_page'])) {
         $per_page = (int) $this->params['per_page'];
     }
     $per_page = $per_page > 0 ? $per_page : 20;
     $pagingName = isset($this->params['paging_parameter_name']) ? $this->params['paging_parameter_name'] : 'p';
     $cond->setPaging(1000, $per_page, $pagingName);
     $limit = $cond->getMongoLimit();
     list($comments, $count) = MongoDatabase::getBookComments($id_book, $per_page, $limit);
     $uids = array();
     $comments['comments'] = isset($comments['comments']) ? $comments['comments'] : array();
     foreach ($comments['comments'] as &$comment) {
         $comment['commenter_id'] = $comment['user_id'];
         $comment['type'] = 'book';
         $comment['time'] = date('Y/m/d H:i:s', $comment['time']);
         $uids[$comment['user_id']] = $comment['user_id'];
     }
     $cond = new Conditions();
     $cond->setPaging($count, $per_page, $pagingName);
     $this->data['conditions'] = $cond->getConditions();
     $this->data['comments'] = isset($comments['comments']) ? $comments['comments'] : array();
     $this->data['comments']['title'] = 'Обсуждение книги «' . $book->getTitle(true) . '»';
     $this->data['comments']['count'] = $count;
     $this->data['users'] = $this->getCommentsUsers($uids);
 }
Esempio n. 29
0
/**
* This function imports a LimeSurvey .lss survey XML file
*
* @param mixed $sFullFilepath  The full filepath of the uploaded file
*/
function XMLImportSurvey($sFullFilepath, $sXMLdata = NULL, $sNewSurveyName = NULL, $iDesiredSurveyId = NULL, $bTranslateInsertansTags = true)
{
    Yii::app()->loadHelper('database');
    $clang = Yii::app()->lang;
    $aGIDReplacements = array();
    if ($sXMLdata == NULL) {
        $xml = simplexml_load_file($sFullFilepath);
    } else {
        $xml = simplexml_load_string($sXMLdata);
    }
    if ($xml->LimeSurveyDocType != 'Survey') {
        $results['error'] = $clang->gT("This is not a valid LimeSurvey survey structure XML file.");
        return $results;
    }
    $iDBVersion = (int) $xml->DBVersion;
    $aQIDReplacements = array();
    $aQuotaReplacements = array();
    $results['defaultvalues'] = 0;
    $results['answers'] = 0;
    $results['surveys'] = 0;
    $results['questions'] = 0;
    $results['subquestions'] = 0;
    $results['question_attributes'] = 0;
    $results['groups'] = 0;
    $results['assessments'] = 0;
    $results['quota'] = 0;
    $results['quotals'] = 0;
    $results['quotamembers'] = 0;
    $results['survey_url_parameters'] = 0;
    $results['importwarnings'] = array();
    $aLanguagesSupported = array();
    foreach ($xml->languages->language as $language) {
        $aLanguagesSupported[] = (string) $language;
    }
    $results['languages'] = count($aLanguagesSupported);
    // Import surveys table ====================================================
    foreach ($xml->surveys->rows->row as $row) {
        $insertdata = array();
        foreach ($row as $key => $value) {
            $insertdata[(string) $key] = (string) $value;
        }
        $iOldSID = $results['oldsid'] = $insertdata['sid'];
        if ($iDesiredSurveyId != NULL) {
            $insertdata['wishSID'] = GetNewSurveyID($iDesiredSurveyId);
        }
        if ($iDBVersion <= 143) {
            if (isset($insertdata['private'])) {
                $insertdata['anonymized'] = $insertdata['private'];
            }
            unset($insertdata['private']);
            unset($insertdata['notification']);
        }
        unset($insertdata['expires']);
        unset($insertdata['startdate']);
        //Make sure it is not set active
        $insertdata['active'] = 'N';
        //Set current user to be the owner
        $insertdata['owner_id'] = Yii::app()->session['loginID'];
        if (isset($insertdata['bouncetime']) && $insertdata['bouncetime'] == '') {
            $insertdata['bouncetime'] = NULL;
        }
        if (isset($insertdata['showXquestions'])) {
            $insertdata['showxquestions'] = $insertdata['showXquestions'];
            unset($insertdata['showXquestions']);
        }
        $iNewSID = $results['newsid'] = Survey::model()->insertNewSurvey($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [1]<br />");
        $results['surveys']++;
    }
    // Import survey languagesettings table ===================================================================================
    foreach ($xml->surveys_languagesettings->rows->row as $row) {
        $insertdata = array();
        foreach ($row as $key => $value) {
            $insertdata[(string) $key] = (string) $value;
        }
        if (!in_array($insertdata['surveyls_language'], $aLanguagesSupported)) {
            continue;
        }
        $insertdata['surveyls_survey_id'] = $iNewSID;
        if ($bTranslateInsertansTags) {
            if ($sNewSurveyName == NULL) {
                $insertdata['surveyls_title'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_title']);
            } else {
                $insertdata['surveyls_title'] = translateLinks('survey', $iOldSID, $iNewSID, $sNewSurveyName);
            }
            if (isset($insertdata['surveyls_description'])) {
                $insertdata['surveyls_description'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_description']);
            }
            if (isset($insertdata['surveyls_welcometext'])) {
                $insertdata['surveyls_welcometext'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_welcometext']);
            }
            if (isset($insertdata['surveyls_urldescription'])) {
                $insertdata['surveyls_urldescription'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_urldescription']);
            }
            if (isset($insertdata['surveyls_email_invite'])) {
                $insertdata['surveyls_email_invite'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_invite']);
            }
            if (isset($insertdata['surveyls_email_remind'])) {
                $insertdata['surveyls_email_remind'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_remind']);
            }
            if (isset($insertdata['surveyls_email_register'])) {
                $insertdata['surveyls_email_register'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_register']);
            }
            if (isset($insertdata['surveyls_email_confirm'])) {
                $insertdata['surveyls_email_confirm'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['surveyls_email_confirm']);
            }
        }
        $result = Surveys_languagesettings::model()->insertNewSurvey($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [2]<br />");
    }
    // Import groups table ===================================================================================
    if (isset($xml->groups->rows->row)) {
        foreach ($xml->groups->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if (!in_array($insertdata['language'], $aLanguagesSupported)) {
                continue;
            }
            $iOldSID = $insertdata['sid'];
            $insertdata['sid'] = $iNewSID;
            $oldgid = $insertdata['gid'];
            unset($insertdata['gid']);
            // save the old qid
            // now translate any links
            if ($bTranslateInsertansTags) {
                $insertdata['group_name'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['group_name']);
                $insertdata['description'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['description']);
            }
            // Insert the new group
            if (isset($aGIDReplacements[$oldgid])) {
                switchMSSQLIdentityInsert('groups', true);
                $insertdata['gid'] = $aGIDReplacements[$oldgid];
            }
            $newgid = Groups::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [3]<br />");
            $results['groups']++;
            if (!isset($aGIDReplacements[$oldgid])) {
                $aGIDReplacements[$oldgid] = $newgid;
                // add old and new qid to the mapping array
            } else {
                switchMSSQLIdentityInsert('groups', false);
            }
        }
    }
    // Import questions table ===================================================================================
    // We have to run the question table data two times - first to find all main questions
    // then for subquestions (because we need to determine the new qids for the main questions first)
    if (isset($xml->questions)) {
        foreach ($xml->questions->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if (!in_array($insertdata['language'], $aLanguagesSupported) || $insertdata['gid'] == 0) {
                continue;
            }
            $iOldSID = $insertdata['sid'];
            $insertdata['sid'] = $iNewSID;
            $insertdata['gid'] = $aGIDReplacements[$insertdata['gid']];
            $oldqid = $insertdata['qid'];
            unset($insertdata['qid']);
            // save the old qid
            // now translate any links
            if ($bTranslateInsertansTags) {
                $insertdata['question'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['question']);
                $insertdata['help'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['help']);
            }
            // Insert the new question
            if (isset($aQIDReplacements[$oldqid])) {
                $insertdata['qid'] = $aQIDReplacements[$oldqid];
                switchMSSQLIdentityInsert('questions', true);
            }
            if ($insertdata) {
                XSSFilterArray($insertdata);
            }
            $newqid = Questions::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [4]<br />");
            if (!isset($aQIDReplacements[$oldqid])) {
                $aQIDReplacements[$oldqid] = $newqid;
                $results['questions']++;
            } else {
                switchMSSQLIdentityInsert('questions', false);
            }
        }
    }
    // Import subquestions -------------------------------------------------------
    if (isset($xml->subquestions)) {
        foreach ($xml->subquestions->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if (!in_array($insertdata['language'], $aLanguagesSupported) || $insertdata['gid'] == 0) {
                continue;
            }
            if (!isset($insertdata['mandatory']) || trim($insertdata['mandatory']) == '') {
                $insertdata['mandatory'] = 'N';
            }
            $insertdata['sid'] = $iNewSID;
            $insertdata['gid'] = $aGIDReplacements[(int) $insertdata['gid']];
            $oldsqid = (int) $insertdata['qid'];
            unset($insertdata['qid']);
            // save the old qid
            $insertdata['parent_qid'] = $aQIDReplacements[(int) $insertdata['parent_qid']];
            // remap the parent_qid
            // now translate any links
            if ($bTranslateInsertansTags) {
                $insertdata['question'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['question']);
                if (isset($insertdata['help'])) {
                    $insertdata['help'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['help']);
                }
            }
            if (isset($aQIDReplacements[$oldsqid])) {
                $insertdata['qid'] = $aQIDReplacements[$oldsqid];
                switchMSSQLIdentityInsert('questions', true);
            }
            if ($insertdata) {
                XSSFilterArray($insertdata);
            }
            $newsqid = Questions::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data [5]<br />");
            if (!isset($insertdata['qid'])) {
                $aQIDReplacements[$oldsqid] = $newsqid;
                // add old and new qid to the mapping array
            } else {
                switchMSSQLIdentityInsert('questions', false);
            }
            $results['subquestions']++;
        }
    }
    // Import answers ------------------------------------------------------------
    if (isset($xml->answers)) {
        foreach ($xml->answers->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if (!in_array($insertdata['language'], $aLanguagesSupported) || !isset($aQIDReplacements[(int) $insertdata['qid']])) {
                continue;
            }
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the parent_qid
            // now translate any links
            if ($bTranslateInsertansTags) {
                $insertdata['answer'] = translateLinks('survey', $iOldSID, $iNewSID, $insertdata['answer']);
            }
            if ($insertdata) {
                XSSFilterArray($insertdata);
            }
            $result = Answers::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['answers']++;
        }
    }
    // Import questionattributes -------------------------------------------------
    if (isset($xml->question_attributes)) {
        $aAllAttributes = questionAttributes(true);
        foreach ($xml->question_attributes->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            unset($insertdata['qaid']);
            if (!isset($aQIDReplacements[(int) $insertdata['qid']])) {
                continue;
            }
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the qid
            if ($iDBVersion < 148 && isset($aAllAttributes[$insertdata['attribute']]['i18n']) && $aAllAttributes[$insertdata['attribute']]['i18n']) {
                foreach ($aLanguagesSupported as $sLanguage) {
                    $insertdata['language'] = $sLanguage;
                    if ($insertdata) {
                        XSSFilterArray($insertdata);
                    }
                    $result = Question_attributes::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
                }
            } else {
                $result = Question_attributes::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            }
            $results['question_attributes']++;
        }
    }
    // Import defaultvalues ------------------------------------------------------
    if (isset($xml->defaultvalues)) {
        $results['defaultvalues'] = 0;
        foreach ($xml->defaultvalues->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the qid
            if (isset($aQIDReplacements[(int) $insertdata['sqid']])) {
                $insertdata['sqid'] = $aQIDReplacements[(int) $insertdata['sqid']];
            }
            // remap the subquestion id
            if ($insertdata) {
                XSSFilterArray($insertdata);
            }
            // now translate any links
            $result = Defaultvalues::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['defaultvalues']++;
        }
    }
    $aOldNewFieldmap = reverseTranslateFieldNames($iOldSID, $iNewSID, $aGIDReplacements, $aQIDReplacements);
    // Import conditions ---------------------------------------------------------
    if (isset($xml->conditions)) {
        $results['conditions'] = 0;
        foreach ($xml->conditions->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            // replace the qid for the new one (if there is no new qid in the $aQIDReplacements array it mean that this condition is orphan -> error, skip this record)
            if (isset($aQIDReplacements[$insertdata['qid']])) {
                $insertdata['qid'] = $aQIDReplacements[$insertdata['qid']];
                // remap the qid
            } else {
                continue;
            }
            // a problem with this answer record -> don't consider
            if ($insertdata['cqid'] != 0) {
                if (isset($aQIDReplacements[$insertdata['cqid']])) {
                    $oldcqid = $insertdata['cqid'];
                    //Save for cfield transformation
                    $insertdata['cqid'] = $aQIDReplacements[$insertdata['cqid']];
                    // remap the qid
                } else {
                    continue;
                }
                // a problem with this answer record -> don't consider
                list($oldcsid, $oldcgid, $oldqidanscode) = explode("X", $insertdata["cfieldname"], 3);
                // replace the gid for the new one in the cfieldname(if there is no new gid in the $aGIDReplacements array it means that this condition is orphan -> error, skip this record)
                if (!isset($aGIDReplacements[$oldcgid])) {
                    continue;
                }
            }
            unset($insertdata["cid"]);
            // recreate the cfieldname with the new IDs
            if ($insertdata['cqid'] != 0) {
                if (preg_match("/^\\+/", $oldcsid)) {
                    $newcfieldname = '+' . $iNewSID . "X" . $aGIDReplacements[$oldcgid] . "X" . $insertdata["cqid"] . substr($oldqidanscode, strlen($oldcqid));
                } else {
                    $newcfieldname = $iNewSID . "X" . $aGIDReplacements[$oldcgid] . "X" . $insertdata["cqid"] . substr($oldqidanscode, strlen($oldcqid));
                }
            } else {
                // The cfieldname is a not a previous question cfield but a {XXXX} replacement field
                $newcfieldname = $insertdata["cfieldname"];
            }
            $insertdata["cfieldname"] = $newcfieldname;
            if (trim($insertdata["method"]) == '') {
                $insertdata["method"] = '==';
            }
            // Now process the value and replace @sgqa@ codes
            if (preg_match("/^@(.*)@\$/", $insertdata["value"], $cfieldnameInCondValue)) {
                if (isset($aOldNewFieldmap[$cfieldnameInCondValue[1]])) {
                    $newvalue = '@' . $aOldNewFieldmap[$cfieldnameInCondValue[1]] . '@';
                    $insertdata["value"] = $newvalue;
                }
            }
            // now translate any links
            $result = Conditions::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['conditions']++;
        }
    }
    // TMSW Conditions->Relevance:  Call  LEM->ConvertConditionsToRelevance
    // Import assessments --------------------------------------------------------
    if (isset($xml->assessments)) {
        foreach ($xml->assessments->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            if ($insertdata['gid'] > 0) {
                $insertdata['gid'] = $aGIDReplacements[(int) $insertdata['gid']];
                // remap the qid
            }
            $insertdata['sid'] = $iNewSID;
            // remap the survey id
            // now translate any links
            $result = Assessment::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['assessments']++;
        }
    }
    // Import quota --------------------------------------------------------------
    if (isset($xml->quota)) {
        foreach ($xml->quota->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['sid'] = $iNewSID;
            // remap the survey id
            $oldid = $insertdata['id'];
            unset($insertdata['id']);
            // now translate any links
            $result = Quota::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $aQuotaReplacements[$oldid] = Yii::app()->db->getCommandBuilder()->getLastInsertID('{{quota}}');
            $results['quota']++;
        }
    }
    // Import quota_members ------------------------------------------------------
    if (isset($xml->quota_members)) {
        foreach ($xml->quota_members->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['sid'] = $iNewSID;
            // remap the survey id
            $insertdata['qid'] = $aQIDReplacements[(int) $insertdata['qid']];
            // remap the qid
            $insertdata['quota_id'] = $aQuotaReplacements[(int) $insertdata['quota_id']];
            // remap the qid
            unset($insertdata['id']);
            // now translate any links
            $result = Quota_members::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['quotamembers']++;
        }
    }
    // Import quota_languagesettings----------------------------------------------
    if (isset($xml->quota_languagesettings)) {
        foreach ($xml->quota_languagesettings->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['quotals_quota_id'] = $aQuotaReplacements[(int) $insertdata['quotals_quota_id']];
            // remap the qid
            unset($insertdata['quotals_id']);
            $result = Quota_languagesettings::model()->insertRecords($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['quotals']++;
        }
    }
    // Import survey_url_parameters ----------------------------------------------
    if (isset($xml->survey_url_parameters)) {
        foreach ($xml->survey_url_parameters->rows->row as $row) {
            $insertdata = array();
            foreach ($row as $key => $value) {
                $insertdata[(string) $key] = (string) $value;
            }
            $insertdata['sid'] = $iNewSID;
            // remap the survey id
            if (isset($insertdata['targetsqid']) && $insertdata['targetsqid'] != '') {
                $insertdata['targetsqid'] = $aSQIDReplacements[(int) $insertdata['targetsqid']];
                // remap the qid
            }
            if (isset($insertdata['targetqid']) && $insertdata['targetqid'] != '') {
                $insertdata['targetqid'] = $aQIDReplacements[(int) $insertdata['targetqid']];
                // remap the qid
            }
            unset($insertdata['id']);
            $result = Survey_url_parameters::model()->insertRecord($insertdata) or safeDie($clang->gT("Error") . ": Failed to insert data<br />");
            $results['survey_url_parameters']++;
        }
    }
    // Set survey rights
    Survey_permissions::model()->giveAllSurveyPermissions(Yii::app()->session['loginID'], $iNewSID);
    $aOldNewFieldmap = reverseTranslateFieldNames($iOldSID, $iNewSID, $aGIDReplacements, $aQIDReplacements);
    $results['FieldReMap'] = $aOldNewFieldmap;
    LimeExpressionManager::SetSurveyId($iNewSID);
    translateInsertansTags($iNewSID, $iOldSID, $aOldNewFieldmap);
    LimeExpressionManager::RevertUpgradeConditionsToRelevance($iNewSID);
    LimeExpressionManager::UpgradeConditionsToRelevance($iNewSID);
    return $results;
}
Esempio n. 30
0
 /**
  * Deletes a survey and all its data
  *
  * @access public
  * @param int $iSurveyID
  * @param bool @recursive
  * @return void
  */
 public function deleteSurvey($iSurveyID, $recursive = true)
 {
     Survey::model()->deleteByPk($iSurveyID);
     if ($recursive == true) {
         if (tableExists("{{survey_" . intval($iSurveyID) . "}}")) {
             Yii::app()->db->createCommand()->dropTable("{{survey_" . intval($iSurveyID) . "}}");
         }
         if (tableExists("{{survey_" . intval($iSurveyID) . "_timings}}")) {
             Yii::app()->db->createCommand()->dropTable("{{survey_" . intval($iSurveyID) . "_timings}}");
         }
         if (tableExists("{{tokens_" . intval($iSurveyID) . "}}")) {
             Yii::app()->db->createCommand()->dropTable("{{tokens_" . intval($iSurveyID) . "}}");
         }
         $oResult = Questions::model()->findAllByAttributes(array('sid' => $iSurveyID));
         foreach ($oResult as $aRow) {
             Answers::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             Conditions::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             Question_attributes::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
             Defaultvalues::model()->deleteAllByAttributes(array('qid' => $aRow['qid']));
         }
         Questions::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Assessment::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Groups::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Surveys_languagesettings::model()->deleteAllByAttributes(array('surveyls_survey_id' => $iSurveyID));
         Survey_permissions::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Saved_control::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Survey_url_parameters::model()->deleteAllByAttributes(array('sid' => $iSurveyID));
         Quota::model()->deleteQuota(array('sid' => $iSurveyID), true);
     }
 }