common_helper.php 283 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
* LimeSurvey
* Copyright (C) 2007-2011 The LimeSurvey Project Team / Carsten Schmitz
* All rights reserved.
* License: GNU/GPL License v2 or later, see LICENSE.php
* LimeSurvey is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*/
Yii::import('application.helpers.sanitize_helper', true);

/**
* Simple function to sort the permissions by title
*
* @param mixed $aPermissionA  Permission A to compare
* @param mixed $aPermissionB  Permission B to compare
*/
function comparePermission($aPermissionA,$aPermissionB)
{
    if($aPermissionA['title'] >$aPermissionB['title']) {
        return 1;
    }
    else {
        return -1;
    }
}

/**
* getQuestionTypeList() Returns list of question types available in LimeSurvey. Edit this if you are adding a new
*    question type
*
* @param string $SelectedCode Value of the Question Type (defaults to "T")
* @param string $ReturnType Type of output from this function (defaults to selector)
*
* @return depending on $ReturnType param, returns a straight "array" of question types, or an <option></option> list
*
* Explanation of questiontype array:
*
* description : Question description
* subquestions : 0= Does not support subquestions x=Number of subquestion scales
* answerscales : 0= Does not need answers x=Number of answer scales (usually 1, but e.g. for dual scale question set to 2)
* assessable : 0=Does not support assessment values when editing answerd 1=Support assessment values
*/
function getQuestionTypeList($SelectedCode = "T", $ReturnType = "selector")
{
    $publicurl = Yii::app()->getConfig('publicurl');
    $clang = Yii::app()->lang;

    $group['Arrays'] = $clang->gT('Arrays');
    $group['MaskQuestions'] = $clang->gT("Mask questions");
    $group['SinChoiceQues'] = $clang->gT("Single choice questions");
    $group['MulChoiceQues'] = $clang->gT("Multiple choice questions");
    $group['TextQuestions'] = $clang->gT("Text questions");


    $qtypes = array(
    "1" => array('description' => $clang->gT("Array dual scale"),
    'group' => $group['Arrays'],
    'subquestions' => 1,
    'assessable' => 1,
    'hasdefaultvalues' => 0,
    'answerscales' => 2),
    "5" => array('description' => $clang->gT("5 Point Choice"),
    'group' => $group['SinChoiceQues'],
    'subquestions' => 0,
    'hasdefaultvalues' => 0,
    'assessable' => 0,
    'answerscales' => 0),
    "A" => array('description' => $clang->gT("Array (5 Point Choice)"),
    'group' => $group['Arrays'],
    'subquestions' => 1,
    'hasdefaultvalues' => 0,
    'assessable' => 1,
    'answerscales' => 0),
    "B" => array('description' => $clang->gT("Array (10 Point Choice)"),
    'group' => $group['Arrays'],
    'subquestions' => 1,
    'hasdefaultvalues' => 0,
    'assessable' => 1,
    'answerscales' => 0),
    "C" => array('description' => $clang->gT("Array (Yes/No/Uncertain)"),
    'group' => $group['Arrays'],
    'subquestions' => 1,
    'hasdefaultvalues' => 0,
    'assessable' => 1,
    'answerscales' => 0),
    "D" => array('description' => $clang->gT("Date/Time"),
    'group' => $group['MaskQuestions'],
    'subquestions' => 0,
    'hasdefaultvalues' => 1,
    'assessable' => 0,
    'answerscales' => 0),
    "E" => array('description' => $clang->gT("Array (Increase/Same/Decrease)"),
    'group' => $group['Arrays'],
    'subquestions' => 1,
    'hasdefaultvalues' => 0,
    'assessable' => 1,
    'answerscales' => 0),
    "F" => array('description' => $clang->gT("Array"),
    'group' => $group['Arrays'],
    'subquestions' => 1,
    'hasdefaultvalues' => 0,
    'assessable' => 1,
    'answerscales' => 1),
    "G" => array('description' => $clang->gT("Gender"),
    'group' => $group['MaskQuestions'],
    'subquestions' => 0,
    'hasdefaultvalues' => 0,
    'assessable' => 0,
    'answerscales' => 0),
    "H" => array('description' => $clang->gT("Array by column"),
    'group' => $group['Arrays'],
    'hasdefaultvalues' => 0,
    'subquestions' => 1,
    'assessable' => 1,
    'answerscales' => 1),
    "I" => array('description' => $clang->gT("Language Switch"),
    'group' => $group['MaskQuestions'],
    'hasdefaultvalues' => 0,
    'subquestions' => 0,
    'assessable' => 0,
    'answerscales' => 0),
    "K" => array('description' => $clang->gT("Multiple Numerical Input"),
    'group' => $group['MaskQuestions'],
    'hasdefaultvalues' => 1,
    'subquestions' => 1,
    'assessable' => 1,
    'answerscales' => 0),
    "L" => array('description' => $clang->gT("List (Radio)"),
    'group' => $group['SinChoiceQues'],
    'subquestions' => 0,
    'hasdefaultvalues' => 1,
    'assessable' => 1,
    'answerscales' => 1),
    "M" => array('description' => $clang->gT("Multiple choice"),
    'group' => $group['MulChoiceQues'],
    'subquestions' => 1,
    'hasdefaultvalues' => 1,
    'assessable' => 1,
    'answerscales' => 0),
    "N" => array('description' => $clang->gT("Numerical Input"),
    'group' => $group['MaskQuestions'],
    'subquestions' => 0,
    'hasdefaultvalues' => 1,
    'assessable' => 0,
    'answerscales' => 0),
    "O" => array('description' => $clang->gT("List with comment"),
    'group' => $group['SinChoiceQues'],
    'subquestions' => 0,
    'hasdefaultvalues' => 1,
    'assessable' => 1,
    'answerscales' => 1),
    "P" => array('description' => $clang->gT("Multiple choice with comments"),
    'group' => $group['MulChoiceQues'],
    'subquestions' => 1,
    'hasdefaultvalues' => 1,
    'assessable' => 1,
    'answerscales' => 0),
    "Q" => array('description' => $clang->gT("Multiple Short Text"),
    'group' => $group['TextQuestions'],
    'subquestions' => 1,
    'hasdefaultvalues' => 1,
    'assessable' => 0,
    'answerscales' => 0),
    "R" => array('description' => $clang->gT("Ranking"),
    'group' => $group['MaskQuestions'],
    'subquestions' => 0,
    'hasdefaultvalues' => 0,
    'assessable' => 1,
    'answerscales' => 1),
    "S" => array('description' => $clang->gT("Short Free Text"),
    'group' => $group['TextQuestions'],
    'subquestions' => 0,
    'hasdefaultvalues' => 1,
    'assessable' => 0,
    'answerscales' => 0),
    "T" => array('description' => $clang->gT("Long Free Text"),
    'group' => $group['TextQuestions'],
    'subquestions' => 0,
    'hasdefaultvalues' => 1,
    'assessable' => 0,
    'answerscales' => 0),
    "U" => array('description' => $clang->gT("Huge Free Text"),
    'group' => $group['TextQuestions'],
    'subquestions' => 0,
    'hasdefaultvalues' => 1,
    'assessable' => 0,
    'answerscales' => 0),
    "X" => array('description' => $clang->gT("Text display"),
    'group' => $group['MaskQuestions'],
    'subquestions' => 0,
    'hasdefaultvalues' => 0,
    'assessable' => 0,
    'answerscales' => 0),
    "Y" => array('description' => $clang->gT("Yes/No"),
    'group' => $group['MaskQuestions'],
    'subquestions' => 0,
    'hasdefaultvalues' => 0,
    'assessable' => 0,
    'answerscales' => 0),
    "!" => array('description' => $clang->gT("List (Dropdown)"),
    'group' => $group['SinChoiceQues'],
    'subquestions' => 0,
    'hasdefaultvalues' => 1,
    'assessable' => 1,
    'answerscales' => 1),
    ":" => array('description' => $clang->gT("Array (Numbers)"),
    'group' => $group['Arrays'],
    'subquestions' => 2,
    'hasdefaultvalues' => 0,
    'assessable' => 1,
    'answerscales' => 0),
    ";" => array('description' => $clang->gT("Array (Texts)"),
    'group' => $group['Arrays'],
    'subquestions' => 2,
    'hasdefaultvalues' => 0,
    'assessable' => 0,
    'answerscales' => 0),
    "|" => array('description' => $clang->gT("File upload"),
    'group' => $group['MaskQuestions'],
    'subquestions' => 0,
    'hasdefaultvalues' => 0,
    'assessable' => 0,
    'answerscales' => 0),
    "*" => array('description' => $clang->gT("Equation"),
    'group' => $group['MaskQuestions'],
    'subquestions' => 0,
    'hasdefaultvalues' => 0,
    'assessable' => 0,
    'answerscales' => 0),
    );
    asort($qtypes);

    if ($ReturnType == "array")
        return $qtypes;

    if ($ReturnType == "group")
    {
        foreach ($qtypes as $qkey => $qtype)
        {
            $newqType[$qtype['group']][$qkey] = $qtype;
        }


        $qtypeselecter = "";
        foreach ($newqType as $group => $members)
        {
            $qtypeselecter .= '<optgroup label="' . $group . '">';
            foreach ($members as $TypeCode => $TypeProperties)
            {
                $qtypeselecter .= "<option value='$TypeCode'";
                if ($SelectedCode == $TypeCode)
                {
                    $qtypeselecter .= " selected='selected'";
                }
                $qtypeselecter .= ">{$TypeProperties['description']}</option>\n";
            }
            $qtypeselecter .= '</optgroup>';
        }

        return $qtypeselecter;
    };
    $qtypeselecter = "";
    foreach ($qtypes as $TypeCode => $TypeProperties)
    {
        $qtypeselecter .= "<option value='$TypeCode'";
        if ($SelectedCode == $TypeCode)
        {
            $qtypeselecter .= " selected='selected'";
        }
        $qtypeselecter .= ">{$TypeProperties['description']}</option>\n";
    }
    return $qtypeselecter;
}

/**
* isStandardTemplate returns true if a template is a standard template
* This function does not check if a template actually exists
*
* @param mixed $sTemplateName template name to look for
* @return bool True if standard template, otherwise false
*/
function isStandardTemplate($sTemplateName)
{
    return in_array($sTemplateName,array('basic',
    'bluengrey',
    'business_grey',
    'citronade',
    'clear_logo',
    'default',
    'eirenicon',
    'limespired',
    'mint_idea',
    'sherpa',
    'vallendar'));
}

/**
* getSurveyList() Queries the database (survey table) for a list of existing surveys
*
* @param boolean $returnarray if set to true an array instead of an HTML option list is given back
* @return string This string is returned containing <option></option> formatted list of existing surveys
*
*/
308
function getSurveyList($returnarray=false, $surveyid=false)
309
{
Menno Dekker's avatar
Menno Dekker committed
310
    static $cached = null;
311 312 313 314 315 316

    $timeadjust = getGlobalSetting('timeadjust');
    $clang = new Limesurvey_lang(Yii::app()->session['adminlang']);

    if(is_null($cached)) {
        if (!hasGlobalPermission('USER_RIGHT_SUPERADMIN'))
317
            $surveyidresult = Survey::model()->permission(Yii::app()->user->getId())->with(array('languagesettings'=>array('condition'=>'surveyls_language=language')))->findAll();
318
        else
319
            $surveyidresult = Survey::model()->with(array('languagesettings'=>array('condition'=>'surveyls_language=language')))->findAll();
320 321 322

        $surveynames = array();
        foreach ($surveyidresult as $result)
323 324 325 326
        {
            $surveynames[] = array_merge($result->attributes, $result->languagesettings[0]->attributes);

        }
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358

        $cached = $surveynames;
    } else {
        $surveynames = $cached;
    }
    $surveyselecter = "";
    if ($returnarray===true) return $surveynames;
    $activesurveys='';
    $inactivesurveys='';
    $expiredsurveys='';
    if ($surveynames)
    {
        foreach($surveynames as $sv)
        {

            $surveylstitle=flattenText($sv['surveyls_title']);
            if (strlen($surveylstitle)>45)
            {
                $surveylstitle = htmlspecialchars(mb_strcut(html_entity_decode($surveylstitle,ENT_QUOTES,'UTF-8'), 0, 45, 'UTF-8'))."...";
            }

            if($sv['active']!='Y')
            {
                $inactivesurveys .= "<option ";
                if(Yii::app()->user->getId() == $sv['owner_id'])
                {
                    $inactivesurveys .= " style=\"font-weight: bold;\"";
                }
                if ($sv['sid'] == $surveyid)
                {
                    $inactivesurveys .= " selected='selected'"; $svexist = 1;
                }
359
                $inactivesurveys .=" value='{$sv['sid']}'>{$surveylstitle}</option>\n";
360 361 362 363 364 365 366 367 368 369 370
            } elseif($sv['expires']!='' && $sv['expires'] < dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust))
            {
                $expiredsurveys .="<option ";
                if (Yii::app()->user->getId() == $sv['owner_id'])
                {
                    $expiredsurveys .= " style=\"font-weight: bold;\"";
                }
                if ($sv['sid'] == $surveyid)
                {
                    $expiredsurveys .= " selected='selected'"; $svexist = 1;
                }
371
                $expiredsurveys .=" value='{$sv['sid']}'>{$surveylstitle}</option>\n";
372 373 374 375 376 377 378 379 380 381 382
            } else
            {
                $activesurveys .= "<option ";
                if(Yii::app()->user->getId() == $sv['owner_id'])
                {
                    $activesurveys .= " style=\"font-weight: bold;\"";
                }
                if ($sv['sid'] == $surveyid)
                {
                    $activesurveys .= " selected='selected'"; $svexist = 1;
                }
383
                $activesurveys .=" value='{$sv['sid']}'>{$surveylstitle}</option>\n";
384 385 386
            }
        } // End Foreach
    }
387
    
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
    //Only show each activesurvey group if there are some
    if ($activesurveys!='')
    {
        $surveyselecter .= "<optgroup label='".$clang->gT("Active")."' class='activesurveyselect'>\n";
        $surveyselecter .= $activesurveys . "</optgroup>";
    }
    if ($expiredsurveys!='')
    {
        $surveyselecter .= "<optgroup label='".$clang->gT("Expired")."' class='expiredsurveyselect'>\n";
        $surveyselecter .= $expiredsurveys . "</optgroup>";
    }
    if ($inactivesurveys!='')
    {
        $surveyselecter .= "<optgroup label='".$clang->gT("Inactive")."' class='inactivesurveyselect'>\n";
        $surveyselecter .= $inactivesurveys . "</optgroup>";
    }
    if (!isset($svexist))
    {
        $surveyselecter = "<option selected='selected' value=''>".$clang->gT("Please choose...")."</option>\n".$surveyselecter;
    } else
    {
409
        $surveyselecter = "<option value=''>".$clang->gT("None")."</option>\n".$surveyselecter;
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
    }
    return $surveyselecter;
}

/**
* Returns true if a user has permissions in the particular survey
*
* @param $iSID The survey ID
* @param $sPermission
* @param $sCRUD
* @param $iUID User ID - if not given the one of the current user is used
* @return bool
*/
function hasSurveyPermission($iSID, $sPermission, $sCRUD, $iUID=null)
{
    if (!in_array($sCRUD,array('create','read','update','delete','import','export'))) return false;
    $sCRUD=$sCRUD.'_p';

428 429 430 431
    $thissurvey=getSurveyInfo($iSID);
    if (!$thissurvey) return false;

    $aSurveyPermissionCache = Yii::app()->getConfig("aSurveyPermissionCache");
432 433 434 435
    if (is_null($iUID))
    {
        if (!Yii::app()->user->getIsGuest()) $iUID = Yii::app()->session['loginID'];
        else return false;
436 437 438
        // Some user have acces to whole survey settings
        if (Yii::app()->session['USER_RIGHT_SUPERADMIN']==1) return true;
        if ($thissurvey && $iUID==$thissurvey['owner_id']) return true;
439
    }
440

441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
    if (!isset($aSurveyPermissionCache[$iSID][$iUID][$sPermission][$sCRUD]))
    {
        $query = Survey_permissions::model()->findByAttributes(array("sid"=> $iSID,"uid"=> $iUID,"permission"=>$sPermission));
        $bPermission = is_null($query) ? array() : $query->attributes;
        if (!isset($bPermission[$sCRUD]) || $bPermission[$sCRUD]==0)
        {
            $bPermission=false;
        }
        else
        {
            $bPermission=true;
        }
        $aSurveyPermissionCache[$iSID][$iUID][$sPermission][$sCRUD]=$bPermission;
    }
    Yii::app()->setConfig("aSurveyPermissionCache", $aSurveyPermissionCache);
    return $aSurveyPermissionCache[$iSID][$iUID][$sPermission][$sCRUD];
}

/**
* Returns true if a user has global permission for a certain action. Available permissions are
*
* USER_RIGHT_CREATE_SURVEY
* USER_RIGHT_CONFIGURATOR
* USER_RIGHT_CREATE_USER
* USER_RIGHT_DELETE_USER
* USER_RIGHT_SUPERADMIN
* USER_RIGHT_MANAGE_TEMPLATE
* USER_RIGHT_MANAGE_LABEL
*
* @param $sPermission
* @return bool
*/
function hasGlobalPermission($sPermission)
{
    if (!Yii::app()->user->getIsGuest()) $iUID = !Yii::app()->user->getId();
    else return false;
    if (Yii::app()->session['USER_RIGHT_SUPERADMIN']==1) return true; //Superadmin has access to all
    if (Yii::app()->session[$sPermission]==1)
    {
        return true;
    }
    else
    {
        return false;
    }

}

function getTemplateList()
{
    $usertemplaterootdir=Yii::app()->getConfig("usertemplaterootdir");
    $standardtemplaterootdir=Yii::app()->getConfig("standardtemplaterootdir");

    if (!$usertemplaterootdir) {die("getTemplateList() no template directory");}
    if ($handle = opendir($standardtemplaterootdir))
    {
        while (false !== ($file = readdir($handle)))
        {
            if (!is_file("$standardtemplaterootdir/$file") && $file != "." && $file != ".." && $file!=".svn" && isStandardTemplate($file))
            {
                $list_of_files[$file] = $standardtemplaterootdir.DIRECTORY_SEPARATOR.$file;
            }
        }
        closedir($handle);
    }

    if ($handle = opendir($usertemplaterootdir))
    {
        while (false !== ($file = readdir($handle)))
        {
            if (!is_file("$usertemplaterootdir/$file") && $file != "." && $file != ".." && $file!=".svn")
            {
                $list_of_files[$file] = $usertemplaterootdir.DIRECTORY_SEPARATOR.$file;
            }
        }
        closedir($handle);
    }
    ksort($list_of_files);

    return $list_of_files;
}

523 524
function getAdminThemeList()
{
525
    // $usertemplaterootdir=Yii::app()->getConfig("usertemplaterootdir");
526 527
    $standardtemplaterootdir=Yii::app()->getConfig("styledir");

528
    //    if (!$usertemplaterootdir) {die("getTemplateList() no template directory");}
529 530 531 532 533 534 535 536 537 538 539 540
    if ($handle = opendir($standardtemplaterootdir))
    {
        while (false !== ($file = readdir($handle)))
        {
            if (!is_file("$standardtemplaterootdir/$file") && $file != "." && $file != ".." && $file!=".svn")
            {
                $list_of_files[$file] = $standardtemplaterootdir.DIRECTORY_SEPARATOR.$file;
            }
        }
        closedir($handle);
    }

541
    /*    if ($handle = opendir($usertemplaterootdir))
542
    {
543 544 545 546 547 548 549 550
    while (false !== ($file = readdir($handle)))
    {
    if (!is_file("$usertemplaterootdir/$file") && $file != "." && $file != ".." && $file!=".svn")
    {
    $list_of_files[$file] = $usertemplaterootdir.DIRECTORY_SEPARATOR.$file;
    }
    }
    closedir($handle);
551 552 553 554 555 556
    }         */
    ksort($list_of_files);

    return $list_of_files;
}

557 558 559 560 561 562 563 564 565 566

/**
* getQuestions() queries the database for an list of all questions matching the current survey and group id
*
* @return This string is returned containing <option></option> formatted list of questions in the current survey and group
*/
function getQuestions($surveyid,$gid,$selectedqid)
{
    $clang = Yii::app()->lang;
    $s_lang = Survey::model()->findByPk($surveyid)->language;
567
    $qrows = Questions::model()->findAllByAttributes(array('sid' => $surveyid, 'gid' => $gid, 'language' => $s_lang, 'parent_qid' => 0),array('order'=>'question_order'));
568

569
    if (!isset($sQuestionselecter)) {$sQuestionselecter="";}
570 571 572 573
    foreach ($qrows as $qrow)
    {
        $qrow = $qrow->attributes;
        $qrow['title'] = strip_tags($qrow['title']);
574
        $link = Yii::app()->getController()->createUrl("/admin/survey/sa/view/surveyid/".$surveyid."/gid/".$gid."/qid/".$qrow['qid']);
575 576 577
        $sQuestionselecter .= "<option value='{$link}'";
        if ($selectedqid == $qrow['qid'])
        {
578 579
            $sQuestionselecter .= " selected='selected'";
            $qexists=true;
580 581 582
        }
        $sQuestionselecter .=">{$qrow['title']}:";
        $sQuestionselecter .= " ";
583
        $question=flattenText($qrow['question']);
584 585
        if (strlen($question)<35)
        {
586
            $sQuestionselecter .= $question;
587 588 589
        }
        else
        {
590
            $sQuestionselecter .= htmlspecialchars(mb_strcut(html_entity_decode($question,ENT_QUOTES,'UTF-8'), 0, 35, 'UTF-8'))."...";
591
        }
592
        $sQuestionselecter .= "</option>\n";
593 594 595 596
    }

    if (!isset($qexists))
    {
597 598 599 600
        $sQuestionselecter = "<option selected='selected'>".$clang->gT("Please choose...")."</option>\n".$sQuestionselecter;
    }
    else
    {
601 602
        $link = Yii::app()->getController()->createUrl("/admin/survey/sa/view/surveyid/".$surveyid."/gid/".$gid);
        $sQuestionselecter = "<option value='{$link}'>".$clang->gT("None")."</option>\n".$sQuestionselecter;
603
    }
604
    return $sQuestionselecter;
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
}

/**
* getGidPrevious() returns the Gid of the group prior to the current active group
*
* @param string $surveyid
* @param string $gid
*
* @return The Gid of the previous group
*/
function getGidPrevious($surveyid, $gid)
{
    $clang = Yii::app()->lang;

    if (!$surveyid) {$surveyid=returnGlobal('sid');}
    $s_lang = Survey::model()->findByPk($surveyid)->language;
621
    $qresult = Groups::model()->findAllByAttributes(array('sid' => $surveyid, 'language' => $s_lang), array('order'=>'group_order'));
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649

    $i = 0;
    $iPrev = -1;
    foreach ($qresult as $qrow)
    {
        $qrow = $qrow->attributes;
        if ($gid == $qrow['gid']) {$iPrev = $i - 1;}
        $i += 1;
    }

    if ($iPrev >= 0) {$GidPrev = $qresult[$iPrev]->gid;}
    else {$GidPrev = "";}
    return $GidPrev;
}

/**
* getQidPrevious() returns the Qid of the question prior to the current active question
*
* @param string $surveyid
* @param string $gid
* @param string $qid
*
* @return This Qid of the previous question
*/
function getQidPrevious($surveyid, $gid, $qid)
{
    $clang = Yii::app()->lang;
    $s_lang = Survey::model()->findByPk($surveyid)->language;
650
    $qrows = Questions::model()->findAllByAttributes(array('gid' => $gid, 'sid' => $surveyid, 'language' => $s_lang, 'parent_qid'=>0),array('order'=>'question_order'));
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686

    $i = 0;
    $iPrev = -1;
    if (count($qrows) > 0)
    {

        foreach ($qrows as $qrow)
        {
            $qrow = $qrow->attributes;
            if ($qid == $qrow['qid']) {$iPrev = $i - 1;}
            $i += 1;
        }
    }
    if ($iPrev >= 0) {$QidPrev = $qrows[$iPrev]->qid;}
    else {$QidPrev = "";}


    return $QidPrev;
}

/**
* getGidNext() returns the Gid of the group next to the current active group
*
* @param string $surveyid
* @param string $gid
*
* @return The Gid of the next group
*/
function getGidNext($surveyid, $gid)
{
    $clang = Yii::app()->lang;
    if (!$surveyid) {$surveyid=returnGlobal('sid');}
    $s_lang = Survey::model()->findByPk($surveyid)->language;

    //$gquery = "SELECT gid FROM ".db_table_name('groups')." WHERE sid=$surveyid AND language='{$s_lang}' ORDER BY group_order";

687
    $qresult = Groups::model()->findAllByAttributes(array('sid' => $surveyid, 'language' => $s_lang), array('order'=>'group_order'));
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718

    $GidNext="";
    $i = 0;
    $iNext = 1;

    foreach ($qresult as $qrow)
    {
        $qrow = $qrow->attributes;

        if ($gid == $qrow['gid']) {$iNext = $i + 1;}
        $i += 1;
    }

    if ($iNext < count($qresult)) {$GidNext = $qresult[$iNext]->gid;}
    else {$GidNext = "";}
    return $GidNext;
}

/**
* getQidNext() returns the Qid of the question prior to the current active question
*
* @param string $surveyid
* @param string $gid
* @param string $qid
*
* @return This Qid of the previous question
*/
function getQidNext($surveyid, $gid, $qid)
{
    $clang = Yii::app()->lang;
    $s_lang = Survey::model()->findByPk($surveyid)->language;
719
    $qrows = Questions::model()->findAllByAttributes(array('gid' => $gid, 'sid' => $surveyid, 'language' => $s_lang, 'parent_qid' => 0), array('order'=>'question_order'));
720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758


    $i = 0;
    $iNext = 1;
    if (count($qrows) > 0)
    {
        foreach ($qrows as $qrow)
        {
            if ($qid == $qrow->qid) {$iNext = $i + 1;}
            $i += 1;
        }
    }
    if ($iNext < count($qrows)) {$QidNext = $qrows[$iNext]->qid;}
    else {$QidNext = "";}
    return $QidNext;
}

function convertGETtoPOST($url)
{
    $url = preg_replace('/&amp;/i','&',$url);
    $stack = explode('?',$url);
    $calledscript = array_shift($stack);
    $query = array_shift($stack);
    $aqueryitems = explode('&',$query);
    $arrayParam = Array();
    $arrayVal = Array();

    foreach ($aqueryitems as $queryitem)
    {
        $stack =  explode ('=', $queryitem);
        $paramname = array_shift($stack);
        $value = array_shift($stack);
        $arrayParam[] = "'".$paramname."'";
        $arrayVal[] = substr($value, 0, 9) != "document." ? "'".$value."'" : $value;
    }
    //	$Paramlist = "[" . implode(",",$arrayParam) . "]";
    //	$Valuelist = "[" . implode(",",$arrayVal) . "]";
    $Paramlist = "new Array(" . implode(",",$arrayParam) . ")";
    $Valuelist = "new Array(" . implode(",",$arrayVal) . ")";
759
    $callscript = "sendPost('$calledscript','',$Paramlist,$Valuelist);";
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
    return $callscript;
}


/**
* This function calculates how much space is actually used by all files uploaded
* using the File Upload question type
*
* @returns integer Actual space used in MB
*/
function calculateTotalFileUploadUsage(){
    global $uploaddir;
    $sQuery='select sid from {{surveys}}';
    $oResult = dbExecuteAssoc($sQuery); //checked
    $aRows = $oResult->readAll();
    $iTotalSize=0.0;
    foreach ($aRows as $aRow)
    {
        $sFilesPath=$uploaddir.'/surveys/'.$aRow['sid'].'/files';
        if (file_exists($sFilesPath))
        {
            $iTotalSize+=(float)getDirectorySize($sFilesPath);
        }
    }
    return (float)$iTotalSize/1024/1024;
}

function getDirectorySize($directory) {
    $size = 0;
    foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file){
        $size+=$file->getSize();
    }
    return $size;
}


/**
* Gets number of groups inside a particular survey
*
* @param string $surveyid
* @param mixed $lang
*/
function getGroupSum($surveyid, $lang)
{
    //$condn = "WHERE sid=".$surveyid." AND language='".$lang."'"; //Getting a count of questions for this survey
    $condn = array('sid'=>$surveyid,'language'=>$lang);
    $sumresult3 = count(Groups::model()->findAllByAttributes($condn)); //Checked)

    return $sumresult3 ;
}


/**
* getMaxGroupOrder($surveyid) queries the database for the maximum sortorder of a group and returns the next higher one.
*
* @param mixed $surveyid
*/
function getMaxGroupOrder($surveyid)
{
    $s_lang = Survey::model()->findByPk($surveyid)->language;

    //$max_sql = "SELECT max( group_order ) AS max FROM ".db_table_name('groups')." WHERE sid =$surveyid AND language='{$s_lang}'" ;
    $query = Groups::model()->find(array('order' => 'group_order desc'));
    $current_max = !is_null($query) ? $query->group_order : '';

    if($current_max!="")
    {
        return ++$current_max ;
    }
    else return "0" ;
}


/**
* getGroupOrder($surveyid,$gid) queries the database for the sortorder of a group.
*
* @param mixed $surveyid
* @param mixed $gid
* @return mixed
*/
function getGroupOrder($surveyid,$gid)
{

    $s_lang = Survey::model()->findByPk($surveyid)->language;

    //$grporder_sql = "SELECT group_order FROM ".db_table_name('groups')." WHERE sid =$surveyid AND language='{$s_lang}' AND gid=$gid" ;
    $grporder_result = Groups::model()->findByAttributes(array('sid' => $surveyid, 'gid' => $gid, 'language' => $s_lang)); //Checked
    $grporder_row = $grporder_result->attributes ;
    $group_order = $grporder_row['group_order'];
    if($group_order=="")
    {
        return "0" ;
    }
    else return $group_order ;
}

/**
* getMaxQuestionOrder($gid) queries the database for the maximum sortorder of a question.
*
*/
function getMaxQuestionOrder($gid,$surveyid)
{
    $gid=sanitize_int($gid);
    $s_lang = Survey::model()->findByPk($surveyid)->language;
    $max_sql = "SELECT max( question_order ) AS max FROM {{questions}} WHERE gid='$gid' AND language='$s_lang'";

    $max_result = Yii::app()->db->createCommand($max_sql)->query(); //Checked
    $maxrow = $max_result->read() ;
    $current_max = $maxrow['max'];
    if($current_max=="")
    {
        return "0" ;
    }
    else return $current_max ;
}

/**
* getQuestionClass() returns a class name for a given question type to allow custom styling for each question type.
*
* @param string $input containing unique character representing each question type.
* @return string containing the class name for a given question type.
*/
function getQuestionClass($input)
{

    switch($input)
    {   // I think this is a bad solution to adding classes to question
        // DIVs but I can't think of a better solution. (eric_t_cruiser)

        case 'X': return 'boilerplate';     //  BOILERPLATE QUESTION
        case '5': return 'choice-5-pt-radio';   //  5 POINT CHOICE radio-buttons
        case 'D': return 'date';        //  DATE
        case 'Z': return 'list-radio-flexible'; //  LIST Flexible radio-button
        case 'L': return 'list-radio';      //  LIST radio-button
        case 'W': return 'list-dropdown-flexible'; //   LIST drop-down (flexible label)
        case '!': return 'list-dropdown';   //  List - dropdown
        case 'O': return 'list-with-comment';   //  LIST radio-button + textarea
        case 'R': return 'ranking';     //  RANKING STYLE
        case 'M': return 'multiple-opt';    //  Multiple choice checkbox
        case 'I': return 'language';        //  Language Question
        case 'P': return 'multiple-opt-comments'; //    Multiple choice with comments checkbox + text
        case 'Q': return 'multiple-short-txt';  //  TEXT
        case 'K': return 'numeric-multi';   //  MULTIPLE NUMERICAL QUESTION
        case 'N': return 'numeric';     //  NUMERICAL QUESTION TYPE
        case 'S': return 'text-short';      //  SHORT FREE TEXT
        case 'T': return 'text-long';       //  LONG FREE TEXT
        case 'U': return 'text-huge';       //  HUGE FREE TEXT
        case 'Y': return 'yes-no';      //  YES/NO radio-buttons
        case 'G': return 'gender';      //  GENDER drop-down list
        case 'A': return 'array-5-pt';      //  ARRAY (5 POINT CHOICE) radio-buttons
        case 'B': return 'array-10-pt';     //  ARRAY (10 POINT CHOICE) radio-buttons
        case 'C': return 'array-yes-uncertain-no'; //   ARRAY (YES/UNCERTAIN/NO) radio-buttons
        case 'E': return 'array-increase-same-decrease'; // ARRAY (Increase/Same/Decrease) radio-buttons
        case 'F': return 'array-flexible-row';  //  ARRAY (Flexible) - Row Format
        case 'H': return 'array-flexible-column'; //    ARRAY (Flexible) - Column Format
            //      case '^': return 'slider';          //  SLIDER CONTROL
        case ':': return 'array-multi-flexi';   //  ARRAY (Multi Flexi) 1 to 10
        case ";": return 'array-multi-flexi-text';
        case "1": return 'array-flexible-duel-scale'; //    Array dual scale
        case "*": return 'equation';    // Equation
        default:  return 'generic_question';    //  Should have a default fallback
    };
};

/**
* setupColumns() defines all the html tags to be wrapped around
* various list type answers.
*
* @param integer $columns - the number of columns, usually supplied by $dcols
* @param integer $answer_count - the number of answers to a question, usually supplied by $anscount
* @param string $wrapperclass - a global class for the wrapper
* @param string $itemclass - a class for the item
* @return array with all the various opening and closing tags to generate a set of columns.
*
* It returns an array with the following items:
*    $wrapper['whole-start']   = Opening wrapper for the whole list
*    $wrapper['whole-end']     = closing wrapper for the whole list
*    $wrapper['col-devide']    = normal column devider
*    $wrapper['col-devide-last'] = the last column devider (to allow
*                                for different styling of the last
*                                column
*    $wrapper['item-start']    = opening wrapper tag for individual
*                                option
*    $wrapper['item-start-other'] = opening wrapper tag for other
*                                option
*    $wrapper['item-start-noanswer'] = opening wrapper tag for no answer
*                                option
*    $wrapper['item-end']      = closing wrapper tag for individual
*                                option
*    $wrapper['maxrows']       = maximum number of rows in each
*                                column
*    $wrapper['cols']          = Number of columns to be inserted
*                                (and checked against)
*
*
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* Columns are a problem.
* Really there is no perfect solution to columns at the moment.
*
* -  Using Tables is problematic semanticly.
* -  Using inline or float to create columns, causes the answers
*    flows horizontally, not vertically which is not ideal visually.
* -  Using CSS3 columns is also a problem because of browser support
*    and also because if you have answeres split across two or more
*    lines, and those answeres happen to fall at the bottom of a
*    column, the answer might be split across columns as well as
*    lines.
* -  Using nested unordered list with the first level of <LI>s
*    floated is the same as using tables and so is bad semantically
*    for the same reason tables are bad.
* -  Breaking the unordered lists into consecutive floated unordered
*    lists is not great semantically but probably not as bad as
*    using tables.
*
* Because I haven't been able to decide which option is the least
* bad, I have handed over that responsibility to the admin who sets
* LimeSurvey up on their server.
*
* There are four options:
*    'css'   using one of the various CSS only methods for
*            rendering columns.
*            (Check the CSS file for your chosen template to see
*             how columns are defined.)
*    'ul'    using multiple floated unordered lists. (DEFAULT)
*    'table' using conventional tables based layout.
*     NULL   blocks the use of columns
*
* 'ul' is the default because it's the best possible compromise
* between semantic markup and visual layout.
*/
function setupColumns($columns, $answer_count,$wrapperclass="",$itemclass="")
{

993 994 995 996 997
    $column_style = Yii::app()->getConfig('column_style');
    if ( !in_array($column_style,array('css','ul','table')) && !is_null($column_style) )
    {
        $column_style = 'ul';
    };
998
    if(!is_null($column_style) && $columns!=1) // Add a global class for all column.
999 1000 1001
    {
        $wrapperclass.= " colstyle-{$column_style}";
    }
1002 1003
    if($columns < 2)
    {
1004
        $column_style = null;
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
        $columns = 1;
    }

    if(($columns > $answer_count) && $answer_count>0)
    {
        $columns = $answer_count;
    };


    $class_first = ' class="'.$wrapperclass.'"';
1015
    if($columns > 1 && !is_null($column_style))
1016
    {
1017
        if($column_style == 'ul')
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
        {
            $ul = '-ul';
        }
        else
        {
            $ul = '';
        }
        $class_first = ' class="'.$wrapperclass.' cols-'.$columns . $ul.' first"';
        $class = ' class="'.$wrapperclass.' cols-'.$columns . $ul.'"';
        $class_last_ul = ' class="'.$wrapperclass.' cols-'.$columns . $ul.' last"';
        $class_last_table = ' class="'.$wrapperclass.' cols-'.$columns.' last"';
    }
    else
    {
        $class = ' class="'.$wrapperclass.'"';
        $class_last_ul = ' class="'.$wrapperclass.'"';
        $class_last_table = ' class="'.$wrapperclass.'"';
    };

    $wrapper = array(
    'whole-start'  => "\n<ul$class_first>\n"
    ,'whole-end'    => "</ul>\n"
    ,'col-devide'   => ''
    ,'col-devide-last' => ''
    ,'item-start'   => "\t<li class=\"{$itemclass}\">\n"
    ,'item-start-other' => "\t<li class=\"{$itemclass} other other-item\">\n"
    ,'item-start-noanswer' => "\t<li class=\"{$itemclass} noanswer-item\">\n"
    ,'item-end' => "\t</li>\n"
    ,'maxrows'  => ceil($answer_count/$columns) //Always rounds up to nearest whole number
    ,'cols'     => $columns
    );

1050
    switch($column_style)
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
    {
        case 'ul':  if($columns > 1)
            {
                $wrapper['col-devide']  = "\n</ul>\n\n<ul$class>\n";
                $wrapper['col-devide-last'] = "\n</ul>\n\n<ul$class_last_ul>\n";
            }
            break;

        case 'table':   $table_cols = '';
            for($cols = $columns ; $cols > 0 ; --$cols)
            {
                switch($cols)
                {
                    case $columns:  $table_cols .= "\t<col$class_first />\n";
                        break;
                    case 1:     $table_cols .= "\t<col$class_last_table />\n";
                        break;
                    default:    $table_cols .= "\t<col$class />\n";
                };
            };

            if($columns > 1)
            {
                $wrapper['col-devide']  = "\t</ul>\n</td>\n\n<td>\n\t<ul>\n";
                $wrapper['col-devide-last'] = "\t</ul>\n</td>\n\n<td class=\"last\">\n\t<ul>\n";
            };
            $wrapper['whole-start'] = "\n<table$class>\n$table_cols\n\t<tbody>\n<tr>\n<td>\n\t<ul>\n";
            $wrapper['whole-end']   = "\t</ul>\n</td>\n</tr>\n\t</tbody>\n</table>\n";
            $wrapper['item-start']  = "<li class=\"{$itemclass}\">\n";
            $wrapper['item-end']    = "</li class=\"{$itemclass}\">\n";
    };

    return $wrapper;
};

function alternation($alternate = '' , $type = 'col')
{
    /**
    * alternation() Returns a class identifyer for alternating between
    * two options. Used to style alternate elements differently. creates
    * or alternates between the odd string and the even string used in
    * as column and row classes for array type questions.
    *
    * @param string $alternate = '' (empty) (default) , 'array2' ,  'array1' , 'odd' , 'even'
    * @param string  $type = 'col' (default) or 'row'
    *
    * @return string representing either the first alternation or the opposite alternation to the one supplied..
    */
    /*
    // The following allows type to be left blank for row in subsequent
    // function calls.
    // It has been left out because 'row' must be defined the first time
    // alternation() is called. Since it is only ever written once for each
    // while statement within a function, 'row' is always defined.
    if(!empty($alternate) && $type != 'row')
    {   if($alternate == ('array2' || 'array1'))
    {
    $type = 'row';
    };
    };
    // It has been left in case it becomes useful but probably should be
    // removed.
    */
    if($type == 'row')
    {
        $odd  = 'array2'; // should be row_odd
        $even = 'array1'; // should be row_even
    }
    else
    {
        $odd  = 'odd';  // should be col_odd
        $even = 'even'; // should be col_even
    };
    if($alternate == $odd)
    {
        $alternate = $even;
    }
    else
    {
        $alternate = $odd;
    };
    return $alternate;
}


/**
* longestString() returns the length of the longest string past to it.
* @peram string $new_string
* @peram integer $longest_length length of the (previously) longest string passed to it.
* @return integer representing the length of the longest string passed (updated if $new_string was longer than $longest_length)
*
* usage should look like this: $longest_length = longestString( $new_string , $longest_length );
*
*/
function longestString( $new_string , $longest_length )
{
    if($longest_length < strlen(trim(strip_tags($new_string))))
    {
        $longest_length = strlen(trim(strip_tags($new_string)));
    };
    return $longest_length;
};



/**
* getNotificationList() returns different options for notifications
*
* @param string $notificationcode - the currently selected one
*
* @return This string is returned containing <option></option> formatted list of notification methods for current survey
*/
function getNotificationList($notificationcode)
{
    $clang = Yii::app()->lang;
    $ntypes = array(
    "0"=>$clang->gT("No email notification"),
    "1"=>$clang->gT("Basic email notification"),
    "2"=>$clang->gT("Detailed email notification with result codes")
    );
    if (!isset($ntypeselector)) {$ntypeselector="";}
    foreach($ntypes as $ntcode=>$ntdescription)
    {
        $ntypeselector .= "<option value='$ntcode'";
        if ($notificationcode == $ntcode) {$ntypeselector .= " selected='selected'";}
        $ntypeselector .= ">$ntdescription</option>\n";
    }
    return $ntypeselector;
}


/**
* getGroupList() queries the database for a list of all groups matching the current survey sid
*
*
* @param string $gid - the currently selected gid/group
*
* @return This string is returned containing <option></option> formatted list of groups to current survey
*/
function getGroupList($gid,$surveyid)
{
    $clang = Yii::app()->lang;
    $groupselecter="";
    $gid=sanitize_int($gid);
    $surveyid=sanitize_int($surveyid);
    if (!$surveyid) {$surveyid=returnGlobal('sid');}
    $s_lang = Survey::model()->findByPk($surveyid)->language;

    $gidquery = "SELECT gid, group_name FROM {{groups}} WHERE sid='{$surveyid}' AND  language='{$s_lang}' ORDER BY group_order";
    $gidresult = Yii::app()->db->createCommand($gidquery)->query(); //Checked
    foreach ($gidresult->readAll() as $gv)
    {
        $groupselecter .= "<option";
        if ($gv['gid'] == $gid) {$groupselecter .= " selected='selected'"; $gvexist = 1;}
        $groupselecter .= " value='".Yii::app()->getConfig('scriptname')."?sid=$surveyid&amp;gid=".$gv['gid']."'>".htmlspecialchars($gv['group_name'])."</option>\n";
    }
    if ($groupselecter)
    {
        if (!isset($gvexist)) {$groupselecter = "<option selected='selected'>".$clang->gT("Please choose...")."</option>\n".$groupselecter;}
        else {$groupselecter .= "<option value='".Yii::app()->getConfig('scriptname')."?sid=$surveyid&amp;gid='>".$clang->gT("None")."</option>\n";}
    }
    return $groupselecter;
}



function getGroupList3($gid,$surveyid)
{
    //$clang = Yii::app()->lang;
    $gid=sanitize_int($gid);
    $surveyid=sanitize_int($surveyid);

    if (!$surveyid) {$surveyid=returnGlobal('sid');}
    $groupselecter = "";
    $s_lang = Survey::model()->findByPk($surveyid)->language;


    //$gidquery = "SELECT gid, group_name FROM ".db_table_name('groups')." WHERE sid=$surveyid AND language='{$s_lang}' ORDER BY group_order";

1230
    $gidresult = Groups::model()->findAllByAttributes(array('sid' => $surveyid, 'language' => $s_lang), array('order'=>'group_order'));
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265

    foreach ($gidresult as $gv)
    {
        $gv = $gv->attributes;
        $groupselecter .= "<option";
        if ($gv['gid'] == $gid) {$groupselecter .= " selected='selected'"; }
        $groupselecter .= " value='".$gv['gid']."'>".htmlspecialchars($gv['group_name'])."</option>\n";
    }


    return $groupselecter;
}

/**
* put your comment there...
*
* @param mixed $gid
* @param mixed $language
*/
function getGroupListLang($gid, $language, $surveyid)
{

    $clang = Yii::app()->lang;

    $groupselecter="";
    if (!$surveyid) {$surveyid=returnGlobal('sid');}

    $gidresult = Groups::model()->findAll(array('condition'=>'sid=:surveyid AND language=:language',
    'order'=>'group_order',
    'params'=>array(':surveyid'=>$surveyid,':language'=>$language)));   //Checked)
    foreach ($gidresult as $gv)
    {
        $gv = $gv->attributes;
        $groupselecter .= "<option";
        if ($gv['gid'] == $gid) {$groupselecter .= " selected='selected'"; $gvexist = 1;}
1266
        $link = Yii::app()->getController()->createUrl("/admin/survey/sa/view/surveyid/".$surveyid."/gid/".$gv['gid']);
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
        $groupselecter .= " value='{$link}'>";
        if (strip_tags($gv['group_name']))
        {
            $groupselecter .= htmlspecialchars(strip_tags($gv['group_name']));
        } else {
            $groupselecter .= htmlspecialchars($gv['group_name']);
        }
        $groupselecter .= "</option>\n";
    }
    if ($groupselecter)
    {
1278
        $link = Yii::app()->getController()->createUrl("/admin/survey/sa/view/surveyid/".$surveyid);
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
        if (!isset($gvexist)) {$groupselecter = "<option selected='selected'>".$clang->gT("Please choose...")."</option>\n".$groupselecter;}
        else {$groupselecter .= "<option value='{$link}'>".$clang->gT("None")."</option>\n";}
    }
    return $groupselecter;
}


function getUserList($outputformat='fullinfoarray')
{
    $clang = Yii::app()->lang;

    if (!empty(Yii::app()->session['loginID']))
    {
        $myuid=sanitize_int(Yii::app()->session['loginID']);
    }
    $usercontrolSameGroupPolicy = Yii::app()->getConfig('usercontrolSameGroupPolicy');
    if (Yii::app()->session['USER_RIGHT_SUPERADMIN'] != 1 && isset($usercontrolSameGroupPolicy) &&
    $usercontrolSameGroupPolicy == true)
    {
        if (isset($myuid))
        {
1300 1301 1302
            $sDatabaseType = Yii::app()->db->getDriverName();
            if ($sDatabaseType=='mssql' || $sDatabaseType=="sqlsrv")
            {
1303
                $sSelectFields = 'users_name,uid,email,full_name,parent_id,create_survey,participant_panel,configurator,create_user,delete_user,superadmin,manage_template,manage_label,CAST(password as varchar) as password';
1304 1305 1306 1307 1308 1309
            }
            else
            {
                $sSelectFields = 'users_name,uid,email,full_name,parent_id,create_survey,participant_panel,configurator,create_user,delete_user,superadmin,manage_template,manage_label,password';
            }

1310 1311 1312
            // List users from same group as me + all my childs
            // a subselect is used here because MSSQL does not like to group by text
            // also Postgres does like this one better
1313 1314 1315 1316 1317
            $uquery = " SELECT {$sSelectFields} from {{users}} where uid in (
                SELECT uid from {{user_in_groups}} where ugid in (
                    SELECT ugid from {{user_in_groups}} where uid={$myuid}
                    )
                )
1318
            UNION
1319 1320 1321 1322
            SELECT {$sSelectFields} from {{users}} v where v.parent_id={$myuid}
            UNION
            SELECT {$sSelectFields} from {{users}} v where uid={$myuid}";
            
1323 1324 1325 1326 1327
        }
        else
        {
            return array(); // Or die maybe
        }
1328
                                                        
1329 1330 1331 1332 1333 1334
    }
    else
    {
        $uquery = "SELECT * FROM {{users}} ORDER BY uid";
    }

1335
    $uresult = Yii::app()->db->createCommand($uquery)->query()->readAll(); //Checked
1336

1337
    if (count($uresult)==0)
1338 1339 1340
    //user is not in a group and usercontrolSameGroupPolicy is activated - at least show his own userinfo
    {
        $uquery = "SELECT u.* FROM {{users}} AS u WHERE u.uid=".$myuid;
1341
        $uresult = Yii::app()->db->createCommand($uquery)->query()->readAll();//Checked
1342 1343 1344 1345 1346
    }

    $userlist = array();
    $userlist[0] = "Reserved for logged in user";
    //while ($srow = $uresult->readAll())
1347
    foreach ($uresult as $srow)
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
    {
        if ($outputformat != 'onlyuidarray')
        {
            if ($srow['uid'] != Yii::app()->session['loginID'])
            {
                $userlist[] = array("user"=>$srow['users_name'], "uid"=>$srow['uid'], "email"=>$srow['email'], "password"=>$srow['password'], "full_name"=>$srow['full_name'], "parent_id"=>$srow['parent_id'], "create_survey"=>$srow['create_survey'], "participant_panel"=>$srow['participant_panel'], "configurator"=>$srow['configurator'], "create_user"=>$srow['create_user'], "delete_user"=>$srow['delete_user'], "superadmin"=>$srow['superadmin'], "manage_template"=>$srow['manage_template'], "manage_label"=>$srow['manage_label']);           //added by Dennis modified by Moses
            }
            else
            {
                $userlist[0] = array("user"=>$srow['users_name'], "uid"=>$srow['uid'], "email"=>$srow['email'], "password"=>$srow['password'], "full_name"=>$srow['full_name'], "parent_id"=>$srow['parent_id'], "create_survey"=>$srow['create_survey'],"participant_panel"=>$srow['participant_panel'], "configurator"=>$srow['configurator'], "create_user"=>$srow['create_user'], "delete_user"=>$srow['delete_user'], "superadmin"=>$srow['superadmin'], "manage_template"=>$srow['manage_template'], "manage_label"=>$srow['manage_label']);
            }
        }
        else
        {
            if ($srow['uid'] != Yii::app()->session['loginID'])
            {
                $userlist[] = $srow['uid'];
            }
            else
            {
                $userlist[0] = $srow['uid'];
            }
        }

    }
    return $userlist;
}


/**
* Gets all survey infos in one big array including the language specific settings
*
* @param string $surveyid  The survey ID
* @param string $languagecode The language code - if not given the base language of the particular survey is used
* @return array Returns array with survey info or false, if survey does not exist
*/
function getSurveyInfo($surveyid, $languagecode='')
{
1386
    static $staticSurveyInfo = array();// Use some static
1387 1388 1389
    $surveyid=sanitize_int($surveyid);
    $languagecode=sanitize_languagecode($languagecode);
    $thissurvey=false;
1390 1391 1392 1393 1394
    // Do job only if this survey exist
    if(!Survey::model()->findByPk($surveyid))
    {
        return false;
    }
1395
    // if no language code is set then get the base language one
1396
    if ((!isset($languagecode) || $languagecode==''))
1397
    {
1398
        $languagecode=Survey::model()->findByPk($surveyid)->language;
1399 1400
    }

1401
    if(isset($staticSurveyInfo[$surveyid][$languagecode]) )
1402
    {
1403 1404 1405 1406 1407
        $thissurvey=$staticSurveyInfo[$surveyid][$languagecode];
    }
    else
    {
        $result = Surveys_languagesettings::model()->with('survey')->findByPk(array('surveyls_survey_id' => $surveyid, 'surveyls_language' => $languagecode));
1408 1409 1410 1411 1412 1413
        if (is_null($result)) {
            // When additional language was added, but not saved it does not exists
            // We should revert to the base language then
            $languagecode=Survey::model()->findByPk($surveyid)->language;
            $result = Surveys_languagesettings::model()->with('survey')->findByPk(array('surveyls_survey_id' => $surveyid, 'surveyls_language' => $languagecode));
        }
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
        if($result)
        {
            $thissurvey=array_merge($result->survey->attributes,$result->attributes);
            $thissurvey['name']=$thissurvey['surveyls_title'];
            $thissurvey['description']=$thissurvey['surveyls_description'];
            $thissurvey['welcome']=$thissurvey['surveyls_welcometext'];
            $thissurvey['templatedir']=$thissurvey['template'];
            $thissurvey['adminname']=$thissurvey['admin'];
            $thissurvey['tablename']='{{survey_'.$thissurvey['sid'] . '}}';
            $thissurvey['urldescrip']=$thissurvey['surveyls_urldescription'];
            $thissurvey['url']=$thissurvey['surveyls_url'];
            $thissurvey['expiry']=$thissurvey['expires'];
            $thissurvey['email_invite_subj']=$thissurvey['surveyls_email_invite_subj'];
            $thissurvey['email_invite']=$thissurvey['surveyls_email_invite'];
            $thissurvey['email_remind_subj']=$thissurvey['surveyls_email_remind_subj'];
            $thissurvey['email_remind']=$thissurvey['surveyls_email_remind'];
            $thissurvey['email_confirm_subj']=$thissurvey['surveyls_email_confirm_subj'];
            $thissurvey['email_confirm']=$thissurvey['surveyls_email_confirm'];
            $thissurvey['email_register_subj']=$thissurvey['surveyls_email_register_subj'];
            $thissurvey['email_register']=$thissurvey['surveyls_email_register'];
            $thissurvey['attributedescriptions'] = $result->survey->tokenAttributes;
            $thissurvey['attributecaptions'] = $result->attributeCaptions;
            if (!isset($thissurvey['adminname'])) {$thissurvey['adminname']=Yii::app()->getConfig('siteadminemail');}
            if (!isset($thissurvey['adminemail'])) {$thissurvey['adminemail']=Yii::app()->getConfig('siteadminname');}
            if (!isset($thissurvey['urldescrip']) || $thissurvey['urldescrip'] == '' ) {$thissurvey['urldescrip']=$thissurvey['surveyls_url'];}
1439 1440
        
            $staticSurveyInfo[$surveyid][$languagecode]=$thissurvey;
1441
        }
1442
        
1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
    }

    return $thissurvey;
}

/**
* Returns the default email template texts as array
*
* @param mixed $oLanguage Required language translationb object
* @param string $mode Escape mode for the translation function
* @return array
*/
function templateDefaultTexts($oLanguage, $mode='html'){
    return array(
    'admin_detailed_notification_subject'=>$oLanguage->gT("Response submission for survey {SURVEYNAME} with results",$mode),
    'admin_detailed_notification'=>$oLanguage->gT("Hello,\n\nA new response was submitted for your survey '{SURVEYNAME}'.\n\nClick the following link to reload the survey:\n{RELOADURL}\n\nClick the following link to see the individual response:\n{VIEWRESPONSEURL}\n\nClick the following link to edit the individual response:\n{EDITRESPONSEURL}\n\nView statistics by clicking here:\n{STATISTICSURL}\n\n\nThe following answers were given by the participant:\n{ANSWERTABLE}",$mode),
    'admin_detailed_notification_css'=>'<style type="text/css">
    .printouttable {
    margin:1em auto;
    }
    .printouttable th {
    text-align: center;
    }
    .printouttable td {
    border-color: #ddf #ddf #ddf #ddf;
    border-style: solid;
    border-width: 1px;
    padding:0.1em 1em 0.1em 0.5em;
    }

    .printouttable td:first-child {
    font-weight: 700;
    text-align: right;
    padding-right: 5px;
    padding-left: 5px;

    }
    .printouttable .printanswersquestion td{
    background-color:#F7F8FF;
    }

    .printouttable .printanswersquestionhead td{
    text-align: left;
    background-color:#ddf;
    }

    .printouttable .printanswersgroup td{
    text-align: center;
    font-weight:bold;
    padding-top:1em;
    }
    </style>',
    'admin_notification_subject'=>$oLanguage->gT("Response submission for survey {SURVEYNAME}",$mode),
    'admin_notification'=>$oLanguage->gT("Hello,\n\nA new response was submitted for your survey '{SURVEYNAME}'.\n\nClick the following link to reload the survey:\n{RELOADURL}\n\nClick the following link to see the individual response:\n{VIEWRESPONSEURL}\n\nClick the following link to edit the individual response:\n{EDITRESPONSEURL}\n\nView statistics by clicking here:\n{STATISTICSURL}",$mode),
    'confirmation_subject'=>$oLanguage->gT("Confirmation of your participation in our survey"),
    'confirmation'=>$oLanguage->gT("Dear {FIRSTNAME},\n\nthis email is to confirm that you have completed the survey titled {SURVEYNAME} and your response has been saved. Thank you for participating.\n\nIf you have any further questions about this email, please contact {ADMINNAME} on {ADMINEMAIL}.\n\nSincerely,\n\n{ADMINNAME}",$mode),
    'invitation_subject'=>$oLanguage->gT("Invitation to participate in a survey",$mode),
1500
    'invitation'=>$oLanguage->gT("Dear {FIRSTNAME},\n\nyou have been invited to participate in a survey.\n\nThe survey is titled:\n\"{SURVEYNAME}\"\n\n\"{SURVEYDESCRIPTION}\"\n\nTo participate, please click on the link below.\n\nSincerely,\n\n{ADMINNAME} ({ADMINEMAIL})\n\n----------------------------------------------\nClick here to do the survey:\n{SURVEYURL}",$mode)."\n\n".$oLanguage->gT("If you do not want to participate in this survey and don't want to receive any more invitations please click the following link:\n{OPTOUTURL}",$mode)."\n\n".$oLanguage->gT("If you are blacklisted but want to participate in this survey and want to receive invitations please click the following link:\n{OPTINURL}",$mode),
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
    'reminder_subject'=>$oLanguage->gT("Reminder to participate in a survey",$mode),
    'reminder'=>$oLanguage->gT("Dear {FIRSTNAME},\n\nRecently we invited you to participate in a survey.\n\nWe note that you have not yet completed the survey, and wish to remind you that the survey is still available should you wish to take part.\n\nThe survey is titled:\n\"{SURVEYNAME}\"\n\n\"{SURVEYDESCRIPTION}\"\n\nTo participate, please click on the link below.\n\nSincerely,\n\n{ADMINNAME} ({ADMINEMAIL})\n\n----------------------------------------------\nClick here to do the survey:\n{SURVEYURL}",$mode)."\n\n".$oLanguage->gT("If you do not want to participate in this survey and don't want to receive any more invitations please click the following link:\n{OPTOUTURL}",$mode),
    'registration_subject'=>$oLanguage->gT("Survey registration confirmation",$mode),
    'registration'=>$oLanguage->gT("Dear {FIRSTNAME},\n\nYou, or someone using your email address, have registered to participate in an online survey titled {SURVEYNAME}.\n\nTo complete this survey, click on the following URL:\n\n{SURVEYURL}\n\nIf you have any questions about this survey, or if you did not register to participate and believe this email is in error, please contact {ADMINNAME} at {ADMINEMAIL}.",$mode)
    );
}

/**
* Compares two elements from an array (passed by the usort function)
* and returns -1, 0 or 1 depending on the result of the comparison of
* the sort order of the group_order and question_order field
*
* @param mixed $a
* @param mixed $b
* @return int
*/
function groupOrderThenQuestionOrder($a, $b)
{
    if (isset($a['group_order']) && isset($b['group_order']))
    {
        $GroupResult = strnatcasecmp($a['group_order'], $b['group_order']);
    }
    else
    {
        $GroupResult = "";
    }
    if ($GroupResult == 0)
    {
        $TitleResult = strnatcasecmp($a["question_order"], $b["question_order"]);
        return $TitleResult;
    }
    return $GroupResult;
}


function fixSortOrderAnswers($qid,$surveyid=null) //Function rewrites the sortorder for a group of answers
{
    $qid=sanitize_int($qid);
    $baselang = Survey::model()->findByPk($surveyid)->language;

    Answers::model()->updateSortOrder($qid,$baselang);
}

/**
* This function rewrites the sortorder for questions inside the named group
1546
* REMOVED the 2012-08-08 : replaced by Questions::model()->updateQuestionOrder
1547 1548 1549
* @param integer $groupid the group id
* @param integer $surveyid the survey id
*/
1550
/**
1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
function fixSortOrderQuestions($groupid, $surveyid) //Function rewrites the sortorder for questions
{
    $gid = sanitize_int($groupid);
    $surveyid = sanitize_int($surveyid);
    $baselang = Survey::model()->findByPk($surveyid)->language;

    $questions = Questions::model()->findAllByAttributes(array('gid' => $gid, 'sid' => $surveyid, 'language' => $baselang));
    $p = 0;
    foreach ($questions as $question)
    {
        $question->question_order = $p;
        $question->save();
        $p++;
    }
}
1566
*/
1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601

function shiftOrderQuestions($sid,$gid,$shiftvalue) //Function shifts the sortorder for questions
{
    $sid=sanitize_int($sid);
    $gid=sanitize_int($gid);
    $shiftvalue=sanitize_int($shiftvalue);

    $baselang = Survey::model()->findByPk($sid)->language;

    Questions::model()->updateQuestionOrder($gid,$baselang,$shiftvalue);
}

function fixSortOrderGroups($surveyid) //Function rewrites the sortorder for groups
{
    $baselang = Survey::model()->findByPk($surveyid)->language;
    Groups::model()->updateGroupOrder($surveyid,$baselang);
}

function fixMovedQuestionConditions($qid,$oldgid,$newgid) //Function rewrites the cfieldname for a question after group change
{
    $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
}


/**
* This function returns POST/REQUEST vars, for some vars like SID and others they are also sanitized
*
* @param mixed $stringname
* @param mixed $urlParam
*/
1602
function returnGlobal($stringname)
1603
{
1604
    if ($stringname=='sid') // don't read SID from a Cookie
1605
    {
1606 1607 1608 1609 1610 1611
        if (isset($_GET[$stringname])) $urlParam = $_GET[$stringname];
        if (isset($_POST[$stringname])) $urlParam = $_POST[$stringname];
    }
    elseif (isset($_REQUEST[$stringname]))
    {
        $urlParam = $_REQUEST[$stringname];
1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630
    }

    if (isset($urlParam))
    {
        if ($stringname == 'sid' || $stringname == "gid" || $stringname == "oldqid" ||
        $stringname == "qid" || $stringname == "tid" ||
        $stringname == "lid" || $stringname == "ugid"||
        $stringname == "thisstep" || $stringname == "scenario" ||
        $stringname == "cqid" || $stringname == "cid" ||
        $stringname == "qaid" || $stringname == "scid" ||
        $stringname == "loadsecurity")
        {
            return sanitize_int($urlParam);
        }
        elseif ($stringname =="lang" || $stringname =="adminlang")
        {
            return sanitize_languagecode($urlParam);
        }
        elseif ($stringname =="htmleditormode" ||
1631 1632 1633 1634
        $stringname =="subaction" ||
        $stringname =="questionselectormode" ||
        $stringname =="templateeditormode"
        )
1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647
        {
            return sanitize_paranoid_string($urlParam);
        }
        elseif ( $stringname =="cquestions")
        {
            return sanitize_cquestions($urlParam);
        }
        return $urlParam;
    }
    else
    {
        return NULL;
    }
1648

1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723
}


function sendCacheHeaders()
{
    global $embedded;
    if ( $embedded ) return;
    if (!headers_sent())
    {
        header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');  // this line lets IE7 run LimeSurvey in an iframe
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");    // Date in the past
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");  // always modified
        header("Cache-Control: no-store, no-cache, must-revalidate");  // HTTP/1.1
        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Pragma: no-cache");
        header('Content-Type: text/html; charset=utf-8');
    }
}

function getSIDGIDQIDAIDType($fieldcode)
{
    // use simple parsing to get {sid}, {gid}
    // and what may be {qid} or {qid}{aid} combination
    list($fsid, $fgid, $fqid) = explode('X', $fieldcode);
    $fsid=sanitize_int($fsid);
    $fgid=sanitize_int($fgid);
    if (!$fqid) {$fqid=0;}
    $fqid=sanitize_int($fqid);
    // try a true parsing of fieldcode (can separate qid from aid)
    // but fails for type M and type P multiple choice
    // questions because the SESSION fieldcode is combined
    // and we want here to pass only the sidXgidXqid for type M and P
    $fields=arraySearchByKey($fieldcode, createFieldMap($fsid,'full',false,false,getBaseLanguageFromSurveyID($fsid)), "fieldname", 1);

    if (count($fields) != 0)
    {
        $aRef['sid']=$fields['sid'];
        $aRef['gid']=$fields['gid'];
        $aRef['qid']=$fields['qid'];
        $aRef['aid']=$fields['aid'];
        $aRef['type']=$fields['type'];
    }
    else
    {
        // either the fielcode doesn't match a question
        // or it is a type M or P question
        $aRef['sid']=$fsid;
        $aRef['gid']=$fgid;
        $aRef['qid']=sanitize_int($fqid);

        $s_lang = Survey::model()->findByPk($fsid)->language;
        $fieldtoselect = array('type');
        $condition = "qid = ".$fqid." AND language='".$s_lang."'";

        $result = Questions::model()->findAllByAttributes(array('qid' => $fqid, 'language' => $s_lang));

        if ( count($result) == 0 )
        { // question doesn't exist
            return array();
        }
        else
        {   // certainly is type M or P
            foreach ($result as $row)
            {
                $aRef['type']=$row['type'];
            }
        }

    }

    //return array('sid'=>$fsid, "gid"=>$fgid, "qid"=>$fqid);
    return $aRef;
}

/**
1724 1725 1726 1727 1728
* @param type $iSurveyID The Survey ID
* @param type $sFieldCode Field code of the particular field
* @param type $sValue The stored response value
* @param object $oLanguage Initialized limesurvey_lang object for the resulting response data
* @return string
1729
*/
1730
function getExtendedAnswer($iSurveyID, $sFieldCode, $sValue, $oLanguage)
1731
{
1732
    if (is_null($sValue) || $sValue=='') return '';
1733 1734
    $sLanguage = $oLanguage->langcode;
    //Fieldcode used to determine question, $sValue used to match against answer code
1735
    //Returns NULL if question type does not suit
1736
    if (strpos($sFieldCode, "{$iSurveyID}X")===0) //Only check if it looks like a real fieldcode
1737
    {
1738 1739 1740
        $fieldmap = createFieldMap($iSurveyID,'short',false,false,$sLanguage);
        if (isset($fieldmap[$sFieldCode]))
            $fields = $fieldmap[$sFieldCode];
1741 1742 1743 1744 1745 1746 1747
        else
            return false;
        //Find out the question type
        $this_type = $fields['type'];
        switch($this_type)
        {
            case 'D':
1748
                if (trim($sValue)!='')
1749 1750
                {
                    $qidattributes = getQuestionAttributeValues($fields['qid']);
1751 1752
                    $dateformatdetails = getDateFormatDataForQID($qidattributes, $iSurveyID);
                    $sValue=convertDateTimeFormat($sValue,"Y-m-d H:i:s",$dateformatdetails['phpdate']);
1753 1754
                }
                break;
1755 1756 1757
            case 'N':
                if (trim($sValue)!='')
                {
1758
                    if(strpos($sValue,".")!==false)
1759
                    {
1760
                        $sValue=rtrim(rtrim($sValue,"0"),".");
1761
                    }
1762 1763 1764 1765 1766 1767 1768
                    $qidattributes = getQuestionAttributeValues($fields['qid']);
                    if($qidattributes['num_value_int_only'])
                    {
                        $sValue=number_format($sValue, 0, '', '');
                    }
                }
                break;
1769 1770 1771 1772 1773 1774
            case "L":
            case "!":
            case "O":
            case "^":
            case "I":
            case "R":
1775
                $result = Answers::model()->getAnswerFromCode($fields['qid'],$sValue,$sLanguage);
1776 1777 1778 1779
                foreach($result as $row)
                {
                    $this_answer=$row['answer'];
                } // while
1780
                if ($sValue == "-oth-")
1781
                {
1782
                    $this_answer=$oLanguage->gT("Other");
1783 1784 1785 1786 1787
                }
                break;
            case "M":
            case "J":
            case "P":
1788
            switch($sValue)
1789
            {
1790
                case "Y": $this_answer=$oLanguage->gT("Yes"); break;
1791 1792 1793
            }
            break;
            case "Y":
1794
            switch($sValue)
1795
            {
1796 1797 1798
                case "Y": $this_answer=$oLanguage->gT("Yes"); break;
                case "N": $this_answer=$oLanguage->gT("No"); break;
                default: $this_answer=$oLanguage->gT("No answer");
1799 1800 1801
            }
            break;
            case "G":
1802
            switch($sValue)
1803
            {
1804 1805 1806
                case "M": $this_answer=$oLanguage->gT("Male"); break;
                case "F": $this_answer=$oLanguage->gT("Female"); break;
                default: $this_answer=$oLanguage->gT("No answer");
1807 1808 1809
            }
            break;
            case "C":
1810
            switch($sValue)
1811
            {
1812 1813 1814
                case "Y": $this_answer=$oLanguage->gT("Yes"); break;
                case "N": $this_answer=$oLanguage->gT("No"); break;
                case "U": $this_answer=$oLanguage->gT("Uncertain"); break;
1815 1816 1817
            }
            break;
            case "E":
1818
            switch($sValue)
1819
            {
1820 1821 1822
                case "I": $this_answer=$oLanguage->gT("Increase"); break;
                case "D": $this_answer=$oLanguage->gT("Decrease"); break;
                case "S": $this_answer=$oLanguage->gT("Same"); break;
1823 1824 1825 1826 1827
            }
            break;
            case "F":
            case "H":
            case "1":
1828
                $aConditions=array('qid' => $fields['qid'], 'code' => $sValue, 'language' => $sLanguage);
1829 1830
                if (isset($fields['scale_id']))
                {
1831
                    $iScaleID=$fields['scale_id'];
1832
                }
1833 1834 1835 1836
                else
                {
                    $iScaleID=0;
                }
1837
                $result = Answers::model()->getAnswerFromCode($fields['qid'],$sValue,$sLanguage,$iScaleID);
1838 1839 1840 1841
                foreach($result as $row)
                {
                    $this_answer=$row['answer'];
                } // while
1842 1843
                $this_answer=$row['answer'];
                if ($sValue == "-oth-")
1844
                {
1845
                    $this_answer=$oLanguage->gT("Other");
1846 1847 1848
                }
                break;
            case "|": //File upload
1849 1850
                if (substr($sFieldCode, -9) == 'filecount') {
                    $this_answer = $oLanguage->gT("File count");
1851 1852
                } else {
                    //Show the filename, size, title and comment -- no link!
1853 1854
                    $files = json_decode($sValue);
                    $sValue = '';
1855 1856
                    if (is_array($files)) {
                        foreach ($files as $file) {
1857
                            $sValue .= $file->name .
1858 1859 1860
                            ' (' . $file->size . 'KB) ' .
                            strip_tags($file->title) .
                            ' - ' . strip_tags($file->comment) . "<br/>";
1861 1862 1863 1864 1865 1866 1867 1868
                        }
                    }
                }
                break;
            default:
                ;
        } // switch
    }
1869
    switch($sFieldCode)
1870 1871
    {
        case 'submitdate':
1872
            if (trim($sValue)!='')
1873
            {
1874 1875
                $dateformatdetails = getDateFormatDataForQID(array('date_format'=>''), $iSurveyID);
                $sValue=convertDateTimeFormat($sValue,"Y-m-d H:i:s",$dateformatdetails['phpdate'].' H:i:s');
1876 1877 1878
            }
            break;
    }
1879 1880
    if (isset($this_answer))
    {
1881
        return $this_answer." [$sValue]";
1882 1883 1884
    }
    else
    {
1885
        return $sValue;
1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110
    }
}

/*function validateEmailAddress($email)
{
// Create the syntactical validation regular expression
// Validate the syntax

// see http://data.iana.org/TLD/tlds-alpha-by-domain.txt
$maxrootdomainlength = 6;
return ( ! preg_match("/^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,".$maxrootdomainlength."}))$/ix", $email)) ? FALSE : TRUE;
}*/

function validateEmailAddress($email){


    $no_ws_ctl    = "[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]";
    $alpha        = "[\\x41-\\x5a\\x61-\\x7a]";
    $digit        = "[\\x30-\\x39]";
    $cr        = "\\x0d";
    $lf        = "\\x0a";
    $crlf        = "(?:$cr$lf)";


    $obs_char    = "[\\x00-\\x09\\x0b\\x0c\\x0e-\\x7f]";
    $obs_text    = "(?:$lf*$cr*(?:$obs_char$lf*$cr*)*)";
    $text        = "(?:[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f]|$obs_text)";


    $text        = "(?:$lf*$cr*$obs_char$lf*$cr*)";
    $obs_qp        = "(?:\\x5c[\\x00-\\x7f])";
    $quoted_pair    = "(?:\\x5c$text|$obs_qp)";


    $wsp        = "[\\x20\\x09]";
    $obs_fws    = "(?:$wsp+(?:$crlf$wsp+)*)";
    $fws        = "(?:(?:(?:$wsp*$crlf)?$wsp+)|$obs_fws)";
    $ctext        = "(?:$no_ws_ctl|[\\x21-\\x27\\x2A-\\x5b\\x5d-\\x7e])";
    $ccontent    = "(?:$ctext|$quoted_pair)";
    $comment    = "(?:\\x28(?:$fws?$ccontent)*$fws?\\x29)";
    $cfws        = "(?:(?:$fws?$comment)*(?:$fws?$comment|$fws))";


    $outer_ccontent_dull    = "(?:$fws?$ctext|$quoted_pair)";
    $outer_ccontent_nest    = "(?:$fws?$comment)";
    $outer_comment        = "(?:\\x28$outer_ccontent_dull*(?:$outer_ccontent_nest$outer_ccontent_dull*)+$fws?\\x29)";



    $atext        = "(?:$alpha|$digit|[\\x21\\x23-\\x27\\x2a\\x2b\\x2d\\x2f\\x3d\\x3f\\x5e\\x5f\\x60\\x7b-\\x7e])";
    $atext_domain     = "(?:$alpha|$digit|[\\x2b\\x2d\\x5f])";

    $atom        = "(?:$cfws?(?:$atext)+$cfws?)";
    $atom_domain       = "(?:$cfws?(?:$atext_domain)+$cfws?)";


    $qtext        = "(?:$no_ws_ctl|[\\x21\\x23-\\x5b\\x5d-\\x7e])";
    $qcontent    = "(?:$qtext|$quoted_pair)";
    $quoted_string    = "(?:$cfws?\\x22(?:$fws?$qcontent)*$fws?\\x22$cfws?)";


    $quoted_string    = "(?:$cfws?\\x22(?:$fws?$qcontent)+$fws?\\x22$cfws?)";
    $word        = "(?:$atom|$quoted_string)";


    $obs_local_part    = "(?:$word(?:\\x2e$word)*)";


    $obs_domain    = "(?:$atom_domain(?:\\x2e$atom_domain)*)";

    $dot_atom_text     = "(?:$atext+(?:\\x2e$atext+)*)";
    $dot_atom_text_domain    = "(?:$atext_domain+(?:\\x2e$atext_domain+)*)";


    $dot_atom    	   = "(?:$cfws?$dot_atom_text$cfws?)";
    $dot_atom_domain   = "(?:$cfws?$dot_atom_text_domain$cfws?)";


    $dtext        = "(?:$no_ws_ctl|[\\x21-\\x5a\\x5e-\\x7e])";
    $dcontent    = "(?:$dtext|$quoted_pair)";
    $domain_literal    = "(?:$cfws?\\x5b(?:$fws?$dcontent)*$fws?\\x5d$cfws?)";


    $local_part    = "(($dot_atom)|($quoted_string)|($obs_local_part))";
    $domain        = "(($dot_atom_domain)|($domain_literal)|($obs_domain))";
    $addr_spec    = "$local_part\\x40$domain";


    if (strlen($email) > 256) return FALSE;


    $email = stripComments($outer_comment, $email, "(x)");



    if (!preg_match("!^$addr_spec$!", $email, $m)){

        return FALSE;
    }

    $bits = array(
    'local'            => isset($m[1]) ? $m[1] : '',
    'local-atom'        => isset($m[2]) ? $m[2] : '',
    'local-quoted'        => isset($m[3]) ? $m[3] : '',
    'local-obs'        => isset($m[4]) ? $m[4] : '',
    'domain'        => isset($m[5]) ? $m[5] : '',
    'domain-atom'        => isset($m[6]) ? $m[6] : '',
    'domain-literal'    => isset($m[7]) ? $m[7] : '',
    'domain-obs'        => isset($m[8]) ? $m[8] : '',
    );



    $bits['local']    = stripComments($comment, $bits['local']);
    $bits['domain']    = stripComments($comment, $bits['domain']);




    if (strlen($bits['local']) > 64) return FALSE;
    if (strlen($bits['domain']) > 255) return FALSE;



    if (strlen($bits['domain-literal'])){

        $Snum            = "(\d{1,3})";
        $IPv4_address_literal    = "$Snum\.$Snum\.$Snum\.$Snum";

        $IPv6_hex        = "(?:[0-9a-fA-F]{1,4})";

        $IPv6_full        = "IPv6\:$IPv6_hex(:?\:$IPv6_hex){7}";

        $IPv6_comp_part        = "(?:$IPv6_hex(?:\:$IPv6_hex){0,5})?";
        $IPv6_comp        = "IPv6\:($IPv6_comp_part\:\:$IPv6_comp_part)";

        $IPv6v4_full        = "IPv6\:$IPv6_hex(?:\:$IPv6_hex){5}\:$IPv4_address_literal";

        $IPv6v4_comp_part    = "$IPv6_hex(?:\:$IPv6_hex){0,3}";
        $IPv6v4_comp        = "IPv6\:((?:$IPv6v4_comp_part)?\:\:(?:$IPv6v4_comp_part\:)?)$IPv4_address_literal";



        if (preg_match("!^\[$IPv4_address_literal\]$!", $bits['domain'], $m)){

            if (intval($m[1]) > 255) return FALSE;
            if (intval($m[2]) > 255) return FALSE;
            if (intval($m[3]) > 255) return FALSE;
            if (intval($m[4]) > 255) return FALSE;

        }else{


            while (1){

                if (preg_match("!^\[$IPv6_full\]$!", $bits['domain'])){
                    break;
                }

                if (preg_match("!^\[$IPv6_comp\]$!", $bits['domain'], $m)){
                    list($a, $b) = explode('::', $m[1]);
                    $folded = (strlen($a) && strlen($b)) ? "$a:$b" : "$a$b";
                    $groups = explode(':', $folded);
                    if (count($groups) > 6) return FALSE;
                    break;
                }

                if (preg_match("!^\[$IPv6v4_full\]$!", $bits['domain'], $m)){

                    if (intval($m[1]) > 255) return FALSE;
                    if (intval($m[2]) > 255) return FALSE;
                    if (intval($m[3]) > 255) return FALSE;
                    if (intval($m[4]) > 255) return FALSE;
                    break;
                }

                if (preg_match("!^\[$IPv6v4_comp\]$!", $bits['domain'], $m)){
                    list($a, $b) = explode('::', $m[1]);
                    $b = substr($b, 0, -1); # remove the trailing colon before the IPv4 address
                    $folded = (strlen($a) && strlen($b)) ? "$a:$b" : "$a$b";
                    $groups = explode(':', $folded);
                    if (count($groups) > 4) return FALSE;
                    break;
                }

                return FALSE;
            }
        }
    }else{


        $labels = explode('.', $bits['domain']);


        if (count($labels) == 1) return FALSE;


        foreach ($labels as $label){

            if (strlen($label) > 63) return FALSE;
            if (substr($label, 0, 1) == '-') return FALSE;
            if (substr($label, -1) == '-') return FALSE;
        }

        if (preg_match('!^[0-9]+$!', array_pop($labels))) return FALSE;
    }


    return TRUE;
}

##################################################################################

function stripComments($comment, $email, $replace=''){

    while (1){
        $new = preg_replace("!$comment!", $replace, $email);
        if (strlen($new) == strlen($email)){
            return $email;
        }
        $email = $new;
    }
}


2111
function validateTemplateDir($sTemplateName)
2112 2113 2114
{
    $usertemplaterootdir = Yii::app()->getConfig('usertemplaterootdir');
    $standardtemplaterootdir = Yii::app()->getConfig('standardtemplaterootdir');
2115 2116
    $sDefaultTemplate = Yii::app()->getConfig('defaulttemplate');
    if (is_dir("$usertemplaterootdir/{$sTemplateName}/"))
2117
    {
2118
        return $sTemplateName;
2119