mirror of
https://github.com/YunoHost-Apps/limesurvey_ynh.git
synced 2024-09-03 19:36:32 +02:00
[enh] Restart with a new repo (the older was a fork of LimeSurvey repo)
This commit is contained in:
commit
b98da2f756
8060 changed files with 1631386 additions and 0 deletions
19
.gitattributes
vendored
Normal file
19
.gitattributes
vendored
Normal file
|
@ -0,0 +1,19 @@
|
|||
# Set default behaviour, in case users don't have core.autocrlf set.
|
||||
* text=auto
|
||||
|
||||
# Declare files that will always have LF line endings on checkout.
|
||||
*.php text eol=lf
|
||||
*.css text eol=lf
|
||||
*.js text eol=lf
|
||||
*.pstpl text eol=lf
|
||||
*.html text eol=lf
|
||||
*.sql text eol=lf
|
||||
*.txt text eol=lf
|
||||
*.lss text eol=lf
|
||||
|
||||
# Denote all files that are truly binary and should not be modified.
|
||||
*.jpg binary
|
||||
*.png binary
|
||||
*.gif binary
|
||||
*.ico binary
|
||||
*.mo binary
|
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
|
8
README.md
Normal file
8
README.md
Normal file
|
@ -0,0 +1,8 @@
|
|||
limesurvey_ynh
|
||||
===============
|
||||
|
||||
LimeSurvey for YunoHost
|
||||
|
||||
LimeSurvey is used to create advanced poll.
|
||||
|
||||
http://www.limesurvey.org/
|
61
conf/config.php.template
Normal file
61
conf/config.php.template
Normal file
|
@ -0,0 +1,61 @@
|
|||
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
|
||||
/*
|
||||
| -------------------------------------------------------------------
|
||||
| DATABASE CONNECTIVITY SETTINGS
|
||||
| -------------------------------------------------------------------
|
||||
| This file will contain the settings needed to access your database.
|
||||
|
|
||||
| For complete instructions please consult the 'Database Connection'
|
||||
| page of the User Guide.
|
||||
|
|
||||
| -------------------------------------------------------------------
|
||||
| EXPLANATION OF VARIABLES
|
||||
| -------------------------------------------------------------------
|
||||
|
|
||||
| 'connectionString' Hostname, database, port and database type for
|
||||
| the connection. Driver example: mysql. Currently supported:
|
||||
| mysql, pgsql, mssql, sqlite, oci
|
||||
| 'username' The username used to connect to the database
|
||||
| 'password' The password used to connect to the database
|
||||
| 'tablePrefix' You can add an optional prefix, which will be added
|
||||
| to the table name when using the Active Record class
|
||||
|
|
||||
*/
|
||||
return array(
|
||||
'components' => array(
|
||||
'db' => array(
|
||||
'connectionString' => 'mysql:host=localhost;port=3306;dbname=yunobase;',
|
||||
'emulatePrepare' => true,
|
||||
'username' => 'yunouser',
|
||||
'password' => 'yunopass',
|
||||
'charset' => 'utf8',
|
||||
'tablePrefix' => 'prefix_',
|
||||
),
|
||||
|
||||
// Uncomment the following line if you need table-based sessions
|
||||
// 'session' => array (
|
||||
// 'class' => 'system.web.CDbHttpSession',
|
||||
// 'connectionID' => 'db',
|
||||
// 'sessionTableName' => '{{sessions}}',
|
||||
// ),
|
||||
|
||||
'urlManager' => array(
|
||||
'urlFormat' => 'get',
|
||||
'rules' => require('routes.php'),
|
||||
'showScriptName' => true,
|
||||
),
|
||||
|
||||
),
|
||||
// Use the following config variable to set modified optional settings copied from config-defaults.php
|
||||
'config'=>array(
|
||||
// debug: Set this to 1 if you are looking for errors. If you still get no errors after enabling this
|
||||
// then please check your error-logs - either in your hosting provider admin panel or in some /logs directory
|
||||
// on your webspace.
|
||||
// LimeSurvey developers: Set this to 2 to additionally display STRICT PHP error messages and get full access to standard templates
|
||||
'debug'=>0,
|
||||
'debugsql'=>0, // Set this to 1 to enanble sql logging, only active when debug = 2
|
||||
'enableLdap'=>true
|
||||
)
|
||||
);
|
||||
/* End of file config.php */
|
||||
/* Location: ./application/config/config.php */
|
144
conf/ldap.php
Normal file
144
conf/ldap.php
Normal file
|
@ -0,0 +1,144 @@
|
|||
<?php
|
||||
/*
|
||||
* 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.
|
||||
*
|
||||
*/
|
||||
|
||||
/*********** LDAP Parameters and Functions ***********************
|
||||
*
|
||||
* - First define your ldap servers and remember the serverId
|
||||
* - Then define your ldap_query and 'attach' it to the serverId
|
||||
******************************************************************/
|
||||
|
||||
/*********************************************/
|
||||
/* LDAP servers */
|
||||
/*********************************************/
|
||||
|
||||
$serverId=0;
|
||||
// Define the server DNS name or IP Address
|
||||
// If encryption is enabled, make sure the name given here
|
||||
// corresponds to the certificate's identity
|
||||
$ldap_server[$serverId]['server'] = "localhost";
|
||||
|
||||
// Define the TCP port on which the LDAP server is listenning
|
||||
// This should be 389 for standard LDAP servers
|
||||
// or 636 for standard LDAPS connections
|
||||
$ldap_server[$serverId]['port'] = "389";
|
||||
|
||||
// Define the ldap protocol to use
|
||||
// 'ldapv2' and 'ldapv3' are supported
|
||||
$ldap_server[$serverId]['protoversion'] = "ldapv3";
|
||||
|
||||
// Define the encryption method to use
|
||||
// 'ldaps' is supported for 'ldapv2' servers
|
||||
// 'start-tls' is supproted for 'ldapv3' servers
|
||||
// 'none' is supproted for no encryption at all
|
||||
// Don't forget to setup your CA's certificate in
|
||||
// the openldap ldap.conf file
|
||||
$ldap_server[$serverId]['encrypt'] = "none";
|
||||
|
||||
// Define the referral option
|
||||
// 'false' is recommended for ActiveDirectory servers
|
||||
$ldap_server[$serverId]['referrals'] = false;
|
||||
|
||||
// Define the encoding used by the Ldap directory
|
||||
// You may omit this parameter (let it commented out)
|
||||
// as the default value, 'utf-8', should work for most installations.
|
||||
// However, Active Directory in West Europe may use 'cp850'.
|
||||
// $ldap_server[$serverId]['encoding'] = 'utf-8';
|
||||
|
||||
// Define the authentication used to bind to the directory
|
||||
// We currently support simple authentication
|
||||
// If anonymous bind must be performed, comment the following two lines
|
||||
// Note that Active Directory (AD) usually requires authentication before
|
||||
// you are authorized to read its content. Remeber as well that user's DN
|
||||
// in AD are in the form of CN=username,CN=Users,DC=WindowsDomainName,DC=mycompany,DC=org
|
||||
//
|
||||
$ldap_server[$serverId]['binddn'] = "uid=mybinduser,dc=yunohost,dc=org";
|
||||
$ldap_server[$serverId]['bindpw'] = "AsecretPassword";
|
||||
|
||||
/********* Copy for more definitions *****
|
||||
$serverId++;
|
||||
$ldap_server[$serverId]['server'] = "ldap.mycompany.org";
|
||||
$ldap_server[$serverId]['port'] = "389";
|
||||
$ldap_server[$serverId]['protoversion'] = "ldapv3";
|
||||
$ldap_server[$serverId]['encrypt'] = "start-tls";
|
||||
$ldap_server[$serverId]['referrals'] = false;
|
||||
$ldap_server[$serverId]['binddn'] = "uid=mybinduser,dc=mycompany,dc=org";
|
||||
$ldap_server[$serverId]['bindpw'] = "AsecretPassword";
|
||||
*****************************************/
|
||||
|
||||
/**********************************************************************/
|
||||
/* Predefined Queries for Token Imports */
|
||||
/* */
|
||||
/* This sample query definition is just an fake template: do not */
|
||||
/* expect it to do something intelligent on your directory */
|
||||
/* Instead have a look at the online documentation: */
|
||||
/* - Section Installation, paragraph LDAP_Settings */
|
||||
/* And for Active Directory tips: */
|
||||
/* - Section Installation FAQ, paragraph */
|
||||
/* How_do_I_configure_LDAP_settings_to_work_with_Active_Directory_ */
|
||||
/**********************************************************************/
|
||||
|
||||
$query_id=0;
|
||||
|
||||
// First define the serverId on which you want to run the query
|
||||
$ldap_queries[$query_id]['ldapServerId'] = 0;
|
||||
|
||||
// Give a name that will appear on the user interface
|
||||
$ldap_queries[$query_id]['name'] = 'Users';
|
||||
|
||||
// Define the ldap base used for user searches
|
||||
$ldap_queries[$query_id]['userbase'] = 'ou=users,dc=yunohost,dc=org';
|
||||
|
||||
// Define the user filter to apply
|
||||
// Must begin with '(' and end with ')'
|
||||
// Note that for AD, checking the 'active' status of a user is done with the following filter:
|
||||
// "(&(objectCategory=Person)(objectClass=user)(!(userAccountControl=514)))"
|
||||
$ldap_queries[$query_id]['userfilter'] = '(&(objectClass=inetOrgPerson))';
|
||||
|
||||
// Define how deep under the userbase you want to search
|
||||
// 'sub' means: search on the entire subtree
|
||||
// 'one' means: only search 1 level under the userbase
|
||||
// 'base' means: only search the userbase DN entry
|
||||
$ldap_queries[$query_id]['userscope'] = 'sub';
|
||||
|
||||
// Define the user's attribute that provides the firstname
|
||||
// do not use capital letters in the attribute name
|
||||
// for instance use 'givenname' and not 'givenName'
|
||||
$ldap_queries[$query_id]['firstname_attr'] = 'givenName';
|
||||
|
||||
// Give the user's attribute that provides the lastname
|
||||
// do not use capital letters in the attribute name
|
||||
$ldap_queries[$query_id]['lastname_attr'] = 'sn';
|
||||
|
||||
// Give the user's attribute that provides the email address
|
||||
// do not use capital letters in the attribute name
|
||||
// If multivalued, only the first entry is read
|
||||
$ldap_queries[$query_id]['email_attr'] = 'mail';
|
||||
|
||||
|
||||
// Optionnally give the user's attributes that provides the
|
||||
// token, language, attr1 and attr2 piece of information
|
||||
// do not use capital letters in the attribute name
|
||||
// if unused, leave empty or comment the lines
|
||||
$ldap_queries[$query_id]['token_attr'] = ''; // Leave empty for Auto Token generation bu phpsv
|
||||
$ldap_queries[$query_id]['language'] = '';
|
||||
$ldap_queries[$query_id]['attr1'] = '';
|
||||
$ldap_queries[$query_id]['attr2'] = '';
|
||||
|
||||
|
||||
|
||||
|
||||
//DO NOT CHANGE BELOW HERE --------------------
|
||||
|
||||
return array('ldap_server' => $ldap_server, 'ldap_queries' => $ldap_queries);
|
||||
?>
|
26
conf/mysql_data.sql
Normal file
26
conf/mysql_data.sql
Normal file
|
@ -0,0 +1,26 @@
|
|||
INSERT INTO `prefix_plugins` (`id`, `name`, `active`) VALUES (1, 'Authdb', 1);
|
||||
INSERT INTO `prefix_plugins` (`id`, `name`, `active`) VALUES (3, 'AuthLDAP', 1);
|
||||
INSERT INTO `prefix_plugins` (`id`, `name`, `active`) VALUES (7, 'Authwebserver', 0);
|
||||
|
||||
INSERT INTO `prefix_permissions` (`id`, `entity`, `entity_id`, `uid`, `permission`, `create_p`, `read_p`, `update_p`, `delete_p`, `import_p`, `export_p`) VALUES (1, 'global', 0, 1, 'superadmin', 0, 1, 0, 0, 0, 0);
|
||||
INSERT INTO `prefix_users` (`uid`, `users_name`, `password`, `full_name`, `parent_id`, `lang`, `email`, `htmleditormode`, `templateeditormode`, `questionselectormode`, `one_time_pw`, `dateformat`, `created`, `modified`) VALUES (1, 'yunoadmin', 0x35653838343839386461323830343731353164306535366638646336323932373733363033643064366161626264643632613131656637323164313534326438, 'Administrator', 0, 'fr', '', 'default', 'default', 'default', NULL, 1, '2014-07-11 22:51:35', NULL);
|
||||
|
||||
INSERT INTO `prefix_plugin_settings` (`id`, `plugin_id`, `model`, `model_id`, `key`, `value`) VALUES
|
||||
(1, 3, NULL, NULL, 'server', '"localhost"'),
|
||||
(2, 3, NULL, NULL, 'ldapport', '"389"'),
|
||||
(3, 3, NULL, NULL, 'ldapversion', '"3"'),
|
||||
(4, 3, NULL, NULL, 'ldapoptreferrals', '"1"'),
|
||||
(5, 3, NULL, NULL, 'ldaptls', '"0"'),
|
||||
(6, 3, NULL, NULL, 'ldapmode', '"searchandbind"'),
|
||||
(7, 3, NULL, NULL, 'userprefix', 'null'),
|
||||
(8, 3, NULL, NULL, 'domainsuffix', 'null'),
|
||||
(9, 3, NULL, NULL, 'searchuserattribute', '"uid"'),
|
||||
(10, 3, NULL, NULL, 'usersearchbase', '"ou=users,dc=yunohost,dc=org"'),
|
||||
(11, 3, NULL, NULL, 'extrauserfilter', '""'),
|
||||
(12, 3, NULL, NULL, 'binddn', '""'),
|
||||
(13, 3, NULL, NULL, 'bindpwd', '""'),
|
||||
(14, 3, NULL, NULL, 'is_default', '1');
|
||||
|
||||
INSERT INTO `prefix_plugin_settings` (`id`, `plugin_id`, `model`, `model_id`, `key`, `value`) VALUES
|
||||
(15, 7, NULL, NULL, 'strip_domain', 'null'),
|
||||
(16, 7, NULL, NULL, 'serverkey', '"REMOTE_USER"');
|
20
conf/nginx.conf
Normal file
20
conf/nginx.conf
Normal file
|
@ -0,0 +1,20 @@
|
|||
location PATHTOCHANGE {
|
||||
alias ALIASTOCHANGE;
|
||||
index index.php;
|
||||
try_files $uri $uri/ /index.php;
|
||||
location ~ [^/]\.php(/|$) {
|
||||
fastcgi_split_path_info ^(.+?\.php)(/.*)$;
|
||||
fastcgi_pass unix:/var/run/php5-fpm.sock;
|
||||
include fastcgi_params;
|
||||
fastcgi_param REMOTE_USER $remote_user;
|
||||
fastcgi_param PATH_INFO $fastcgi_path_info;
|
||||
fastcgi_param HTTPS on;
|
||||
fastcgi_param SCRIPT_FILENAME $request_filename;
|
||||
}
|
||||
# Include SSOWAT user panel.
|
||||
include conf.d/yunohost_panel.conf.inc;
|
||||
}
|
||||
|
||||
location ~ ^PATHTOCHANGE/(data|config|\.ht|db_structure\.xml|README) {
|
||||
deny all;
|
||||
}
|
5
hooks/post_user_create
Normal file
5
hooks/post_user_create
Normal file
|
@ -0,0 +1,5 @@
|
|||
#!/bin/bash
|
||||
|
||||
db_pwd=$(sudo cat /etc/yunohost/mysql)
|
||||
user=$1
|
||||
mysql -u root -p$db_pwd limesurvey -e "INSERT INTO prefix_users (users_name) VALUES ('$user');INSERT INTO prefix_permissions (entity,entity_id,uid,permission,create_p,read_p,update_p,delete_p,import_p,export_p) SELECT 'global',0,uid,'surveys',1,1,1,1,0,1 FROM prefix_users WHERE users_name='$user'"
|
55
manifest.json
Normal file
55
manifest.json
Normal file
|
@ -0,0 +1,55 @@
|
|||
{
|
||||
"name": "LimeSurvey",
|
||||
"id": "limesurvey",
|
||||
"description": {
|
||||
"en": "LimeSurvey is used to create advanced poll.",
|
||||
"fr": "LimeSurvey est un outil de création et diffusion de sondage en ligne."
|
||||
},
|
||||
"license": "GPLv2",
|
||||
"developer": {
|
||||
"name": "zamentur",
|
||||
"email": "valentin@grimaud.me",
|
||||
"url": "http://www.limesurvey.org/"
|
||||
},
|
||||
"multi_instance": "true",
|
||||
"arguments": {
|
||||
"install" : [
|
||||
{
|
||||
"name": "domain",
|
||||
"ask": {
|
||||
"en": "Choose a domain for LimeSurvey",
|
||||
"fr": "Choisissez un nom de domaine pour LimeSurvey"
|
||||
},
|
||||
"example": "domain.org"
|
||||
},
|
||||
{
|
||||
"name": "path",
|
||||
"ask": {
|
||||
"en": "Choose a path for LimeSurvey",
|
||||
"fr": "Choisissez l'adresse pour LimeSurvey"
|
||||
},
|
||||
"example": "/poll",
|
||||
"default": "/poll"
|
||||
},
|
||||
{
|
||||
"name": "admin",
|
||||
"ask": {
|
||||
"en": "Choose the LimeSurvey administrator (must be an existing YunoHost user)",
|
||||
"fr": "Choisissez l'administrateur de LimeSurvey (doit être un utilisateur YunoHost)"
|
||||
},
|
||||
"example": "homer"
|
||||
},
|
||||
{
|
||||
"name": "language",
|
||||
"ask": {
|
||||
"en": "Choose the default language of this LimeSurvey",
|
||||
"fr": "Choisissez la langue par défault de LimeSurvey"
|
||||
},
|
||||
"choices": ["en_GB", "fr_FR","es_ES", "de_DE"],
|
||||
"default": "en_GB"
|
||||
}
|
||||
|
||||
|
||||
]
|
||||
}
|
||||
}
|
0
nbproject/private/config.properties
Normal file
0
nbproject/private/config.properties
Normal file
8
nbproject/private/private.properties
Normal file
8
nbproject/private/private.properties
Normal file
|
@ -0,0 +1,8 @@
|
|||
copy.src.files=false
|
||||
copy.src.target=/var/www/limesurvey_ynh
|
||||
index.file=
|
||||
remote.connection=grimaud.me-aac780
|
||||
remote.directory=/limesurvey__1
|
||||
remote.upload=ON_RUN
|
||||
run.as=REMOTE
|
||||
url=https://grimaud.me/sondage/
|
7
nbproject/project.properties
Normal file
7
nbproject/project.properties
Normal file
|
@ -0,0 +1,7 @@
|
|||
include.path=${php.global.include.path}
|
||||
php.version=PHP_5
|
||||
source.encoding=UTF-8
|
||||
src.dir=.
|
||||
tags.asp=false
|
||||
tags.short=true
|
||||
web.root=.
|
9
nbproject/project.xml
Normal file
9
nbproject/project.xml
Normal file
|
@ -0,0 +1,9 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://www.netbeans.org/ns/project/1">
|
||||
<type>org.netbeans.modules.php.project</type>
|
||||
<configuration>
|
||||
<data xmlns="http://www.netbeans.org/ns/php-project/1">
|
||||
<name>limesurvey_ynh</name>
|
||||
</data>
|
||||
</configuration>
|
||||
</project>
|
70
scripts/install
Executable file
70
scripts/install
Executable file
|
@ -0,0 +1,70 @@
|
|||
#!/bin/bash
|
||||
|
||||
app="limesurvey"
|
||||
|
||||
# Retrieve arguments
|
||||
domain=$1
|
||||
path=$2
|
||||
admin=$3
|
||||
language=$4
|
||||
|
||||
# Check if admin exists
|
||||
sudo yunohost user list --json | grep -q "\"username\": \"$admin\""
|
||||
if [[ ! $? -eq 0 ]]; then
|
||||
echo "Wrong admin"
|
||||
exit 1
|
||||
fi
|
||||
sudo yunohost app setting $app admin -v $admin
|
||||
sudo yunohost app setting $app language -v $language
|
||||
|
||||
# Check domain/path availability
|
||||
sudo yunohost app checkurl $domain$path -a $app
|
||||
if [[ ! $? -eq 0 ]]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Generate random password
|
||||
db_pwd=$(dd if=/dev/urandom bs=1 count=200 2> /dev/null | tr -c -d '[A-Za-z0-9]' | sed -n 's/\(.\{24\}\).*/\1/p')
|
||||
|
||||
# Use 'opensondage' as database name and user
|
||||
db_user=$app
|
||||
|
||||
# Initialize database and store mysql password for upgrade
|
||||
sudo yunohost app initdb $db_user -p $db_pwd
|
||||
sudo yunohost app setting $app mysqlpwd -v $db_pwd
|
||||
|
||||
# Copy files to the right place
|
||||
final_path=/var/www/$app
|
||||
sudo mkdir -p $final_path
|
||||
sudo cp -a ../sources/* $final_path
|
||||
|
||||
|
||||
# Db installation
|
||||
mysql -u $db_user -p$db_pwd $db_user < ../sources/installer/sql/create-mysql.sql
|
||||
sudo sed -i "s/yunoadmin/$admin/g" ../conf/mysql_data.sql
|
||||
mysql -u $db_user -p$db_pwd $db_user < ../conf/mysql_data.sql
|
||||
|
||||
|
||||
sudo cp ../conf/config.php.template $final_path/application/config/config.php
|
||||
|
||||
sudo sed -i "s/yunouser/$db_user/g" $final_path/application/config/config.php
|
||||
sudo sed -i "s/yunopass/$db_pwd/g" $final_path/application/config/config.php
|
||||
sudo sed -i "s/yunobase/$db_user/g" $final_path/application/config/config.php
|
||||
|
||||
# Set permissions
|
||||
sudo chown -R www-data: $final_path
|
||||
sudo chmod u+w $final_path/tmp
|
||||
sudo chmod u+w $final_path/upload
|
||||
sudo chmod u+w $final_path/application/config/
|
||||
|
||||
sudo yunohost app addaccess $app -u $admin
|
||||
|
||||
# Modify Nginx configuration file and copy it to Nginx conf directory
|
||||
sed -i "s@PATHTOCHANGE@$path@g" ../conf/nginx.conf
|
||||
sed -i "s@ALIASTOCHANGE@$final_path/@g" ../conf/nginx.conf
|
||||
sudo cp ../conf/nginx.conf /etc/nginx/conf.d/$domain.d/$app.conf
|
||||
# Reload Nginx and regenerate SSOwat conf
|
||||
sudo service nginx reload
|
||||
sudo yunohost app setting $app skipped_uris -v "/"
|
||||
#sudo yunohost app setting $app protected_uris -v "/index.php?r=admin,/index.php?r=plugins,/scripts"
|
||||
sudo yunohost app ssowatconf
|
10
scripts/remove
Executable file
10
scripts/remove
Executable file
|
@ -0,0 +1,10 @@
|
|||
#!/bin/bash
|
||||
app="limesurvey"
|
||||
db_user=$app
|
||||
db_name=$app
|
||||
root_pwd=$(sudo cat /etc/yunohost/mysql)
|
||||
domain=$(sudo yunohost app setting $app domain)
|
||||
|
||||
mysql -u root -p$root_pwd -e "DROP DATABASE $db_name ; DROP USER $db_user@localhost ;"
|
||||
sudo rm -rf /var/www/$app
|
||||
sudo rm -f /etc/nginx/conf.d/$domain.d/$app.conf
|
3
scripts/upgrade
Normal file
3
scripts/upgrade
Normal file
|
@ -0,0 +1,3 @@
|
|||
#!/bin/bash
|
||||
|
||||
|
11
sources/.htaccess
Normal file
11
sources/.htaccess
Normal file
|
@ -0,0 +1,11 @@
|
|||
<IfModule mod_rewrite.c>
|
||||
RewriteEngine on
|
||||
|
||||
# if a directory or a file exists, use it directly
|
||||
RewriteCond %{REQUEST_FILENAME} !-f
|
||||
|
||||
# otherwise forward it to index.php
|
||||
RewriteRule . index.php
|
||||
</IfModule>
|
||||
# General setting to properly handle LimeSurvey paths
|
||||
# AcceptPathInfo on
|
11
sources/.scrutinizer.yml
Normal file
11
sources/.scrutinizer.yml
Normal file
|
@ -0,0 +1,11 @@
|
|||
filter:
|
||||
excluded_paths: [framework/*, locale/*, docs/*, fonts/*, third_party/*, application/third_party/*, images/*, styles/*, styles-public/*, templates/*, themes/*, tmp/*, upload/*]
|
||||
paths: [application/*]
|
||||
tools:
|
||||
php_code_sniffer:
|
||||
config:
|
||||
standard: "PSR1"
|
||||
php_pdepend:
|
||||
command: pdepend
|
||||
php_cs_fixer:
|
||||
config: { level: psr1 }
|
1
sources/README
Normal file
1
sources/README
Normal file
|
@ -0,0 +1 @@
|
|||
Please check out the /docs directory for further information.
|
2
sources/admin/admin.php
Normal file
2
sources/admin/admin.php
Normal file
|
@ -0,0 +1,2 @@
|
|||
<?php
|
||||
include 'index.php';
|
31
sources/admin/index.php
Normal file
31
sources/admin/index.php
Normal file
|
@ -0,0 +1,31 @@
|
|||
<?php
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
$config_folder = dirname(__FILE__) . '/../application/config/';
|
||||
$config_file = $config_folder . 'config.php';
|
||||
if (!file_exists($config_file))
|
||||
{
|
||||
$config_file = $config_folder . 'config-sample-mysql.php';
|
||||
}
|
||||
define('BASEPATH', dirname(__FILE__) . '/..'); // To prevent direct access not allowed
|
||||
$config = require($config_file);
|
||||
|
||||
$urlStyle = $config['components']['urlManager']['urlFormat'];
|
||||
|
||||
// Simple redirect to still have the old /admin URL
|
||||
if ($urlStyle == 'path') {
|
||||
header( 'Location: ../index.php/admin' );
|
||||
} else {
|
||||
// For IIS use get style
|
||||
header( 'Location: ../index.php?r=admin' );
|
||||
}
|
1
sources/application/.htaccess
Normal file
1
sources/application/.htaccess
Normal file
|
@ -0,0 +1 @@
|
|||
Deny from all
|
175
sources/application/commands/InstallCommand.php
Normal file
175
sources/application/commands/InstallCommand.php
Normal file
|
@ -0,0 +1,175 @@
|
|||
<?php
|
||||
/*
|
||||
* LimeSurvey (tm)
|
||||
* Copyright (C) 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.
|
||||
*
|
||||
*/
|
||||
class InstallCommand extends CConsoleCommand
|
||||
{
|
||||
/**
|
||||
*
|
||||
* @var CDbConnection
|
||||
*/
|
||||
public $connection;
|
||||
|
||||
public function run($sArgument)
|
||||
{
|
||||
if (!isset($sArgument) || !isset($sArgument[0]) || !isset($sArgument[1]) || !isset($sArgument[2]) || !isset($sArgument[3])) die('You have to set admin/password/full name and email address on the command line like this: php starter.php adminname mypassword fullname emailaddress');
|
||||
Yii::import('application.helpers.common_helper', true);
|
||||
|
||||
try
|
||||
{
|
||||
$this->connection = App()->getDb();
|
||||
$this->connection->active=true;
|
||||
}
|
||||
catch(CDbException $e){
|
||||
$this->createDatabase();
|
||||
};
|
||||
|
||||
$this->connection->charset = 'utf8';
|
||||
switch ($this->connection->driverName) {
|
||||
case 'mysql':
|
||||
case 'mysqli':
|
||||
$this->connection->createCommand("ALTER DATABASE ". $this->connection->quoteTableName($this->getDBConnectionStringProperty('dbname')) ." DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;")->execute();
|
||||
$sql_file = 'mysql';
|
||||
break;
|
||||
case 'pgsql':
|
||||
if (version_compare($this->connection->getServerVersion(),'9','>=')) {
|
||||
$this->connection->createCommand("ALTER DATABASE ". $this->connection->quoteTableName($this->getDBConnectionStringProperty('dbname')) ." SET bytea_output='escape';")->execute();
|
||||
}
|
||||
$sql_file = 'pgsql';
|
||||
break;
|
||||
case 'dblib':
|
||||
case 'mssql':
|
||||
case 'sqlsrv':
|
||||
$sql_file = 'mssql';
|
||||
break;
|
||||
default:
|
||||
throw new Exception(sprintf('Unkown database type "%s".', $this->connection->driverName));
|
||||
}
|
||||
$this->_executeSQLFile(dirname(Yii::app()->basePath).'/installer/sql/create-'.$sql_file.'.sql');
|
||||
$this->connection->createCommand()->insert($this->connection->tablePrefix.'users', array(
|
||||
'users_name'=>$sArgument[0],
|
||||
'password'=>hash('sha256',$sArgument[1]),
|
||||
'full_name'=>$sArgument[2],
|
||||
'parent_id'=>0,
|
||||
'lang'=>'auto',
|
||||
'email'=>$sArgument[3]
|
||||
));
|
||||
$this->connection->createCommand()->insert($this->connection->tablePrefix.'permissions', array(
|
||||
'entity'=>'global',
|
||||
'entity_id'=>0,
|
||||
'uid'=>1,
|
||||
'permission'=>'superadmin',
|
||||
'create_p'=>0,
|
||||
'read_p'=>1,
|
||||
'update_p'=>0,
|
||||
'delete_p'=>0,
|
||||
'import_p'=>0,
|
||||
'export_p'=>0
|
||||
));
|
||||
}
|
||||
|
||||
function _executeSQLFile($sFileName)
|
||||
{
|
||||
echo $sFileName;
|
||||
$aMessages = array();
|
||||
$sCommand = '';
|
||||
|
||||
if (!is_readable($sFileName)) {
|
||||
return false;
|
||||
} else {
|
||||
$aLines = file($sFileName);
|
||||
}
|
||||
foreach ($aLines as $sLine) {
|
||||
$sLine = rtrim($sLine);
|
||||
$iLineLength = strlen($sLine);
|
||||
|
||||
if ($iLineLength && $sLine[0] != '#' && substr($sLine,0,2) != '--') {
|
||||
if (substr($sLine, $iLineLength-1, 1) == ';') {
|
||||
$line = substr($sLine, 0, $iLineLength-1);
|
||||
$sCommand .= $sLine;
|
||||
$sCommand = str_replace('prefix_', $this->connection->tablePrefix, $sCommand); // Table prefixes
|
||||
|
||||
try {
|
||||
$this->connection->createCommand($sCommand)->execute();
|
||||
} catch(Exception $e) {
|
||||
$aMessages[] = "Executing: ".$sCommand." failed! Reason: ".$e;
|
||||
}
|
||||
|
||||
$sCommand = '';
|
||||
} else {
|
||||
$sCommand .= $sLine;
|
||||
}
|
||||
}
|
||||
}
|
||||
return $aMessages;
|
||||
|
||||
|
||||
}
|
||||
|
||||
function getDBConnectionStringProperty($sProperty, $connectionString = null)
|
||||
{
|
||||
if (!isset($connectionString))
|
||||
{
|
||||
$connectionString = $this->connection->connectionString;
|
||||
}
|
||||
// Yii doesn't give us a good way to get the database name
|
||||
if ( preg_match('/'.$sProperty.'=([^;]*)/', $connectionString, $aMatches) == 1 ) {
|
||||
return $aMatches[1];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
protected function createDatabase()
|
||||
{
|
||||
$connectionString = $this->connection->connectionString;
|
||||
$this->connection->connectionString = preg_replace('/dbname=([^;]*)/', '', $connectionString);
|
||||
try
|
||||
{
|
||||
$this->connection->active=true;
|
||||
}
|
||||
catch(Exception $e){
|
||||
throw new CException("Invalid access data. Check your config.php db access data");
|
||||
}
|
||||
|
||||
$sDatabaseName= $this->getDBConnectionStringProperty('dbname', $connectionString);
|
||||
try {
|
||||
switch ($this->connection->driverName)
|
||||
{
|
||||
case 'mysqli':
|
||||
case 'mysql':
|
||||
$this->connection->createCommand("CREATE DATABASE `$sDatabaseName` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci")->execute();
|
||||
break;
|
||||
case 'dblib':
|
||||
case 'mssql':
|
||||
case 'odbc':
|
||||
$this->connection->createCommand("CREATE DATABASE [$sDatabaseName];")->execute();
|
||||
break;
|
||||
case 'postgres':
|
||||
$this->connection->createCommand("CREATE DATABASE \"$sDatabaseName\" ENCODING 'UTF8'")->execute();
|
||||
break;
|
||||
default:
|
||||
$this->connection->createCommand("CREATE DATABASE $sDatabaseName")->execute();
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (Exception $e)
|
||||
{
|
||||
throw new CException('Database could not be created because it either existed or you have no permissions');
|
||||
}
|
||||
|
||||
$this->connection->active = false;
|
||||
$this->connection->connectionString = $connectionString;
|
||||
$this->connection->active = true;
|
||||
}
|
||||
|
||||
}
|
||||
?>
|
30
sources/application/commands/PluginCommand.php
Normal file
30
sources/application/commands/PluginCommand.php
Normal file
|
@ -0,0 +1,30 @@
|
|||
<?php
|
||||
/*
|
||||
* LimeSurvey (tm)
|
||||
* Copyright (C) 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.
|
||||
*
|
||||
*/
|
||||
class PluginCommand extends CConsoleCommand
|
||||
{
|
||||
public $connection;
|
||||
|
||||
public function actionCron($interval)
|
||||
{
|
||||
|
||||
$pm = Yii::app()->getPluginManager();
|
||||
$event = new PluginEvent('cron');
|
||||
$event->set('interval', $interval);
|
||||
$pm->dispatchEvent($event);
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
34
sources/application/commands/ResetPasswordCommand.php
Normal file
34
sources/application/commands/ResetPasswordCommand.php
Normal file
|
@ -0,0 +1,34 @@
|
|||
<?php
|
||||
/*
|
||||
* LimeSurvey (tm)
|
||||
* Copyright (C) 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.
|
||||
*
|
||||
*/
|
||||
class ResetPasswordCommand extends CConsoleCommand
|
||||
{
|
||||
public $connection;
|
||||
|
||||
public function run($sArgument)
|
||||
{
|
||||
if (!isset($sArgument) || !isset($sArgument[0]) || !isset($sArgument[1])) die('You have to set username and password on the command line like this: php console.php username password');
|
||||
$iUserID=User::model()->getID($sArgument[0]);
|
||||
if ($iUserID)
|
||||
{
|
||||
User::model()->updatePassword($iUserID,$sArgument[1]);
|
||||
echo "Password for user {$sArgument[0]} was set.\n";
|
||||
}
|
||||
else
|
||||
{
|
||||
echo "User {$sArgument[0]} not found.\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
49
sources/application/commands/console.php
Normal file
49
sources/application/commands/console.php
Normal file
|
@ -0,0 +1,49 @@
|
|||
#!/usr/bin/php
|
||||
<?php
|
||||
/*
|
||||
* LimeSurvey (tm)
|
||||
* Copyright (C) 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.
|
||||
*
|
||||
*
|
||||
* File edited by Sam Mousa for Marcel Minke.
|
||||
* This loader bypasses the default Yii loader and loads a custom console class instead.
|
||||
*/
|
||||
if (!isset($argv[0])) die();
|
||||
define('BASEPATH','.');
|
||||
|
||||
require_once(dirname(dirname(dirname(__FILE__))) . DIRECTORY_SEPARATOR . 'framework' . DIRECTORY_SEPARATOR . 'yii.php');
|
||||
// Load configuration.
|
||||
$sCurrentDir=dirname(__FILE__);
|
||||
$config=require (dirname($sCurrentDir).DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'internal.php');
|
||||
$core = dirname($sCurrentDir) . DIRECTORY_SEPARATOR . 'core' . DIRECTORY_SEPARATOR;
|
||||
unset ($config['defaultController']);
|
||||
unset ($config['config']);
|
||||
|
||||
|
||||
|
||||
// fix for fcgi
|
||||
defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
|
||||
|
||||
defined('YII_DEBUG') or define('YII_DEBUG',true);
|
||||
|
||||
|
||||
|
||||
if(isset($config))
|
||||
{
|
||||
require_once($core . 'ConsoleApplication.php');
|
||||
$app=Yii::createApplication('ConsoleApplication', $config);
|
||||
define('APPPATH', Yii::app()->getBasePath() . DIRECTORY_SEPARATOR);
|
||||
$app->commandRunner->addCommands(YII_PATH.'/cli/commands');
|
||||
$env=@getenv('YII_CONSOLE_COMMANDS');
|
||||
if(!empty($env))
|
||||
$app->commandRunner->addCommands($env);
|
||||
}
|
||||
$app->run();
|
||||
?>
|
23
sources/application/commands/starter.php
Normal file
23
sources/application/commands/starter.php
Normal file
|
@ -0,0 +1,23 @@
|
|||
#!/usr/bin/php
|
||||
<?php
|
||||
/*
|
||||
* LimeSurvey (tm)
|
||||
* Copyright (C) 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.
|
||||
*
|
||||
*/
|
||||
if (!isset($argv[0])) die();
|
||||
define('BASEPATH','.');
|
||||
$sCurrentDir=dirname(__FILE__);
|
||||
$config=require (dirname($sCurrentDir).DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'config.php');
|
||||
unset ($config['defaultController']);
|
||||
unset ($config['config']);
|
||||
require (dirname(dirname($sCurrentDir)).DIRECTORY_SEPARATOR.'framework'.DIRECTORY_SEPARATOR.'yiic.php');
|
||||
|
||||
?>
|
1
sources/application/config/.gitignore
vendored
Normal file
1
sources/application/config/.gitignore
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
/config.php
|
632
sources/application/config/config-defaults.php
Normal file
632
sources/application/config/config-defaults.php
Normal file
|
@ -0,0 +1,632 @@
|
|||
<?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.
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* This file contains the default settings for LimeSurvey
|
||||
* Do not edit this file as it may change in future revisions of the software.
|
||||
* Correct procedure to setup LimeSurvey is the following:
|
||||
* - copy the corresponding parameter you want to change from this file to the config.php file (config section)
|
||||
* - adjust the setting in config.php
|
||||
*
|
||||
* @package configuration
|
||||
*/
|
||||
|
||||
|
||||
$config = array();
|
||||
|
||||
// CAUTION
|
||||
// This file contains the default settings for LimeSurvey
|
||||
// Do not edit this file as it may change in future revisions of the software.
|
||||
// Correct procedure to setup LimeSurvey is the following:
|
||||
// * copy the lines corresponding to the parameter you want to change
|
||||
// from this file to the config.php file
|
||||
// * edit these lines in config.php
|
||||
|
||||
|
||||
// FILE LOCATIONS
|
||||
|
||||
$config['rootdir'] = getcwd(); //dirname(__FILE__); // This is the physical disk location for your limesurvey installation. Normally you don't have to touch this setting.
|
||||
// If you use IIS then you MUST enter the complete rootdir e.g. : $rootDir="C:\Inetpub\wwwroot\limesurvey"!
|
||||
// Some IIS installations also require to use forward slashes instead of backslashes, e.g. $rootDir="C:/Inetpub/wwwroot/limesurvey"!
|
||||
// If you use OS/2 this must be the complete rootdir with FORWARD slashes e.g.: $rootDir="c:/limesurvey";!
|
||||
|
||||
|
||||
// Site Info
|
||||
$config['sitename'] = 'LimeSurvey'; // The official name of the site (appears in the Window title)
|
||||
$config['scriptname'] = 'admin.php'; // The name of the admin script
|
||||
|
||||
$config['defaultuser'] = 'admin'; // This is the default username when LimeSurvey is installed
|
||||
$config['defaultpass'] = 'password'; // This is the default password for the default user when LimeSurvey is installed
|
||||
|
||||
// Styling options
|
||||
$config['admintheme'] = 'gringegreen'; // This setting specifys the directory where the admin finds it theme/css style files, e.g. setting 'default' points to /admin/styles/default
|
||||
$config['adminthemeiconsize'] = 32; // This settings describes the icon size for a normal toolbar icon - default for gringegreen is 32
|
||||
|
||||
|
||||
// If the user enters password incorrectly
|
||||
$config['maxLoginAttempt'] = 3; // Lock them out after 3 attempts
|
||||
$config['timeOutTime'] = 60 * 10; // Lock them out for 10 minutes.
|
||||
|
||||
// Site Settings
|
||||
$config['dropdownthreshold'] = '25'; // The number of answers to a list type question before it switches from Radio Buttons to List
|
||||
$config['printanswershonorsconditions'] = 1; // If set to 1, only relevant answers to questions can be printed by user. If set to 0, also questions not shown are printed
|
||||
|
||||
// Only applicable, of course, if you have chosen 'R' for $dropdowns and/or $lwcdropdowns
|
||||
$config['repeatheadings'] = '25'; // The number of answers to show before repeating the headings in array (flexible) questions. Set to 0 to turn this feature off
|
||||
$config['minrepeatheadings'] = 3; // The minimum number of remaining answers that are required before repeating the headings in array (flexible) questions.
|
||||
$config['defaultlang'] = 'en'; // The default language to use - the available languages are the directory names in the /locale dir - for example de = German
|
||||
|
||||
$config['timeadjust'] = 0; // Number of hours to adjust between your webserver local time and your own local time (for datestamping responses)
|
||||
$config['allowexportalldb'] = 1; // 0 will only export prefixed tables when doing a database dump. If set to 1 ALL tables in the database will be exported
|
||||
$config['maxdumpdbrecords'] = 500; // The maximum number of records that would be ouputted in a go during a database backup. Reduce this number if you're getting errors while backing up the entire database.
|
||||
$config['allowmandbackwards'] = 1; // Allow moving backwards (ie: << prev) through survey if a mandatory question
|
||||
// has not been answered. 1=Allow, 0=Deny
|
||||
$config['deletenonvalues'] = 1; // By default, LimeSurvey does not save responses to conditional questions that haven't been answered/shown. To have LimeSurvey save these responses change this value to 0.
|
||||
$config['stringcomparizonoperators'] = 0; // By default, LimeSurvey assumes the numrical order for comparizon operators in conditions. If you need string comparizon operators, set this parameter to 1
|
||||
$config['shownoanswer'] = 1; // Show 'no answer' for non mandatory questions ( 0 = no , 1 = yes , 2 = survey admin can choose )
|
||||
$config['blacklistallsurveys'] = 'N'; // Blacklist all current surveys for participant once the global field is set
|
||||
$config['blacklistnewsurveys'] = 'N'; // Blacklist participant for any new added survey once the global field is set
|
||||
$config['blockaddingtosurveys'] = 'Y'; // Don't allow blacklisted participants to be added to new survey
|
||||
$config['hideblacklisted'] = 'N'; // Don't show blacklisted participants
|
||||
$config['deleteblacklisted'] = 'N'; // Delete globally blacklisted participant from the database
|
||||
$config['allowunblacklist'] = 'N'; // Allow participant to unblacklist himself/herself
|
||||
$config['userideditable'] = 'N'; // Allow editing of user IDs
|
||||
$config['defaulttemplate'] = 'default'; // This setting specifys the default theme used for the 'public list' of surveys
|
||||
|
||||
$config['allowedtemplateuploads'] = 'gif,ico,jpg,png,css,js'; // File types allowed to be uploaded in the templates section.
|
||||
|
||||
$config['allowedresourcesuploads'] = '7z,aiff,asf,avi,bmp,csv,doc,docx,fla,flv,gif,gz,gzip,ico,jpeg,jpg,mid,mov,mp3,mp4,mpc,mpeg,mpg,ods,odt,pdf,png,ppt,pxd,qt,ram,rar,rm,rmi,rmvb,rtf,sdc,sitd,swf,sxc,sxw,tar,tgz,tif,tiff,txt,vsd,wav,wma,wmv,xls,xlsx,xml,zip,pstpl,css,js'; // File types allowed to be uploaded in the resources sections, and with the HTML Editor
|
||||
|
||||
$config['memory_limit'] = '32'; // This sets how much memory LimeSurvey can access in megabytes. 32 mb is the minimum recommended - if you are using PDF functions up to 64 mb may be needed
|
||||
|
||||
$config['showpopups'] = 1; // Show popup messages if mandatory or conditional questions have not been answered correctly.
|
||||
// 1=Show popup message, 0=Show message on page instead.
|
||||
|
||||
$config['maxemails'] = 50; // The maximum number of emails to send in one go (this is to prevent your mail server or script from timeouting when sending mass mail)
|
||||
|
||||
// Enable or Disable LDAP feature
|
||||
$config['enableLdap'] = false;
|
||||
|
||||
// Experimental parameters, only change if you know what you're doing
|
||||
//
|
||||
// filterout_incomplete_answers
|
||||
// * default behaviour of LimeS regarding answer records with no submitdate
|
||||
// * can be overwritten by module parameters choose one of the following://
|
||||
// * filter: Show only complete answers
|
||||
// * show: Show both complete and incomplete answers
|
||||
// * incomplete: Show only incomplete answers
|
||||
$config['filterout_incomplete_answers'] = 'show';
|
||||
|
||||
// strip_query_from_referer_url (default is false)
|
||||
// * default behaviour is to record the full referer url when requested
|
||||
// * set to true in order to remove the parameter part of the referer url
|
||||
$config['strip_query_from_referer_url'] = false;
|
||||
|
||||
// defaulthtmleditormode
|
||||
// * sets the default mode for htmleditor: none, inline, popup
|
||||
// users without specific preference inherit this setup
|
||||
// * inline: inline replacement of fields by an HTML editor:
|
||||
// --> slow but convenient and user friendly
|
||||
// * popup: adds an icon that runs a popup with and html editor
|
||||
// --> faster, but html code is displayed on the form
|
||||
// * none: no html editor
|
||||
$config['defaulthtmleditormode'] = 'inline';
|
||||
|
||||
// surveyPreview_require_Auth
|
||||
// Enforce Authentication to the LS system before beeing able to preview a survey (testing a non active survey)
|
||||
// Default is true
|
||||
$config['surveyPreview_require_Auth'] = true;
|
||||
|
||||
|
||||
// use_one_time_passwords
|
||||
// Activate One time passwords
|
||||
// The user can call the limesurvey login at /limesurvey/admin and pass username and
|
||||
// a one time password which was previously written into the users table (column one_time_pw) by
|
||||
// an external application.
|
||||
// This setting has to be turned on to enable the usage of one time passwords (default = off).
|
||||
$config['use_one_time_passwords'] = false;
|
||||
|
||||
|
||||
// display_user_password_in_html
|
||||
// Option to tell LS to display the automatically generated user password in the html GUI or not
|
||||
$config['display_user_password_in_html'] = false;
|
||||
|
||||
|
||||
// display_user_password_in_email
|
||||
// Option to tell LS to display the automatically generated user password in the welcome email or not
|
||||
$config['display_user_password_in_email'] = true;
|
||||
|
||||
|
||||
// auth_webserver
|
||||
// Enable delegation of authentication to the webserver.
|
||||
// If you set this parameter to true and set your webserver to authenticate
|
||||
// users accessing the /admin subdirectory, then the username returned by
|
||||
// the webserver will be trusted by LimeSurvey and used for authentication
|
||||
// unless a username mapping is used see auth_webserver_user_map below
|
||||
//
|
||||
// The user still needs to be defined in the limesurvey database in order to
|
||||
// login and get his permissions (unless auth_webserver_autocreate_user is set to true)
|
||||
$config['auth_webserver'] = false;
|
||||
|
||||
// auth_webserver_user_map
|
||||
// Enable username mapping
|
||||
// This parameter is an array mapping username from the webserver to username
|
||||
// defined in LimeSurvey
|
||||
// Can be usefull if you have no way to add an 'admin' user to the database
|
||||
// used by the webserver, then you could map your true loginame to admin with
|
||||
// $config['auth_webserver_user_map'] = array ('mylogin' => 'admin');
|
||||
$config['auth_webserver_user_map'] = array();
|
||||
//
|
||||
// auth_webserver_autocreate_user
|
||||
// Enable this if you want to automatically create users authenticated by the
|
||||
// webserver in LS
|
||||
// Default is false (commenting this options also means false)
|
||||
$config['auth_webserver_autocreate_user'] = false;
|
||||
|
||||
// auth_webserver_autocreate_profile
|
||||
// This is an array describing the default profile to use for auto-created users
|
||||
// This profile will be the same for all users (unless you define the optionnal
|
||||
// 'hook_get_auth_webserver_profile' function).
|
||||
//
|
||||
$config['auth_webserver_autocreate_profile'] = Array(
|
||||
'full_name' => 'autouser',
|
||||
'email' => 'autouser@test.test',
|
||||
'lang' => 'en',
|
||||
'htmleditormode' => $config['defaulthtmleditormode']
|
||||
);
|
||||
|
||||
$config['auth_webserver_autocreate_permissions'] = Array(
|
||||
'surveys' => array('create'=>true,'read'=>true,'update'=>true,'delete'=>true)
|
||||
);
|
||||
|
||||
// hook_get_auth_webserver_profile
|
||||
// The optionnal 'hook_get_auth_webserver_profile' function is for advanced user usage only.
|
||||
// It is used to customize the profile of the imported user
|
||||
// If set, the this function will overwrite the auth_webserver_autocreate_profile
|
||||
// defined above by its return value
|
||||
//
|
||||
// You can use any external DB in order to fill the profile for the user_name passed as the first parameter
|
||||
// A dummy example for the 'hook_get_auth_webserver_profile' function is given below:
|
||||
//
|
||||
//function hook_get_auth_webserver_profile($user_name)
|
||||
//{
|
||||
// return Array(
|
||||
// 'full_name' => '$user_name',
|
||||
// 'email' => "$user_name@localdomain.org",
|
||||
// 'lang' => 'en',
|
||||
// 'htmleditormode' => 'inline');
|
||||
//}
|
||||
|
||||
|
||||
// filterxsshtml
|
||||
// Enables filtering of suspicious html tags in survey, group, questions
|
||||
// and answer texts in the administration interface
|
||||
// Only set this to false if you absolutely trust the users
|
||||
// you created for the administration of LimeSurvey and if you want to
|
||||
// allow these users to be able to use Javascript etc. .
|
||||
$config['filterxsshtml'] = true;
|
||||
|
||||
// usercontrolSameGroupPolicy
|
||||
// If this option is set to true, then limesurvey operators will only 'see'
|
||||
// users that belong to at least one of their groups
|
||||
// Otherwise they can see all operators defines in LimeSurvey
|
||||
$config['usercontrolSameGroupPolicy'] = true;
|
||||
|
||||
|
||||
// demoMode
|
||||
// If this option is set to true, then LimeSurvey will go into demo mode.
|
||||
// Demo mode disables the following things:
|
||||
//
|
||||
// * Disables changing of the admin user's details and password
|
||||
// * Disables uploading files on the Template Editor
|
||||
// * Disables sending email invitations and reminders
|
||||
// * Disables doing a database dump
|
||||
// * Disables the ability to save the following global settings: Site name, Default language, Default Htmleditor Mode, XSS filter
|
||||
|
||||
$config['demoMode'] = false;
|
||||
|
||||
/**
|
||||
* Prefill the login mask using the parameters 'defaultuser' and 'default pass'. This works only if demo mode (demoMode) is activated.
|
||||
* Also a notice will be shown that the user knows that he can just login by using the Login button.
|
||||
*
|
||||
* @var $config['demoModePrefill'] boolan If set to true prefill the login mask
|
||||
*/
|
||||
$config['demoModePrefill'] = false;
|
||||
|
||||
|
||||
/**
|
||||
* column_style
|
||||
* Because columns are tricky things, in terms of balancing visual
|
||||
* layout against semantic markup. The choice has been left to the
|
||||
* system administrator or designer. (Who ever cares most.)
|
||||
*
|
||||
* $column_style defines how columns are rendered for survey answers.
|
||||
* There are four possible options:
|
||||
* 'css' using one of the various CSS only methods for creating
|
||||
columns (see template style sheet for details).
|
||||
* 'ul' using multiple floated unordered lists. (DEFAULT)
|
||||
* 'table' using conventional tables based layout.
|
||||
* NULL blocks the use of columns
|
||||
*/
|
||||
$config['column_style'] = 'ul';
|
||||
|
||||
/**
|
||||
* hide_groupdescr_allinone.
|
||||
* This parameter 'hide_groupdescr_allinone' can be set to control
|
||||
* if the group description should be hidden if the group description of a group of questions
|
||||
* with all questions hidden by conditions is displayed in all-in-one survey mode.
|
||||
* hide_groupdescr_allinone can be set to true or false (default: true)
|
||||
*/
|
||||
$config['hide_groupdescr_allinone']=true;
|
||||
|
||||
|
||||
/**
|
||||
* use_firebug_lite
|
||||
* Use FireBug Lite for JavaScript and template development and testing.
|
||||
* This allows you to use all the features of Firebug in any browser.
|
||||
* see http://getfirebug.com/lite.html for more info.
|
||||
*/
|
||||
$config['use_firebug_lite'] = false;
|
||||
|
||||
/*
|
||||
* showaggregateddata
|
||||
* When activated there are additional values like arithmetic mean and standard deviation at statistics.
|
||||
* This only affects question types "A" (5 point array) and "5" (5 point choice).
|
||||
* Furthermore data is aggregated to get a faster overview.
|
||||
*/
|
||||
$config['showaggregateddata'] = 1;
|
||||
|
||||
|
||||
/**
|
||||
* When this settings is true/1 (default) then the standard templates that are delivered with the
|
||||
* LimeSurvey installation package are read-only. If you want to modify a template just copy it first.
|
||||
* This prevents upgrade problems later because if you modify your standard templates you could accidenitally
|
||||
* overwrite these on a LimSurvey upgrade. Only set this to 0 if you know what you are doing.
|
||||
*/
|
||||
$config['standard_templates_readonly'] = true;
|
||||
|
||||
|
||||
/**
|
||||
* When this settings is true/1 (default = false/0) then the printable survey option will show a reference
|
||||
* to the "lime_survey_12345" table which stores the survey answers.
|
||||
* It will show a code like "12345X22X333name":
|
||||
* 12345 = surveyID
|
||||
* 22 = groupID
|
||||
* 333 = questionID
|
||||
* name = answer code (only shown for certain question types
|
||||
*
|
||||
* This code will be shown in front of each question and in front of each answer option at the printable survey.
|
||||
* It can be used as a data analysis code book for querying data from the main response table.
|
||||
*/
|
||||
$config['showsgqacode'] = false;
|
||||
|
||||
/**
|
||||
* When this settings is true/1 (default = false/0) then the printable survey option will show
|
||||
* the raw relevance equation below the general fill-out instructions in case the question has conditions.
|
||||
*/
|
||||
$config['showrelevance'] = false;
|
||||
|
||||
/**
|
||||
* PDF Export Settings
|
||||
* This feature configures PDF export for Export Answers
|
||||
* PDF core fonts are not included in PDF: make ligther pdf
|
||||
* See http://www.tcpdf.org/fonts.php to have the list of PDF core fonts
|
||||
*/
|
||||
|
||||
$config['pdfdefaultfont'] = 'auto'; //Default font for the pdf Export
|
||||
/**
|
||||
* $alternatepdffontfile - array of the font file name used to created pdf in statistics in specific langage - this font are included in tcpdf core
|
||||
* Only used if $pdfdefaultfont is set to auto or set to a PDF core fonts
|
||||
* Some langage are not tested : need translation for Yes,No and Gender : ckb, swh
|
||||
*/
|
||||
$config['alternatepdffontfile']=array(
|
||||
'ar'=>'dejavusans',// 'dejavusans' work but maybe more characters in aealarabiya or almohanad: but then need a dynamic font size too
|
||||
'be'=>'dejavusans',
|
||||
'bg'=>'dejavusans',
|
||||
'zh-Hans'=>'chinese',
|
||||
'zh-Hant-HK'=>'chinese',
|
||||
'zh-Hant-TW'=>'chinese',
|
||||
'cs'=>'dejavusans',
|
||||
'cs-informal'=>'dejavusans',// This one not really tested: no translation for Yes/No or Gender
|
||||
'el'=>'dejavusans',
|
||||
'he'=>'freesans',
|
||||
'hi'=>'dejavusans',
|
||||
'hu'=>'dejavusans',
|
||||
'ja'=>'cid0jp',
|
||||
'ko'=>'cid0kr',
|
||||
'lv'=>'dejavusans',
|
||||
'lt'=>'dejavusans',
|
||||
'mk'=>'dejavusans',
|
||||
'mt'=>'dejavusans',
|
||||
'fa'=>'dejavusans',
|
||||
'pl'=>'dejavusans',
|
||||
'pa'=>'freesans',
|
||||
'ro'=>'dejavusans',
|
||||
'ru'=>'dejavusans',
|
||||
'sr'=>'dejavusans',
|
||||
);
|
||||
/**
|
||||
* $notsupportlanguages - array of language where no font was found for PDF
|
||||
* Seems not used actually
|
||||
*/
|
||||
$config['notsupportlanguages'] = array(
|
||||
'am',// Amharic
|
||||
'si',// Sinhala
|
||||
'th',// Thai
|
||||
);
|
||||
$config['pdffontsize'] = 9; //Fontsize for normal text; Surveytitle is +4; grouptitle is +2
|
||||
$config['pdforientation'] = 'P'; // Set L for Landscape or P for portrait format
|
||||
|
||||
// QueXML-PDF: If set to true, the printable_help attribute will be visible on the exported PDF questionnaires
|
||||
// If used, the appearance (font size, justification, etc.) may be adjusted by editing td.questionHelpBefore and $helpBeforeBorderBottom of quexml.
|
||||
$config['quexmlshowprintablehelp'] = false;
|
||||
|
||||
// CAS Settings
|
||||
/**
|
||||
* Please note that CAS functionality is very basic and you have to modify the client to your needs.
|
||||
* At least the hard work is done.
|
||||
* The Client is deployed in Limesurvey and a file login_check_cas.php does what login_check.php does in normal mode.
|
||||
*
|
||||
* $casEnabled determines if CAS should be used or not for Authentication.
|
||||
* $casAuthServer the servername of the cas Auth Server. Without http://
|
||||
* $casAuthPort CAS Server listening Port
|
||||
* $casAuthUri relative uri from $casAuthServer to cas workingdirectory
|
||||
*/
|
||||
$config['casEnabled'] = false;
|
||||
$config['casAuthServer'] = 'localhost';
|
||||
$config['casAuthPort'] = 8443;
|
||||
$config['casAuthUri'] = '/cas-server/';
|
||||
|
||||
|
||||
/**
|
||||
* Statistics chart settings
|
||||
* Different languages need different fonts to properly create charts - this is what the following settings are for
|
||||
*/
|
||||
|
||||
/**
|
||||
* $chartfontfile - set the font file name used to created the charts in statistics - this font must reside in <limesurvey root folder>/fonts
|
||||
* Set this to specific font-file (for example 'DejaVuSans.ttf') or set it to 'auto' and LimeSurvey tried to pick the best font depending on your survey base language
|
||||
*/
|
||||
$config['chartfontfile']='auto';
|
||||
/**
|
||||
* $alternatechartfontfile - array of the font file name used to created the charts in statistics in specific langage - this font must reside in <limesurvey root folder>/fonts
|
||||
* Only used if $chartfontfile is set to auto. If font file doesn't exist in <limesurvey root folder>/fonts, an alert is sent to admin
|
||||
*/
|
||||
$config['alternatechartfontfile']=array(
|
||||
'hi'=>'FreeSans.ttf',
|
||||
'ja'=> 'migmix-1p-regular.ttf',
|
||||
'ko'=>'UnBatang.ttf',
|
||||
'si'=>'FreeSans.ttf',
|
||||
'th'=>'TlwgTypist.ttf',
|
||||
'zh-Hans'=>'fireflysung.ttf',
|
||||
'zh-Hant-HK'=>'fireflysung.ttf',
|
||||
'zh-Hant-TW'=>'fireflysung.ttf',
|
||||
);
|
||||
|
||||
/**
|
||||
* $chartfontsize - set the size of the font to created the charts in statistics
|
||||
*/
|
||||
$config['chartfontsize'] =10;
|
||||
|
||||
|
||||
/**
|
||||
* $updatecheckperiod - sets how often LimeSurvey checks for updates - the number sets the number of days between updates.
|
||||
* Set to 0 to disable any update checks
|
||||
* Recommended: 7
|
||||
*/
|
||||
$config['updatecheckperiod']=7;
|
||||
|
||||
|
||||
/**
|
||||
* @var $showxquestions string allows you to control whether or not
|
||||
* {THEREAREXQUESTIONS} is displayed (if it is included in a template)
|
||||
* hide = always hide {THEREAREXQUESTIONS}
|
||||
* show = always show {THEREAREXQUESTIONS}
|
||||
* choose = allow survey admins to choose
|
||||
*/
|
||||
$config['showxquestions'] = 'choose';
|
||||
|
||||
|
||||
/**
|
||||
* @var $showgroupinfo string allows you to control whether or not
|
||||
* {GROUPNAME} and/or {GROUPDESCRIPTION} are displayed (if they are
|
||||
* included in a template)
|
||||
* none = always hide both title and description
|
||||
* name = always {GROUPNAME} only
|
||||
* description = always show {GROUPDESCRIPTION} only
|
||||
* both = always show both {GROUPNAME} and {GROUPDESCRIPTION}
|
||||
* choose = allow survey admins to choose
|
||||
*/
|
||||
$config['showgroupinfo'] = 'choose';
|
||||
|
||||
|
||||
/**
|
||||
* @var $showqnumcode string allows you to control whether or not
|
||||
* {QUESTION_NUMBER} and/or {QUESTION_CODE} are displayed (if they
|
||||
* are included in a template)
|
||||
* none = always hide both {QUESTION_NUMBER} and {QUESTION_CODE}
|
||||
* code = always show {QUESTION_CODE} only
|
||||
* number = always show {QUESTION_NUMBER} only
|
||||
* both = always show both {QUESTION_NUMBER} and {QUESTION_CODE}
|
||||
* choose = allow survey admins to choose
|
||||
*/
|
||||
$config['showqnumcode'] = 'choose';
|
||||
|
||||
|
||||
/**
|
||||
* @var $force_ssl string - forces LimeSurvey to run through HTTPS or to block HTTPS
|
||||
* 'on' = force SSL/HTTPS to be on (This will cause LimeSurvey
|
||||
* to fail in SSL is turned off)
|
||||
* 'off' = block SSL/HTTPS (this prevents LimeSurvey from
|
||||
* running through SSL)
|
||||
* '' = do nothing (default)
|
||||
*
|
||||
* DO NOT turn on secure unless you are sure SSL/HTTPS is working and
|
||||
* that you have a current, working, valid certificate. If you are
|
||||
* unsure whether your server has a valid certificate, just add 's'
|
||||
* to the http part of your normal LimeSurvey URL.
|
||||
* e.g. https://your.domain.org/limesurvey/admin/admin.php
|
||||
* If LimeSurvey comes up as normal, then everything is fine. If you
|
||||
* get a page not found error or permission denied error then
|
||||
*/
|
||||
$config['force_ssl'] = ''; // DO not turn on unless you are sure your server supports SSL/HTTPS
|
||||
|
||||
|
||||
/**
|
||||
* @var $ssl_emergency_override boolean forces SSL off
|
||||
* if You've turned HTTPS/SSL on in the global settings but your
|
||||
* server doesn't have HTTPS enabled, the only way to turn it off is
|
||||
* by changing a value in the database directly. This allows you to
|
||||
* force HTTPS off while you change the global settings for Force Secure.
|
||||
*
|
||||
* false = do nothing;
|
||||
* true = override $force_ssl=on;
|
||||
*
|
||||
* This should always be false except in emergencies where you change
|
||||
* it to true until you fix the problem.
|
||||
*/
|
||||
$config['ssl_emergency_override'] = false;
|
||||
|
||||
|
||||
// Get your IP Info DB key from http://ipinfodb.com/
|
||||
// If you have the API key, you can use it to get the approximate location of the user initially.
|
||||
|
||||
$config['ipInfoDbAPIKey'] = '';
|
||||
|
||||
// Google Maps API key. http://code.google.com/apis/maps/signup.html
|
||||
// To have questions that require google Maps!
|
||||
|
||||
$config['googleMapsAPIKey'] = '';
|
||||
|
||||
// Google Translate API key: https://code.google.com/apis/language/translate/v2/getting_started.html
|
||||
$googletranslateapikey = '';
|
||||
|
||||
/**
|
||||
* This variable defines the total space available to the file upload question across all surveys. If set to 0 then no limit applies.
|
||||
*
|
||||
* @var $config['iFileUploadTotalSpaceMB'] Integer number to determine the available space in MB - Default: 0
|
||||
*
|
||||
*/
|
||||
$config['iFileUploadTotalSpaceMB']= 0;
|
||||
|
||||
|
||||
// defines if the CKeditor toolbar should be opened by default
|
||||
$config['ckeditexpandtoolbar'] = true;
|
||||
|
||||
/**
|
||||
* This variable defines the languages available in LimeSurvey (front- and backend)
|
||||
* and should contain a space-separated list of language codes. If empty then no restrictions
|
||||
* are set and all languages are available
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
$config['restrictToLanguages'] = '';
|
||||
|
||||
/**
|
||||
* This parameter enables/disables the RPC interface
|
||||
* Set to 'json' (for JSON-RPC) )or 'xml' (for XML-RPC) to enable and 'off' to disable
|
||||
* @var string
|
||||
*/
|
||||
$config['RPCInterface'] = 'off';
|
||||
|
||||
/**
|
||||
* This parameter sets the default session expiration time in seconds
|
||||
* Default is 2 hours
|
||||
* @var integer
|
||||
*/
|
||||
$config['iSessionExpirationTime'] = 7200;
|
||||
|
||||
/**
|
||||
* This parameter can be used to set some question not selectable in LimeReplacementFiels
|
||||
* Default is an empty array, leave it for new question modules system
|
||||
* @var array
|
||||
*/
|
||||
$config['InsertansUnsupportedtypes'] = array();
|
||||
|
||||
/**
|
||||
* This parameter sets if and what update notifications are shown to the administrator. Valid values are 'never', 'stable', 'both' (for stable and unstable)
|
||||
* Default is 'stable'
|
||||
* @var string
|
||||
*/
|
||||
$config['updatenotification'] = 'both';
|
||||
|
||||
// Proxy settings for ComfortUpdate
|
||||
/**
|
||||
* Set these if you are behind a proxy and want to update LS using ComfortUpdate
|
||||
*
|
||||
* $proxy_host_name Your proxy server name (string)
|
||||
* $proxy_host_port Your proxy server port (int)
|
||||
*/
|
||||
$config['proxy_host_name'] = '';
|
||||
$config['proxy_host_port'] = 80;
|
||||
|
||||
|
||||
// === Advanced Setup
|
||||
// The following parameters need information from config.php
|
||||
// and thus are defined here (After reading your config.php file).
|
||||
// This means that if you want to tweak these very advanced parameters
|
||||
// you'll have to do this in this file and not in config.php
|
||||
// In this case, don't forget to backup your config-defaults.php settings when upgrading LS
|
||||
// and report them to the new config-defaults.php file (Do not simply overwrite the new
|
||||
// config-defaults file with your old one
|
||||
|
||||
//The following url and dir locations do not need to be modified unless you have a non-standard
|
||||
//LimeSurvey installation. Do not change unless you know what you are doing.
|
||||
|
||||
if(!isset($argv[0]))
|
||||
{
|
||||
$config['publicurl'] = Yii::app()->baseUrl . '/'; // The public website location (url) of the public survey script
|
||||
}
|
||||
else
|
||||
{
|
||||
$config['publicurl'] = '/';
|
||||
}
|
||||
|
||||
$config['homeurl'] = $config['publicurl'].'admin'; // The website location (url) of the admin scripts
|
||||
$config['tempurl'] = $config['publicurl'].'tmp';
|
||||
$config['imageurl'] = $config['publicurl'].'images'; // Location of button bar files for admin script
|
||||
$config['uploadurl'] = $config['publicurl'].'upload';
|
||||
$config['standardtemplaterooturl'] = $config['publicurl'].'templates'; // Location of the standard templates
|
||||
$config['adminscripts'] = $config['publicurl'].'scripts/admin/';
|
||||
$config['generalscripts'] = $config['publicurl'].'scripts/';
|
||||
$config['third_party'] = $config['publicurl'].'third_party/';
|
||||
$config['styleurl'] = $config['publicurl'].'styles/';
|
||||
$config['publicstyleurl'] = $config['publicurl'].'styles-public/';
|
||||
$config['sCKEditorURL'] = $config['third_party'].'ckeditor';
|
||||
//$config['sCKEditorURL'] = '/scripts/admin/ckeditor.36';
|
||||
$config['usertemplaterooturl'] = $config['uploadurl'].'/templates'; // Location of the user templates
|
||||
$config['adminimageurl'] = $config['styleurl'].$config['admintheme'].'/images/'; // Location of button bar files for admin script
|
||||
$config['adminstyleurl'] = $config['styleurl'].$config['admintheme'].'/'; // Location of button bar files for admin script
|
||||
|
||||
|
||||
$config['publicdir'] = $config['rootdir']; // The directory path of the public scripts
|
||||
$config['homedir'] = $config['rootdir']; // The directory path of the admin scripts
|
||||
$config['tempdir'] = $config['rootdir'].DIRECTORY_SEPARATOR."tmp"; // The directory path where LimeSurvey can store temporary files
|
||||
$config['imagedir'] = $config['rootdir'].DIRECTORY_SEPARATOR."images"; // The directory path of the image directory
|
||||
$config['uploaddir'] = $config['rootdir'].DIRECTORY_SEPARATOR."upload";
|
||||
$config['standardtemplaterootdir'] = $config['rootdir'].DIRECTORY_SEPARATOR."templates"; // The directory path of the standard templates
|
||||
$config['usertemplaterootdir'] = $config['uploaddir'].DIRECTORY_SEPARATOR."templates"; // The directory path of the user templates
|
||||
$config['styledir'] = $config['rootdir'].DIRECTORY_SEPARATOR.'styles';
|
||||
|
||||
// Use alias notation, we should move to this format everywhere.
|
||||
$config['plugindir'] = 'webroot.plugins';
|
||||
|
||||
// (javascript) Fix automatically the value entered in numeric question type : 1: remove all non numeric caracters; 0 : leave all caracters
|
||||
$config['bFixNumAuto'] = 1;
|
||||
// (javascript) Send real value entered when using Numeric question type in Expression Manager : 0 : {NUMERIC} with bad caracters send '', 1 : {NUMERIC} send all caracters entered
|
||||
$config['bNumRealValue'] = 0;
|
||||
|
||||
|
||||
return $config;
|
||||
//settings deleted
|
61
sources/application/config/config-sample-dblib.php
Normal file
61
sources/application/config/config-sample-dblib.php
Normal file
|
@ -0,0 +1,61 @@
|
|||
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
|
||||
/*
|
||||
| -------------------------------------------------------------------
|
||||
| DATABASE CONNECTIVITY SETTINGS
|
||||
| -------------------------------------------------------------------
|
||||
| This file will contain the settings needed to access your database.
|
||||
|
|
||||
| For complete instructions please consult the 'Database Connection'
|
||||
| page of the User Guide.
|
||||
|
|
||||
| -------------------------------------------------------------------
|
||||
| EXPLANATION OF VARIABLES
|
||||
| -------------------------------------------------------------------
|
||||
|
|
||||
| 'connectionString' Hostname, database, port and database type for
|
||||
| the connection. Driver example: mysql. Currently supported:
|
||||
| mysql, pgsql, mssql, sqlite, oci
|
||||
| 'username' The username used to connect to the database
|
||||
| 'password' The password used to connect to the database
|
||||
| 'tablePrefix' You can add an optional prefix, which will be added
|
||||
| to the table name when using the Active Record class
|
||||
|
|
||||
*/
|
||||
return array(
|
||||
'name' => 'LimeSurvey',
|
||||
'components' => array(
|
||||
'db' => array(
|
||||
'connectionString' => 'dblib:host=localhost;dbname=limesurvey',
|
||||
'username' => 'sa',
|
||||
'password' => 'somepassword',
|
||||
'charset' => 'utf8',
|
||||
'tablePrefix' => 'lime_',
|
||||
'initSQLs'=>array('SET DATEFORMAT ymd;','SET QUOTED_IDENTIFIER ON;'),
|
||||
),
|
||||
|
||||
// Uncomment the following line if you need table-based sessions
|
||||
// 'session' => array (
|
||||
// 'class' => 'system.web.CDbHttpSession',
|
||||
// 'connectionID' => 'db',
|
||||
// 'sessionTableName' => '{{sessions}}',
|
||||
// ),
|
||||
|
||||
'urlManager' => array(
|
||||
'urlFormat' => 'get',
|
||||
'rules' => require('routes.php'),
|
||||
'showScriptName' => true,
|
||||
),
|
||||
|
||||
),
|
||||
// Use the following config variable to set modified optional settings copied from config-defaults.php
|
||||
'config'=>array(
|
||||
// debug: Set this to 1 if you are looking for errors. If you still get no errors after enabling this
|
||||
// then please check your error-logs - either in your hosting provider admin panel or in some /logs directory
|
||||
// on your webspace.
|
||||
// LimeSurvey developers: Set this to 2 to additionally display STRICT PHP error messages and get full access to standard templates
|
||||
'debug'=>0,
|
||||
'debugsql'=>0 // Set this to 1 to enanble sql logging, only active when debug = 2
|
||||
)
|
||||
);
|
||||
/* End of file config.php */
|
||||
/* Location: ./application/config/config.php */
|
62
sources/application/config/config-sample-mysql.php
Normal file
62
sources/application/config/config-sample-mysql.php
Normal file
|
@ -0,0 +1,62 @@
|
|||
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
|
||||
/*
|
||||
| -------------------------------------------------------------------
|
||||
| DATABASE CONNECTIVITY SETTINGS
|
||||
| -------------------------------------------------------------------
|
||||
| This file will contain the settings needed to access your database.
|
||||
|
|
||||
| For complete instructions please consult the 'Database Connection'
|
||||
| page of the User Guide.
|
||||
|
|
||||
| -------------------------------------------------------------------
|
||||
| EXPLANATION OF VARIABLES
|
||||
| -------------------------------------------------------------------
|
||||
|
|
||||
| 'connectionString' Hostname, database, port and database type for
|
||||
| the connection. Driver example: mysql. Currently supported:
|
||||
| mysql, pgsql, mssql, sqlite, oci
|
||||
| 'username' The username used to connect to the database
|
||||
| 'password' The password used to connect to the database
|
||||
| 'tablePrefix' You can add an optional prefix, which will be added
|
||||
| to the table name when using the Active Record class
|
||||
|
|
||||
*/
|
||||
return array(
|
||||
'name' => 'LimeSurvey',
|
||||
'components' => array(
|
||||
'db' => array(
|
||||
'connectionString' => 'mysql:host=localhost;port=3306;dbname=limesurvey',
|
||||
'emulatePrepare' => true,
|
||||
'username' => 'root',
|
||||
'password' => '',
|
||||
'charset' => 'utf8',
|
||||
'tablePrefix' => 'lime_',
|
||||
),
|
||||
// Uncomment the following section if you wish to store sessions in the database
|
||||
// rather than in files.
|
||||
// Make sure MySQL max_allowed_packet setting is large enough, some surveys generate over 2 MB of session data.
|
||||
/*
|
||||
'session' => array (
|
||||
'class' => 'system.web.CDbHttpSession',
|
||||
'connectionID' => 'db',
|
||||
'sessionTableName' => '{{sessions}}',
|
||||
),
|
||||
*/
|
||||
'urlManager' => array(
|
||||
'urlFormat' => 'get',
|
||||
'rules' => require('routes.php'),
|
||||
'showScriptName' => true,
|
||||
),
|
||||
),
|
||||
// Use the following config variable to set modified optional settings copied from config-defaults.php
|
||||
'config'=>array(
|
||||
// debug: Set this to 1 if you are looking for errors. If you still get no errors after enabling this
|
||||
// then please check your error-logs - either in your hosting provider admin panel or in some /logs directory
|
||||
// on your webspace.
|
||||
// LimeSurvey developers: Set this to 2 to additionally display STRICT PHP error messages and get full access to standard templates
|
||||
'debug'=>0,
|
||||
'debugsql'=>0 // Set this to 1 to enanble sql logging, only active when debug = 2
|
||||
)
|
||||
);
|
||||
/* End of file config.php */
|
||||
/* Location: ./application/config/config.php */
|
61
sources/application/config/config-sample-pgsql.php
Normal file
61
sources/application/config/config-sample-pgsql.php
Normal file
|
@ -0,0 +1,61 @@
|
|||
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
|
||||
/*
|
||||
| -------------------------------------------------------------------
|
||||
| DATABASE CONNECTIVITY SETTINGS
|
||||
| -------------------------------------------------------------------
|
||||
| This file will contain the settings needed to access your database.
|
||||
|
|
||||
| For complete instructions please consult the 'Database Connection'
|
||||
| page of the User Guide.
|
||||
|
|
||||
| -------------------------------------------------------------------
|
||||
| EXPLANATION OF VARIABLES
|
||||
| -------------------------------------------------------------------
|
||||
|
|
||||
| 'connectionString' Hostname, database, port and database type for
|
||||
| the connection. Driver example: mysql. Currently supported:
|
||||
| mysql, pgsql, mssql, sqlite, oci
|
||||
| 'username' The username used to connect to the database
|
||||
| 'password' The password used to connect to the database
|
||||
| 'tablePrefix' You can add an optional prefix, which will be added
|
||||
| to the table name when using the Active Record class
|
||||
|
|
||||
*/
|
||||
return array(
|
||||
'name' => 'LimeSurvey',
|
||||
'components' => array(
|
||||
'db' => array(
|
||||
'connectionString' => 'pgsql:host=localhost;port=5432;user=postgres;password=somepassword;dbname=limesurvey;',
|
||||
'emulatePrepare' => true,
|
||||
'username' => 'postgres',
|
||||
'password' => 'somepassword',
|
||||
'charset' => 'utf8',
|
||||
'tablePrefix' => 'lime_',
|
||||
),
|
||||
|
||||
// Uncomment the following line if you need table-based sessions
|
||||
// 'session' => array (
|
||||
// 'class' => 'system.web.CDbHttpSession',
|
||||
// 'connectionID' => 'db',
|
||||
// 'sessionTableName' => '{{sessions}}',
|
||||
// ),
|
||||
|
||||
'urlManager' => array(
|
||||
'urlFormat' => 'get',
|
||||
'rules' => require('routes.php'),
|
||||
'showScriptName' => true,
|
||||
),
|
||||
|
||||
),
|
||||
// Use the following config variable to set modified optional settings copied from config-defaults.php
|
||||
'config'=>array(
|
||||
// debug: Set this to 1 if you are looking for errors. If you still get no errors after enabling this
|
||||
// then please check your error-logs - either in your hosting provider admin panel or in some /logs directory
|
||||
// on your webspace.
|
||||
// LimeSurvey developers: Set this to 2 to additionally display STRICT PHP error messages and get full access to standard templates
|
||||
'debug'=>0,
|
||||
'debugsql'=>0 // Set this to 1 to enanble sql logging, only active when debug = 2
|
||||
)
|
||||
);
|
||||
/* End of file config.php */
|
||||
/* Location: ./application/config/config.php */
|
61
sources/application/config/config-sample-sqlsrv.php
Normal file
61
sources/application/config/config-sample-sqlsrv.php
Normal file
|
@ -0,0 +1,61 @@
|
|||
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
|
||||
/*
|
||||
| -------------------------------------------------------------------
|
||||
| DATABASE CONNECTIVITY SETTINGS
|
||||
| -------------------------------------------------------------------
|
||||
| This file will contain the settings needed to access your database.
|
||||
|
|
||||
| For complete instructions please consult the 'Database Connection'
|
||||
| page of the User Guide.
|
||||
|
|
||||
| -------------------------------------------------------------------
|
||||
| EXPLANATION OF VARIABLES
|
||||
| -------------------------------------------------------------------
|
||||
|
|
||||
| 'connectionString' Hostname, database, port and database type for
|
||||
| the connection. Driver example: mysql. Currently supported:
|
||||
| mysql, pgsql, mssql, sqlite, oci
|
||||
| 'username' The username used to connect to the database
|
||||
| 'password' The password used to connect to the database
|
||||
| 'tablePrefix' You can add an optional prefix, which will be added
|
||||
| to the table name when using the Active Record class
|
||||
|
|
||||
*/
|
||||
return array(
|
||||
'name' => 'LimeSurvey',
|
||||
'components' => array(
|
||||
'db' => array(
|
||||
'connectionString' => 'sqlsrv:Server=localhost;Database=limesurvey',
|
||||
'username' => 'sa',
|
||||
'password' => 'somepassword',
|
||||
'charset' => 'utf8',
|
||||
'tablePrefix' => 'lime_',
|
||||
'initSQLs'=>array('SET DATEFORMAT ymd;','SET QUOTED_IDENTIFIER ON;'),
|
||||
),
|
||||
|
||||
// Uncomment the following line if you need table-based sessions
|
||||
// 'session' => array (
|
||||
// 'class' => 'system.web.CDbHttpSession',
|
||||
// 'connectionID' => 'db',
|
||||
// 'sessionTableName' => '{{sessions}}',
|
||||
// ),
|
||||
|
||||
'urlManager' => array(
|
||||
'urlFormat' => 'get',
|
||||
'rules' => require('routes.php'),
|
||||
'showScriptName' => true,
|
||||
),
|
||||
|
||||
),
|
||||
// Use the following config variable to set modified optional settings copied from config-defaults.php
|
||||
'config'=>array(
|
||||
// debug: Set this to 1 if you are looking for errors. If you still get no errors after enabling this
|
||||
// then please check your error-logs - either in your hosting provider admin panel or in some /logs directory
|
||||
// on your webspace.
|
||||
// LimeSurvey developers: Set this to 2 to additionally display STRICT PHP error messages and get full access to standard templates
|
||||
'debug'=>0,
|
||||
'debugsql'=>0 // Set this to 1 to enanble sql logging, only active when debug = 2
|
||||
)
|
||||
);
|
||||
/* End of file config.php */
|
||||
/* Location: ./application/config/config.php */
|
51
sources/application/config/email.php
Normal file
51
sources/application/config/email.php
Normal file
|
@ -0,0 +1,51 @@
|
|||
<?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.
|
||||
*/
|
||||
|
||||
|
||||
// ===== CAUTION - DO NOT EDIT THIS FILE ======
|
||||
// This file contains the default email settings for LimeSurvey
|
||||
// Do not edit this file as it may change in future revisions of the software.
|
||||
//
|
||||
// Correct procedure to set up LimeSurvey is the following:
|
||||
// 1.) copy the lines corresponding to the parameter you want to change
|
||||
// from this file to the config.php file
|
||||
// 2.) edit these lines in config.php
|
||||
|
||||
|
||||
// Email Settings
|
||||
// These settings determine how LimeSurvey will send emails
|
||||
$config = array();
|
||||
$config['siteadminemail'] = 'your-email@example.net'; // The default email address of the site administrator
|
||||
$config['siteadminbounce'] = 'your-email@example.net'; // The default email address used for error notification of sent messages for the site administrator (Return-Path)
|
||||
$config['siteadminname'] = 'Your Name'; // The name of the site administrator
|
||||
|
||||
$config['emailmethod'] = 'mail'; // The following values can be used:
|
||||
$config['protocol'] = $config['emailmethod'];
|
||||
// mail - use internal PHP Mailer
|
||||
// sendmail - use Sendmail Mailer
|
||||
// smtp - use SMTP relaying
|
||||
|
||||
$config['emailsmtphost'] = 'localhost'; // Sets the SMTP host. You can also specify a different port than 25 by using
|
||||
// this format: [hostname:port] (e.g. 'smtp1.example.com:25').
|
||||
|
||||
$config['emailsmtpuser'] = ''; // SMTP authorisation username - only set this if your server requires authorization - if you set it you HAVE to set a password too
|
||||
$config['emailsmtppassword'] = ''; // SMTP authorisation password - empty password is not allowed
|
||||
$config['emailsmtpssl'] = ''; // Set this to 'ssl' or 'tls' to use SSL/TLS for SMTP connection
|
||||
|
||||
$config['emailsmtpdebug'] = 0; // Settings this to 1 activates SMTP debug mode
|
||||
|
||||
$config['maxemails'] = 50; // The maximum number of emails to send in one go (this is to prevent your mail server or script from timeouting when sending mass mail)
|
||||
|
||||
$config['emailcharset'] = "utf-8";
|
||||
|
||||
return $config; // You can change this to change the charset of outgoing emails to some other encoding - like 'iso-8859-1'
|
10
sources/application/config/index.html
Normal file
10
sources/application/config/index.html
Normal file
|
@ -0,0 +1,10 @@
|
|||
<html>
|
||||
<head>
|
||||
<title>403 Forbidden</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<p>Directory access is forbidden.</p>
|
||||
|
||||
</body>
|
||||
</html>
|
75
sources/application/config/internal.php
Normal file
75
sources/application/config/internal.php
Normal file
|
@ -0,0 +1,75 @@
|
|||
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
|
||||
|
||||
/**
|
||||
* This file contains configuration parameters for the Yii framework.
|
||||
* Do not change these unless you know what you are doing.
|
||||
*
|
||||
*/
|
||||
@date_default_timezone_set(@date_default_timezone_get());
|
||||
$internalConfig = array(
|
||||
'basePath' => dirname(dirname(__FILE__)),
|
||||
'runtimePath' => dirname(dirname(dirname(__FILE__))).DIRECTORY_SEPARATOR.'tmp'.DIRECTORY_SEPARATOR.'runtime',
|
||||
'name' => 'LimeSurvey',
|
||||
'defaultController' => 'surveys',
|
||||
'import' => array(
|
||||
'application.core.*',
|
||||
'application.models.*',
|
||||
'application.controllers.*',
|
||||
'application.modules.*',
|
||||
),
|
||||
'components' => array(
|
||||
'bootstrap' => array(
|
||||
'class' => 'application.core.LSBootstrap',
|
||||
'responsiveCss' => false,
|
||||
'jqueryCss' => false
|
||||
),
|
||||
'urlManager' => array(
|
||||
'urlFormat' => 'get',
|
||||
'rules' => require('routes.php'),
|
||||
'showScriptName' => true,
|
||||
),
|
||||
|
||||
'clientScript' => array(
|
||||
'packages' => require('third_party.php')
|
||||
),
|
||||
'assetManager' => array(
|
||||
'baseUrl' => '/tmp/assets'
|
||||
),
|
||||
'request' => array(
|
||||
'class'=>'LSHttpRequest',
|
||||
'noCsrfValidationRoutes'=>array(
|
||||
// '^services/wsdl.*$' // Set here additional regex rules for routes not to be validate
|
||||
'remotecontrol'
|
||||
),
|
||||
'enableCsrfValidation'=>true, // CSRF protection
|
||||
'enableCookieValidation'=>false // Enable to activate cookie protection
|
||||
),
|
||||
'user' => array(
|
||||
'class' => 'LSWebUser',
|
||||
),
|
||||
'log' => array(
|
||||
'class' => 'CLogRouter'
|
||||
),
|
||||
'cache'=>array(
|
||||
'class'=>'system.caching.CFileCache',
|
||||
),
|
||||
'db' => array(
|
||||
'schemaCachingDuration' => 3600,
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
if (!file_exists(dirname(__FILE__) . '/config.php')) {
|
||||
$userConfig = require(dirname(__FILE__) . '/config-sample-mysql.php');
|
||||
} else {
|
||||
$userConfig = require(dirname(__FILE__) . '/config.php');
|
||||
}
|
||||
|
||||
$result = CMap::mergeArray($internalConfig, $userConfig);
|
||||
/**
|
||||
* Some workarounds for erroneous settings in user config.php.
|
||||
*/
|
||||
$result['defaultController'] = $internalConfig['defaultController'];
|
||||
return $result;
|
||||
/* End of file internal.php */
|
||||
/* Location: ./application/config/internal.php */
|
213
sources/application/config/ldap.php
Normal file
213
sources/application/config/ldap.php
Normal file
|
@ -0,0 +1,213 @@
|
|||
<?php
|
||||
/*
|
||||
* 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.
|
||||
*
|
||||
*/
|
||||
|
||||
/*********** LDAP Parameters and Functions ***********************
|
||||
*
|
||||
* - First define your ldap servers and remember the serverId
|
||||
* - Then define your ldap_query and 'attach' it to the serverId
|
||||
******************************************************************/
|
||||
|
||||
/*********************************************/
|
||||
/* LDAP servers */
|
||||
/*********************************************/
|
||||
|
||||
$serverId=0;
|
||||
// Define the server DNS name or IP Address
|
||||
// If encryption is enabled, make sure the name given here
|
||||
// corresponds to the certificate's identity
|
||||
$ldap_server[$serverId]['server'] = "ldap.mycompany.org";
|
||||
|
||||
// Define the TCP port on which the LDAP server is listenning
|
||||
// This should be 389 for standard LDAP servers
|
||||
// or 636 for standard LDAPS connections
|
||||
$ldap_server[$serverId]['port'] = "636";
|
||||
|
||||
// Define the ldap protocol to use
|
||||
// 'ldapv2' and 'ldapv3' are supported
|
||||
$ldap_server[$serverId]['protoversion'] = "ldapv2";
|
||||
|
||||
// Define the encryption method to use
|
||||
// 'ldaps' is supported for 'ldapv2' servers
|
||||
// 'start-tls' is supproted for 'ldapv3' servers
|
||||
// 'none' is supproted for no encryption at all
|
||||
// Don't forget to setup your CA's certificate in
|
||||
// the openldap ldap.conf file
|
||||
$ldap_server[$serverId]['encrypt'] = "ldaps";
|
||||
|
||||
// Define the referral option
|
||||
// 'false' is recommended for ActiveDirectory servers
|
||||
$ldap_server[$serverId]['referrals'] = false;
|
||||
|
||||
// Define the encoding used by the Ldap directory
|
||||
// You may omit this parameter (let it commented out)
|
||||
// as the default value, 'utf-8', should work for most installations.
|
||||
// However, Active Directory in West Europe may use 'cp850'.
|
||||
// $ldap_server[$serverId]['encoding'] = 'utf-8';
|
||||
|
||||
// Define the authentication used to bind to the directory
|
||||
// We currently support simple authentication
|
||||
// If anonymous bind must be performed, comment the following two lines
|
||||
// Note that Active Directory (AD) usually requires authentication before
|
||||
// you are authorized to read its content. Remeber as well that user's DN
|
||||
// in AD are in the form of CN=username,CN=Users,DC=WindowsDomainName,DC=mycompany,DC=org
|
||||
//
|
||||
$ldap_server[$serverId]['binddn'] = "uid=mybinduser,dc=mycompany,dc=org";
|
||||
$ldap_server[$serverId]['bindpw'] = "AsecretPassword";
|
||||
|
||||
/********* Copy for more definitions *****
|
||||
$serverId++;
|
||||
$ldap_server[$serverId]['server'] = "ldap.mycompany.org";
|
||||
$ldap_server[$serverId]['port'] = "389";
|
||||
$ldap_server[$serverId]['protoversion'] = "ldapv3";
|
||||
$ldap_server[$serverId]['encrypt'] = "start-tls";
|
||||
$ldap_server[$serverId]['referrals'] = false;
|
||||
$ldap_server[$serverId]['binddn'] = "uid=mybinduser,dc=mycompany,dc=org";
|
||||
$ldap_server[$serverId]['bindpw'] = "AsecretPassword";
|
||||
*****************************************/
|
||||
|
||||
/**********************************************************************/
|
||||
/* Predefined Queries for Token Imports */
|
||||
/* */
|
||||
/* This sample query definition is just an fake template: do not */
|
||||
/* expect it to do something intelligent on your directory */
|
||||
/* Instead have a look at the online documentation: */
|
||||
/* - Section Installation, paragraph LDAP_Settings */
|
||||
/* And for Active Directory tips: */
|
||||
/* - Section Installation FAQ, paragraph */
|
||||
/* How_do_I_configure_LDAP_settings_to_work_with_Active_Directory_ */
|
||||
/**********************************************************************/
|
||||
|
||||
$query_id=0;
|
||||
|
||||
// First define the serverId on which you want to run the query
|
||||
$ldap_queries[$query_id]['ldapServerId'] = 0;
|
||||
|
||||
// Give a name that will appear on the user interface
|
||||
$ldap_queries[$query_id]['name'] = 'Staff with an enabled account';
|
||||
|
||||
// Define the ldap base used for user searches
|
||||
$ldap_queries[$query_id]['userbase'] = 'ou=staff,dc=mycompany,dc=org';
|
||||
|
||||
// Define the user filter to apply
|
||||
// Must begin with '(' and end with ')'
|
||||
// Note that for AD, checking the 'active' status of a user is done with the following filter:
|
||||
// "(&(objectCategory=Person)(objectClass=user)(!(userAccountControl=514)))"
|
||||
$ldap_queries[$query_id]['userfilter'] = '(&(objectClass=inetOrgPerson)(my-fake-accountstatus-attribute=enabled))';
|
||||
|
||||
// Define how deep under the userbase you want to search
|
||||
// 'sub' means: search on the entire subtree
|
||||
// 'one' means: only search 1 level under the userbase
|
||||
// 'base' means: only search the userbase DN entry
|
||||
$ldap_queries[$query_id]['userscope'] = 'sub';
|
||||
|
||||
// Define the user's attribute that provides the firstname
|
||||
// do not use capital letters in the attribute name
|
||||
// for instance use 'givenname' and not 'givenName'
|
||||
$ldap_queries[$query_id]['firstname_attr'] = 'givenname';
|
||||
|
||||
// Give the user's attribute that provides the lastname
|
||||
// do not use capital letters in the attribute name
|
||||
$ldap_queries[$query_id]['lastname_attr'] = 'sn';
|
||||
|
||||
// Give the user's attribute that provides the email address
|
||||
// do not use capital letters in the attribute name
|
||||
// If multivalued, only the first entry is read
|
||||
$ldap_queries[$query_id]['email_attr'] = 'mail';
|
||||
|
||||
|
||||
// Optionnally give the user's attributes that provides the
|
||||
// token, language, attr1 and attr2 piece of information
|
||||
// do not use capital letters in the attribute name
|
||||
// if unused, leave empty or comment the lines
|
||||
$ldap_queries[$query_id]['token_attr'] = ''; // Leave empty for Auto Token generation bu phpsv
|
||||
$ldap_queries[$query_id]['language'] = '';
|
||||
$ldap_queries[$query_id]['attr1'] = '';
|
||||
$ldap_queries[$query_id]['attr2'] = '';
|
||||
|
||||
/********** Other queries examples ********************/
|
||||
|
||||
// This query is an example of a group search in which group members are DNs
|
||||
// The query runs in two steps:
|
||||
// 1- Look for user candidates matching the group filter part
|
||||
// 2- Then, Apply a user filter to user candidates found in step 1
|
||||
$query_id++;
|
||||
$ldap_queries[$query_id]['ldapServerId'] = 0;
|
||||
$ldap_queries[$query_id]['name'] = 'Administrator group';
|
||||
// Define a group filter (base, filter, scope)
|
||||
// Note that in AD, user groups are defined in the foloowing base:
|
||||
// CN=Users,DC=WindowsDomainName,DC=mycompany,DC=org
|
||||
$ldap_queries[$query_id]['groupbase'] = 'ou=groups,dc=mycompany,dc=org';
|
||||
$ldap_queries[$query_id]['groupfilter'] = '(&(objectClass=groupOfNames)(cn=AdministratorGroup))';
|
||||
$ldap_queries[$query_id]['groupscope'] = 'sub';
|
||||
// Define which group's attribute is used to get users' Ids
|
||||
$ldap_queries[$query_id]['groupmemberattr'] = 'member';
|
||||
// Define if the groupmemberattr contains users's DNs or NOT
|
||||
$ldap_queries[$query_id]['groupmemberisdn'] = true;
|
||||
|
||||
// Optionnally you can complete the group query with an additionnal
|
||||
// user filter that will be applied to the user's found by the group search
|
||||
// Comment the userbase, userfilter, and userscope lines
|
||||
// if you don't use this extra filter.
|
||||
$ldap_queries[$query_id]['userbase'] = 'ou=users,dc=mycompany,dc=org';
|
||||
$ldap_queries[$query_id]['userfilter'] = '(my-fake-accountstatus-attribute=enabled)';
|
||||
$ldap_queries[$query_id]['userscope'] = 'sub';
|
||||
|
||||
$ldap_queries[$query_id]['firstname_attr'] = 'givenname';
|
||||
$ldap_queries[$query_id]['lastname_attr'] = 'sn';
|
||||
$ldap_queries[$query_id]['email_attr'] = 'mail';
|
||||
$ldap_queries[$query_id]['token_attr'] = ''; // Leave empty for Auto Token generation bu phpsv
|
||||
$ldap_queries[$query_id]['language'] = '';
|
||||
$ldap_queries[$query_id]['attr1'] = '';
|
||||
$ldap_queries[$query_id]['attr2'] = '';
|
||||
|
||||
|
||||
// This query is an example of a group search in which group members are UIDs
|
||||
// an additionnal user filter is applied to a already found users
|
||||
$query_id++;
|
||||
$ldap_queries[$query_id]['ldapServerId'] = 0;
|
||||
$ldap_queries[$query_id]['name'] = 'Admins via POSIXGroups';
|
||||
$ldap_queries[$query_id]['groupbase'] = 'ou=group,dc=mycompany,dc=org';
|
||||
$ldap_queries[$query_id]['groupfilter'] = '(&(cn=admins)(objectclass=posixgroup))';
|
||||
$ldap_queries[$query_id]['groupscope'] = 'sub';
|
||||
// Define which attribute within the group entry contains users' IDs
|
||||
$ldap_queries[$query_id]['groupmemberattr'] = 'memberuid';
|
||||
// Declare that groupmemberattr contains users' IDs and not DNs
|
||||
$ldap_queries[$query_id]['groupmemberisdn'] = FALSE;
|
||||
// Give the name of the attribute in the user entry that matches the
|
||||
// 'groupmemberattr' value
|
||||
$ldap_queries[$query_id]['useridattr'] = 'uid';
|
||||
// Give the base DN used to search the users based on the users' IDs
|
||||
$ldap_queries[$query_id]['userbase'] = 'ou=people,dc=mycompany,dc=org';
|
||||
// Optionnally give an additionnal filter to filter users
|
||||
$ldap_queries[$query_id]['userfilter'] = '(objectclass=*)';
|
||||
$ldap_queries[$query_id]['userscope'] = 'sub';
|
||||
|
||||
$ldap_queries[$query_id]['firstname_attr'] = 'givenname';
|
||||
$ldap_queries[$query_id]['lastname_attr'] = 'sn';
|
||||
$ldap_queries[$query_id]['email_attr'] = 'mail';
|
||||
$ldap_queries[$query_id]['token_attr'] = ''; // Leave empty for Auto Token generation bu phpsv
|
||||
$ldap_queries[$query_id]['language'] = '';
|
||||
$ldap_queries[$query_id]['attr1'] = '';
|
||||
$ldap_queries[$query_id]['attr2'] = '';
|
||||
|
||||
/********
|
||||
$query_id++;
|
||||
//Copy previous definition lines
|
||||
********/
|
||||
|
||||
|
||||
//DO NOT CHANGE BELOW HERE --------------------
|
||||
|
||||
return array('ldap_server' => $ldap_server, 'ldap_queries' => $ldap_queries);
|
||||
?>
|
39
sources/application/config/routes.php
Normal file
39
sources/application/config/routes.php
Normal file
|
@ -0,0 +1,39 @@
|
|||
<?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.
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
//Compatibility with classic modrewrite
|
||||
$route['<_sid:\d+>/lang-<_lang:\w+[-\w]+>/tk-<_token:\w+>/*'] = "survey/index/sid/<_sid>/lang/<_lang>/token/<_token>"; //This one must be first
|
||||
$route['<_sid:\d+>/lang-<_lang:\w+[-\w]+>/*'] = "survey/index/sid/<_sid>/lang/<_lang>";
|
||||
$route['<_sid:\d+>/tk-<_token:\w+>/*'] = "survey/index/sid/<_sid>/token/<_token>";
|
||||
$route['<_sid:\d+>/*'] = "survey/index/sid/<_sid>";
|
||||
|
||||
//Admin Routes
|
||||
$route['admin/index'] = "admin";
|
||||
$route['admin/<action:\w+>/sa/<sa:\w+>/*'] = 'admin/<action>/sa/<sa>';
|
||||
$route['admin/<action:\w+>/<sa:\w+>/*'] = 'admin/<action>/sa/<sa>';
|
||||
|
||||
//question
|
||||
$route['admin/labels/<_action:\w+>'] = "admin/labels/index/<_action>";
|
||||
$route['admin/labels/<_action:\w+>/<_lid:\d+>'] = "admin/labels/index/<_action>/<_lid>";
|
||||
|
||||
$route['<_controller:\w+>/<_action:\w+>'] = '<_controller>/<_action>';
|
||||
|
||||
//Expression Manager tests
|
||||
$route['admin/expressions'] = "admin/expressions/index";
|
||||
|
||||
//optout
|
||||
$route['optout/<_sid:\d+>/(:any)/(:any)'] = "optout/index/<_sid>/$2/$3";
|
||||
|
||||
return $route;
|
263
sources/application/config/tcpdf.php
Normal file
263
sources/application/config/tcpdf.php
Normal file
|
@ -0,0 +1,263 @@
|
|||
<?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.
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* TCPDF configuration file
|
||||
*
|
||||
* @package configuration
|
||||
*/
|
||||
|
||||
|
||||
/***************************************************************************
|
||||
* PATH CONFIGURATION PARAMETERS
|
||||
**************************************************************************/
|
||||
|
||||
|
||||
/************************************************************
|
||||
* TCPDF installation directory
|
||||
* ----------------------------------------------------------
|
||||
* This is the base installation directory for your TCPDF
|
||||
* package (the folder that contains tcpdf.php).
|
||||
*
|
||||
* ADD TRAILING SLASH!
|
||||
***********************************************************/
|
||||
|
||||
$tcpdf['base_directory'] = APPPATH.'third_party'.DIRECTORY_SEPARATOR.'tcpdf'.DIRECTORY_SEPARATOR;
|
||||
|
||||
|
||||
/************************************************************
|
||||
* TCPDF installation directory URL
|
||||
* ----------------------------------------------------------
|
||||
* This is the URL path to the TCPDF base installation
|
||||
* directory (the URL equivalent to the 'base_directory'
|
||||
* option above).
|
||||
*
|
||||
* ADD TRAILING SLASH!
|
||||
***********************************************************/
|
||||
|
||||
$tcpdf['base_url'] = '';
|
||||
|
||||
|
||||
/************************************************************
|
||||
* TCPDF fonts directory
|
||||
* ----------------------------------------------------------
|
||||
* This is the directory of the TCPDF fonts folder.
|
||||
* Use $tcpdf['base_directory'].'fonts/old/' for old non-UTF8
|
||||
* fonts.
|
||||
*
|
||||
* ADD TRAILING SLASH!
|
||||
***********************************************************/
|
||||
|
||||
$tcpdf['fonts_directory'] = $tcpdf['base_directory'].'fonts'.DIRECTORY_SEPARATOR;
|
||||
|
||||
|
||||
/************************************************************
|
||||
* TCPDF disk cache settings
|
||||
* ----------------------------------------------------------
|
||||
* Enable caching; Cache directory for TCPDF (make sure that
|
||||
* it is writable by the webserver).
|
||||
*
|
||||
* ADD TRAILING SLASH!
|
||||
***********************************************************/
|
||||
|
||||
$tcpdf['enable_disk_cache'] = FALSE;
|
||||
$tcpdf['cache_directory'] = Yii::app()->getConfig('tempdir').DIRECTORY_SEPARATOR;
|
||||
|
||||
|
||||
/************************************************************
|
||||
* TCPDF image directory
|
||||
* ----------------------------------------------------------
|
||||
* This is the image directory for TCPDF. This is where you
|
||||
* can store images to use in your PDF files.
|
||||
*
|
||||
* ADD TRAILING SLASH!
|
||||
***********************************************************/
|
||||
|
||||
$tcpdf['image_directory'] = Yii::app()->getConfig('rootdir').DIRECTORY_SEPARATOR.'styles'.DIRECTORY_SEPARATOR.Yii::app()->getConfig('admintheme').DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR;
|
||||
|
||||
/************************************************************
|
||||
* TCPDF default (blank) image
|
||||
* ----------------------------------------------------------
|
||||
* This is the path and filename to the default (blank)
|
||||
* image.
|
||||
***********************************************************/
|
||||
|
||||
$tcpdf['blank_image'] = $tcpdf['image_directory'].'_blank.png';
|
||||
|
||||
|
||||
/************************************************************
|
||||
* TCPDF language settings file
|
||||
* ----------------------------------------------------------
|
||||
* Directory and filename of the language settings file
|
||||
***********************************************************/
|
||||
|
||||
$tcpdf['language_file'] = $tcpdf['base_directory'].'config'.DIRECTORY_SEPARATOR.'lang'.DIRECTORY_SEPARATOR.'eng.php';
|
||||
|
||||
|
||||
|
||||
/***************************************************************************
|
||||
* DOCUMENT CONFIGURATION PARAMETERS
|
||||
**************************************************************************/
|
||||
|
||||
|
||||
/************************************************************
|
||||
* TCPDF default page format
|
||||
* ----------------------------------------------------------
|
||||
* This is the default page size. Supported formats include:
|
||||
*
|
||||
* 4A0, 2A0, A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, B0,
|
||||
* B1, B2, B3, B4, B5, B6, B7, B8, B9, B10, C0, C1, C2, C3,
|
||||
* C4, C5, C6, C7, C8, C9, C10, RA0, RA1, RA2, RA3, RA4,
|
||||
* SRA0, SRA1, SRA2, SRA3, SRA4, LETTER, LEGAL, EXECUTIVE,
|
||||
* FOLIO
|
||||
*
|
||||
* Or, you can optionally specify a custom format in the form
|
||||
* of a two-element array containing the width and the height.
|
||||
************************************************************/
|
||||
|
||||
$tcpdf['page_format'] = 'A4';
|
||||
|
||||
|
||||
/************************************************************
|
||||
* TCPDF default page orientation
|
||||
* ----------------------------------------------------------
|
||||
* Default page layout.
|
||||
* P = portrait, L = landscape
|
||||
***********************************************************/
|
||||
|
||||
$tcpdf['page_orientation'] = 'P';
|
||||
|
||||
|
||||
/************************************************************
|
||||
* TCPDF default unit of measure
|
||||
* ----------------------------------------------------------
|
||||
* Unit of measure.
|
||||
* mm = millimeters, cm = centimeters,
|
||||
* pt = points, in = inches
|
||||
*
|
||||
* 1 point = 1/72 in = ~0.35 mm
|
||||
* 1 inch = 2.54 cm
|
||||
***********************************************************/
|
||||
|
||||
$tcpdf['page_unit'] = 'mm';
|
||||
|
||||
|
||||
/************************************************************
|
||||
* TCPDF auto page break
|
||||
* ----------------------------------------------------------
|
||||
* Enables automatic flowing of content to the next page if
|
||||
* you run out of room on the current page.
|
||||
***********************************************************/
|
||||
|
||||
$tcpdf['page_break_auto'] = TRUE;
|
||||
|
||||
|
||||
/************************************************************
|
||||
* TCPDF text encoding
|
||||
* ----------------------------------------------------------
|
||||
* Specify TRUE if the input text you will be using is
|
||||
* unicode, and specify the default encoding.
|
||||
***********************************************************/
|
||||
|
||||
$tcpdf['unicode'] = TRUE;
|
||||
$tcpdf['encoding'] = 'UTF-8';
|
||||
|
||||
|
||||
/************************************************************
|
||||
* TCPDF default document creator and author strings
|
||||
***********************************************************/
|
||||
|
||||
$tcpdf['creator'] = 'TCPDF';
|
||||
$tcpdf['author'] = 'TCPDF';
|
||||
|
||||
|
||||
/************************************************************
|
||||
* TCPDF default page margin
|
||||
* ----------------------------------------------------------
|
||||
* Top, bottom, left, right, header, and footer margin
|
||||
* settings in the default unit of measure.
|
||||
***********************************************************/
|
||||
|
||||
$tcpdf['margin_top'] = 27;
|
||||
$tcpdf['margin_bottom'] = 27;
|
||||
$tcpdf['margin_left'] = 15;
|
||||
$tcpdf['margin_right'] = 15;
|
||||
|
||||
|
||||
/************************************************************
|
||||
* TCPDF default font settings
|
||||
* ----------------------------------------------------------
|
||||
* Page font, font size, header and footer fonts,
|
||||
* HTML <small> font size ratio
|
||||
***********************************************************/
|
||||
|
||||
$tcpdf['page_font'] = 'freemono';
|
||||
$tcpdf['page_font_size'] = 9;
|
||||
|
||||
$tcpdf['small_font_ratio'] = 2/3;
|
||||
|
||||
|
||||
/************************************************************
|
||||
* TCPDF header settings
|
||||
* ----------------------------------------------------------
|
||||
* Enable the header, set the font, default text, margin,
|
||||
* description string, and logo
|
||||
***********************************************************/
|
||||
|
||||
$tcpdf['header_on'] = TRUE;
|
||||
$tcpdf['header_font'] = $tcpdf['page_font'];
|
||||
$tcpdf['header_font_size'] = 10;
|
||||
$tcpdf['header_margin'] = 5;
|
||||
//$tcpdf['header_title'] = 'TCPDF Example';
|
||||
//$tcpdf['header_string'] = "by Nicola Asuni - Tecnick.com\nwww.tcpdf.org";
|
||||
$tcpdf['header_title'] = '';
|
||||
$tcpdf['header_string'] = "";
|
||||
//$tcpdf['header_logo'] = 'tcpdf_logo.jpg';
|
||||
$tcpdf['header_logo'] = '';
|
||||
$tcpdf['header_logo_width'] = 30;
|
||||
|
||||
|
||||
/************************************************************
|
||||
* TCPDF footer settings
|
||||
* ----------------------------------------------------------
|
||||
* Enable the header, set the font, default text, and margin
|
||||
***********************************************************/
|
||||
|
||||
$tcpdf['footer_on'] = TRUE;
|
||||
$tcpdf['footer_font'] = $tcpdf['page_font'];
|
||||
$tcpdf['footer_font_size'] = 8;
|
||||
$tcpdf['footer_margin'] = 10;
|
||||
|
||||
|
||||
/************************************************************
|
||||
* TCPDF image scale ratio
|
||||
* ----------------------------------------------------------
|
||||
* Image scale ratio (decimal format).
|
||||
***********************************************************/
|
||||
|
||||
$tcpdf['image_scale'] = 4;
|
||||
|
||||
|
||||
/************************************************************
|
||||
* TCPDF cell settings
|
||||
* ----------------------------------------------------------
|
||||
* Fontsize-to-height ratio, cell padding
|
||||
***********************************************************/
|
||||
|
||||
$tcpdf['cell_height_ratio'] = 1.25;
|
||||
$tcpdf['cell_padding'] = 0;
|
||||
|
||||
return $tcpdf;
|
||||
|
226
sources/application/config/third_party.php
Normal file
226
sources/application/config/third_party.php
Normal file
|
@ -0,0 +1,226 @@
|
|||
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
|
||||
|
||||
/**
|
||||
* This file contains package definition for third party libraries.
|
||||
* Defining them here allows for easy inclusion in views.
|
||||
*/
|
||||
return array(
|
||||
'jquery' => array(
|
||||
'baseUrl' => 'third_party/jquery/',
|
||||
'js' => array(
|
||||
'jquery-1.11.1.min.js'
|
||||
)
|
||||
),
|
||||
'jqgrid' => array(
|
||||
'baseUrl' => 'third_party/jqgrid/',
|
||||
'js' => array(
|
||||
'js/jquery.jqGrid.min.js',
|
||||
'js/i18n/grid.locale-en.js',
|
||||
'plugins/jquery.searchFilter.js'
|
||||
),
|
||||
'css' => array(
|
||||
'css/ui.jqgrid.css'
|
||||
),
|
||||
'depends' => array(
|
||||
'jquery'
|
||||
)
|
||||
|
||||
),
|
||||
'jqgrid.addons' => array(
|
||||
'baseUrl' => 'third_party/jqgrid/plugins/',
|
||||
'js' => array(
|
||||
'grid.addons.js'
|
||||
),
|
||||
'depends' => array(
|
||||
'jqgrid'
|
||||
)
|
||||
|
||||
),
|
||||
'jquery-notify' => array(
|
||||
'baseUrl' => 'third_party/jquery-notify',
|
||||
'js' => array(
|
||||
'src/jquery.notify.min.js'
|
||||
),
|
||||
'css' => array(
|
||||
'ui.notify.css'
|
||||
),
|
||||
'depends' => array(
|
||||
'jqueryui'
|
||||
)
|
||||
|
||||
),
|
||||
'jqueryui' => array(
|
||||
'baseUrl' => 'third_party/jqueryui/',
|
||||
'js' => array(
|
||||
'js/jquery-ui-1.10.3.custom.min.js'
|
||||
),
|
||||
'css' => array(
|
||||
//'css/smoothness/jquery-ui-1.10.0.custom.min.css'
|
||||
),
|
||||
'depends' => array(
|
||||
'jquery',
|
||||
'bootstrap'
|
||||
)
|
||||
),
|
||||
'jquery-bindWithDelay' => array(
|
||||
'baseUrl' => 'third_party/jquery-bindWithDelay',
|
||||
'js' => array(
|
||||
'bindWithDelay.js'
|
||||
),
|
||||
'depends' => array(
|
||||
'jquery'
|
||||
)
|
||||
),
|
||||
'jquery-cookie' => array(
|
||||
'baseUrl' => 'third_party/jquery-cookie',
|
||||
'js' => array(
|
||||
'jquery.cookie.js'
|
||||
),
|
||||
'depends' => array(
|
||||
'jquery'
|
||||
)
|
||||
),
|
||||
'jquery-superfish' => array(
|
||||
'baseUrl' => 'third_party/jquery-superfish',
|
||||
'js' => array(
|
||||
'js/superfish.js',
|
||||
'js/hoverIntent.js'
|
||||
),
|
||||
'css' => array(
|
||||
'css/superfish.css'
|
||||
),
|
||||
'depends' => array(
|
||||
'jquery'
|
||||
)
|
||||
|
||||
),
|
||||
'jquery-json' => array(
|
||||
'baseUrl' => 'third_party/jquery-json',
|
||||
'js' => array(
|
||||
'jquery.json-2.4.min.js'
|
||||
),
|
||||
'depends' => array(
|
||||
'jquery'
|
||||
)
|
||||
),
|
||||
'jquery-blockUI' => array(
|
||||
'baseUrl' => 'third_party/jquery-blockui',
|
||||
'js' => array(
|
||||
'jquery.blockUI.js'
|
||||
)
|
||||
),
|
||||
'qTip2' => array(
|
||||
'baseUrl' => 'third_party/qTip2',
|
||||
'js' => array(
|
||||
'dist/jquery.qtip.min.js'
|
||||
),
|
||||
'css' => array(
|
||||
'dist/jquery.qtip.min.css'
|
||||
),
|
||||
'depends' => array(
|
||||
'jquery'
|
||||
)
|
||||
|
||||
),
|
||||
'jquery-tablesorter' => array(
|
||||
'baseUrl' => 'third_party/jquery-tablesorter',
|
||||
'js' => array(
|
||||
'jquery.tablesorter.min.js'
|
||||
),
|
||||
'depends' => array(
|
||||
'jquery'
|
||||
)
|
||||
),
|
||||
'jquery-nestedSortable' => array(
|
||||
'baseUrl' => 'third_party/jquery-nestedSortable',
|
||||
'js' => array(
|
||||
'jquery.mjs.nestedSortable.js'
|
||||
),
|
||||
'depends' => array(
|
||||
'jqueryui'
|
||||
)
|
||||
),
|
||||
'jquery-multiselect' => array(
|
||||
'baseUrl' => 'third_party/jquery-multiselect',
|
||||
'js' => array(
|
||||
'src/jquery.multiselect.min.js',
|
||||
'src/jquery.multiselect.filter.min.js'
|
||||
),
|
||||
'css' => array(
|
||||
'jquery.multiselect.css',
|
||||
'jquery.multiselect.filter.css'
|
||||
),
|
||||
'depends' => array(
|
||||
'jquery'
|
||||
)
|
||||
),
|
||||
'bootstrap-multiselect' => array(
|
||||
'baseUrl' => 'third_party/bootstrap-multiselect',
|
||||
'js' => array(
|
||||
'js/bootstrap-multiselect.js',
|
||||
),
|
||||
'css' => array(
|
||||
'css/bootstrap-multiselect.css',
|
||||
),
|
||||
'depends' => array(
|
||||
'jquery'
|
||||
)
|
||||
),
|
||||
'ace' => array(
|
||||
'baseUrl' => 'third_party/ace',
|
||||
'js' => array(
|
||||
'ace.js'
|
||||
),
|
||||
'depends' => array(
|
||||
'jquery-ace'
|
||||
)
|
||||
),
|
||||
'jquery-ace' => array(
|
||||
'baseUrl' => 'third_party/jquery-ace',
|
||||
'js' => array(
|
||||
'jquery.ace.js',
|
||||
),
|
||||
'depends' => array(
|
||||
'jquery',
|
||||
)
|
||||
),
|
||||
'jquery-selectboxes' => array(
|
||||
'baseUrl' => 'third_party/jquery-selectboxes/selectboxes',
|
||||
'js' => array(
|
||||
'jquery.selectboxes.js'
|
||||
),
|
||||
'depends' => array(
|
||||
'jquery'
|
||||
)
|
||||
),
|
||||
'jquery-actual' => array(
|
||||
'baseUrl' => 'third_party/jquery-actual/',
|
||||
'js' => array(
|
||||
'jquery.actual.min.js'
|
||||
),
|
||||
'depends' => array(
|
||||
'jquery'
|
||||
)
|
||||
),
|
||||
'jquery-touch-punch' => array(
|
||||
'baseUrl' => 'third_party/jquery-touch-punch/',
|
||||
'js' => array(
|
||||
'jquery.ui.touch-punch.min.js'
|
||||
),
|
||||
'depends' => array(
|
||||
'jqueryui'
|
||||
)
|
||||
),
|
||||
'jqueryui-timepicker' => array(
|
||||
'baseUrl' => 'third_party/jquery-ui-timepicker-addon/',
|
||||
'js' => array(
|
||||
'jquery-ui-timepicker-addon.js'
|
||||
),
|
||||
'css' => array(
|
||||
'jquery-ui-timepicker-addon.css'
|
||||
),
|
||||
'depends' => array(
|
||||
'jqueryui'
|
||||
)
|
||||
)
|
||||
);
|
22
sources/application/config/version.php
Normal file
22
sources/application/config/version.php
Normal file
|
@ -0,0 +1,22 @@
|
|||
<?php
|
||||
/*
|
||||
* 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.
|
||||
*
|
||||
*/
|
||||
|
||||
$config['versionnumber'] = "2.05+";
|
||||
$config['dbversionnumber'] = 177;
|
||||
$config['buildnumber'] = '';
|
||||
$config['updatable'] = true;
|
||||
|
||||
return $config;
|
||||
|
||||
?>
|
430
sources/application/controllers/AdminController.php
Normal file
430
sources/application/controllers/AdminController.php
Normal file
|
@ -0,0 +1,430 @@
|
|||
<?php
|
||||
/*
|
||||
* 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.
|
||||
*
|
||||
*/
|
||||
|
||||
class AdminController extends LSYii_Controller
|
||||
{
|
||||
public $lang = null;
|
||||
public $layout = false;
|
||||
protected $user_id = 0;
|
||||
|
||||
/**
|
||||
* Initialises this controller, does some basic checks and setups
|
||||
*
|
||||
* @access protected
|
||||
* @return void
|
||||
*/
|
||||
protected function _init()
|
||||
{
|
||||
parent::_init();
|
||||
App()->getComponent('bootstrap');
|
||||
$sUpdateLastCheck = getGlobalSetting('updatelastcheck');
|
||||
|
||||
$this->_sessioncontrol();
|
||||
|
||||
if (Yii::app()->getConfig('buildnumber') != "" && Yii::app()->getConfig('updatecheckperiod') > 0 && $sUpdateLastCheck < dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", "-". Yii::app()->getConfig('updatecheckperiod')." days"))
|
||||
updateCheck();
|
||||
|
||||
//unset(Yii::app()->session['FileManagerContext']);
|
||||
App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . "admin_core.js");
|
||||
$this->user_id = Yii::app()->user->getId();
|
||||
if (!Yii::app()->getConfig("surveyid")) {Yii::app()->setConfig("surveyid", returnGlobal('sid'));} //SurveyID
|
||||
if (!Yii::app()->getConfig("ugid")) {Yii::app()->setConfig("ugid", returnGlobal('ugid'));} //Usergroup-ID
|
||||
if (!Yii::app()->getConfig("gid")) {Yii::app()->setConfig("gid", returnGlobal('gid'));} //GroupID
|
||||
if (!Yii::app()->getConfig("qid")) {Yii::app()->setConfig("qid", returnGlobal('qid'));} //QuestionID
|
||||
if (!Yii::app()->getConfig("lid")) {Yii::app()->setConfig("lid", returnGlobal('lid'));} //LabelID
|
||||
if (!Yii::app()->getConfig("code")) {Yii::app()->setConfig("code", returnGlobal('code'));} // ??
|
||||
if (!Yii::app()->getConfig("action")) {Yii::app()->setConfig("action", returnGlobal('action'));} //Desired action
|
||||
if (!Yii::app()->getConfig("subaction")) {Yii::app()->setConfig("subaction", returnGlobal('subaction'));} //Desired subaction
|
||||
if (!Yii::app()->getConfig("editedaction")) {Yii::app()->setConfig("editedaction", returnGlobal('editedaction'));} // for html editor integration
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows a nice error message to the world
|
||||
*
|
||||
* @access public
|
||||
* @param string $message The error message
|
||||
* @param string|array $url URL. Either a string. Or array with keys url and title
|
||||
* @return void
|
||||
*/
|
||||
public function error($message, $sURL = array())
|
||||
{
|
||||
$clang = $this->lang;
|
||||
|
||||
$this->_getAdminHeader();
|
||||
$sOutput = "<div class='messagebox ui-corner-all'>\n";
|
||||
$sOutput .= '<div class="warningheader">'.$clang->gT('Error').'</div><br />'."\n";
|
||||
$sOutput .= $message . '<br /><br />'."\n";
|
||||
if (!empty($sURL) && !is_array($sURL))
|
||||
{
|
||||
$sTitle = $clang->gT('Back');
|
||||
}
|
||||
elseif (!empty($sURL['url']))
|
||||
{
|
||||
if (!empty($sURL['title']))
|
||||
{
|
||||
$sTitle = $sURL['title'];
|
||||
}
|
||||
else
|
||||
{
|
||||
$sTitle = $clang->gT('Back');
|
||||
}
|
||||
$sURL = $sURL['url'];
|
||||
}
|
||||
else
|
||||
{
|
||||
$sTitle = $clang->gT('Main Admin Screen');
|
||||
$sURL = $this->createUrl('/admin');
|
||||
}
|
||||
$sOutput .= '<input type="submit" value="'.$sTitle.'" onclick=\'window.open("'.$sURL.'", "_top")\' /><br /><br />'."\n";
|
||||
$sOutput .= '</div>'."\n";
|
||||
$sOutput .= '</div>'."\n";
|
||||
echo $sOutput;
|
||||
|
||||
$this->_getAdminFooter('http://manual.limesurvey.org', $clang->gT('LimeSurvey online manual'));
|
||||
|
||||
die;
|
||||
}
|
||||
/**
|
||||
* Load and set session vars
|
||||
*
|
||||
* @access protected
|
||||
* @return void
|
||||
*/
|
||||
protected function _sessioncontrol()
|
||||
{
|
||||
Yii::import('application.libraries.Limesurvey_lang');
|
||||
// From personal settings
|
||||
if (Yii::app()->request->getPost('action') == 'savepersonalsettings') {
|
||||
if (Yii::app()->request->getPost('lang')=='auto')
|
||||
{
|
||||
$sLanguage= getBrowserLanguage();
|
||||
}
|
||||
else
|
||||
{
|
||||
$sLanguage=sanitize_languagecode(Yii::app()->request->getPost('lang'));
|
||||
}
|
||||
Yii::app()->session['adminlang'] = $sLanguage;
|
||||
}
|
||||
|
||||
if (empty(Yii::app()->session['adminlang']))
|
||||
Yii::app()->session["adminlang"] = Yii::app()->getConfig("defaultlang");
|
||||
|
||||
global $clang; // Needed so EM can localize equation hints until a better solution is found
|
||||
$this->lang = $clang = new Limesurvey_lang(Yii::app()->session['adminlang']);
|
||||
Yii::app()->setLang($this->lang);
|
||||
|
||||
if (!empty($this->user_id))
|
||||
$this->_GetSessionUserRights($this->user_id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks for action specific authorization and then executes an action
|
||||
*
|
||||
* @access public
|
||||
* @param string $action
|
||||
* @return bool
|
||||
*/
|
||||
public function run($action)
|
||||
{
|
||||
// Check if the DB is up to date
|
||||
if (Yii::app()->db->schema->getTable('{{surveys}}'))
|
||||
{
|
||||
$sDBVersion = getGlobalSetting('DBVersion');
|
||||
if ((int) $sDBVersion < Yii::app()->getConfig('dbversionnumber') && $action != 'update' && $action != 'authentication')
|
||||
$this->redirect(array('/admin/update/sa/db'));
|
||||
}
|
||||
|
||||
if ($action != "update" && $action != "db")
|
||||
if (empty($this->user_id) && $action != "authentication" && $action != "remotecontrol")
|
||||
{
|
||||
if (!empty($action) && $action != 'index')
|
||||
Yii::app()->session['redirect_after_login'] = $this->createUrl('/');
|
||||
|
||||
App()->user->setReturnUrl(App()->request->requestUri);
|
||||
|
||||
$this->redirect(array('/admin/authentication/sa/login'));
|
||||
}
|
||||
elseif (!empty($this->user_id) && $action != "remotecontrol")
|
||||
{
|
||||
if (Yii::app()->session['session_hash'] != hash('sha256',getGlobalSetting('SessionName').Yii::app()->user->getName().Yii::app()->user->getId()))
|
||||
{
|
||||
Yii::app()->session->clear();
|
||||
Yii::app()->session->close();
|
||||
$this->redirect(array('/admin/authentication/sa/login'));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return parent::run($action);
|
||||
}
|
||||
|
||||
/**
|
||||
* Routes all the actions to their respective places
|
||||
*
|
||||
* @access public
|
||||
* @return array
|
||||
*/
|
||||
public function actions()
|
||||
{
|
||||
$aActions = $this->getActionClasses();
|
||||
|
||||
foreach ($aActions as $action => $class)
|
||||
{
|
||||
$aActions[$action] = "application.controllers.admin.{$class}";
|
||||
}
|
||||
|
||||
return $aActions;
|
||||
}
|
||||
|
||||
public function getActionClasses()
|
||||
{
|
||||
return array(
|
||||
'assessments' => 'assessments',
|
||||
'authentication' => 'authentication',
|
||||
'checkintegrity' => 'checkintegrity',
|
||||
'conditions' => 'conditionsaction',
|
||||
'database' => 'database',
|
||||
'dataentry' => 'dataentry',
|
||||
'dumpdb' => 'dumpdb',
|
||||
'emailtemplates' => 'emailtemplates',
|
||||
'export' => 'export',
|
||||
'expressions' => 'expressions',
|
||||
'globalsettings' => 'globalsettings',
|
||||
'htmleditor_pop' => 'htmleditor_pop',
|
||||
'limereplacementfields' => 'limereplacementfields',
|
||||
'index' => 'index',
|
||||
'labels' => 'labels',
|
||||
'participants' => 'participantsaction',
|
||||
'printablesurvey' => 'printablesurvey',
|
||||
'questiongroups' => 'questiongroups',
|
||||
'questions' => 'questions',
|
||||
'quotas' => 'quotas',
|
||||
'remotecontrol' => 'remotecontrol',
|
||||
'responses' => 'responses',
|
||||
'saved' => 'saved',
|
||||
'statistics' => 'statistics',
|
||||
'survey' => 'surveyadmin',
|
||||
'surveypermission' => 'surveypermission',
|
||||
'user' => 'useraction',
|
||||
'usergroups' => 'usergroups',
|
||||
'templates' => 'templates',
|
||||
'tokens' => 'tokens',
|
||||
'translate' => 'translate',
|
||||
'update' => 'update',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set Session User Rights
|
||||
*
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function _GetSessionUserRights($loginID)
|
||||
{
|
||||
$oUser = User::model()->findByPk($loginID);
|
||||
|
||||
// SuperAdmins
|
||||
// * original superadmin with uid=1 unless manually changed and defined
|
||||
// in config-defaults.php
|
||||
// * or any user having USER_RIGHT_SUPERADMIN right
|
||||
|
||||
// Let's check if I am the Initial SuperAdmin
|
||||
|
||||
$oUser = User::model()->findByAttributes(array('parent_id' => 0));
|
||||
|
||||
if (!is_null($oUser) && $oUser->uid == $loginID)
|
||||
Yii::app()->session['USER_RIGHT_INITIALSUPERADMIN'] = 1;
|
||||
else
|
||||
Yii::app()->session['USER_RIGHT_INITIALSUPERADMIN'] = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints Admin Header
|
||||
*
|
||||
* @access protected
|
||||
* @param bool $meta
|
||||
* @param bool $return
|
||||
* @return mixed
|
||||
*/
|
||||
public function _getAdminHeader($meta = false, $return = false)
|
||||
{
|
||||
if (empty(Yii::app()->session['adminlang']))
|
||||
Yii::app()->session["adminlang"] = Yii::app()->getConfig("defaultlang");
|
||||
|
||||
$aData = array();
|
||||
$aData['adminlang'] = $this->lang->getlangcode();
|
||||
//$data['admin'] = getLanguageRTL;
|
||||
$aData['test'] = "t";
|
||||
$aData['languageRTL']="";
|
||||
$aData['styleRTL']="";
|
||||
|
||||
Yii::app()->loadHelper("surveytranslator");
|
||||
|
||||
if (getLanguageRTL($aData['adminlang']))
|
||||
{
|
||||
$aData['languageRTL'] = " dir=\"rtl\" ";
|
||||
$aData['bIsRTL']=true;
|
||||
}
|
||||
else
|
||||
{
|
||||
$aData['languageRTL'] = " dir=\"ltr\" ";
|
||||
$aData['bIsRTL']=false;
|
||||
}
|
||||
|
||||
$aData['meta']="";
|
||||
if ($meta)
|
||||
{
|
||||
$aData['meta']=$meta;
|
||||
}
|
||||
|
||||
$aData['baseurl'] = Yii::app()->baseUrl . '/';
|
||||
$aData['datepickerlang']="";
|
||||
if ($aData['adminlang'] != 'en')
|
||||
Yii::app()->getClientScript()->registerScriptFile(App()->baseUrl . "/third_party/jqueryui/development-bundle/ui/i18n/jquery.ui.datepicker-" . $aData['adminlang'] .".js");
|
||||
|
||||
|
||||
$aData['sitename'] = Yii::app()->getConfig("sitename");
|
||||
$aData['admintheme'] = Yii::app()->getConfig("admintheme");
|
||||
$aData['firebug'] = useFirebug();
|
||||
|
||||
if (!empty(Yii::app()->session['dateformat']))
|
||||
$aData['formatdata'] = getDateFormatData(Yii::app()->session['dateformat']);
|
||||
|
||||
$sOutput = $this->renderPartial("/admin/super/header", $aData, true);
|
||||
|
||||
|
||||
if ($return)
|
||||
{
|
||||
return $sOutput;
|
||||
}
|
||||
else
|
||||
{
|
||||
echo $sOutput;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints Admin Footer
|
||||
*
|
||||
* @access protected
|
||||
* @param string $url
|
||||
* @param string $explanation
|
||||
* @param bool $return
|
||||
* @return mixed
|
||||
*/
|
||||
public function _getAdminFooter($url, $explanation, $return = false)
|
||||
{
|
||||
$clang = $this->lang;
|
||||
$aData['clang'] = $clang;
|
||||
|
||||
$aData['versionnumber'] = Yii::app()->getConfig("versionnumber");
|
||||
|
||||
$aData['buildtext'] = "";
|
||||
if(Yii::app()->getConfig("buildnumber")!="") {
|
||||
$aData['buildtext']= "Build ".Yii::app()->getConfig("buildnumber");
|
||||
}
|
||||
|
||||
//If user is not logged in, don't print the version number information in the footer.
|
||||
if (empty(Yii::app()->session['loginID']))
|
||||
{
|
||||
$aData['versionnumber']="";
|
||||
$aData['versiontitle']="";
|
||||
$aData['buildtext']="";
|
||||
}
|
||||
else
|
||||
{
|
||||
$aData['versiontitle'] = $clang->gT('Version');
|
||||
}
|
||||
|
||||
$aData['imageurl'] = Yii::app()->getConfig("imageurl");
|
||||
$aData['url'] = $url;
|
||||
|
||||
return $this->renderPartial("/admin/super/footer", $aData, $return);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows a message box
|
||||
*
|
||||
* @access public
|
||||
* @param string $title
|
||||
* @param string $message
|
||||
* @param string $class
|
||||
* @return void
|
||||
*/
|
||||
public function _showMessageBox($title,$message,$class="header ui-widget-header")
|
||||
{
|
||||
$aData['title'] = $title;
|
||||
$aData['message'] = $message;
|
||||
$aData['class'] = $class;
|
||||
$aData['clang'] = $this->lang;
|
||||
|
||||
$this->renderPartial('/admin/super/messagebox', $aData);
|
||||
}
|
||||
|
||||
/**
|
||||
* _showadminmenu() function returns html text for the administration button bar
|
||||
*
|
||||
* @access public
|
||||
* @global string $homedir
|
||||
* @global string $scriptname
|
||||
* @global string $surveyid
|
||||
* @global string $setfont
|
||||
* @global string $imageurl
|
||||
* @param int $surveyid
|
||||
* @return string $adminmenu
|
||||
*/
|
||||
public function _showadminmenu($surveyid = false)
|
||||
{
|
||||
|
||||
$clang = $this->lang;
|
||||
$aData['clang']= $clang;
|
||||
|
||||
if (Yii::app()->session['pw_notify'] && Yii::app()->getConfig("debug")<2) {
|
||||
Yii::app()->session['flashmessage'] = $clang->gT("Warning: You are still using the default password ('password'). Please change your password and re-login again.");
|
||||
}
|
||||
|
||||
$aData['showupdate'] = (Yii::app()->session['USER_RIGHT_SUPERADMIN'] == 1 && getGlobalSetting("updatenotification")!='never' && getGlobalSetting("updateavailable")==1 && Yii::app()->getConfig("updatable") );
|
||||
if($aData['showupdate'])
|
||||
{
|
||||
$aData['aUpdateVersions'] = json_decode(getGlobalSetting("updateversions"),true);
|
||||
$aUpdateTexts=array();
|
||||
foreach ($aData['aUpdateVersions'] as $aVersion)
|
||||
{
|
||||
$aUpdateTexts[]=$aVersion['versionnumber'].'('.$aVersion['build'].')';
|
||||
}
|
||||
$aData['sUpdateText']=implode(' '.$clang->gT('or').' ',$aUpdateTexts);
|
||||
}
|
||||
$aData['surveyid'] = $surveyid;
|
||||
$aData['iconsize'] = Yii::app()->getConfig('adminthemeiconsize');
|
||||
$aData['sImageURL'] = Yii::app()->getConfig('adminimageurl');
|
||||
$this->renderPartial("/admin/super/adminmenu", $aData);
|
||||
|
||||
}
|
||||
|
||||
public function _loadEndScripts()
|
||||
{
|
||||
static $bRendered = false;
|
||||
if ($bRendered)
|
||||
return true;
|
||||
$bRendered = true;
|
||||
if (empty(Yii::app()->session['metaHeader']))
|
||||
Yii::app()->session['metaHeader'] = '';
|
||||
|
||||
unset(Yii::app()->session['metaHeader']);
|
||||
|
||||
return $this->renderPartial('/admin/endScripts_view', array());
|
||||
}
|
||||
}
|
1270
sources/application/controllers/InstallerController.php
Normal file
1270
sources/application/controllers/InstallerController.php
Normal file
File diff suppressed because it is too large
Load diff
120
sources/application/controllers/OptinController.php
Normal file
120
sources/application/controllers/OptinController.php
Normal file
|
@ -0,0 +1,120 @@
|
|||
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
|
||||
/*
|
||||
* LimeSurvey
|
||||
* Copyright (C) 2013 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.
|
||||
*
|
||||
*
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* optin
|
||||
*
|
||||
* @package LimeSurvey
|
||||
* @copyright 2011
|
||||
* @access public
|
||||
*/
|
||||
class OptinController extends LSYii_Controller {
|
||||
|
||||
public $layout = 'bare';
|
||||
public $defaultAction = 'tokens';
|
||||
|
||||
function actiontokens($surveyid, $token, $langcode = '')
|
||||
{
|
||||
Yii::app()->loadHelper('database');
|
||||
Yii::app()->loadHelper('sanitize');
|
||||
$sLanguageCode = $langcode;
|
||||
$iSurveyID = $surveyid;
|
||||
$sToken = $token;
|
||||
$sToken = sanitize_token($sToken);
|
||||
|
||||
if (!$iSurveyID)
|
||||
{
|
||||
$this->redirect(array('/'));
|
||||
}
|
||||
$iSurveyID = (int)$iSurveyID;
|
||||
|
||||
//Check that there is a SID
|
||||
// Get passed language from form, so that we dont loose this!
|
||||
if (!isset($sLanguageCode) || $sLanguageCode == "" || !$sLanguageCode)
|
||||
{
|
||||
$sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
|
||||
Yii::import('application.libraries.Limesurvey_lang', true);
|
||||
$clang = new Limesurvey_lang($sBaseLanguage);
|
||||
}
|
||||
else
|
||||
{
|
||||
$sLanguageCode = sanitize_languagecode($sLanguageCode);
|
||||
Yii::import('application.libraries.Limesurvey_lang', true);
|
||||
$clang = new Limesurvey_lang($sLanguageCode);
|
||||
$sBaseLanguage = $sLanguageCode;
|
||||
}
|
||||
|
||||
Yii::app()->lang = $clang;
|
||||
|
||||
$aSurveyInfo=getSurveyInfo($iSurveyID,$sBaseLanguage);
|
||||
|
||||
if ($aSurveyInfo == false || !tableExists("{{tokens_{$iSurveyID}}}"))
|
||||
{
|
||||
$sMessage = $clang->gT('This survey does not seem to exist.');
|
||||
}
|
||||
else
|
||||
{
|
||||
$oToken = Token::model($iSurveyID)->findByAttributes(array('token' => $token));
|
||||
|
||||
if (!isset($oToken))
|
||||
{
|
||||
$sMessage = $clang->gT('You are not a participant in this survey.');
|
||||
}
|
||||
else
|
||||
{
|
||||
if ($oToken->emailstatus =='OptOut')
|
||||
{
|
||||
$oToken->emailstatus = 'OK';
|
||||
$oToken->save();
|
||||
$sMessage = $clang->gT('You have been successfully added back to this survey.');
|
||||
}
|
||||
elseif ($oToken->emailstatus == 'OK')
|
||||
{
|
||||
$sMessage = $clang->gT('You are already a part of this survey.');
|
||||
}
|
||||
else
|
||||
{
|
||||
$sMessage = $clang->gT('You have been already removed from this survey.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//PRINT COMPLETED PAGE
|
||||
if (!$aSurveyInfo['templatedir'])
|
||||
{
|
||||
$sTemplate=getTemplatePath(Yii::app()->getConfig("defaulttemplate"));
|
||||
}
|
||||
else
|
||||
{
|
||||
$sTemplate=getTemplatePath($aSurveyInfo['templatedir']);
|
||||
}
|
||||
$this->_renderHtml($sMessage,$sTemplate,$clang,$aSurveyInfo);
|
||||
}
|
||||
|
||||
private function _renderHtml($html,$thistpl, $oLanguage, $aSurveyInfo)
|
||||
{
|
||||
sendCacheHeaders();
|
||||
doHeader();
|
||||
$aSupportData=array('thissurvey'=>$aSurveyInfo, 'clang'=>$oLanguage);
|
||||
echo templatereplace(file_get_contents($thistpl.DIRECTORY_SEPARATOR.'startpage.pstpl'),array(), $aSupportData);
|
||||
$aData['html'] = $html;
|
||||
$aData['thistpl'] = $thistpl;
|
||||
$this->render('/opt_view',$aData);
|
||||
echo templatereplace(file_get_contents($thistpl.DIRECTORY_SEPARATOR.'endpage.pstpl'),array(), $aSupportData);
|
||||
doFooter();
|
||||
}
|
||||
|
||||
}
|
206
sources/application/controllers/OptoutController.php
Normal file
206
sources/application/controllers/OptoutController.php
Normal file
|
@ -0,0 +1,206 @@
|
|||
<?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.
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* optout
|
||||
*
|
||||
* @package LimeSurvey
|
||||
* @copyright 2011
|
||||
* @access public
|
||||
*/
|
||||
class OptoutController extends LSYii_Controller {
|
||||
|
||||
public $layout = 'bare';
|
||||
public $defaultAction = 'tokens';
|
||||
|
||||
/* This function is run when opting out of an individual token table. The other function /optout/participants
|
||||
* opts the user out of ALL survey invitations from the system
|
||||
*
|
||||
*
|
||||
* */
|
||||
function actiontokens()
|
||||
{
|
||||
$iSurveyID=Yii::app()->request->getQuery('surveyid');
|
||||
$sLanguageCode=Yii::app()->request->getQuery('langcode');
|
||||
$sToken=sanitize_token(Yii::app()->request->getQuery('token'));
|
||||
Yii::app()->loadHelper('database');
|
||||
Yii::app()->loadHelper('sanitize');
|
||||
if (!$iSurveyID) //IF there is no survey id, redirect back to the default public page
|
||||
{
|
||||
$this->redirect(array('/'));
|
||||
}
|
||||
$iSurveyID = (int)$iSurveyID; //Make sure it's an integer (protect from SQL injects)
|
||||
//Check that there is a SID
|
||||
// Get passed language from form, so that we dont lose this!
|
||||
if (!isset($sLanguageCode) || $sLanguageCode == "" || !$sLanguageCode)
|
||||
{
|
||||
$sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
|
||||
Yii::import('application.libraries.Limesurvey_lang', true);
|
||||
$clang = new Limesurvey_lang($sBaseLanguage);
|
||||
}
|
||||
else
|
||||
{
|
||||
$sBaseLanguage = sanitize_languagecode($sLanguageCode);
|
||||
Yii::import('application.libraries.Limesurvey_lang', true);
|
||||
$clang = new Limesurvey_lang($sBaseLanguage);
|
||||
}
|
||||
|
||||
Yii::app()->lang = $clang;
|
||||
|
||||
$aSurveyInfo=getSurveyInfo($iSurveyID,$sBaseLanguage);
|
||||
|
||||
if ($aSurveyInfo==false || !tableExists("{{tokens_{$iSurveyID}}}")){
|
||||
$sMessage = $clang->gT('This survey does not seem to exist.');
|
||||
}
|
||||
else
|
||||
{
|
||||
$oToken = Token::model($iSurveyID)->findByAttributes(array('token'=>$sToken));
|
||||
|
||||
if (!isset($oToken))
|
||||
{
|
||||
$sMessage = $clang->gT('You are not a participant in this survey.');
|
||||
}
|
||||
else
|
||||
{
|
||||
if ($oToken->emailstatus == 'OK')
|
||||
{
|
||||
$oToken->emailstatus = 'OptOut';
|
||||
$oToken->save();
|
||||
$sMessage = $clang->gT('You have been successfully removed from this survey.');
|
||||
}
|
||||
else
|
||||
{
|
||||
$sMessage = $clang->gT('You have been already removed from this survey.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//PRINT COMPLETED PAGE
|
||||
if (!$aSurveyInfo['templatedir'])
|
||||
{
|
||||
$sTemplate=getTemplatePath(Yii::app()->getConfig("defaulttemplate"));
|
||||
}
|
||||
else
|
||||
{
|
||||
$sTemplate=getTemplatePath($aSurveyInfo['templatedir']);
|
||||
}
|
||||
|
||||
$this->_renderHtml($sMessage,$sTemplate,$aSurveyInfo);
|
||||
}
|
||||
|
||||
/* This function is run when opting out of the participants system. The other function /optout/token
|
||||
* opts the user out of just a single token/survey invite list
|
||||
*
|
||||
*
|
||||
* */
|
||||
function actionparticipants()
|
||||
{
|
||||
$iSurveyID=Yii::app()->request->getQuery('surveyid');
|
||||
$sLanguageCode=Yii::app()->request->getQuery('langcode');
|
||||
$sToken=sanitize_token(Yii::app()->request->getQuery('token'));
|
||||
Yii::app()->loadHelper('database');
|
||||
Yii::app()->loadHelper('sanitize');
|
||||
if (!$iSurveyID) //IF there is no survey id, redirect back to the default public page
|
||||
{
|
||||
$this->redirect(array('/'));
|
||||
}
|
||||
$iSurveyID = (int)$iSurveyID; //Make sure it's an integer (protect from SQL injects)
|
||||
//Check that there is a SID
|
||||
// Get passed language from form, so that we dont lose this!
|
||||
if (!isset($sLanguageCode) || $sLanguageCode == "" || !$sLanguageCode)
|
||||
{
|
||||
$sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
|
||||
Yii::import('application.libraries.Limesurvey_lang', true);
|
||||
$clang = new Limesurvey_lang($sBaseLanguage);
|
||||
}
|
||||
else
|
||||
{
|
||||
$sLanguageCode = sanitize_languagecode($sLanguageCode);
|
||||
Yii::import('application.libraries.Limesurvey_lang', true);
|
||||
$clang = new Limesurvey_lang($sLanguageCode);
|
||||
$sBaseLanguage = $sLanguageCode;
|
||||
}
|
||||
|
||||
Yii::app()->lang = $clang;
|
||||
|
||||
$aSurveyInfo=getSurveyInfo($iSurveyID,$sBaseLanguage);
|
||||
|
||||
if ($aSurveyInfo==false || !tableExists("{{tokens_{$iSurveyID}}}")){
|
||||
$sMessage = $clang->gT('This survey does not seem to exist.');
|
||||
}
|
||||
else
|
||||
{
|
||||
$oToken = Token::model($iSurveyID)->findByAttributes(array('token' => $sToken));
|
||||
if (!isset($oToken))
|
||||
{
|
||||
$sMessage = $clang->gT('You are not a participant in this survey.');
|
||||
}
|
||||
else
|
||||
{
|
||||
if ($oToken->emailstatus == 'OK')
|
||||
{
|
||||
$oToken->emailstatus = 'OptOut';
|
||||
$oToken->save();
|
||||
$sMessage = $clang->gT('You have been successfully removed from this survey.');
|
||||
}
|
||||
else
|
||||
{
|
||||
$sMessage = $clang->gT('You have been already removed from this survey.');
|
||||
}
|
||||
if(!empty($oToken->participant_id))
|
||||
{
|
||||
//Participant also exists in central db
|
||||
$oParticipant = Participant::model()->findByPk($oToken->participant_id);
|
||||
if($oParticipant->blacklisted=="Y")
|
||||
{
|
||||
$sMessage .= "<br />";
|
||||
$sMessage .= $clang->gT("You have already been removed from the central participants list for this site");
|
||||
} else
|
||||
{
|
||||
$oParticipant->blacklisted='Y';
|
||||
$oParticipant->save();
|
||||
$sMessage .= "<br />";
|
||||
$sMessage .= $clang->gT("You have been removed from the central participants list for this site");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//PRINT COMPLETED PAGE
|
||||
if (!$aSurveyInfo['templatedir'])
|
||||
{
|
||||
$sTemplate=getTemplatePath(Yii::app()->getConfig("defaulttemplate"));
|
||||
}
|
||||
else
|
||||
{
|
||||
$sTemplate=getTemplatePath($aSurveyInfo['templatedir']);
|
||||
}
|
||||
|
||||
$this->_renderHtml($sMessage,$sTemplate, $aSurveyInfo);
|
||||
}
|
||||
|
||||
private function _renderHtml($html, $thistpl, $aSurveyInfo)
|
||||
{
|
||||
sendCacheHeaders();
|
||||
doHeader();
|
||||
$aSupportData=array('thissurvey'=>$aSurveyInfo);
|
||||
echo templatereplace(file_get_contents($thistpl.DIRECTORY_SEPARATOR.'startpage.pstpl'),array(), $aSupportData);
|
||||
$aData['html'] = $html;
|
||||
$aData['thistpl'] = $thistpl;
|
||||
$this->render('/opt_view',$aData);
|
||||
echo templatereplace(file_get_contents($thistpl.DIRECTORY_SEPARATOR.'endpage.pstpl'),array(), $aSupportData);
|
||||
doFooter();
|
||||
}
|
||||
|
||||
}
|
217
sources/application/controllers/PluginsController.php
Normal file
217
sources/application/controllers/PluginsController.php
Normal file
|
@ -0,0 +1,217 @@
|
|||
<?php
|
||||
|
||||
class PluginsController extends LSYii_Controller
|
||||
{
|
||||
|
||||
public $layout = 'main';
|
||||
|
||||
/**
|
||||
* Stored dynamic properties set and unset via __get and __set.
|
||||
* @var array of mixed.
|
||||
*/
|
||||
protected $properties = array();
|
||||
|
||||
public function __get($property)
|
||||
{
|
||||
return $this->properties[$property];
|
||||
}
|
||||
|
||||
public function __set($property, $value)
|
||||
{
|
||||
$this->properties[$property] = $value;
|
||||
}
|
||||
|
||||
public function _init()
|
||||
{
|
||||
parent::_init();
|
||||
Yii::app()->bootstrap->init(); // Make sure bootstrap css is rendered in time
|
||||
}
|
||||
|
||||
public function accessRules()
|
||||
{
|
||||
$aRules = array(
|
||||
array('allow', 'roles' => array('administrator')),
|
||||
array('allow', 'actions' => array('direct')),
|
||||
array('deny')
|
||||
);
|
||||
|
||||
|
||||
// Note the order; rules are numerically indexed and we want to
|
||||
// parents rules to be executed only if ours dont apply.
|
||||
return array_merge($aRules, parent::accessRules());
|
||||
}
|
||||
|
||||
public function actionActivate($id)
|
||||
{
|
||||
$oPlugin = Plugin::model()->findByPk($id);
|
||||
if (!is_null($oPlugin))
|
||||
{
|
||||
$iStatus = $oPlugin->active;
|
||||
if ($iStatus == 0)
|
||||
{
|
||||
// Load the plugin:
|
||||
App()->getPluginManager()->loadPlugin($oPlugin->name, $id);
|
||||
$result = App()->getPluginManager()->dispatchEvent(new PluginEvent('beforeActivate', $this), $oPlugin->name);
|
||||
if ($result->get('success', true))
|
||||
{
|
||||
$iStatus = 1;
|
||||
} else
|
||||
{
|
||||
$sMessage = $result->get('message', gT('Failed to activate the plugin.'));
|
||||
App()->user->setFlash('pluginActivation', $sMessage);
|
||||
$this->redirect(array('plugins/'));
|
||||
}
|
||||
}
|
||||
$oPlugin->active = $iStatus;
|
||||
$oPlugin->save();
|
||||
}
|
||||
$this->redirect(array('plugins/'));
|
||||
}
|
||||
|
||||
public function actionConfigure($id)
|
||||
{
|
||||
$arPlugin = Plugin::model()->findByPk($id)->attributes;
|
||||
$oPluginObject = App()->getPluginManager()->loadPlugin($arPlugin['name'], $arPlugin['id']);
|
||||
|
||||
if ($arPlugin === null)
|
||||
{
|
||||
Yii::app()->user->setFlash('pluginmanager', 'Plugin not found');
|
||||
$this->redirect(array('plugins/'));
|
||||
}
|
||||
|
||||
// If post handle data, yt0 seems to be the submit button
|
||||
if (App()->request->isPostRequest && App()->request->getPost('yt0'))
|
||||
{
|
||||
|
||||
$aSettings = $oPluginObject->getPluginSettings(false);
|
||||
$aSave = array();
|
||||
foreach ($aSettings as $name => $setting)
|
||||
{
|
||||
$aSave[$name] = App()->request->getPost($name, null);
|
||||
}
|
||||
$oPluginObject->saveSettings($aSave);
|
||||
|
||||
Yii::app()->user->setFlash('pluginmanager', 'Settings saved');
|
||||
$this->forward('plugins/index', true);
|
||||
}
|
||||
|
||||
$aSettings = $oPluginObject->getPluginSettings();
|
||||
|
||||
if (empty($aSettings))
|
||||
{
|
||||
// And show a message
|
||||
Yii::app()->user->setFlash('pluginmanager', 'This plugin has no settings');
|
||||
$this->forward('plugins/index', true);
|
||||
}
|
||||
$this->render('/plugins/configure', array('settings' => $aSettings, 'plugin' => $arPlugin));
|
||||
}
|
||||
|
||||
public function actionDeactivate($id)
|
||||
{
|
||||
$oPlugin = Plugin::model()->findByPk($id);
|
||||
if (!is_null($oPlugin))
|
||||
{
|
||||
$iStatus = $oPlugin->active;
|
||||
if ($iStatus == 1)
|
||||
{
|
||||
$result = App()->getPluginManager()->dispatchEvent(new PluginEvent('beforeDeactivate', $this), $oPlugin->name);
|
||||
if ($result->get('success', true))
|
||||
{
|
||||
$iStatus = 0;
|
||||
} else
|
||||
{
|
||||
$message = $result->get('message', gT('Failed to deactivate the plugin.'));
|
||||
App()->user->setFlash('pluginActivation', $message);
|
||||
$this->redirect(array('plugins/'));
|
||||
}
|
||||
}
|
||||
$oPlugin->active = $iStatus;
|
||||
$oPlugin->save();
|
||||
}
|
||||
$this->redirect(array('plugins/'));
|
||||
}
|
||||
|
||||
public function actionDirect($plugin, $function)
|
||||
{
|
||||
$oEvent = new PluginEvent('newDirectRequest');
|
||||
// The intended target of the call.
|
||||
$oEvent->set('target', $plugin);
|
||||
// The name of the function.
|
||||
$oEvent->set('function', $function);
|
||||
$oEvent->set('request', App()->request);
|
||||
|
||||
App()->getPluginManager()->dispatchEvent($oEvent);
|
||||
|
||||
$sOutput = '';
|
||||
foreach ($oEvent->getAllContent() as $content)
|
||||
{
|
||||
$sOutput .= $content->getContent();
|
||||
}
|
||||
|
||||
if (!empty($sOutput))
|
||||
{
|
||||
$this->renderText($sOutput);
|
||||
}
|
||||
}
|
||||
|
||||
public function actionIndex()
|
||||
{
|
||||
$oPluginManager = App()->getPluginManager();
|
||||
|
||||
// Scan the plugins folder.
|
||||
$aDiscoveredPlugins = $oPluginManager->scanPlugins();
|
||||
$aInstalledPlugins = $oPluginManager->getInstalledPlugins();
|
||||
$aInstalledNames = array_map(function ($installedPlugin) {
|
||||
return $installedPlugin->name;
|
||||
}, $aInstalledPlugins);
|
||||
|
||||
// Install newly discovered plugins.
|
||||
foreach ($aDiscoveredPlugins as $discoveredPlugin)
|
||||
{
|
||||
if (!in_array($discoveredPlugin['pluginClass'], $aInstalledNames))
|
||||
{
|
||||
$oPlugin = new Plugin();
|
||||
$oPlugin->name = $discoveredPlugin['pluginClass'];
|
||||
$oPlugin->active = 0;
|
||||
$oPlugin->save();
|
||||
}
|
||||
}
|
||||
|
||||
$aoPlugins = Plugin::model()->findAll();
|
||||
$data = array();
|
||||
foreach ($aoPlugins as $oPlugin)
|
||||
{
|
||||
/* @var $plugin Plugin */
|
||||
if (array_key_exists($oPlugin->name, $aDiscoveredPlugins))
|
||||
{
|
||||
$aPluginSettings = App()->getPluginManager()->loadPlugin($oPlugin->name, $oPlugin->id)->getPluginSettings(false);
|
||||
$data[] = array(
|
||||
'id' => $oPlugin->id,
|
||||
'name' => $aDiscoveredPlugins[$oPlugin->name]['pluginName'],
|
||||
'description' => $aDiscoveredPlugins[$oPlugin->name]['description'],
|
||||
'active' => $oPlugin->active,
|
||||
'settings' => $aPluginSettings,
|
||||
'new' => !in_array($oPlugin->name, $aInstalledNames)
|
||||
);
|
||||
} else
|
||||
{
|
||||
// This plugin is missing, maybe the files were deleted but the record was not removed from the database
|
||||
// Now delete this record. Depending on the plugin the settings will be preserved
|
||||
App()->user->setFlash('pluginDelete' . $oPlugin->id, sprintf(gT("Plugin '%s' was missing and is removed from the database."), $oPlugin->name));
|
||||
$oPlugin->delete();
|
||||
}
|
||||
}
|
||||
echo $this->render('/plugins/index', compact('data'));
|
||||
}
|
||||
|
||||
public function filters()
|
||||
{
|
||||
$aFilters = array(
|
||||
'accessControl'
|
||||
);
|
||||
return array_merge(parent::filters(), $aFilters);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
?>
|
196
sources/application/controllers/PrintanswersController.php
Normal file
196
sources/application/controllers/PrintanswersController.php
Normal file
|
@ -0,0 +1,196 @@
|
|||
<?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.
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* printanswers
|
||||
*
|
||||
* @package LimeSurvey
|
||||
* @copyright 2011
|
||||
* @access public
|
||||
*/
|
||||
class PrintanswersController extends LSYii_Controller {
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* printanswers::view()
|
||||
* View answers at the end of a survey in one place. To export as pdf, set 'usepdfexport' = 1 in lsconfig.php and $printableexport='pdf'.
|
||||
* @param mixed $surveyid
|
||||
* @param bool $printableexport
|
||||
* @return
|
||||
*/
|
||||
function actionView($surveyid,$printableexport=FALSE)
|
||||
{
|
||||
Yii::app()->loadHelper("frontend");
|
||||
Yii::import('application.libraries.admin.pdf');
|
||||
|
||||
$iSurveyID = (int)$surveyid;
|
||||
$sExportType = $printableexport;
|
||||
|
||||
Yii::app()->loadHelper('database');
|
||||
|
||||
if (isset($_SESSION['survey_'.$iSurveyID]['sid']))
|
||||
{
|
||||
$iSurveyID = $_SESSION['survey_'.$iSurveyID]['sid'];
|
||||
}
|
||||
else
|
||||
{
|
||||
//die('Invalid survey/session');
|
||||
}
|
||||
// Get the survey inforamtion
|
||||
// Set the language for dispay
|
||||
if (isset($_SESSION['survey_'.$iSurveyID]['s_lang']))
|
||||
{
|
||||
$sLanguage = $_SESSION['survey_'.$iSurveyID]['s_lang'];
|
||||
}
|
||||
elseif(Survey::model()->findByPk($iSurveyID))// survey exist
|
||||
{
|
||||
$sLanguage = Survey::model()->findByPk($iSurveyID)->language;
|
||||
}
|
||||
else
|
||||
{
|
||||
$iSurveyID=0;
|
||||
$sLanguage = Yii::app()->getConfig("defaultlang");
|
||||
}
|
||||
$clang = SetSurveyLanguage($iSurveyID, $sLanguage);
|
||||
$aSurveyInfo = getSurveyInfo($iSurveyID,$sLanguage);
|
||||
//SET THE TEMPLATE DIRECTORY
|
||||
if (!isset($aSurveyInfo['templatedir']) || !$aSurveyInfo['templatedir'])
|
||||
{
|
||||
$aSurveyInfo['templatedir']=Yii::app()->getConfig('defaulttemplate');
|
||||
}
|
||||
$sTemplate = validateTemplateDir($aSurveyInfo['templatedir']);
|
||||
//Survey is not finished or don't exist
|
||||
if (!isset($_SESSION['survey_'.$iSurveyID]['finished']) || !isset($_SESSION['survey_'.$iSurveyID]['srid']))
|
||||
//display "sorry but your session has expired"
|
||||
{
|
||||
sendCacheHeaders();
|
||||
doHeader();
|
||||
echo templatereplace(file_get_contents(getTemplatePath($sTemplate).'/startpage.pstpl'),array());
|
||||
echo "<center><br />\n"
|
||||
."\t<font color='RED'><strong>".$clang->gT("Error")."</strong></font><br />\n"
|
||||
."\t".$clang->gT("We are sorry but your session has expired.")."<br />".$clang->gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection.")."<br />\n"
|
||||
."\t".sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), Yii::app()->getConfig("siteadminname"), Yii::app()->getConfig("siteadminemail"))."\n"
|
||||
."</center><br />\n";
|
||||
echo templatereplace(file_get_contents(getTemplatePath($sTemplate).'/endpage.pstpl'),array());
|
||||
doFooter();
|
||||
exit;
|
||||
}
|
||||
//Fin session time out
|
||||
$sSRID = $_SESSION['survey_'.$iSurveyID]['srid']; //I want to see the answers with this id
|
||||
//Ensure script is not run directly, avoid path disclosure
|
||||
//if (!isset($rootdir) || isset($_REQUEST['$rootdir'])) {die( "browse - Cannot run this script directly");}
|
||||
if ($aSurveyInfo['printanswers'] == 'N')
|
||||
{
|
||||
die(); //Die quietly if print answers is not permitted
|
||||
}
|
||||
//CHECK IF SURVEY IS ACTIVATED AND EXISTS
|
||||
$sSurveyName = $aSurveyInfo['surveyls_title'];
|
||||
$sAnonymized = $aSurveyInfo['anonymized'];
|
||||
//OK. IF WE GOT THIS FAR, THEN THE SURVEY EXISTS AND IT IS ACTIVE, SO LETS GET TO WORK.
|
||||
//SHOW HEADER
|
||||
$sOutput = CHtml::form(array("printanswers/view/surveyid/{$iSurveyID}/printableexport/pdf"), 'post')
|
||||
."<center><input type='submit' value='".$clang->gT("PDF export")."'id=\"exportbutton\"/><input type='hidden' name='printableexport' /></center></form>";
|
||||
if($sExportType == 'pdf')
|
||||
{
|
||||
//require (Yii::app()->getConfig('rootdir').'/application/config/tcpdf.php');
|
||||
Yii::import('application.libraries.admin.pdf', true);
|
||||
Yii::import('application.helpers.pdfHelper');
|
||||
$aPdfLanguageSettings=pdfHelper::getPdfLanguageSettings($clang->langcode);
|
||||
$oPDF = new pdf();
|
||||
$oPDF->SetTitle($clang->gT("Survey name (ID)",'unescaped').": {$sSurveyName} ({$iSurveyID})");
|
||||
$oPDF->SetSubject($sSurveyName);
|
||||
$oPDF->SetDisplayMode('fullpage', 'two');
|
||||
$oPDF->setLanguageArray($aPdfLanguageSettings['lg']);
|
||||
$oPDF->setHeaderFont(Array($aPdfLanguageSettings['pdffont'], '', PDF_FONT_SIZE_MAIN));
|
||||
$oPDF->setFooterFont(Array($aPdfLanguageSettings['pdffont'], '', PDF_FONT_SIZE_DATA));
|
||||
$oPDF->SetFont($aPdfLanguageSettings['pdffont'], '', $aPdfLanguageSettings['pdffontsize']);
|
||||
$oPDF->AddPage();
|
||||
$oPDF->titleintopdf($clang->gT("Survey name (ID)",'unescaped').": {$sSurveyName} ({$iSurveyID})");
|
||||
}
|
||||
$sOutput .= "\t<div class='printouttitle'><strong>".$clang->gT("Survey name (ID):")."</strong> $sSurveyName ($iSurveyID)</div><p> \n";
|
||||
LimeExpressionManager::StartProcessingPage(true); // means that all variables are on the same page
|
||||
// Since all data are loaded, and don't need JavaScript, pretend all from Group 1
|
||||
LimeExpressionManager::StartProcessingGroup(1,($aSurveyInfo['anonymized']!="N"),$iSurveyID);
|
||||
$printanswershonorsconditions = Yii::app()->getConfig('printanswershonorsconditions');
|
||||
$aFullResponseTable = getFullResponseTable($iSurveyID,$sSRID,$sLanguage,$printanswershonorsconditions);
|
||||
//Get the fieldmap @TODO: do we need to filter out some fields?
|
||||
if($aSurveyInfo['datestamp']!="Y" || $sAnonymized == 'Y'){
|
||||
unset ($aFullResponseTable['submitdate']);
|
||||
}else{
|
||||
unset ($aFullResponseTable['id']);
|
||||
}
|
||||
unset ($aFullResponseTable['token']);
|
||||
unset ($aFullResponseTable['lastpage']);
|
||||
unset ($aFullResponseTable['startlanguage']);
|
||||
unset ($aFullResponseTable['datestamp']);
|
||||
unset ($aFullResponseTable['startdate']);
|
||||
$sOutput .= "<table class='printouttable' >\n";
|
||||
foreach ($aFullResponseTable as $sFieldname=>$fname)
|
||||
{
|
||||
if (substr($sFieldname,0,4) == 'gid_')
|
||||
{
|
||||
|
||||
|
||||
$sOutput .= "\t<tr class='printanswersgroup'><td colspan='2'>{$fname[0]}</td></tr>\n";
|
||||
}
|
||||
elseif (substr($sFieldname,0,4)=='qid_')
|
||||
{
|
||||
$sOutput .= "\t<tr class='printanswersquestionhead'><td colspan='2'>{$fname[0]}</td></tr>\n";
|
||||
}
|
||||
elseif ($sFieldname=='submitdate')
|
||||
{
|
||||
if($sAnonymized != 'Y')
|
||||
{
|
||||
$sOutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]} {$sFieldname}</td><td class='printanswersanswertext'>{$fname[2]}</td></tr>";
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
$sOutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]}</td><td class='printanswersanswertext'>".flattenText($fname[2])."</td></tr>";
|
||||
}
|
||||
}
|
||||
$sOutput .= "</table>\n";
|
||||
if($sExportType == 'pdf')
|
||||
{
|
||||
$oPDF->writeHTML($sOutput);
|
||||
header("Pragma: public");
|
||||
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
|
||||
$sExportFileName = sanitize_filename($sSurveyName);
|
||||
$oPDF->Output($sExportFileName."-".$iSurveyID.".pdf","D");
|
||||
}
|
||||
else//Display the page with user answers
|
||||
{
|
||||
ob_start(function($buffer, $phase) {
|
||||
App()->getClientScript()->render($buffer);
|
||||
App()->getClientScript()->reset();
|
||||
return $buffer;
|
||||
});
|
||||
ob_implicit_flush(false);
|
||||
|
||||
sendCacheHeaders();
|
||||
doHeader();
|
||||
$sData['thissurvey']=$aSurveyInfo;
|
||||
echo templatereplace(file_get_contents(getTemplatePath($sTemplate).'/startpage.pstpl'),array(),$sData);
|
||||
echo templatereplace(file_get_contents(getTemplatePath($sTemplate).'/printanswers.pstpl'),array('ANSWERTABLE'=>$sOutput),$sData);
|
||||
echo templatereplace(file_get_contents(getTemplatePath($sTemplate).'/endpage.pstpl'),array(),$sData);
|
||||
echo "</body></html>";
|
||||
|
||||
ob_flush();
|
||||
}
|
||||
|
||||
LimeExpressionManager::FinishProcessingGroup();
|
||||
LimeExpressionManager::FinishProcessingPage();
|
||||
}
|
||||
}
|
263
sources/application/controllers/RegisterController.php
Normal file
263
sources/application/controllers/RegisterController.php
Normal file
|
@ -0,0 +1,263 @@
|
|||
<?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.
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* register
|
||||
*
|
||||
* @package LimeSurvey
|
||||
* @copyright 2011
|
||||
* @access public
|
||||
*/
|
||||
class RegisterController extends LSYii_Controller {
|
||||
|
||||
function actionAJAXRegisterForm($surveyid)
|
||||
{
|
||||
Yii::app()->loadHelper('database');
|
||||
Yii::app()->loadHelper('replacements');
|
||||
$redata = compact(array_keys(get_defined_vars()));
|
||||
$iSurveyID = sanitize_int($surveyid);
|
||||
$oSurvey = Survey::model()->find('sid=:sid',array(':sid' => $iSurveyID)) or show_error("Can't find survey data");
|
||||
$thistpl=getTemplatePath(validateTemplateDir($oSurvey->template));
|
||||
$data['sid'] = $iSurveyID;
|
||||
$data['startdate'] = $oSurvey->startdate;
|
||||
$data['enddate'] = $oSurvey->expires;
|
||||
$data['thissurvey'] = getSurveyInfo($iSurveyID , $oSurvey->language);
|
||||
Yii::import('application.libraries.Limesurvey_lang');
|
||||
Yii::app()->lang = new Limesurvey_lang($oSurvey->language);
|
||||
echo templatereplace(file_get_contents("$thistpl/register.pstpl"),array(),$data,'register.php',false,NULL,$data);
|
||||
unset($_SESSION['survey_'.$iSurveyID]['register_errormsg']);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* register::index()
|
||||
* Process register form data and take appropriate action
|
||||
* @return
|
||||
*/
|
||||
function actionIndex($iSurveyID = null)
|
||||
{
|
||||
Yii::app()->loadHelper('database');
|
||||
Yii::app()->loadHelper('replacements');
|
||||
$sLanguage = Yii::app()->request->getParam('lang','');
|
||||
if($iSurveyID == null)
|
||||
{
|
||||
$iSurveyID = Yii::app()->request->getPost('sid');
|
||||
}
|
||||
if (!$iSurveyID)
|
||||
{
|
||||
$this->redirect(Yii::app()->baseUrl);
|
||||
}
|
||||
|
||||
if ($sLanguage=="" )
|
||||
{
|
||||
$sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
|
||||
}
|
||||
else
|
||||
{
|
||||
$sBaseLanguage = $sLanguage;
|
||||
}
|
||||
Yii::import('application.libraries.Limesurvey_lang');
|
||||
Yii::app()->lang = new Limesurvey_lang($sBaseLanguage);
|
||||
$clang = Yii::app()->lang;
|
||||
$thissurvey=getSurveyInfo($iSurveyID,$sBaseLanguage);
|
||||
|
||||
$register_errormsg = "";
|
||||
// Check the security question's answer
|
||||
if (function_exists("ImageCreate") && isCaptchaEnabled('registrationscreen',$thissurvey['usecaptcha']) )
|
||||
{
|
||||
if (!isset($_POST['loadsecurity']) ||
|
||||
!isset($_SESSION['survey_'.$iSurveyID]['secanswer']) ||
|
||||
Yii::app()->request->getPost('loadsecurity') != $_SESSION['survey_'.$iSurveyID]['secanswer'])
|
||||
{
|
||||
$register_errormsg .= $clang->gT("The answer to the security question is incorrect.")."<br />\n";
|
||||
}
|
||||
}
|
||||
|
||||
//Check that the email is a valid style address
|
||||
if (!validateEmailAddress(Yii::app()->request->getPost('register_email')))
|
||||
{
|
||||
$register_errormsg .= $clang->gT("The email you used is not valid. Please try again.");
|
||||
}
|
||||
|
||||
// Check for additional fields
|
||||
$attributeinsertdata = array();
|
||||
foreach (GetParticipantAttributes($iSurveyID) as $field => $data)
|
||||
{
|
||||
if (empty($data['show_register']) || $data['show_register'] != 'Y')
|
||||
continue;
|
||||
|
||||
$value = sanitize_xss_string(Yii::app()->request->getPost('register_' . $field));
|
||||
if (trim($value) == '' && $data['mandatory'] == 'Y')
|
||||
$register_errormsg .= sprintf($clang->gT("%s cannot be left empty"), $thissurvey['attributecaptions'][$field]);
|
||||
$attributeinsertdata[$field] = $value;
|
||||
}
|
||||
if ($register_errormsg != "")
|
||||
{
|
||||
$_SESSION['survey_'.$iSurveyID]['register_errormsg']=$register_errormsg;
|
||||
$this->redirect($this->createUrl("survey/index/sid/{$iSurveyID}",array('lang'=>$sBaseLanguage)));
|
||||
}
|
||||
|
||||
//Check if this email already exists in token database
|
||||
$oToken=TokenDynamic::model($iSurveyID)->find('email=:email',array(':email'=>Yii::app()->request->getPost('register_email')));
|
||||
if ($oToken)
|
||||
{
|
||||
$register_errormsg=$clang->gT("The email you used has already been registered.");
|
||||
$_SESSION['survey_'.$iSurveyID]['register_errormsg']=$register_errormsg;
|
||||
$this->redirect($this->createUrl("survey/index/sid/{$iSurveyID}",array('lang'=>$sBaseLanguage)));
|
||||
//include "index.php";
|
||||
//exit;
|
||||
}
|
||||
|
||||
$mayinsert = false;
|
||||
|
||||
// Get the survey settings for token length
|
||||
|
||||
$tokenlength = $thissurvey['tokenlength'];
|
||||
//if tokenlength is not set or there are other problems use the default value (15)
|
||||
if(!isset($tokenlength) || $tokenlength == '')
|
||||
{
|
||||
$tokenlength = 15;
|
||||
}
|
||||
|
||||
while ($mayinsert != true)
|
||||
{
|
||||
$newtoken = randomChars($tokenlength);
|
||||
$oTokenExist=TokenDynamic::model($iSurveyID)->find('token=:token',array(':token'=>$newtoken));
|
||||
if (!$oTokenExist) {$mayinsert = true;}
|
||||
}
|
||||
|
||||
$postfirstname=sanitize_xss_string(strip_tags(Yii::app()->request->getPost('register_firstname')));
|
||||
$postlastname=sanitize_xss_string(strip_tags(Yii::app()->request->getPost('register_lastname')));
|
||||
$starttime = sanitize_xss_string(Yii::app()->request->getPost('startdate'));
|
||||
$endtime = sanitize_xss_string(Yii::app()->request->getPost('enddate'));
|
||||
/*$postattribute1=sanitize_xss_string(strip_tags(returnGlobal('register_attribute1')));
|
||||
$postattribute2=sanitize_xss_string(strip_tags(returnGlobal('register_attribute2'))); */
|
||||
|
||||
// Insert new entry into tokens db
|
||||
$oToken = Token::create($thissurvey['sid']);
|
||||
$oToken->firstname = $postfirstname;
|
||||
$oToken->lastname = $postlastname;
|
||||
$oToken->email = Yii::app()->request->getPost('register_email');
|
||||
$oToken->emailstatus = 'OK';
|
||||
$oToken->token = $newtoken;
|
||||
if ($starttime && $endtime)
|
||||
{
|
||||
$oToken->validfrom = $starttime;
|
||||
$oToken->validuntil = $endtime;
|
||||
}
|
||||
$oToken->setAttributes($attributeinsertdata, false);
|
||||
$result = $oToken->save();
|
||||
|
||||
//$tid = $oToken->tid;// Not needed any more
|
||||
$fieldsarray["{ADMINNAME}"]=$thissurvey['adminname'];
|
||||
$fieldsarray["{ADMINEMAIL}"]=$thissurvey['adminemail'];
|
||||
$fieldsarray["{SURVEYNAME}"]=$thissurvey['name'];
|
||||
$fieldsarray["{SURVEYDESCRIPTION}"]=$thissurvey['description'];
|
||||
$fieldsarray["{FIRSTNAME}"]=$postfirstname;
|
||||
$fieldsarray["{LASTNAME}"]=$postlastname;
|
||||
$fieldsarray["{EXPIRY}"]=$thissurvey["expiry"];
|
||||
$fieldsarray["{TOKEN}"]=$oToken->token;
|
||||
$fieldsarray["{EMAIL}"]=$oToken->email;
|
||||
|
||||
$token=$oToken->token;
|
||||
|
||||
|
||||
$message=preg_replace("/{TOKEN:([A-Z0-9_]+)}/","{"."$1"."}",$thissurvey['email_register']);
|
||||
$subject=preg_replace("/{TOKEN:([A-Z0-9_]+)}/","{"."$1"."}",$thissurvey['email_register_subj']);
|
||||
|
||||
|
||||
$from = "{$thissurvey['adminname']} <{$thissurvey['adminemail']}>";
|
||||
|
||||
$surveylink = $this->createAbsoluteUrl("/survey/index/sid/{$iSurveyID}",array('lang'=>$sBaseLanguage,'token'=>$newtoken));
|
||||
$optoutlink = $this->createAbsoluteUrl("/optout/tokens/surveyid/{$iSurveyID}",array('langcode'=>$sBaseLanguage,'token'=>$newtoken));
|
||||
$optinlink = $this->createAbsoluteUrl("/optin/tokens/surveyid/{$iSurveyID}",array('langcode'=>$sBaseLanguage,'token'=>$newtoken));
|
||||
if (getEmailFormat($iSurveyID) == 'html')
|
||||
{
|
||||
$useHtmlEmail = true;
|
||||
$fieldsarray["{SURVEYURL}"]="<a href='$surveylink'>".$surveylink."</a>";
|
||||
$fieldsarray["{OPTOUTURL}"]="<a href='$optoutlink'>".$optoutlink."</a>";
|
||||
$fieldsarray["{OPTINURL}"]="<a href='$optinlink'>".$optinlink."</a>";
|
||||
}
|
||||
else
|
||||
{
|
||||
$useHtmlEmail = false;
|
||||
$fieldsarray["{SURVEYURL}"]= $surveylink;
|
||||
$fieldsarray["{OPTOUTURL}"]= $optoutlink;
|
||||
$fieldsarray["{OPTINURL}"]= $optinlink;
|
||||
}
|
||||
|
||||
$message=ReplaceFields($message, $fieldsarray);
|
||||
$subject=ReplaceFields($subject, $fieldsarray);
|
||||
|
||||
$html = ""; //Set variable
|
||||
$sitename = Yii::app()->getConfig('sitename');
|
||||
|
||||
if (SendEmailMessage($message, $subject, Yii::app()->request->getPost('register_email'), $from, $sitename,$useHtmlEmail,getBounceEmail($iSurveyID)))
|
||||
{
|
||||
// TLR change to put date into sent
|
||||
$today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig('timeadjust'));
|
||||
$oToken->sent=$today;
|
||||
$oToken->save();
|
||||
$html="<div id='wrapper' class='message tokenmessage'>"
|
||||
. "<p>".$clang->gT("Thank you for registering to participate in this survey.")."</p>\n"
|
||||
. "<p>".$clang->gT("An email has been sent to the address you provided with access details for this survey. Please follow the link in that email to proceed.")."</p>\n"
|
||||
. "<p>".$clang->gT("Survey administrator")." {ADMINNAME} ({ADMINEMAIL})</p>"
|
||||
. "</div>\n";
|
||||
$html=ReplaceFields($html, $fieldsarray);
|
||||
}
|
||||
else
|
||||
{
|
||||
$html="Email Error";
|
||||
}
|
||||
|
||||
//PRINT COMPLETED PAGE
|
||||
if (!$thissurvey['template'])
|
||||
{
|
||||
$thistpl=getTemplatePath(validateTemplateDir('default'));
|
||||
}
|
||||
else
|
||||
{
|
||||
$thistpl=getTemplatePath(validateTemplateDir($thissurvey['template']));
|
||||
}
|
||||
|
||||
// Same fix than http://bugs.limesurvey.org/view.php?id=8441
|
||||
ob_start(function($buffer, $phase) {
|
||||
App()->getClientScript()->render($buffer);
|
||||
App()->getClientScript()->reset();
|
||||
return $buffer;
|
||||
});
|
||||
ob_implicit_flush(false);
|
||||
sendCacheHeaders();
|
||||
doHeader();
|
||||
Yii::app()->lang = $clang;
|
||||
// fetch the defined variables and pass it to the header footer templates.
|
||||
$redata = compact(array_keys(get_defined_vars()));
|
||||
$this->_printTemplateContent($thistpl.'/startpage.pstpl', $redata, __LINE__);
|
||||
$this->_printTemplateContent($thistpl.'/survey.pstpl', $redata, __LINE__);
|
||||
echo $html;
|
||||
$this->_printTemplateContent($thistpl.'/endpage.pstpl', $redata, __LINE__);
|
||||
doFooter();
|
||||
ob_flush();
|
||||
}
|
||||
|
||||
/**
|
||||
* function will parse the templates data
|
||||
* @return displays the requested template
|
||||
*/
|
||||
function _printTemplateContent($sTemplateFile, &$redata, $iDebugLine = -1)
|
||||
{
|
||||
echo templatereplace(file_get_contents($sTemplateFile),array(),$redata,'survey['.$iDebugLine.']');
|
||||
}
|
||||
|
||||
}
|
468
sources/application/controllers/Statistics_userController.php
Normal file
468
sources/application/controllers/Statistics_userController.php
Normal file
|
@ -0,0 +1,468 @@
|
|||
<?php
|
||||
/*
|
||||
* 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.
|
||||
*
|
||||
*/
|
||||
|
||||
/*
|
||||
* Created 12-2008 by Maziminke (maziminke@web.de)
|
||||
*
|
||||
* This file handles the "Show results to users" option:
|
||||
* Survey Settings -> Presentation & navigation -> "Public statistics?"
|
||||
*
|
||||
* The admin can set a question attribute "public_statistics" for each question
|
||||
* to determine whether the results of a certain question should be shown to the user
|
||||
* after he/she has submitted the survey.
|
||||
*
|
||||
*/
|
||||
|
||||
class Statistics_userController extends LSYii_Controller {
|
||||
|
||||
|
||||
public function _remap($method, $params = array())
|
||||
{
|
||||
array_unshift($params, $method);
|
||||
return call_user_func_array(array($this, "action"), $params);
|
||||
}
|
||||
|
||||
function actionAction($surveyid,$language)
|
||||
{
|
||||
ob_start(function($buffer, $phase) {
|
||||
App()->getClientScript()->render($buffer);
|
||||
return $buffer;
|
||||
});
|
||||
ob_implicit_flush(false);
|
||||
$iSurveyID=(int)$surveyid;
|
||||
//$postlang = returnglobal('lang');
|
||||
Yii::import('application.libraries.admin.progressbar',true);
|
||||
Yii::app()->loadHelper("admin/statistics");
|
||||
Yii::app()->loadHelper('database');
|
||||
Yii::app()->loadHelper('surveytranslator');
|
||||
|
||||
$data = array();
|
||||
|
||||
//XXX enable/disable this for testing
|
||||
//$publicgraphs = 1;
|
||||
//$showaggregateddata = 1;
|
||||
|
||||
/*
|
||||
* List of important settings:
|
||||
* - publicstatistics: General survey setting which determines if public statistics for this survey
|
||||
* should be shown at all.
|
||||
*
|
||||
* - publicgraphs: General survey setting which determines if public statistics for this survey
|
||||
* should include graphs or only show a tabular overview.
|
||||
*
|
||||
* - public_statistics: Question attribute which has to be applied to each question so that
|
||||
* its statistics will be shown to the user. If not set no statistics for this question will be shown.
|
||||
*
|
||||
* - filterout_incomplete_answers: Setting taken from config-defaults.php which determines if
|
||||
* not completed answers will be filtered.
|
||||
*/
|
||||
|
||||
if(!isset($iSurveyID))
|
||||
{
|
||||
$iSurveyID=returnGlobal('sid');
|
||||
}
|
||||
else
|
||||
{
|
||||
$iSurveyID = (int) $iSurveyID;
|
||||
}
|
||||
if (!$iSurveyID)
|
||||
{
|
||||
//This next line ensures that the $iSurveyID value is never anything but a number.
|
||||
safeDie('You have to provide a valid survey ID.');
|
||||
}
|
||||
|
||||
|
||||
if ($iSurveyID)
|
||||
{
|
||||
$actresult = Survey::model()->findAll('sid = :sid AND active = :active', array(':sid' => $iSurveyID, ':active' => 'Y')); //Checked
|
||||
if (count($actresult) == 0)
|
||||
{
|
||||
safeDie('You have to provide a valid survey ID.');
|
||||
}
|
||||
else
|
||||
{
|
||||
$surveyinfo = getSurveyInfo($iSurveyID);
|
||||
// CHANGE JSW_NZ - let's get the survey title for display
|
||||
$thisSurveyTitle = $surveyinfo["name"];
|
||||
// CHANGE JSW_NZ - let's get css from individual template.css - so define path
|
||||
$thisSurveyCssPath = getTemplateURL($surveyinfo["template"]);
|
||||
if ($surveyinfo['publicstatistics']!='Y')
|
||||
{
|
||||
safeDie('The public statistics for this survey are deactivated.');
|
||||
}
|
||||
|
||||
//check if graphs should be shown for this survey
|
||||
if ($surveyinfo['publicgraphs']=='Y')
|
||||
{
|
||||
$publicgraphs = 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
$publicgraphs = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//we collect all the output within this variable
|
||||
$statisticsoutput ='';
|
||||
|
||||
|
||||
//for creating graphs we need some more scripts which are included here
|
||||
//True -> include
|
||||
//False -> forget about charts
|
||||
if (isset($publicgraphs) && $publicgraphs == 1)
|
||||
{
|
||||
require_once(APPPATH.'third_party/pchart/pchart/pChart.class');
|
||||
require_once(APPPATH.'third_party/pchart/pchart/pData.class');
|
||||
require_once(APPPATH.'third_party/pchart/pchart/pCache.class');
|
||||
|
||||
$MyCache = new pCache(Yii::app()->getConfig("tempdir").DIRECTORY_SEPARATOR);
|
||||
//$currentuser is created as prefix for pchart files
|
||||
if (isset($_SERVER['REDIRECT_REMOTE_USER']))
|
||||
{
|
||||
$currentuser=$_SERVER['REDIRECT_REMOTE_USER'];
|
||||
}
|
||||
else if (session_id())
|
||||
{
|
||||
$currentuser=substr(session_id(), 0, 15);
|
||||
}
|
||||
else
|
||||
{
|
||||
$currentuser="standard";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Set language for questions and labels to base language of this survey
|
||||
if (isset($postlang) && $postlang != null )
|
||||
$language = $postlang;
|
||||
else
|
||||
$language = Survey::model()->findByPk($iSurveyID)->language;
|
||||
|
||||
|
||||
//set survey language for translations
|
||||
$clang = SetSurveyLanguage($iSurveyID, $language);
|
||||
|
||||
|
||||
//Create header (fixes bug #3097)
|
||||
$surveylanguage= $language;
|
||||
sendCacheHeaders();
|
||||
$condition = false;
|
||||
$sitename = Yii::app()->getConfig("sitename");
|
||||
|
||||
$data['surveylanguage'] = $surveylanguage;
|
||||
$data['sitename'] = $sitename;
|
||||
$data['condition'] = $condition;
|
||||
$data['thisSurveyCssPath'] = $thisSurveyCssPath;
|
||||
|
||||
/*
|
||||
* only show questions where question attribute "public_statistics" is set to "1"
|
||||
*/
|
||||
|
||||
$query = "SELECT q.* , group_name, group_order FROM {{questions}} q, {{groups}} g, {{question_attributes}} qa
|
||||
WHERE g.gid = q.gid AND g.language = :lang1 AND q.language = :lang2 AND q.sid = :surveyid AND q.qid = qa.qid AND q.parent_qid = 0 AND qa.attribute = 'public_statistics'";
|
||||
$databasetype = Yii::app()->db->getDriverName();
|
||||
if ($databasetype=='mssql' || $databasetype=="sqlsrv" || $databasetype=="dblib")
|
||||
{
|
||||
$query .=" AND CAST(CAST(qa.value as varchar) as int)='1'\n";
|
||||
}
|
||||
else
|
||||
{
|
||||
$query .=" AND qa.value='1'\n";
|
||||
}
|
||||
|
||||
//execute query
|
||||
$result = Yii::app()->db->createCommand($query)->bindParam(":lang1", $language, PDO::PARAM_STR)->bindParam(":lang2", $language, PDO::PARAM_STR)->bindParam(":surveyid", $iSurveyID, PDO::PARAM_INT)->queryAll();
|
||||
|
||||
//store all the data in $rows
|
||||
$rows = $result;
|
||||
|
||||
|
||||
//SORT IN NATURAL ORDER!
|
||||
usort($rows, 'groupOrderThenQuestionOrder');
|
||||
|
||||
//put the question information into the filter array
|
||||
foreach ($rows as $row)
|
||||
{
|
||||
//store some column names in $filters array
|
||||
$filters[]=array($row['qid'],
|
||||
$row['gid'],
|
||||
$row['type'],
|
||||
$row['title'],
|
||||
$row['group_name'],
|
||||
flattenText($row['question']));
|
||||
}
|
||||
|
||||
//number of records for this survey
|
||||
$totalrecords = 0;
|
||||
|
||||
//count number of answers
|
||||
$query = "SELECT count(*) FROM {{survey_".intval($iSurveyID)."}}";
|
||||
|
||||
//if incompleted answers should be filtert submitdate has to be not null
|
||||
//this setting is taken from config-defaults.php
|
||||
if (Yii::app()->getConfig("filterout_incomplete_answers") == true)
|
||||
{
|
||||
$query .= " WHERE {{survey_".intval($iSurveyID)."}}.submitdate is not null";
|
||||
}
|
||||
$result = Yii::app()->db->createCommand($query)->queryAll();
|
||||
|
||||
//$totalrecords = total number of answers
|
||||
foreach($result as $row)
|
||||
{
|
||||
$totalrecords = reset($row);
|
||||
}
|
||||
|
||||
|
||||
//this is the array which we need later...
|
||||
$summary = array();
|
||||
//...while this is the array from copy/paste which we don't want to replace because this is a nasty source of error
|
||||
$allfields = array();
|
||||
|
||||
|
||||
//---------- CREATE SGQA OF ALL QUESTIONS WHICH USE "PUBLIC_STATISTICS" ----------
|
||||
|
||||
/*
|
||||
* let's go through the filter array which contains
|
||||
* ['qid'],
|
||||
['gid'],
|
||||
['type'],
|
||||
['title'],
|
||||
['group_name'],
|
||||
['question'];
|
||||
*/
|
||||
|
||||
$currentgroup='';
|
||||
// use to check if there are any question with public statistics
|
||||
if(isset($filters)){
|
||||
foreach ($filters as $flt)
|
||||
{
|
||||
//SGQ identifier
|
||||
$myfield = "{$iSurveyID}X{$flt[1]}X{$flt[0]}";
|
||||
|
||||
//let's switch through the question type for each question
|
||||
switch ($flt[2])
|
||||
{
|
||||
case "K": // Multiple Numerical
|
||||
case "Q": // Multiple Short Text
|
||||
//get answers
|
||||
$query = "SELECT title as code, question as answer FROM {{questions}} WHERE parent_qid=:flt_0 AND language = :lang ORDER BY question_order";
|
||||
$result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $language, PDO::PARAM_STR)->queryAll();
|
||||
|
||||
//go through all the (multiple) answers
|
||||
foreach($result as $row)
|
||||
{
|
||||
$myfield2=$flt[2].$myfield.reset($row);
|
||||
$allfields[] = $myfield2;
|
||||
}
|
||||
break;
|
||||
case "A": // ARRAY OF 5 POINT CHOICE QUESTIONS
|
||||
case "B": // ARRAY OF 10 POINT CHOICE QUESTIONS
|
||||
case "C": // ARRAY OF YES\No\$clang->gT("Uncertain") QUESTIONS
|
||||
case "E": // ARRAY OF Increase/Same/Decrease QUESTIONS
|
||||
case "F": // FlEXIBLE ARRAY
|
||||
case "H": // ARRAY (By Column)
|
||||
//get answers
|
||||
$query = "SELECT title as code, question as answer FROM {{questions}} WHERE parent_qid=:flt_0 AND language = :lang ORDER BY question_order";
|
||||
$result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $language, PDO::PARAM_STR)->queryAll();
|
||||
|
||||
//go through all the (multiple) answers
|
||||
foreach($result as $row)
|
||||
{
|
||||
$myfield2 = $myfield.reset($row);
|
||||
$allfields[]=$myfield2;
|
||||
}
|
||||
break;
|
||||
// all "free text" types (T, U, S) get the same prefix ("T")
|
||||
case "T": // Long free text
|
||||
case "U": // Huge free text
|
||||
case "S": // Short free text
|
||||
$myfield="T$myfield";
|
||||
$allfields[] = $myfield;
|
||||
break;
|
||||
case ";": //ARRAY (Multi Flex) (Text)
|
||||
case ":": //ARRAY (Multi Flex) (Numbers)
|
||||
$query = "SELECT title, question FROM {{questions}} WHERE parent_qid=:flt_0 AND language=:lang AND scale_id = 0 ORDER BY question_order";
|
||||
$result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $language, PDO::PARAM_STR)->queryAll();
|
||||
foreach($result as $row)
|
||||
{
|
||||
$fquery = "SELECT * FROM {{questions}} WHERE parent_qid = :flt_0 AND language = :lang AND scale_id = 1 ORDER BY question_order, title";
|
||||
$fresult = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $language, PDO::PARAM_STR)->queryAll();
|
||||
foreach($fresult as $frow)
|
||||
{
|
||||
$myfield2 = $myfield . reset($row) . "_" . $frow['title'];
|
||||
$allfields[]=$myfield2;
|
||||
}
|
||||
}
|
||||
break;
|
||||
case "R": //RANKING
|
||||
//get some answers
|
||||
$query = "SELECT code, answer FROM {{answers}} WHERE qid = :flt_0 AND language = :lang ORDER BY sortorder, answer";
|
||||
$result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $language, PDO::PARAM_STR)->queryAll();
|
||||
|
||||
//get number of answers
|
||||
$count = count($result);
|
||||
|
||||
//loop through all answers. if there are 3 items to rate there will be 3 statistics
|
||||
for ($i=1; $i<=$count; $i++)
|
||||
{
|
||||
$myfield2 = "R" . $myfield . $i . "-" . strlen($i);
|
||||
$allfields[]=$myfield2;
|
||||
}
|
||||
break;
|
||||
//Boilerplate questions are only used to put some text between other questions -> no analysis needed
|
||||
case "X": //This is a boilerplate question and it has no business in this script
|
||||
break;
|
||||
case "1": // MULTI SCALE
|
||||
//get answers
|
||||
$query = "SELECT title, question FROM {{questions}} WHERE parent_qid = :flt_0 AND language = :lang ORDER BY question_order";
|
||||
$result = Yii::app()->db->createCommand($query)->bindParam(":flt_0", $flt[0], PDO::PARAM_INT)->bindParam(":lang", $language, PDO::PARAM_STR)->queryAll();
|
||||
|
||||
//loop through answers
|
||||
foreach($result as $row)
|
||||
{
|
||||
//----------------- LABEL 1 ---------------------
|
||||
$myfield2 = $myfield . $row['title']."#0";
|
||||
$allfields[]=$myfield2;
|
||||
//----------------- LABEL 2 ---------------------
|
||||
$myfield2 = $myfield . $row['title']."#1";
|
||||
$allfields[]=$myfield2;
|
||||
} //end WHILE -> loop through all answers
|
||||
break;
|
||||
|
||||
case "P": //P - Multiple choice with comments
|
||||
case "M": //M - Multiple choice
|
||||
case "N": //N - Numerical input
|
||||
case "D": //D - Date
|
||||
$myfield2 = $flt[2].$myfield;
|
||||
$allfields[]=$myfield2;
|
||||
break;
|
||||
default: //Default settings
|
||||
$allfields[] = $myfield;
|
||||
break;
|
||||
|
||||
} //end switch -> check question types and create filter forms
|
||||
}
|
||||
//end foreach -> loop through all questions with "public_statistics" enabled
|
||||
}// end if -> for removing the error message in case there are no filters
|
||||
$summary = $allfields;
|
||||
|
||||
|
||||
// Get the survey inforamtion
|
||||
$thissurvey = getSurveyInfo($surveyid,$language);
|
||||
|
||||
//SET THE TEMPLATE DIRECTORY
|
||||
if (!isset($thissurvey['templatedir']) || !$thissurvey['templatedir'])
|
||||
{
|
||||
$data['sTemplatePath'] = validateTemplateDir(Yii::app()->getConfig("defaulttemplate"));
|
||||
}
|
||||
else
|
||||
{
|
||||
$data['sTemplatePath'] = validateTemplateDir($thissurvey['templatedir']);
|
||||
}
|
||||
|
||||
|
||||
//---------- CREATE STATISTICS ----------
|
||||
$redata = compact(array_keys(get_defined_vars()));
|
||||
doHeader();
|
||||
echo templatereplace(file_get_contents(getTemplatePath(validateTemplateDir($data['sTemplatePath'])).DIRECTORY_SEPARATOR."startpage.pstpl"),array(), $redata);
|
||||
|
||||
|
||||
//some progress bar stuff
|
||||
|
||||
// Create progress bar which is shown while creating the results
|
||||
$prb = new ProgressBar();
|
||||
$prb->pedding = 2; // Bar Pedding
|
||||
$prb->brd_color = "#404040 #dfdfdf #dfdfdf #404040"; // Bar Border Color
|
||||
|
||||
$prb->setFrame(); // set ProgressBar Frame
|
||||
$prb->frame['left'] = 50; // Frame position from left
|
||||
$prb->frame['top'] = 80; // Frame position from top
|
||||
$prb->addLabel('text','txt1',$clang->gT("Please wait ...")); // add Text as Label 'txt1' and value 'Please wait'
|
||||
$prb->addLabel('percent','pct1'); // add Percent as Label 'pct1'
|
||||
$prb->addButton('btn1',$clang->gT('Go back'),'?action=statistics&sid='.$iSurveyID); // add Button as Label 'btn1' and action '?restart=1'
|
||||
|
||||
//progress bar starts with 35%
|
||||
$process_status = 35;
|
||||
$prb->show(); // show the ProgressBar
|
||||
|
||||
|
||||
// 1: Get list of questions with answers chosen
|
||||
//"Getting Questions and Answer ..." is shown above the bar
|
||||
$prb->setLabelValue('txt1',$clang->gT('Getting questions and answers ...'));
|
||||
$prb->moveStep(5);
|
||||
|
||||
// creates array of post variable names
|
||||
for (reset($_POST); $key=key($_POST); next($_POST))
|
||||
{
|
||||
$postvars[]=$key;
|
||||
}
|
||||
$data['thisSurveyTitle'] = $thisSurveyTitle;
|
||||
$data['totalrecords'] = $totalrecords;
|
||||
$data['clang'] = $clang;
|
||||
$data['summary'] = $summary;
|
||||
//show some main data at the beginnung
|
||||
// CHANGE JSW_NZ - let's allow html formatted questions to show
|
||||
|
||||
|
||||
//push progress bar from 35 to 40
|
||||
$process_status = 40;
|
||||
|
||||
//Show Summary results
|
||||
if (isset($summary) && $summary)
|
||||
{
|
||||
//"Generating Summaries ..." is shown above the progress bar
|
||||
$prb->setLabelValue('txt1',$clang->gT('Generating summaries ...'));
|
||||
$prb->moveStep($process_status);
|
||||
|
||||
//let's run through the survey // Fixed bug 3053 with array_unique
|
||||
$runthrough=array_unique($summary);
|
||||
|
||||
//loop through all selected questions
|
||||
foreach ($runthrough as $rt)
|
||||
{
|
||||
|
||||
//update progress bar
|
||||
if ($process_status < 100) $process_status++;
|
||||
$prb->moveStep($process_status);
|
||||
|
||||
} // end foreach -> loop through all questions
|
||||
|
||||
$helper = new statistics_helper();
|
||||
$statisticsoutput .= $helper->generate_statistics($iSurveyID, $summary, $summary, $publicgraphs, 'html', null,$language,false);
|
||||
|
||||
} //end if -> show summary results
|
||||
|
||||
$data['statisticsoutput']=$statisticsoutput;
|
||||
//done! set progress bar to 100%
|
||||
if (isset($prb))
|
||||
{
|
||||
$prb->setLabelValue('txt1',$clang->gT('Completed'));
|
||||
$prb->moveStep(100);
|
||||
$prb->hide();
|
||||
}
|
||||
|
||||
$redata = compact(array_keys(get_defined_vars()));
|
||||
$data['redata'] = $redata;
|
||||
Yii::app()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . 'statistics_user.js');
|
||||
$this->renderPartial('/statistics_user_view',$data);
|
||||
|
||||
//output footer
|
||||
echo getFooter();
|
||||
|
||||
//Delete all Session Data
|
||||
Yii::app()->session['finished'] = true;
|
||||
}
|
||||
|
||||
}
|
80
sources/application/controllers/SurveyController.php
Normal file
80
sources/application/controllers/SurveyController.php
Normal file
|
@ -0,0 +1,80 @@
|
|||
<?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.
|
||||
*
|
||||
*/
|
||||
class SurveyController extends LSYii_Controller
|
||||
{
|
||||
public $lang = null;
|
||||
|
||||
/**
|
||||
* Initialises this controller, does some basic checks and setups
|
||||
*
|
||||
* @access protected
|
||||
* @return void
|
||||
*/
|
||||
protected function _init()
|
||||
{
|
||||
parent::_init();
|
||||
|
||||
$this->_sessioncontrol();
|
||||
|
||||
unset(Yii::app()->session['FileManagerContext']);
|
||||
|
||||
if (!Yii::app()->getConfig("surveyid")) {Yii::app()->setConfig("surveyid", returnGlobal('sid'));} //SurveyID
|
||||
if (!Yii::app()->getConfig("ugid")) {Yii::app()->setConfig("ugid", returnGlobal('ugid'));} //Usergroup-ID
|
||||
if (!Yii::app()->getConfig("gid")) {Yii::app()->setConfig("gid", returnGlobal('gid'));} //GroupID
|
||||
if (!Yii::app()->getConfig("qid")) {Yii::app()->setConfig("qid", returnGlobal('qid'));} //QuestionID
|
||||
if (!Yii::app()->getConfig("lid")) {Yii::app()->setConfig("lid", returnGlobal('lid'));} //LabelID
|
||||
if (!Yii::app()->getConfig("code")) {Yii::app()->setConfig("code", returnGlobal('code'));} // ??
|
||||
if (!Yii::app()->getConfig("action")) {Yii::app()->setConfig("action", returnGlobal('action'));} //Desired action
|
||||
if (!Yii::app()->getConfig("subaction")) {Yii::app()->setConfig("subaction", returnGlobal('subaction'));} //Desired subaction
|
||||
if (!Yii::app()->getConfig("editedaction")) {Yii::app()->setConfig("editedaction", returnGlobal('editedaction'));} // for html editor integration
|
||||
}
|
||||
|
||||
/**
|
||||
* Load and set session vars
|
||||
*
|
||||
* @access protected
|
||||
* @return void
|
||||
*/
|
||||
protected function _sessioncontrol()
|
||||
{
|
||||
if (!Yii::app()->session["adminlang"] || Yii::app()->session["adminlang"]=='')
|
||||
Yii::app()->session["adminlang"] = Yii::app()->getConfig("defaultlang");
|
||||
|
||||
Yii::import('application.libraries.Limesurvey_lang');
|
||||
$this->lang = new Limesurvey_lang(Yii::app()->session['adminlang']);
|
||||
Yii::app()->setLang($this->lang);
|
||||
}
|
||||
|
||||
/**
|
||||
* Routes all the actions to their respective places
|
||||
*
|
||||
* @access public
|
||||
* @return array
|
||||
*/
|
||||
public function actions()
|
||||
{
|
||||
return array(
|
||||
'index' => 'application.controllers.survey.index',
|
||||
'optin' => 'application.controllers.optin',
|
||||
'optout' => 'application.controllers.optout',
|
||||
'printanswers' => 'application.controllers.printanswers',
|
||||
'register' => 'application.controllers.register',
|
||||
'statistics_user' => 'application.controllers.statistics_user',
|
||||
'tcpdf_check' => 'application.controllers.tcpdf_check',
|
||||
'uploader' => 'application.controllers.uploader',
|
||||
'verification' => 'application.controllers.verification'
|
||||
);
|
||||
}
|
||||
|
||||
}
|
41
sources/application/controllers/SurveysController.php
Normal file
41
sources/application/controllers/SurveysController.php
Normal file
|
@ -0,0 +1,41 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* This class will handle survey creation and manipulation.
|
||||
*/
|
||||
class SurveysController extends LSYii_Controller
|
||||
{
|
||||
public $layout = 'bare';
|
||||
public $defaultAction = 'publicList';
|
||||
public function actionPublicList($lang = null)
|
||||
{
|
||||
$this->sessioncontrol();
|
||||
if (isset($lang))
|
||||
{
|
||||
App()->setLang(new Limesurvey_lang($lang));
|
||||
}
|
||||
|
||||
$this->render('publicSurveyList', array(
|
||||
'publicSurveys' => Survey::model()->active()->open()->public()->with('languagesettings')->findAll(),
|
||||
'futureSurveys' => Survey::model()->active()->registration()->public()->with('languagesettings')->findAll(),
|
||||
|
||||
));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Load and set session vars
|
||||
* @todo Remove this ugly code. Language settings should be moved to Application instead of Controller.
|
||||
* @access protected
|
||||
* @return void
|
||||
*/
|
||||
protected function sessioncontrol()
|
||||
{
|
||||
if (!Yii::app()->session["adminlang"] || Yii::app()->session["adminlang"]=='')
|
||||
Yii::app()->session["adminlang"] = Yii::app()->getConfig("defaultlang");
|
||||
|
||||
Yii::import('application.libraries.Limesurvey_lang');
|
||||
Yii::app()->setLang(new Limesurvey_lang(Yii::app()->session['adminlang']));
|
||||
}
|
||||
}
|
||||
?>
|
381
sources/application/controllers/UploaderController.php
Normal file
381
sources/application/controllers/UploaderController.php
Normal file
|
@ -0,0 +1,381 @@
|
|||
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
|
||||
/*
|
||||
* LimeSurvey
|
||||
* Copyright (C) 2007-2014 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.
|
||||
*
|
||||
*/
|
||||
|
||||
class UploaderController extends SurveyController {
|
||||
function run($actionID)
|
||||
{
|
||||
if(isset($_SESSION['LEMsid']) && $oSurvey=Survey::model()->findByPk($_SESSION['LEMsid'])){
|
||||
$surveyid= $_SESSION['LEMsid'];
|
||||
}else{
|
||||
throw new CHttpException(400);// See for debug > 1
|
||||
}
|
||||
if (isset($_SESSION['survey_'.$surveyid]['s_lang']))
|
||||
{
|
||||
$sLanguage = $_SESSION['survey_'.$surveyid]['s_lang'];
|
||||
}
|
||||
else
|
||||
{
|
||||
$sLanguage='';
|
||||
}
|
||||
|
||||
$clang = SetSurveyLanguage( $surveyid, $sLanguage);
|
||||
$uploaddir = Yii::app()->getConfig("uploaddir");
|
||||
$tempdir = Yii::app()->getConfig("tempdir");
|
||||
|
||||
Yii::app()->loadHelper("database");
|
||||
|
||||
// Fill needed var
|
||||
$sFileGetContent=Yii::app()->request->getParam('filegetcontents','');// The file to view fu_ or fu_tmp
|
||||
$bDelete=Yii::app()->request->getParam('delete');
|
||||
$sFieldName = Yii::app()->request->getParam('fieldname');
|
||||
$sFileName = Yii::app()->request->getParam('filename','');// The file to delete fu_ or fu_tmp
|
||||
$sOriginalFileName = Yii::app()->request->getParam('name','');// Used for javascript return only
|
||||
$sMode = Yii::app()->request->getParam('mode');
|
||||
$sPreview=Yii::app()->request->getParam('preview',0);
|
||||
|
||||
// Validate and filter and throw error if problems
|
||||
// Using 'futmp_'.randomChars(15).'_'.$pathinfo['extension'] for filename, then remove all other characters
|
||||
$sFileGetContentFiltered=preg_replace('/[^a-z0-9_]/', '', $sFileGetContent);
|
||||
$sFileNameFiltered = preg_replace('/[^a-z0-9_]/', '',$sFileName);
|
||||
$sFieldNameFiltered=preg_replace('/[^X0-9]/', '', $sFieldName);
|
||||
if($sFileGetContent!=$sFileGetContentFiltered || $sFileName!=$sFileNameFiltered || $sFieldName!=$sFieldNameFiltered)
|
||||
{// If one seems to be a hack: Bad request
|
||||
throw new CHttpException(400);// See for debug > 1
|
||||
}
|
||||
if ($sFileGetContent)
|
||||
{
|
||||
if (substr($sFileGetContent,0,6)=='futmp_')
|
||||
{
|
||||
$sFileDir = $tempdir.'/upload/';
|
||||
}
|
||||
elseif(substr($sFileGetContent,0,3)=='fu_')
|
||||
{
|
||||
// Need to validate $_SESSION['srid'], and this file is from this srid !
|
||||
$sFileDir = "{$uploaddir}/surveys/{$surveyid}/files/";
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new CHttpException(400);// See for debug > 1
|
||||
}
|
||||
if(is_file($sFileDir.$sFileGetContent))// Validate file before else 500 error by getMimeType
|
||||
{
|
||||
header('Content-Type: '. CFileHelper::getMimeType($sFileDir.$sFileGetContent));
|
||||
readfile($sFileDir.$sFileGetContent);
|
||||
Yii::app()->end();
|
||||
}
|
||||
else
|
||||
{
|
||||
Yii::app()->end();
|
||||
}
|
||||
}
|
||||
elseif ($bDelete) {
|
||||
if (substr($sFileName,0,6)=='futmp_')
|
||||
{
|
||||
$sFileDir = $tempdir.'/upload/';
|
||||
}
|
||||
elseif(substr($sFileName,0,3)=='fu_')
|
||||
{
|
||||
// Need to validate $_SESSION['srid'], and this file is from this srid !
|
||||
$sFileDir = "{$uploaddir}/surveys/{$surveyid}/files/";
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new CHttpException(400);// See for debug > 1
|
||||
}
|
||||
if(isset($_SESSION[$sFieldName])) {// We already have $sFieldName ?
|
||||
$sJSON = $_SESSION[$sFieldName];
|
||||
$aFiles = json_decode(stripslashes($sJSON),true);
|
||||
|
||||
if(substr($sFileName,0,3)=='fu_'){
|
||||
$iFileIndex=0;
|
||||
$found=false;
|
||||
foreach ($aFiles as $aFile)
|
||||
{
|
||||
if ($aFile['filename']==$sFileName)
|
||||
{
|
||||
$found=true;
|
||||
break;
|
||||
}
|
||||
$iFileIndex++;
|
||||
}
|
||||
if ($found==true) unset($aFiles[$iFileIndex]);
|
||||
$_SESSION[$sFieldName] = ls_json_encode($aFiles);
|
||||
}
|
||||
}
|
||||
//var_dump($sFileDir.$sFilename);
|
||||
// Return some json to do a beautiful text
|
||||
if (@unlink($sFileDir.$sFileName))
|
||||
{
|
||||
echo sprintf($clang->gT('File %s deleted'), $sOriginalFileName);
|
||||
}
|
||||
else
|
||||
echo $clang->gT('Oops, There was an error deleting the file');
|
||||
Yii::app()->end();
|
||||
}
|
||||
|
||||
|
||||
if($sMode == "upload")
|
||||
{
|
||||
$clang = Yii::app()->lang;
|
||||
|
||||
$sTempUploadDir = $tempdir.'/upload/';
|
||||
// Check if exists and is writable
|
||||
if (!file_exists($sTempUploadDir)) {
|
||||
// Try to create
|
||||
mkdir($sTempUploadDir);
|
||||
}
|
||||
$filename = $_FILES['uploadfile']['name'];
|
||||
// Do we filter file name ? It's used on displaying only , but not save like that.
|
||||
//$filename = sanitize_filename($_FILES['uploadfile']['name']);// This remove all non alpha numeric characters and replaced by _ . Leave only one dot .
|
||||
$size = 0.001 * $_FILES['uploadfile']['size'];
|
||||
$preview = Yii::app()->session['preview'];
|
||||
$aFieldMap = createFieldMap($surveyid,'short',false,false,$sLanguage);
|
||||
if (!isset($aFieldMap[$sFieldName]))
|
||||
{
|
||||
throw new CHttpException(400);// See for debug > 1
|
||||
}
|
||||
$aAttributes=getQuestionAttributeValues($aFieldMap[$sFieldName]['qid'],$aFieldMap[$sFieldName]['type']);
|
||||
|
||||
$maxfilesize = (int) $aAttributes['max_filesize'];
|
||||
$valid_extensions_array = explode(",", $aAttributes['allowed_filetypes']);
|
||||
$valid_extensions_array = array_map('trim',$valid_extensions_array);
|
||||
|
||||
$pathinfo = pathinfo($_FILES['uploadfile']['name']);
|
||||
$ext = $pathinfo['extension'];
|
||||
$randfilename = 'futmp_'.randomChars(15).'_'.$pathinfo['extension'];
|
||||
$randfileloc = $sTempUploadDir . $randfilename;
|
||||
|
||||
// check to see that this file type is allowed
|
||||
// it is also checked at the client side, but jst double checking
|
||||
if (!in_array(strtolower($ext), $valid_extensions_array))
|
||||
{
|
||||
$return = array(
|
||||
"success" => false,
|
||||
"msg" => sprintf($clang->gT("Sorry, this file extension (%s) is not allowed!"),$ext)
|
||||
);
|
||||
//header('Content-Type: application/json');
|
||||
echo ls_json_encode($return);
|
||||
Yii::app()->end();
|
||||
}
|
||||
|
||||
// If this is just a preview, don't save the file
|
||||
if ($preview)
|
||||
{
|
||||
if ($size > $maxfilesize)
|
||||
{
|
||||
$return = array(
|
||||
"success" => false,
|
||||
"msg" => sprintf($clang->gT("Sorry, this file is too large. Only files upto %s KB are allowed."), $maxfilesize)
|
||||
);
|
||||
//header('Content-Type: application/json');
|
||||
echo ls_json_encode($return);
|
||||
Yii::app()->end();
|
||||
}
|
||||
|
||||
else if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $randfileloc))
|
||||
{
|
||||
|
||||
$return = array(
|
||||
"success" => true,
|
||||
"file_index" => $filecount,
|
||||
"size" => $size,
|
||||
"name" => rawurlencode(basename($filename)),
|
||||
"ext" => $ext,
|
||||
"filename" => $randfilename,
|
||||
"msg" => $clang->gT("The file has been successfuly uploaded.")
|
||||
);
|
||||
// TODO : unlink this file since this is just a preview. But we can do it only if it's not needed, and still needed to have the file content
|
||||
// Maybe use a javascript 'onunload' on preview question/group
|
||||
// unlink($randfileloc)
|
||||
//header('Content-Type: application/json');
|
||||
echo ls_json_encode($return);;
|
||||
Yii::app()->end();
|
||||
}
|
||||
}
|
||||
else
|
||||
{ // if everything went fine and the file was uploaded successfuly,
|
||||
// send the file related info back to the client
|
||||
$iFileUploadTotalSpaceMB = Yii::app()->getConfig("iFileUploadTotalSpaceMB");
|
||||
if ($size > $maxfilesize)
|
||||
{
|
||||
$return = array(
|
||||
"success" => false,
|
||||
"msg" => sprintf($clang->gT("Sorry, this file is too large. Only files up to %s KB are allowed.",'unescaped'), $maxfilesize)
|
||||
);
|
||||
//header('Content-Type: application/json');
|
||||
echo ls_json_encode($return);
|
||||
Yii::app()->end();
|
||||
}
|
||||
elseif ($iFileUploadTotalSpaceMB>0 && ((calculateTotalFileUploadUsage()+($size/1024/1024))>$iFileUploadTotalSpaceMB))
|
||||
{
|
||||
$return = array(
|
||||
"success" => false,
|
||||
"msg" => $clang->gT("We are sorry but there was a system error and your file was not saved. An email has been dispatched to notify the survey administrator.",'unescaped')
|
||||
);
|
||||
//header('Content-Type: application/json');
|
||||
echo ls_json_encode($return);
|
||||
Yii::app()->end();
|
||||
}
|
||||
elseif (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $randfileloc))
|
||||
{
|
||||
$return = array(
|
||||
"success" => true,
|
||||
"size" => $size,
|
||||
"name" => rawurlencode(basename($filename)),
|
||||
"ext" => $ext,
|
||||
"filename" => $randfilename,
|
||||
"msg" => $clang->gT("The file has been successfuly uploaded.")
|
||||
);
|
||||
//header('Content-Type: application/json');
|
||||
echo ls_json_encode($return);
|
||||
Yii::app()->end();
|
||||
}
|
||||
// if there was some error, report error message
|
||||
else
|
||||
{
|
||||
// check for upload error
|
||||
if ($_FILES['uploadfile']['error'] > 2)
|
||||
{
|
||||
$return = array(
|
||||
"success" => false,
|
||||
"msg" => $clang->gT("Sorry, there was an error uploading your file")
|
||||
);
|
||||
//header('Content-Type: application/json');
|
||||
echo ls_json_encode($return);
|
||||
Yii::app()->end();
|
||||
}
|
||||
// check to ensure that the file does not cross the maximum file size
|
||||
else if ( $_FILES['uploadfile']['error'] == 1 || $_FILES['uploadfile']['error'] == 2 || $size > $maxfilesize)
|
||||
{
|
||||
$return = array(
|
||||
"success" => false,
|
||||
"msg" => sprintf($clang->gT("Sorry, this file is too large. Only files upto %s KB are allowed."), $maxfilesize)
|
||||
);
|
||||
//header('Content-Type: application/json');
|
||||
echo ls_json_encode($return);
|
||||
Yii::app()->end();
|
||||
}
|
||||
else
|
||||
{
|
||||
$return = array(
|
||||
"success" => false,
|
||||
"msg" => $clang->gT("Unknown error")
|
||||
);
|
||||
//header('Content-Type: application/json');
|
||||
echo ls_json_encode($return);
|
||||
Yii::app()->end();
|
||||
}
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
$clang = Yii::app()->lang;
|
||||
$meta = '';
|
||||
App()->getClientScript()->registerPackage('jqueryui');
|
||||
App()->getClientScript()->registerPackage('jquery-superfish');
|
||||
$sNeededScriptVar='
|
||||
var uploadurl = "'.$this->createUrl('/uploader/index/mode/upload/').'";
|
||||
var imageurl = "'.Yii::app()->getConfig('imageurl').'/";
|
||||
var surveyid = "'.$surveyid.'";
|
||||
var fieldname = "'.$sFieldName.'";
|
||||
var questgrppreview = '.$sPreview.';
|
||||
csrfToken = '.ls_json_encode(Yii::app()->request->csrfToken).';
|
||||
showpopups="'.Yii::app()->getConfig("showpopups").'";
|
||||
';
|
||||
$sLangScriptVar="
|
||||
translt = {
|
||||
titleFld: '" . $clang->gT('Title','js') . "',
|
||||
commentFld: '" . $clang->gT('Comment','js') . "',
|
||||
errorNoMoreFiles: '" . $clang->gT('Sorry, no more files can be uploaded!','js') . "',
|
||||
errorOnlyAllowed: '" . $clang->gT('Sorry, only %s files can be uploaded for this question!','js') . "',
|
||||
uploading: '" . $clang->gT('Uploading','js') . "',
|
||||
selectfile: '" . $clang->gT('Select file','js') . "',
|
||||
errorNeedMore: '" . $clang->gT('Please upload %s more file(s).','js') . "',
|
||||
errorMoreAllowed: '" . $clang->gT('If you wish, you may upload %s more file(s); else you may return back to survey.','js') . "',
|
||||
errorMaxReached: '" . $clang->gT('The maximum number of files has been uploaded. You may return back to survey.','js') . "',
|
||||
errorTooMuch: '" . $clang->gT('The maximum number of files has been uploaded. You may return back to survey.','js') . "',
|
||||
errorNeedMoreConfirm: '" . $clang->gT("You need to upload %s more files for this question.\nAre you sure you want to exit?",'js') . "'
|
||||
};
|
||||
";
|
||||
$aSurveyInfo=getSurveyInfo($surveyid, $sLanguage);
|
||||
$oEvent = new PluginEvent('beforeSurveyPage');
|
||||
$oEvent->set('surveyId', $surveyid);
|
||||
App()->getPluginManager()->dispatchEvent($oEvent);
|
||||
if (!is_null($oEvent->get('template')))
|
||||
{
|
||||
$aSurveyInfo['templatedir'] = $event->get('template');
|
||||
}
|
||||
$sTemplateDir = getTemplatePath($aSurveyInfo['template']);
|
||||
$sTemplateUrl = getTemplateURL($aSurveyInfo['template'])."/";
|
||||
App()->clientScript->registerScript('sNeededScriptVar',$sNeededScriptVar,CClientScript::POS_HEAD);
|
||||
App()->clientScript->registerScript('sLangScriptVar',$sLangScriptVar,CClientScript::POS_HEAD);
|
||||
App()->getClientScript()->registerScriptFile(Yii::app()->getConfig("generalscripts").'ajaxupload.js');
|
||||
App()->getClientScript()->registerScriptFile(Yii::app()->getConfig("generalscripts").'uploader.js');
|
||||
App()->getClientScript()->registerScriptFile("{$sTemplateUrl}template.js");
|
||||
App()->clientScript->registerCssFile(Yii::app()->getConfig("publicstyleurl")."uploader.css");
|
||||
if (file_exists($sTemplateDir .DIRECTORY_SEPARATOR.'jquery-ui-custom.css'))
|
||||
{
|
||||
Yii::app()->getClientScript()->registerCssFile("{$sTemplateUrl}jquery-ui-custom.css");
|
||||
}
|
||||
elseif(file_exists($sTemplateDir.DIRECTORY_SEPARATOR.'jquery-ui.css'))
|
||||
{
|
||||
Yii::app()->getClientScript()->registerCssFile("{$sTemplateUrl}jquery-ui.css");
|
||||
}
|
||||
else
|
||||
{
|
||||
Yii::app()->getClientScript()->registerCssFile(Yii::app()->getConfig('publicstyleurl')."jquery-ui.css");
|
||||
}
|
||||
App()->clientScript->registerCssFile("{$sTemplateUrl}template.css");
|
||||
$header = getHeader($meta);
|
||||
|
||||
echo $header;
|
||||
|
||||
$fn = $sFieldName;
|
||||
$qid = (int)Yii::app()->request->getParam('qid');
|
||||
$minfiles = (int)Yii::app()->request->getParam('minfiles');
|
||||
$maxfiles = (int)Yii::app()->request->getParam('maxfiles');
|
||||
$qidattributes=getQuestionAttributeValues($qid);
|
||||
$qidattributes['max_filesize']=floor(min($qidattributes['max_filesize']*1024,getMaximumFileUploadSize())/1024);
|
||||
$body = '</head><body>
|
||||
<div id="notice"></div>
|
||||
<input type="hidden" id="ia" value="'.$fn.'" />
|
||||
<input type="hidden" id="'.$fn.'_minfiles" value="'.$minfiles.'" />
|
||||
<input type="hidden" id="'.$fn.'_maxfiles" value="'.$maxfiles.'" />
|
||||
<input type="hidden" id="'.$fn.'_maxfilesize" value="'.$qidattributes['max_filesize'].'" />
|
||||
<input type="hidden" id="'.$fn.'_allowed_filetypes" value="'.$qidattributes['allowed_filetypes'].'" />
|
||||
<input type="hidden" id="preview" value="'.Yii::app()->session['preview'].'" />
|
||||
<input type="hidden" id="'.$fn.'_show_comment" value="'.$qidattributes['show_comment'].'" />
|
||||
<input type="hidden" id="'.$fn.'_show_title" value="'.$qidattributes['show_title'].'" />
|
||||
<input type="hidden" id="'.$fn.'_licount" value="0" />
|
||||
<input type="hidden" id="'.$fn.'_filecount" value="0" />
|
||||
|
||||
<!-- The upload button -->
|
||||
<div class="upload-div">
|
||||
<button id="button1" class="button upload-button" type="button" >'.$clang->gT("Select file").'</button>
|
||||
</div>
|
||||
|
||||
<p class="uploadmsg">'.sprintf($clang->gT("You can upload %s under %s KB each."),$qidattributes['allowed_filetypes'],$qidattributes['max_filesize']).'</p>
|
||||
<div class="uploadstatus" id="uploadstatus"></div>
|
||||
|
||||
<!-- The list of uploaded files -->
|
||||
|
||||
</body>
|
||||
</html>';
|
||||
App()->getClientScript()->render($body);
|
||||
echo $body;
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
104
sources/application/controllers/VerificationController.php
Normal file
104
sources/application/controllers/VerificationController.php
Normal file
|
@ -0,0 +1,104 @@
|
|||
<?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.
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* the Verification class, this is grouped with
|
||||
* other classes in the "limesurvey_yii" package and * is part of "controllers" subpackage
|
||||
* @package limesurvey_yii
|
||||
* @subpackage controllers
|
||||
*/
|
||||
class VerificationController extends LSYii_Controller
|
||||
{
|
||||
function actionImage($sid)
|
||||
{
|
||||
$iSurveyID=(int)$sid;
|
||||
Yii::app()->loadHelper('database');
|
||||
$rootdir = Yii::app()->getConfig('rootdir');
|
||||
|
||||
// header for png
|
||||
Header("Content-Type: image/png");
|
||||
|
||||
// Create Image
|
||||
$im = ImageCreate(75, 20);
|
||||
$white = ImageColorAllocate($im, 255, 255, 255);
|
||||
$black = ImageColorAllocate($im, 0, 0, 0);
|
||||
$red = ImageColorAllocate($im, 255, 0, 0);
|
||||
$blue = ImageColorAllocate($im, 0, 0, 255);
|
||||
$grey_shade = ImageColorAllocate($im, 204, 204, 204);
|
||||
|
||||
// Create the random numberes
|
||||
srand((double)microtime()*1000000);
|
||||
|
||||
$num1 = rand(1,5);
|
||||
$found = false;
|
||||
while ($found == false)
|
||||
{
|
||||
$num2 = rand(1,100);
|
||||
if (preg_match('/^[0-9]+$/', $num2/5))
|
||||
{
|
||||
$found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
$font_c_rand = rand(1,3);
|
||||
if ($font_c_rand == 1)
|
||||
{
|
||||
$font_color = $black;
|
||||
} else if ($font_c_rand == 2)
|
||||
{
|
||||
$font_color = $red;
|
||||
} else if ($font_c_rand == 3)
|
||||
{
|
||||
$font_color = $blue;
|
||||
}
|
||||
|
||||
$font_rand = rand(1,2);//Maybe add other specific hard font
|
||||
if ($font_rand == 1)
|
||||
{
|
||||
$font = $rootdir."/fonts/FreeSans.ttf";
|
||||
} else {
|
||||
$font = $rootdir."/fonts/DejaVuSans.ttf";
|
||||
}
|
||||
|
||||
$line_rand = rand(1,3);
|
||||
if ($line_rand == 1)
|
||||
{
|
||||
$line_color = $black;
|
||||
} else if ($line_rand == 2)
|
||||
{
|
||||
$line_color = $red;
|
||||
} else if ($line_rand == 3)
|
||||
{
|
||||
$line_color = $blue;
|
||||
}
|
||||
|
||||
// Fill image, make transparent
|
||||
ImageFill($im, 0, 0, $grey_shade);
|
||||
//imagecolortransparent ($im, $white);
|
||||
imageline($im,0,0,0,20,$line_color);
|
||||
imageline($im,74,0,74,19,$line_color);
|
||||
imageline($im,0,0,74,0,$line_color);
|
||||
imageline($im,0,19,74,19,$line_color);
|
||||
// Write math question in a nice TTF Font
|
||||
ImageTTFText($im, 10, 0, 3, 16,$font_color, $font, $num1." + ".$num2." =" );
|
||||
|
||||
// Display Image
|
||||
ImagePNG($im);
|
||||
ImageDestroy($im);
|
||||
|
||||
// Add the answer to the session
|
||||
$_SESSION['survey_'.$iSurveyID]['secanswer'] = $num1+$num2;
|
||||
}
|
||||
}
|
||||
|
210
sources/application/controllers/admin/assessments.php
Normal file
210
sources/application/controllers/admin/assessments.php
Normal file
|
@ -0,0 +1,210 @@
|
|||
<?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.
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* Assessments Controller
|
||||
*
|
||||
* This controller performs assessments actions
|
||||
*
|
||||
* @package LimeSurvey
|
||||
* @subpackage Backend
|
||||
*/
|
||||
class Assessments extends Survey_Common_Action
|
||||
{
|
||||
|
||||
/**
|
||||
* Routes to the correct sub-action
|
||||
*
|
||||
* @access public
|
||||
* @param int $iSurveyID
|
||||
* @return void
|
||||
*/
|
||||
public function index($iSurveyID)
|
||||
{
|
||||
$iSurveyID = sanitize_int($iSurveyID);
|
||||
$sAction = Yii::app()->request->getPost('action');
|
||||
|
||||
$languages = Survey::model()->findByPk($iSurveyID)->additionalLanguages;
|
||||
$surveyLanguage = Survey::model()->findByPk($iSurveyID)->language;
|
||||
|
||||
Yii::app()->session['FileManagerContext'] = "edit:assessments:{$iSurveyID}";
|
||||
|
||||
array_unshift($languages, $surveyLanguage); // makes an array with ALL the languages supported by the survey -> $assessmentlangs
|
||||
|
||||
Yii::app()->setConfig("baselang", $surveyLanguage);
|
||||
Yii::app()->setConfig("assessmentlangs", $languages);
|
||||
|
||||
if ($sAction == "assessmentadd")
|
||||
$this->_add($iSurveyID);
|
||||
if ($sAction == "assessmentupdate")
|
||||
$this->_update($iSurveyID);
|
||||
if ($sAction == "assessmentdelete")
|
||||
$this->_delete($iSurveyID, $_POST['id']);
|
||||
|
||||
if (Permission::model()->hasSurveyPermission($iSurveyID, 'assessments', 'read')) {
|
||||
$clang = $this->getController()->lang;
|
||||
|
||||
if ($iSurveyID == '') {
|
||||
show_error($clang->gT("No SID Provided"));
|
||||
die();
|
||||
}
|
||||
|
||||
$this->_showAssessments($iSurveyID, $sAction, $surveyLanguage, $clang);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders template(s) wrapped in header and footer
|
||||
*
|
||||
* @param string $sAction Current action, the folder to fetch views from
|
||||
* @param string|array $aViewUrls View url(s)
|
||||
* @param array $aData Data to be passed on. Optional.
|
||||
*/
|
||||
protected function _renderWrappedTemplate($sAction = 'assessments', $aViewUrls = array(), $aData = array())
|
||||
{
|
||||
App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . 'assessments.js');
|
||||
App()->getClientScript()->registerPackage('jquery-tablesorter');
|
||||
App()->getClientScript()->registerPackage('jquery-superfish');
|
||||
|
||||
parent::_renderWrappedTemplate($sAction, $aViewUrls, $aData);
|
||||
}
|
||||
|
||||
private function _showAssessments($iSurveyID, $action, $surveyLanguage, Limesurvey_lang $clang)
|
||||
{
|
||||
$oAssessments = Assessment::model()->findAllByAttributes(array('sid' => $iSurveyID));
|
||||
$aData = $this->_collectGroupData($iSurveyID);
|
||||
$aHeadings = array($clang->gT("Scope"), $clang->gT("Question group"), $clang->gT("Minimum"), $clang->gT("Maximum"));
|
||||
$aData['actiontitle'] = $clang->gT("Add");
|
||||
$aData['actionvalue'] = "assessmentadd";
|
||||
$aData['editId'] = '';
|
||||
|
||||
if ($action == "assessmentedit" && Permission::model()->hasSurveyPermission($iSurveyID, 'assessments', 'update')) {
|
||||
$aData = $this->_collectEditData($surveyLanguage, $aData, $clang);
|
||||
}
|
||||
|
||||
$surveyinfo = getSurveyInfo($iSurveyID);
|
||||
$aData['clang'] = $clang;
|
||||
$aData['surveyinfo'] = $surveyinfo;
|
||||
$aData['imageurl'] = Yii::app()->getConfig('adminimageurl');
|
||||
$aData['surveyid'] = $iSurveyID;
|
||||
$aData['headings'] = $aHeadings;
|
||||
$aData['assessments'] = $oAssessments;
|
||||
$aData['assessmentlangs'] = Yii::app()->getConfig("assessmentlangs");
|
||||
$aData['baselang'] = $surveyLanguage;
|
||||
$aData['action'] = $action;
|
||||
$aData['gid'] = empty($_POST['gid']) ? '' : sanitize_int($_POST['gid']);
|
||||
|
||||
Yii::app()->loadHelper('admin/htmleditor');
|
||||
if ($surveyinfo['assessments']!='Y')
|
||||
$urls['message'] = array('title' => $clang->gT("Assessments mode not activated"), 'message' => sprintf($clang->gT("Assessment mode for this survey is not activated. You can activate it in the %s survey settings %s (tab 'Notification & data management')."),'<a href="'.$this->getController()->createUrl('admin/survey/sa/editsurveysettings/surveyid/'.$iSurveyID).'">','</a>'), 'class'=> 'warningheader');
|
||||
$urls['assessments_view'][]= $aData;
|
||||
$this->_renderWrappedTemplate('', $urls, $aData);
|
||||
}
|
||||
|
||||
private function _collectGroupData($iSurveyID)
|
||||
{
|
||||
$aData = array();
|
||||
$groups = QuestionGroup::model()->findAllByAttributes(array('sid' => $iSurveyID));
|
||||
foreach ($groups as $group) {
|
||||
$groupId = $group->attributes['gid'];
|
||||
$groupName = $group->attributes['group_name'];
|
||||
$aData['groups'][$groupId] = $groupName;
|
||||
}
|
||||
return $aData;
|
||||
}
|
||||
|
||||
private function _collectEditData($surveyLanguage, array $aData, Limesurvey_lang $clang)
|
||||
{
|
||||
$assessments = Assessment::model()->findAllByAttributes(array('id' => sanitize_int($_POST['id']), 'language' => $surveyLanguage));
|
||||
|
||||
foreach ($assessments as $assessment) {
|
||||
$editData = $assessment->attributes;
|
||||
}
|
||||
$aData['actiontitle'] = $clang->gT("Edit");
|
||||
$aData['actionvalue'] = "assessmentupdate";
|
||||
$aData['editId'] = $editData['id'];
|
||||
$aData['editdata'] = $editData;
|
||||
return $aData;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts an assessment to the database. Receives input from POST
|
||||
*/
|
||||
private function _add($iSurveyID)
|
||||
{
|
||||
if (Permission::model()->hasSurveyPermission($iSurveyID, 'assessments', 'create')) {
|
||||
$bFirst = true;
|
||||
$iAssessmentID = -1;
|
||||
$aLanguages = Yii::app()->getConfig("assessmentlangs");
|
||||
foreach ($aLanguages as $sLanguage)
|
||||
{
|
||||
$aData = $this->_getAssessmentPostData($iSurveyID, $sLanguage);
|
||||
|
||||
if ($bFirst == false) {
|
||||
$aData['id'] = $iAssessmentID;
|
||||
}
|
||||
$assessment = Assessment::model()->insertRecords($aData);
|
||||
if ($bFirst == true) {
|
||||
$bFirst = false;
|
||||
$iAssessmentID = $assessment->id;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates an assessment. Receives input from POST
|
||||
*/
|
||||
private function _update($iSurveyID)
|
||||
{
|
||||
if (Permission::model()->hasSurveyPermission($iSurveyID, 'assessments', 'update') && isset($_POST['id'])) {
|
||||
|
||||
$aid = sanitize_int($_POST['id']);
|
||||
$languages = Yii::app()->getConfig("assessmentlangs");
|
||||
foreach ($languages as $language)
|
||||
{
|
||||
$aData = $this->_getAssessmentPostData($iSurveyID, $language);
|
||||
Assessment::model()->updateAssessment($aid, $iSurveyID, $language, $aData);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes an assessment.
|
||||
*/
|
||||
private function _delete($iSurveyID, $assessmentId)
|
||||
{
|
||||
if (Permission::model()->hasSurveyPermission($iSurveyID, 'assessments', 'delete')) {
|
||||
Assessment::model()->deleteAllByAttributes(array('id' => $assessmentId, 'sid' => $iSurveyID));
|
||||
}
|
||||
}
|
||||
|
||||
private function _getAssessmentPostData($iSurveyID, $language)
|
||||
{
|
||||
if (!isset($_POST['gid']))
|
||||
$_POST['gid'] = 0;
|
||||
|
||||
return array(
|
||||
'sid' => $iSurveyID,
|
||||
'scope' => sanitize_paranoid_string($_POST['scope']),
|
||||
'gid' => sanitize_int($_POST['gid']),
|
||||
'minimum' => intval($_POST['minimum']),
|
||||
'maximum' => intval($_POST['maximum']),
|
||||
'name' => $_POST['name_' . $language],
|
||||
'language' => $language,
|
||||
'message' => $_POST['assessmentmessage_' . $language]
|
||||
);
|
||||
}
|
||||
}
|
286
sources/application/controllers/admin/authentication.php
Normal file
286
sources/application/controllers/admin/authentication.php
Normal file
|
@ -0,0 +1,286 @@
|
|||
<?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.
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* Authentication Controller
|
||||
*
|
||||
* This controller performs authentication
|
||||
*
|
||||
* @package LimeSurvey
|
||||
* @subpackage Backend
|
||||
*/
|
||||
class Authentication extends Survey_Common_Action
|
||||
{
|
||||
|
||||
/**
|
||||
* Show login screen and parse login data
|
||||
*/
|
||||
public function index()
|
||||
{
|
||||
$this->_redirectIfLoggedIn();
|
||||
|
||||
// Make sure after first run / update the authdb plugin is registered and active
|
||||
// it can not be deactivated
|
||||
if (!class_exists('Authdb', false)) {
|
||||
$plugin = Plugin::model()->findByAttributes(array('name'=>'Authdb'));
|
||||
if (!$plugin) {
|
||||
$plugin = new Plugin();
|
||||
$plugin->name = 'Authdb';
|
||||
$plugin->active = 1;
|
||||
$plugin->save();
|
||||
App()->getPluginManager()->loadPlugin('Authdb', $plugin->id);
|
||||
} else {
|
||||
$plugin->active = 1;
|
||||
$plugin->save();
|
||||
}
|
||||
}
|
||||
|
||||
$beforeLogin = new PluginEvent('beforeLogin');
|
||||
$beforeLogin->set('identity', new LSUserIdentity('', ''));
|
||||
|
||||
App()->getPluginManager()->dispatchEvent($beforeLogin);
|
||||
/* @var $identity LSUserIdentity */
|
||||
$identity = $beforeLogin->get('identity');
|
||||
|
||||
if (!$beforeLogin->isStopped() && is_null(App()->getRequest()->getPost('login_submit')))
|
||||
{
|
||||
if (!is_null($beforeLogin->get('default'))) {
|
||||
$aData['defaultAuth'] = $beforeLogin->get('default');
|
||||
}
|
||||
$newLoginForm = new PluginEvent('newLoginForm');
|
||||
App()->getPluginManager()->dispatchEvent($newLoginForm);
|
||||
$aData['summary'] = $this->_getSummary('logout');
|
||||
$aData['pluginContent'] = $newLoginForm->getAllContent();
|
||||
$this->_renderWrappedTemplate('authentication', 'login', $aData);
|
||||
} else {
|
||||
// Handle getting the post and populating the identity there
|
||||
$authMethod = App()->getRequest()->getPost('authMethod', $identity->plugin);
|
||||
$identity->plugin = $authMethod;
|
||||
|
||||
$event = new PluginEvent('afterLoginFormSubmit');
|
||||
$event->set('identity', $identity);
|
||||
App()->getPluginManager()->dispatchEvent($event, array($authMethod));
|
||||
$identity = $event->get('identity');
|
||||
|
||||
// Now authenticate
|
||||
if ($identity->authenticate())
|
||||
{
|
||||
FailedLoginAttempt::model()->deleteAttempts();
|
||||
App()->user->setState('plugin', $authMethod);
|
||||
$this->getController()->_GetSessionUserRights(Yii::app()->session['loginID']);
|
||||
Yii::app()->session['just_logged_in'] = true;
|
||||
Yii::app()->session['loginsummary'] = $this->_getSummary();
|
||||
$this->_doRedirect();
|
||||
|
||||
} else {
|
||||
// Failed
|
||||
$message = $identity->errorMessage;
|
||||
if (empty($message)) {
|
||||
// If no message, return a default message
|
||||
$clang = $this->getController()->lang;
|
||||
$message = $clang->gT('Incorrect username and/or password!');
|
||||
}
|
||||
App()->user->setFlash('loginError', $message);
|
||||
$this->getController()->redirect(array('/admin/authentication/sa/login'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Logout user
|
||||
*/
|
||||
public function logout()
|
||||
{
|
||||
// Fetch the current user
|
||||
$plugin = App()->user->getState('plugin', null); // Save for afterLogout, current user will be destroyed by then
|
||||
|
||||
/* Adding beforeLogout event */
|
||||
$beforeLogout = new PluginEvent('beforeLogout');
|
||||
App()->getPluginManager()->dispatchEvent($beforeLogout, array($plugin));
|
||||
|
||||
App()->user->logout();
|
||||
App()->user->setFlash('loginmessage', gT('Logout successful.'));
|
||||
|
||||
/* Adding afterLogout event */
|
||||
$event = new PluginEvent('afterLogout');
|
||||
App()->getPluginManager()->dispatchEvent($event, array($plugin));
|
||||
|
||||
$this->getController()->redirect(array('/admin/authentication/sa/login'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Forgot Password screen
|
||||
*/
|
||||
public function forgotpassword()
|
||||
{
|
||||
$this->_redirectIfLoggedIn();
|
||||
|
||||
if (!Yii::app()->request->getPost('action'))
|
||||
{
|
||||
$this->_renderWrappedTemplate('authentication', 'forgotpassword');
|
||||
}
|
||||
else
|
||||
{
|
||||
$sUserName = Yii::app()->request->getPost('user');
|
||||
$sEmailAddr = Yii::app()->request->getPost('email');
|
||||
|
||||
$aFields = User::model()->findAllByAttributes(array('users_name' => $sUserName, 'email' => $sEmailAddr));
|
||||
|
||||
if (count($aFields) < 1)
|
||||
{
|
||||
// wrong or unknown username and/or email
|
||||
$aData['errormsg'] = $this->getController()->lang->gT('User name and/or email not found!');
|
||||
$aData['maxattempts'] = '';
|
||||
$this->_renderWrappedTemplate('authentication', 'error', $aData);
|
||||
}
|
||||
else
|
||||
{
|
||||
$aData['message'] = $this->_sendPasswordEmail($sEmailAddr, $aFields);
|
||||
$this->_renderWrappedTemplate('authentication', 'message', $aData);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send the forgot password email
|
||||
*
|
||||
* @param string $sEmailAddr
|
||||
* @param array $aFields
|
||||
*/
|
||||
private function _sendPasswordEmail($sEmailAddr, $aFields)
|
||||
{
|
||||
$clang = $this->getController()->lang;
|
||||
$sFrom = Yii::app()->getConfig("siteadminname") . " <" . Yii::app()->getConfig("siteadminemail") . ">";
|
||||
$sTo = $sEmailAddr;
|
||||
$sSubject = $clang->gT('User data');
|
||||
$sNewPass = createPassword();
|
||||
$sSiteName = Yii::app()->getConfig('sitename');
|
||||
$sSiteAdminBounce = Yii::app()->getConfig('siteadminbounce');
|
||||
|
||||
$username = sprintf($clang->gT('Username: %s'), $aFields[0]['users_name']);
|
||||
$email = sprintf($clang->gT('Email: %s'), $sEmailAddr);
|
||||
$password = sprintf($clang->gT('New password: %s'), $sNewPass);
|
||||
|
||||
$body = array();
|
||||
$body[] = sprintf($clang->gT('Your user data for accessing %s'), Yii::app()->getConfig('sitename'));
|
||||
$body[] = $username;
|
||||
$body[] = $password;
|
||||
$body = implode("\n", $body);
|
||||
|
||||
if (SendEmailMessage($body, $sSubject, $sTo, $sFrom, $sSiteName, false, $sSiteAdminBounce))
|
||||
{
|
||||
User::model()->updatePassword($aFields[0]['uid'], $sNewPass);
|
||||
$sMessage = $username . '<br />' . $email . '<br /><br />' . $clang->gT('An email with your login data was sent to you.');
|
||||
}
|
||||
else
|
||||
{
|
||||
$sTmp = str_replace("{NAME}", '<strong>' . $aFields[0]['users_name'] . '</strong>', $clang->gT("Email to {NAME} ({EMAIL}) failed."));
|
||||
$sMessage = str_replace("{EMAIL}", $sEmailAddr, $sTmp) . '<br />';
|
||||
}
|
||||
|
||||
return $sMessage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get's the summary
|
||||
* @param string $sMethod login|logout
|
||||
* @param string $sSummary Default summary
|
||||
* @return string Summary
|
||||
*/
|
||||
private function _getSummary($sMethod = 'login', $sSummary = '')
|
||||
{
|
||||
if (!empty($sSummary))
|
||||
{
|
||||
return $sSummary;
|
||||
}
|
||||
|
||||
$clang = $this->getController()->lang;
|
||||
|
||||
switch ($sMethod) {
|
||||
case 'logout' :
|
||||
$sSummary = $clang->gT('Please log in first.');
|
||||
break;
|
||||
|
||||
case 'login' :
|
||||
default :
|
||||
$sSummary = '<br />' . sprintf($clang->gT('Welcome %s!'), Yii::app()->session['full_name']) . '<br /> ';
|
||||
if (!empty(Yii::app()->session['redirect_after_login']) && strpos(Yii::app()->session['redirect_after_login'], 'logout') === FALSE)
|
||||
{
|
||||
Yii::app()->session['metaHeader'] = '<meta http-equiv="refresh"'
|
||||
. ' content="1;URL=' . Yii::app()->session['redirect_after_login'] . '" />';
|
||||
$sSummary = '<p><font size="1"><i>' . $clang->gT('Reloading screen. Please wait.') . '</i></font>';
|
||||
unset(Yii::app()->session['redirect_after_login']);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
return $sSummary;
|
||||
}
|
||||
|
||||
/**
|
||||
* Redirects a logged in user to the administration page
|
||||
*/
|
||||
private function _redirectIfLoggedIn()
|
||||
{
|
||||
if (!Yii::app()->user->getIsGuest())
|
||||
{
|
||||
$this->getController()->redirect(array('/admin'));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a user can log in
|
||||
* @return bool|array
|
||||
*/
|
||||
private function _userCanLogin()
|
||||
{
|
||||
$failed_login_attempts = FailedLoginAttempt::model();
|
||||
$failed_login_attempts->cleanOutOldAttempts();
|
||||
|
||||
if ($failed_login_attempts->isLockedOut())
|
||||
{
|
||||
return $this->_getAuthenticationFailedErrorMessage();
|
||||
}
|
||||
else
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Redirect after login
|
||||
*/
|
||||
private function _doRedirect()
|
||||
{
|
||||
$returnUrl = App()->user->getReturnUrl(array('/admin'));
|
||||
$this->getController()->redirect($returnUrl);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders template(s) wrapped in header and footer
|
||||
*
|
||||
* @param string $sAction Current action, the folder to fetch views from
|
||||
* @param string|array $aViewUrls View url(s)
|
||||
* @param array $aData Data to be passed on. Optional.
|
||||
*/
|
||||
protected function _renderWrappedTemplate($sAction = 'authentication', $aViewUrls = array(), $aData = array())
|
||||
{
|
||||
$aData['display']['menu_bars'] = false;
|
||||
parent::_renderWrappedTemplate($sAction, $aViewUrls, $aData);
|
||||
}
|
||||
|
||||
}
|
835
sources/application/controllers/admin/checkintegrity.php
Normal file
835
sources/application/controllers/admin/checkintegrity.php
Normal file
|
@ -0,0 +1,835 @@
|
|||
<?php
|
||||
/*
|
||||
* 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.
|
||||
*
|
||||
*/
|
||||
/**
|
||||
* CheckIntegrity Controller
|
||||
*
|
||||
* This controller performs database repair functions.
|
||||
*
|
||||
* @package LimeSurvey
|
||||
* @subpackage Backend
|
||||
*/
|
||||
class CheckIntegrity extends Survey_Common_Action
|
||||
{
|
||||
|
||||
public function __construct($controller, $id)
|
||||
{
|
||||
parent::__construct($controller, $id);
|
||||
|
||||
if (!Permission::model()->hasGlobalPermission('settings','read')){
|
||||
$clang = $this->getController()->lang;
|
||||
Yii::app()->session['flashmessage'] = $clang->gT("You do not have sufficient rights to access this page.");
|
||||
$this->getController()->redirect($this->getController()->createUrl("/admin/"));
|
||||
}
|
||||
|
||||
Yii::app()->loadHelper('database');
|
||||
Yii::app()->loadHelper('surveytranslator');
|
||||
}
|
||||
|
||||
public function index()
|
||||
{
|
||||
$aData = $this->_checkintegrity();
|
||||
$this->_renderWrappedTemplate('checkintegrity', 'check_view', $aData);
|
||||
}
|
||||
|
||||
public function fixredundancy()
|
||||
{
|
||||
$clang = Yii::app()->lang;
|
||||
$oldsmultidelete=Yii::app()->request->getPost('oldsmultidelete', array());
|
||||
$aData['messages'] = array();
|
||||
if ( Permission::model()->hasGlobalPermission('settings','update') && Yii::app()->request->getPost('ok') == 'Y') {
|
||||
$aDelete = $this->_checkintegrity();
|
||||
if (isset($aDelete['redundanttokentables'])) {
|
||||
foreach ($aDelete['redundanttokentables'] as $aTokenTable)
|
||||
{
|
||||
if(in_array($aTokenTable['table'],$oldsmultidelete))
|
||||
{
|
||||
Yii::app()->db->createCommand()->dropTable($aTokenTable['table']);
|
||||
$aData['messages'][] = sprintf($clang->gT('Deleting token table: %s'),$aTokenTable['table']);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (isset($aDelete['redundantsurveytables'])) {
|
||||
foreach ($aDelete['redundantsurveytables'] as $aSurveyTable)
|
||||
{
|
||||
if(in_array($aSurveyTable['table'],$oldsmultidelete))
|
||||
{
|
||||
Yii::app()->db->createCommand()->dropTable($aSurveyTable['table']);
|
||||
$aData['messages'][] = sprintf($clang->gT('Deleting survey table: %s'),$aSurveyTable['table']);
|
||||
}
|
||||
}
|
||||
}
|
||||
if(count($aData['messages'])==0)
|
||||
{
|
||||
$aData['messages'][] = $clang->gT('No old survey or token table selected.');
|
||||
}
|
||||
$this->_renderWrappedTemplate('checkintegrity', 'fix_view', $aData);
|
||||
}
|
||||
}
|
||||
|
||||
public function fixintegrity()
|
||||
{
|
||||
$aData = array();
|
||||
$clang = Yii::app()->lang;
|
||||
if (Permission::model()->hasGlobalPermission('settings','update') && Yii::app()->request->getPost('ok') == 'Y') {
|
||||
$aDelete = $this->_checkintegrity();
|
||||
|
||||
// TMSW Condition->Relevance: Update this to process relevance instead
|
||||
if (isset($aDelete['conditions'])) {
|
||||
$aData = $this->_deleteConditions($aDelete['conditions'], $aData, $clang);
|
||||
}
|
||||
|
||||
if (isset($aDelete['questionattributes'])) {
|
||||
$aData = $this->_deleteQuestionAttributes($aDelete['questionattributes'], $aData, $clang);
|
||||
}
|
||||
|
||||
if ($aDelete['defaultvalues']) {
|
||||
$aData = $this->_deleteDefaultValues($aData, $clang);
|
||||
}
|
||||
|
||||
if ($aDelete['quotas']) {
|
||||
$aData = $this->_deleteQuotas($aData, $clang);
|
||||
}
|
||||
|
||||
if ($aDelete['quotals']) {
|
||||
$this->_deleteQuotaLanguageSettings();
|
||||
}
|
||||
|
||||
if ($aDelete['quotamembers']) {
|
||||
$aData = $this->_deleteQuotaMembers($aData, $clang);
|
||||
}
|
||||
|
||||
if (isset($aDelete['assessments'])) {
|
||||
$aData = $this->_deleteAssessments($aDelete['assessments'], $aData, $clang);
|
||||
}
|
||||
|
||||
if (isset($aDelete['answers'])) {
|
||||
$aData = $this->_deleteAnswers($aDelete['answers'], $aData, $clang);
|
||||
}
|
||||
|
||||
if (isset($aDelete['surveys'])) {
|
||||
$aData = $this->_deleteSurveys($aDelete['surveys'], $aData, $clang);
|
||||
}
|
||||
|
||||
if (isset($aDelete['surveylanguagesettings'])) {
|
||||
$aData = $this->_deleteSurveyLanguageSettings($aDelete['surveylanguagesettings'], $aData, $clang);
|
||||
}
|
||||
|
||||
if (isset($aDelete['questions'])) {
|
||||
$aData = $this->_deleteQuestions($aDelete['questions'], $aData, $clang);
|
||||
}
|
||||
|
||||
|
||||
if (isset($aDelete['groups'])) {
|
||||
$aData = $this->_deleteGroups($aDelete['groups'], $aData, $clang);
|
||||
}
|
||||
|
||||
if (isset($aDelete['orphansurveytables'])) {
|
||||
$aData = $this->_dropOrphanSurveyTables($aDelete['orphansurveytables'], $aData, $clang);
|
||||
}
|
||||
|
||||
if (isset($aDelete['orphantokentables'])) {
|
||||
$aData = $this->_deleteOrphanTokenTables($aDelete['orphantokentables'], $aData, $clang);
|
||||
}
|
||||
|
||||
$this->_renderWrappedTemplate('checkintegrity', 'fix_view', $aData);
|
||||
}
|
||||
}
|
||||
|
||||
private function _deleteOrphanTokenTables(array $tokenTables, array $aData, Limesurvey_lang $clang)
|
||||
{
|
||||
foreach ($tokenTables as $aTokenTable)
|
||||
{
|
||||
Yii::app()->db->createCommand()->dropTable($aTokenTable);
|
||||
$aData['messages'][] = $clang->gT('Deleting orphan token table:') . ' ' . $aTokenTable;
|
||||
}
|
||||
return $aData;
|
||||
}
|
||||
|
||||
private function _dropOrphanSurveyTables(array $surveyTables, array $aData, Limesurvey_lang $clang)
|
||||
{
|
||||
foreach ($surveyTables as $aSurveyTable)
|
||||
{
|
||||
Yii::app()->db->createCommand()->dropTable($aSurveyTable);
|
||||
$aData['messages'][] = $clang->gT('Deleting orphan survey table:') . ' ' . $aSurveyTable;
|
||||
}
|
||||
return $aData;
|
||||
}
|
||||
|
||||
private function _deleteGroups(array $groups, array $aData, Limesurvey_lang $clang)
|
||||
{
|
||||
foreach ($groups as $group) $gids[] = $group['gid'];
|
||||
|
||||
$criteria = new CDbCriteria;
|
||||
$criteria->addInCondition('gid', $gids);
|
||||
QuestionGroup::model()->deleteAll($criteria);
|
||||
if (QuestionGroup::model()->hasErrors()) safeDie(QuestionGroup::model()->getError());
|
||||
$aData['messages'][] = sprintf($clang->gT('Deleting groups: %u groups deleted'), count($groups));
|
||||
return $aData;
|
||||
}
|
||||
|
||||
private function _deleteQuestions(array $questions, array $aData, Limesurvey_lang $clang)
|
||||
{
|
||||
foreach ($questions as $question) $qids[] = $question['qid'];
|
||||
|
||||
$criteria = new CDbCriteria;
|
||||
$criteria->addInCondition('qid', $qids);
|
||||
Question::model()->deleteAll($criteria);
|
||||
if (Question::model()->hasErrors()) safeDie(Question::model()->getError());
|
||||
$aData['messages'][] = sprintf($clang->gT('Deleting questions: %u questions deleted'), count($questions));
|
||||
return array($criteria, $aData);
|
||||
}
|
||||
|
||||
private function _deleteSurveyLanguageSettings(array $surveyLanguageSettings, array $aData, Limesurvey_lang $clang)
|
||||
{
|
||||
foreach ($surveyLanguageSettings as $surveylanguagesetting) $surveyls_survey_ids[] = $surveylanguagesetting['slid'];
|
||||
|
||||
$criteria = new CDbCriteria;
|
||||
$criteria->compare('surveyls_survey_id', $surveyls_survey_ids);
|
||||
SurveyLanguageSetting::model()->deleteAll($criteria);
|
||||
if (SurveyLanguageSetting::model()->hasErrors()) safeDie(SurveyLanguageSetting::model()->getError());
|
||||
$aData['messages'][] = sprintf($clang->gT('Deleting survey languagesettings: %u survey languagesettings deleted'), count($surveyLanguageSettings));
|
||||
return array($criteria, $aData);
|
||||
}
|
||||
|
||||
private function _deleteSurveys(array $surveys, array $aData, Limesurvey_lang $clang)
|
||||
{
|
||||
foreach ($surveys as $survey)
|
||||
{
|
||||
Survey::model()->deleteByPk($survey['sid']);
|
||||
}
|
||||
|
||||
if (Survey::model()->hasErrors()) safeDie(Survey::model()->getError());
|
||||
$aData['messages'][] = sprintf($clang->gT('Deleting surveys: %u surveys deleted'), count($surveys));
|
||||
return $aData;
|
||||
}
|
||||
|
||||
private function _deleteAnswers(array $answers, array $aData, Limesurvey_lang $clang)
|
||||
{
|
||||
foreach ($answers as $aAnswer) {
|
||||
Answer::model()->deleteAll('qid=:qid AND code=:code',array(':qid'=>$aAnswer['qid'],':code'=>$aAnswer['code']));
|
||||
if (Answer::model()->hasErrors()) safeDie(Answer::model()->getError());
|
||||
}
|
||||
$aData['messages'][] = sprintf($clang->gT('Deleting answers: %u answers deleted'), count($answers));
|
||||
return $aData;
|
||||
}
|
||||
|
||||
private function _deleteAssessments(array $assessments, array $aData, Limesurvey_lang $clang)
|
||||
{
|
||||
foreach ($assessments as $assessment) $assessments_ids[] = $assessment['id'];
|
||||
|
||||
$assessments_ids = array();
|
||||
Assessment::model()->deleteByPk('id',$assessments_ids);
|
||||
if (Assessment::model()->hasErrors()) safeDie(Assessment::model()->getError());
|
||||
$aData['messages'][] = sprintf($clang->gT('Deleting assessments: %u assessment entries deleted'), count($assessments));
|
||||
return $aData;
|
||||
}
|
||||
|
||||
private function _deleteQuotaMembers(array $aData, Limesurvey_lang $clang)
|
||||
{
|
||||
$quota_ids = array();
|
||||
$quotas = Quota::model()->findAll();
|
||||
foreach ($quotas as $quota) $quota_ids[] = $quota['id'];
|
||||
$criteria = new CDbCriteria;
|
||||
$criteria->addNotInCondition('quota_id', $quota_ids);
|
||||
|
||||
$qids = array();
|
||||
$questions = Question::model()->findAll();
|
||||
foreach ($questions as $question) $qids[] = $question['qid'];
|
||||
$criteria->addNotInCondition('qid', $qids, 'OR');
|
||||
|
||||
$sids = array();
|
||||
$surveys = Survey::model()->findAll();
|
||||
foreach ($surveys as $survey) $sids[] = $survey['sid'];
|
||||
$criteria->addNotInCondition('sid', $sids, 'OR');
|
||||
|
||||
QuotaMember::model()->deleteAll($criteria);
|
||||
if (QuotaLanguageSetting::model()->hasErrors()) safeDie(QuotaLanguageSetting::model()->getError());
|
||||
$aData['messages'][] = $clang->gT('Deleting orphaned quota members.');
|
||||
return $aData;
|
||||
}
|
||||
|
||||
private function _deleteQuotaLanguageSettings()
|
||||
{
|
||||
$quotas = Quota::model()->findAll();
|
||||
foreach ($quotas as $quota) $quota_ids[] = $quota['id'];
|
||||
$criteria = new CDbCriteria;
|
||||
$criteria->addNotInCondition('quotals_quota_id', $quota_ids);
|
||||
|
||||
QuotaLanguageSetting::model()->deleteAll($criteria);
|
||||
if (QuotaLanguageSetting::model()->hasErrors()) safeDie(QuotaLanguageSetting::model()->getError());
|
||||
}
|
||||
|
||||
private function _deleteQuotas(array $aData, Limesurvey_lang $clang)
|
||||
{
|
||||
$sids = array();
|
||||
$surveys = Survey::model()->findAll();
|
||||
foreach ($surveys as $survey) $sids[] = $survey['sid'];
|
||||
$criteria = new CDbCriteria;
|
||||
$criteria->addNotInCondition('sid', $sids);
|
||||
|
||||
Quota::model()->deleteAll($criteria);
|
||||
if (Quota::model()->hasErrors()) safeDie(Quota::model()->getError());
|
||||
$aData['messages'][] = $clang->gT('Deleting orphaned quotas.');
|
||||
return $aData;
|
||||
}
|
||||
|
||||
private function _deleteDefaultValues(array $aData, Limesurvey_lang $clang)
|
||||
{
|
||||
$qids = array();
|
||||
$questions = Question::model()->findAll();
|
||||
foreach ($questions as $question) $qids[] = $question['qid'];
|
||||
$criteria = new CDbCriteria;
|
||||
$criteria->addNotInCondition('qid', $qids);
|
||||
|
||||
DefaultValue::model()->deleteAll($criteria);
|
||||
if (DefaultValue::model()->hasErrors()) safeDie(DefaultValue::model()->getError());
|
||||
$aData['messages'][] = $clang->gT('Deleting orphaned default values.');
|
||||
return $aData;
|
||||
}
|
||||
|
||||
private function _deleteQuestionAttributes(array $questionAttributes, array $aData, Limesurvey_lang $clang)
|
||||
{
|
||||
$qids = array();
|
||||
foreach ($questionAttributes as $questionattribute) $qids[] = $questionattribute['qid'];
|
||||
$criteria = new CDbCriteria;
|
||||
$criteria->addInCondition('qid', $qids);
|
||||
|
||||
QuestionAttribute::model()->deleteAll($criteria);
|
||||
if (QuestionAttribute::model()->hasErrors()) safeDie(QuestionAttribute::model()->getError());
|
||||
$aData['messages'][] = sprintf($clang->gT('Deleting question attributes: %u attributes deleted'), count($questionAttributes));
|
||||
return $aData;
|
||||
}
|
||||
|
||||
private function _deleteConditions(array $conditions, array $aData, Limesurvey_lang $clang)
|
||||
{
|
||||
$cids = array();
|
||||
foreach ($conditions as $condition) $cids[] = $condition['cid'];
|
||||
|
||||
Condition::model()->deleteByPk($cids);
|
||||
if (Condition::model()->hasErrors()) safeDie(Condition::model()->getError());
|
||||
$aData['messages'][] = sprintf($clang->gT('Deleting conditions: %u conditions deleted'), count($condition));
|
||||
return $aData;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* This function checks the LimeSurvey database for logical consistency and returns an according array
|
||||
* containing all issues in the particular tables.
|
||||
* @returns Array with all found issues.
|
||||
*/
|
||||
protected function _checkintegrity()
|
||||
{
|
||||
$clang = Yii::app()->lang;
|
||||
|
||||
/*** Plainly delete survey permissions if the survey or user does not exist ***/
|
||||
$users = User::model()->findAll();
|
||||
$uids = array();
|
||||
foreach ($users as $user) $uids[] = $user['uid'];
|
||||
$criteria = new CDbCriteria;
|
||||
$criteria->addNotInCondition('uid', $uids, 'OR');
|
||||
|
||||
$surveys = Survey::model()->findAll();
|
||||
$sids = array();
|
||||
foreach ($surveys as $survey) $sids[] = $survey['sid'];
|
||||
$criteria->addNotInCondition('entity_id', $sids, 'OR');
|
||||
$criteria->addCondition("entity='survey'");
|
||||
|
||||
Permission::model()->deleteAll($criteria);
|
||||
|
||||
|
||||
// Deactivate surveys that have a missing response table
|
||||
foreach ($surveys as $survey)
|
||||
{
|
||||
if ($survey['active']=='Y' && !tableExists("{{survey_{$survey['sid']}}}"))
|
||||
{
|
||||
Survey::model()->updateByPk($survey['sid'],array('active'=>'N'));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Fix subquestions
|
||||
fixSubquestions();
|
||||
|
||||
/*** Check for active survey tables with missing survey entry and rename them ***/
|
||||
$sDBPrefix = Yii::app()->db->tablePrefix;
|
||||
$sQuery = dbSelectTablesLike('{{survey}}\_%');
|
||||
$aResult = dbQueryOrFalse($sQuery) or safeDie("Couldn't get list of conditions from database<br />{$sQuery}<br />");
|
||||
foreach ($aResult->readAll() as $aRow)
|
||||
{
|
||||
$sTableName = substr(reset($aRow), strlen($sDBPrefix));
|
||||
if ($sTableName == 'survey_links' || $sTableName == 'survey_url_parameters') continue;
|
||||
$aTableName=explode('_',$sTableName);
|
||||
if (isset($aTableName[1]) && ctype_digit($aTableName[1]))
|
||||
{
|
||||
$iSurveyID = $aTableName[1];
|
||||
if (!in_array($iSurveyID, $sids)) {
|
||||
$sDate = date('YmdHis') . rand(1, 1000);
|
||||
$sOldTable = "survey_{$iSurveyID}";
|
||||
$sNewTable = "old_survey_{$iSurveyID}_{$sDate}";
|
||||
try {
|
||||
$deactivateresult = Yii::app()->db->createCommand()->renameTable("{{{$sOldTable}}}", "{{{$sNewTable}}}");
|
||||
} catch (CDbException $e) {
|
||||
die ('Couldn\'t make backup of the survey table. Please try again. The database reported the following error:<br />' . htmlspecialchars($e) . '<br />');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*** Check for active token tables with missing survey entry ***/
|
||||
$aResult = dbQueryOrFalse(dbSelectTablesLike('{{tokens}}\_%')) or safeDie("Couldn't get list of conditions from database<br />{$sQuery}<br />");
|
||||
foreach ($aResult->readAll() as $aRow)
|
||||
{
|
||||
$sTableName = substr(reset($aRow), strlen($sDBPrefix));
|
||||
$iSurveyID = substr($sTableName, strpos($sTableName, '_') + 1);
|
||||
if (!in_array($iSurveyID, $sids)) {
|
||||
$sDate = date('YmdHis') . rand(1, 1000);
|
||||
$sOldTable = "tokens_{$iSurveyID}";
|
||||
$sNewTable = "old_tokens_{$iSurveyID}_{$sDate}";
|
||||
try {
|
||||
$deactivateresult = Yii::app()->db->createCommand()->renameTable("{{{$sOldTable}}}", "{{{$sNewTable}}}");
|
||||
} catch (CDbException $e) {
|
||||
die ('Couldn\'t make backup of the survey table. Please try again. The database reported the following error:<br />' . htmlspecialchars($e) . '<br />');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**********************************************************************/
|
||||
/* Check conditions */
|
||||
/**********************************************************************/
|
||||
// TMSW Condition->Relevance: Replace this with analysis of relevance
|
||||
$conditions = Condition::model()->findAll();
|
||||
if (Condition::model()->hasErrors()) safeDie(Condition::model()->getError());
|
||||
$okQuestion = array();
|
||||
foreach ($conditions as $condition)
|
||||
{
|
||||
if ($condition['cqid'] != 0) { // skip case with cqid=0 for codnitions on {TOKEN:EMAIL} for instance
|
||||
if (!array_key_exists($condition['cqid'], $okQuestion)) {
|
||||
$iRowCount = Question::model()->countByAttributes(array('qid' => $condition['cqid']));
|
||||
if (Question::model()->hasErrors()) safeDie(Question::model()->getError());
|
||||
if (!$iRowCount) {
|
||||
$aDelete['conditions'][] = array('cid' => $condition['cid'], 'reason' => $clang->gT('No matching CQID'));
|
||||
} else {
|
||||
$okQuestion[$condition['cqid']] = $condition['cqid'];
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($condition['cfieldname']) //Only do this if there actually is a 'cfieldname'
|
||||
{
|
||||
if (preg_match('/^\+{0,1}[0-9]+X[0-9]+X*$/', $condition['cfieldname'])) { // only if cfieldname isn't Tag such as {TOKEN:EMAIL} or any other token
|
||||
list ($surveyid, $gid, $rest) = explode('X', $condition['cfieldname']);
|
||||
$iRowCount = count(QuestionGroup::model()->findAllByAttributes(array('gid'=>$gid)));
|
||||
if (QuestionGroup::model()->hasErrors()) safeDie(QuestionGroup::model()->getError());
|
||||
if (!$iRowCount) $aDelete['conditions'][] = array('cid' => $condition['cid'], 'reason' => $clang->gT('No matching CFIELDNAME group!') . " ($gid) ({$condition['cfieldname']})");
|
||||
}
|
||||
}
|
||||
elseif (!$condition['cfieldname'])
|
||||
{
|
||||
$aDelete['conditions'][] = array('cid' => $condition['cid'], 'reason' => $clang->gT('No CFIELDNAME field set!') . " ({$condition['cfieldname']})");
|
||||
}
|
||||
}
|
||||
|
||||
/**********************************************************************/
|
||||
/* Check question attributes */
|
||||
/**********************************************************************/
|
||||
$question_attributes = QuestionAttribute::model()->findAllBySql('select qid from {{question_attributes}} where qid not in (select qid from {{questions}})');
|
||||
if (QuestionAttribute::model()->hasErrors()) safeDie(QuestionAttribute::model()->getError());
|
||||
foreach ($question_attributes as $question_attribute)
|
||||
{
|
||||
$aDelete['questionattributes'][] = array('qid' => $question_attribute['qid']);
|
||||
} // foreach
|
||||
|
||||
|
||||
/**********************************************************************/
|
||||
/* Check default values */
|
||||
/**********************************************************************/
|
||||
$questions = Question::model()->findAll();
|
||||
if (Question::model()->hasErrors()) safeDie(Question::model()->getError());
|
||||
$qids = array();
|
||||
foreach ($questions as $question) $qids[] = $question['qid'];
|
||||
$criteria = new CDbCriteria;
|
||||
$criteria->addNotInCondition('qid', $qids);
|
||||
|
||||
$aDelete['defaultvalues'] = count(DefaultValue::model()->findAll($criteria));
|
||||
if (DefaultValue::model()->hasErrors()) safeDie(DefaultValue::model()->getError());
|
||||
|
||||
/**********************************************************************/
|
||||
/* Check quotas */
|
||||
/**********************************************************************/
|
||||
$surveys = Survey::model()->findAll();
|
||||
if (Survey::model()->hasErrors()) safeDie(Survey::model()->getError());
|
||||
$sids = array();
|
||||
foreach ($surveys as $survey) $sids[] = $survey['sid'];
|
||||
$criteria = new CDbCriteria;
|
||||
$criteria->addNotInCondition('sid', $sids);
|
||||
|
||||
$aDelete['quotas'] = count(Quota::model()->findAll($criteria));
|
||||
if (Quota::model()->hasErrors()) safeDie(Quota::model()->getError());
|
||||
|
||||
/**********************************************************************/
|
||||
/* Check quota languagesettings */
|
||||
/**********************************************************************/
|
||||
$quotas = Quota::model()->findAll();
|
||||
if (Quota::model()->hasErrors()) safeDie(Quota::model()->getError());
|
||||
$ids = array();
|
||||
foreach ($quotas as $quota) $ids[] = $quota['id'];
|
||||
$criteria = new CDbCriteria;
|
||||
$criteria->addNotInCondition('quotals_quota_id', $ids);
|
||||
|
||||
$aDelete['quotals'] = count(QuotaLanguageSetting::model()->findAll($criteria));
|
||||
if (QuotaLanguageSetting::model()->hasErrors()) safeDie(QuotaLanguageSetting::model()->getError());
|
||||
|
||||
/**********************************************************************/
|
||||
/* Check quota members */
|
||||
/**********************************************************************/
|
||||
$quotas = Quota::model()->findAll();
|
||||
$quota_ids = array();
|
||||
foreach ($quotas as $quota) $quota_ids[] = $quota['id'];
|
||||
$criteria = new CDbCriteria;
|
||||
$criteria->addNotInCondition('quota_id', $quota_ids);
|
||||
|
||||
$questions = Question::model()->findAll();
|
||||
$qids = array();
|
||||
foreach ($questions as $question) $qids[] = $question['qid'];
|
||||
$criteria->addNotInCondition('qid', $qids, 'OR');
|
||||
|
||||
$surveys = Survey::model()->findAll();
|
||||
$sids = array();
|
||||
foreach ($surveys as $survey) $sids[] = $survey['sid'];
|
||||
$criteria->addNotInCondition('sid', $sids, 'OR');
|
||||
|
||||
$aDelete['quotamembers'] = count(QuotaMember::model()->findAll($criteria));
|
||||
if (QuotaMember::model()->hasErrors()) safeDie(QuotaMember::model()->getError());
|
||||
|
||||
/**********************************************************************/
|
||||
/* Check assessments */
|
||||
/**********************************************************************/
|
||||
$criteria = new CDbCriteria;
|
||||
$criteria->compare('scope', 'T');
|
||||
$assessments = Assessment::model()->findAll($criteria);
|
||||
if (Assessment::model()->hasErrors()) safeDie(Assessment::model()->getError());
|
||||
foreach ($assessments as $assessment)
|
||||
{
|
||||
$iAssessmentCount = count(Survey::model()->findAllByPk($assessment['sid']));
|
||||
if (Survey::model()->hasErrors()) safeDie(Survey::model()->getError());
|
||||
if (!$iAssessmentCount) {
|
||||
$aDelete['assessments'][] = array('id' => $assessment['id'], 'assessment' => $assessment['name'], 'reason' => $clang->gT('No matching survey'));
|
||||
}
|
||||
}
|
||||
|
||||
$criteria = new CDbCriteria;
|
||||
$criteria->compare('scope', 'G');
|
||||
$assessments = Assessment::model()->findAll($criteria);
|
||||
if (Assessment::model()->hasErrors()) safeDie(Assessment::model()->getError());
|
||||
foreach ($assessments as $assessment)
|
||||
{
|
||||
$iAssessmentCount = count(QuestionGroup::model()->findAllByPk(array('gid'=>$assessment['gid'], 'language'=>$assessment['language'])));
|
||||
if (QuestionGroup::model()->hasErrors()) safeDie(QuestionGroup::model()->getError());
|
||||
if (!$iAssessmentCount) {
|
||||
$aDelete['assessments'][] = array('id' => $assessment['id'], 'assessment' => $assessment['name'], 'reason' => $clang->gT('No matching group'));
|
||||
}
|
||||
}
|
||||
/**********************************************************************/
|
||||
/* Check answers */
|
||||
/**********************************************************************/
|
||||
$answers = Answer::model()->findAll();
|
||||
if (Answer::model()->hasErrors()) safeDie(Answer::model()->getError());
|
||||
$okQuestion = array();
|
||||
foreach ($answers as $answer)
|
||||
{
|
||||
if (!array_key_exists($answer['qid'], $okQuestion)) {
|
||||
$iAnswerCount = Question::model()->countByAttributes(array('qid' => $answer['qid']));
|
||||
if (Question::model()->hasErrors()) safeDie(Question::model()->getError());
|
||||
if (!$iAnswerCount) {
|
||||
$aDelete['answers'][] = array('qid' => $answer['qid'], 'code' => $answer['code'], 'reason' => $clang->gT('No matching question'));
|
||||
} else {
|
||||
$okQuestion[$answer['qid']] = $answer['qid'];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/***************************************************************************/
|
||||
/* Check survey languagesettings and restore them if they don't exist */
|
||||
/***************************************************************************/
|
||||
|
||||
$surveys = Survey::model()->findAll();
|
||||
foreach ($surveys as $survey)
|
||||
{
|
||||
$aLanguages=$survey->additionalLanguages;
|
||||
$aLanguages[]=$survey->language;
|
||||
foreach ($aLanguages as $langname)
|
||||
{
|
||||
if ($langname)
|
||||
{
|
||||
$oLanguageSettings = SurveyLanguageSetting::model()->find('surveyls_survey_id=:surveyid AND surveyls_language=:langname', array(':surveyid'=>$survey->sid,':langname'=>$langname));
|
||||
if(!$oLanguageSettings)
|
||||
{
|
||||
$oLanguageSettings= new SurveyLanguageSetting;
|
||||
$languagedetails=getLanguageDetails($langname);
|
||||
$insertdata = array(
|
||||
'surveyls_survey_id' => $survey->sid,
|
||||
'surveyls_language' => $langname,
|
||||
'surveyls_title' => '',
|
||||
'surveyls_dateformat' => $languagedetails['dateformat']
|
||||
);
|
||||
foreach ($insertdata as $k => $v)
|
||||
$oLanguageSettings->$k = $v;
|
||||
$usresult=$oLanguageSettings->save();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**********************************************************************/
|
||||
/* Check survey language settings */
|
||||
/**********************************************************************/
|
||||
$surveys = Survey::model()->findAll();
|
||||
if (Survey::model()->hasErrors()) safeDie(Survey::model()->getError());
|
||||
$sids = array();
|
||||
foreach ($surveys as $survey) $sids[] = $survey['sid'];
|
||||
$criteria = new CDbCriteria;
|
||||
$criteria->addNotInCondition('surveyls_survey_id', $sids);
|
||||
$surveys_languagesettings = SurveyLanguageSetting::model()->findAll($criteria);
|
||||
if (SurveyLanguageSetting::model()->hasErrors()) safeDie(SurveyLanguageSetting::model()->getError());
|
||||
|
||||
foreach ($surveys_languagesettings as $surveys_languagesetting)
|
||||
{
|
||||
$aDelete['surveylanguagesettings'][] = array('slid' => $surveys_languagesetting['surveyls_survey_id'], 'reason' => $clang->gT('The related survey is missing.'));
|
||||
}
|
||||
|
||||
/**********************************************************************/
|
||||
/* Check questions */
|
||||
/**********************************************************************/
|
||||
$questions = Question::model()->findAll();
|
||||
if (Question::model()->hasErrors()) safeDie(Question::model()->getError());
|
||||
$groups = QuestionGroup::model()->findAll();
|
||||
if (QuestionGroup::model()->hasErrors()) safeDie(QuestionGroup::model()->getError());
|
||||
$gids = array();
|
||||
foreach ($groups as $group) $gids[] = $group['gid'];
|
||||
|
||||
foreach ($questions as $question)
|
||||
{
|
||||
//Make sure the group exists
|
||||
if (!in_array($question['gid'], $gids)) {
|
||||
$aDelete['questions'][] = array('qid' => $question['qid'], 'reason' => $clang->gT('No matching group') . " ({$question['gid']})");
|
||||
}
|
||||
//Make sure survey exists
|
||||
if (!in_array($question['sid'], $sids)) {
|
||||
$aDelete['questions'][] = array('qid' => $question['qid'], 'reason' => $clang->gT('There is no matching survey.') . " ({$question['sid']})");
|
||||
}
|
||||
}
|
||||
|
||||
/**********************************************************************/
|
||||
/* Check groups */
|
||||
/**********************************************************************/
|
||||
$surveys = Survey::model()->findAll();
|
||||
if (Survey::model()->hasErrors()) safeDie(Survey::model()->getError());
|
||||
$sids = array();
|
||||
foreach ($surveys as $survey) $sids[] = $survey['sid'];
|
||||
$criteria = new CDbCriteria;
|
||||
$criteria->addNotInCondition('sid', $sids);
|
||||
$groups = QuestionGroup::model()->findAll($criteria);
|
||||
foreach ($groups as $group)
|
||||
{
|
||||
$aDelete['groups'][] = array('gid' => $group['gid'], 'reason' => $clang->gT('There is no matching survey.') . ' SID:' . $group['sid']);
|
||||
}
|
||||
|
||||
/**********************************************************************/
|
||||
/* Check old survey tables */
|
||||
/**********************************************************************/
|
||||
//1: Get list of 'old_survey' tables and extract the survey id
|
||||
//2: Check if that survey id still exists
|
||||
//3: If it doesn't offer it for deletion
|
||||
$sQuery = dbSelectTablesLike('{{old_survey}}%');
|
||||
$aResult = dbQueryOrFalse($sQuery) or safeDie("Couldn't get list of conditions from database<br />$sQuery<br />");
|
||||
$aTables = $aResult->readAll();
|
||||
|
||||
$aOldSIDs = array();
|
||||
$aSIDs = array();
|
||||
foreach ($aTables as $sTable)
|
||||
{
|
||||
$sTable = reset($sTable);
|
||||
list($sOldText, $SurveyText, $iSurveyID, $sDate) = explode('_', substr($sTable, strlen($sDBPrefix)));
|
||||
$aOldSIDs[] = $iSurveyID;
|
||||
$aFullOldSIDs[$iSurveyID][] = $sTable;
|
||||
}
|
||||
$aOldSIDs = array_unique($aOldSIDs);
|
||||
//$sQuery = 'SELECT sid FROM {{surveys}} ORDER BY sid';
|
||||
//$oResult = dbExecuteAssoc($sQuery) or safeDie('Couldn\'t get unique survey ids');
|
||||
$surveys = Survey::model()->findAll();
|
||||
if (Survey::model()->hasErrors()) safeDie(Survey::model()->getError());
|
||||
$aSIDs = array();
|
||||
foreach ($surveys as $survey)
|
||||
{
|
||||
$aSIDs[] = $survey['sid'];
|
||||
}
|
||||
foreach ($aOldSIDs as $iOldSID)
|
||||
{
|
||||
if (!in_array($iOldSID, $aSIDs)) {
|
||||
foreach ($aFullOldSIDs[$iOldSID] as $sTableName)
|
||||
{
|
||||
$aDelete['orphansurveytables'][] = $sTableName;
|
||||
}
|
||||
} else {
|
||||
foreach ($aFullOldSIDs[$iOldSID] as $sTableName)
|
||||
{
|
||||
$aTableParts = explode('_', substr($sTableName, strlen($sDBPrefix)));
|
||||
if (count($aTableParts) == 4) {
|
||||
$sOldText = $aTableParts[0];
|
||||
$SurveyText = $aTableParts[1];
|
||||
$iSurveyID = $aTableParts[2];
|
||||
$sDateTime = $aTableParts[3];
|
||||
$sType = $clang->gT('responses');
|
||||
} elseif (count($aTableParts) == 5) {
|
||||
//This is a timings table (
|
||||
$sOldText = $aTableParts[0];
|
||||
$SurveyText = $aTableParts[1];
|
||||
$iSurveyID = $aTableParts[2];
|
||||
$sDateTime = $aTableParts[4];
|
||||
$sType = $clang->gT('timings');
|
||||
}
|
||||
$iYear = substr($sDateTime, 0, 4);
|
||||
$iMonth = substr($sDateTime, 4, 2);
|
||||
$iDay = substr($sDateTime, 6, 2);
|
||||
$iHour = substr($sDateTime, 8, 2);
|
||||
$iMinute = substr($sDateTime, 10, 2);
|
||||
$sDate = date('d M Y H:i', mktime($iHour, $iMinute, 0, $iMonth, $iDay, $iYear));
|
||||
$sQuery = 'SELECT count(*) as recordcount FROM ' . $sTableName;
|
||||
$aFirstRow = Yii::app()->db->createCommand($sQuery)->queryRow();
|
||||
if ($aFirstRow['recordcount']==0) { // empty table - so add it to immediate deletion
|
||||
$aDelete['orphansurveytables'][] = $sTableName;
|
||||
} else {
|
||||
$aOldSurveyTableAsk[] = array('table' => $sTableName, 'details' => sprintf($clang->gT('Survey ID %d saved at %s containing %d record(s) (%s)'), $iSurveyID, $sDate, $aFirstRow['recordcount'], $sType));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**********************************************************************/
|
||||
/* CHECK OLD TOKEN TABLES */
|
||||
/**********************************************************************/
|
||||
//1: Get list of 'old_token' tables and extract the survey id
|
||||
//2: Check if that survey id still exists
|
||||
//3: If it doesn't offer it for deletion
|
||||
$aResult = dbQueryOrFalse(dbSelectTablesLike('{{old_token}}%')) or safeDie("Couldn't get list of conditions from database<br />$sQuery<br />");
|
||||
$aTables = $aResult->readAll();
|
||||
|
||||
$aOldTokenSIDs = array();
|
||||
$aTokenSIDs = array();
|
||||
$aFullOldTokenSIDs = array();
|
||||
|
||||
foreach ($aTables as $sTable)
|
||||
{
|
||||
$sTable = reset($sTable);
|
||||
|
||||
list($sOldText, $SurveyText, $iSurveyID, $sDateTime) = explode('_', substr($sTable, strlen($sDBPrefix)));
|
||||
$aTokenSIDs[] = $iSurveyID;
|
||||
$aFullOldTokenSIDs[$iSurveyID][] = $sTable;
|
||||
}
|
||||
$aOldTokenSIDs = array_unique($aTokenSIDs);
|
||||
$surveys = Survey::model()->findAll();
|
||||
if (Survey::model()->hasErrors()) safeDie(Survey::model()->getError());
|
||||
$aSIDs = array();
|
||||
foreach ($surveys as $survey)
|
||||
{
|
||||
$aSIDs[] = $survey['sid'];
|
||||
}
|
||||
foreach ($aOldTokenSIDs as $iOldTokenSID)
|
||||
{
|
||||
if (!in_array($iOldTokenSID, $aOldTokenSIDs)) {
|
||||
foreach ($aFullOldTokenSIDs[$iOldTokenSID] as $sTableName)
|
||||
{
|
||||
$aDelete['orphantokentables'][] = $sTableName;
|
||||
}
|
||||
} else {
|
||||
foreach ($aFullOldTokenSIDs[$iOldTokenSID] as $sTableName)
|
||||
{
|
||||
list($sOldText, $sTokensText, $iSurveyID, $sDateTime) = explode('_', substr($sTableName, strlen($sDBPrefix)));
|
||||
$iYear = substr($sDateTime, 0, 4);
|
||||
$iMonth = substr($sDateTime, 4, 2);
|
||||
$iDay = substr($sDateTime, 6, 2);
|
||||
$iHour = substr($sDateTime, 8, 2);
|
||||
$iMinute = substr($sDateTime, 10, 2);
|
||||
$sDate = date('D, d M Y h:i a', mktime($iHour, $iMinute, 0, $iMonth, $iDay, $iYear));
|
||||
$sQuery = 'SELECT count(*) as recordcount FROM ' . $sTableName;
|
||||
|
||||
$aFirstRow = Yii::app()->db->createCommand($sQuery)->queryRow();
|
||||
if ($aFirstRow['recordcount']==0) { // empty table - so add it to immediate deletion
|
||||
$aDelete['orphantokentables'][] = $sTableName;
|
||||
}
|
||||
else
|
||||
{
|
||||
$aOldTokenTableAsk[] = array('table' => $sTableName, 'details' => sprintf($clang->gT('Survey ID %d saved at %s containing %d record(s)'), $iSurveyID, $sDate, $aFirstRow['recordcount']));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($aDelete['defaultvalues'] == 0 && $aDelete['quotamembers'] == 0 &&
|
||||
$aDelete['quotas'] == 0 && $aDelete['quotals'] == 0 && count($aDelete) == 4
|
||||
) {
|
||||
$aDelete['integrityok'] = true;
|
||||
} else {
|
||||
$aDelete['integrityok'] = false;
|
||||
}
|
||||
|
||||
if (!isset($aOldTokenTableAsk) && !isset($aOldSurveyTableAsk)) {
|
||||
$aDelete['redundancyok'] = true;
|
||||
} else {
|
||||
$aDelete['redundancyok'] = false;
|
||||
$aDelete['redundanttokentables'] = array();
|
||||
$aDelete['redundantsurveytables'] = array();
|
||||
if (isset($aOldTokenTableAsk)) {
|
||||
$aDelete['redundanttokentables'] = $aOldTokenTableAsk;
|
||||
}
|
||||
if (isset($aOldSurveyTableAsk)) {
|
||||
$aDelete['redundantsurveytables'] = $aOldSurveyTableAsk;
|
||||
}
|
||||
}
|
||||
|
||||
/**********************************************************************/
|
||||
/* CHECK CPDB SURVEY_LINKS TABLE FOR REDUNDENT TOKEN TABLES */
|
||||
/**********************************************************************/
|
||||
//1: Get distinct list of survey_link survey ids, check if tokens
|
||||
// table still exists for each one, and remove if not
|
||||
|
||||
|
||||
/* TODO */
|
||||
|
||||
/**********************************************************************/
|
||||
/* CHECK CPDB SURVEY_LINKS TABLE FOR REDUNDENT TOKEN ENTRIES */
|
||||
/**********************************************************************/
|
||||
//1: For each survey_link, see if the matching entry still exists in
|
||||
// the token table and remove if it doesn't.
|
||||
|
||||
|
||||
/* TODO */
|
||||
|
||||
return $aDelete;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders template(s) wrapped in header and footer
|
||||
*
|
||||
* @param string $sAction Current action, the folder to fetch views from
|
||||
* @param string|array $aViewUrls View url(s)
|
||||
* @param array $aData Data to be passed on. Optional.
|
||||
*/
|
||||
protected function _renderWrappedTemplate($sAction = 'checkintegrity', $aViewUrls = array(), $aData = array())
|
||||
{
|
||||
parent::_renderWrappedTemplate($sAction, $aViewUrls, $aData);
|
||||
}
|
||||
}
|
2120
sources/application/controllers/admin/conditionsaction.php
Normal file
2120
sources/application/controllers/admin/conditionsaction.php
Normal file
File diff suppressed because it is too large
Load diff
1196
sources/application/controllers/admin/database.php
Normal file
1196
sources/application/controllers/admin/database.php
Normal file
File diff suppressed because it is too large
Load diff
2400
sources/application/controllers/admin/dataentry.php
Normal file
2400
sources/application/controllers/admin/dataentry.php
Normal file
File diff suppressed because it is too large
Load diff
66
sources/application/controllers/admin/dumpdb.php
Normal file
66
sources/application/controllers/admin/dumpdb.php
Normal file
|
@ -0,0 +1,66 @@
|
|||
<?php
|
||||
/*
|
||||
* 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.
|
||||
*
|
||||
*/
|
||||
/**
|
||||
* Dump Database
|
||||
*
|
||||
* @package LimeSurvey
|
||||
* @copyright 2011
|
||||
* @access public
|
||||
*/
|
||||
class Dumpdb extends Survey_Common_Action {
|
||||
|
||||
function __construct($controller, $id)
|
||||
{
|
||||
parent::__construct($controller, $id);
|
||||
|
||||
if (!Permission::model()->hasGlobalPermission('superadmin','read'))
|
||||
{
|
||||
die();
|
||||
}
|
||||
|
||||
if (!in_array(Yii::app()->db->getDriverName(), array('mysql', 'mysqli')) || Yii::app()->getConfig('demoMode') == true)
|
||||
{
|
||||
die($this->getController()->lang->gT('This feature is only available for MySQL databases.'));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Base function
|
||||
*
|
||||
* This functions receives the request to generate a dump file for the
|
||||
* database and does so! Only superadmins are allowed to do this!
|
||||
*/
|
||||
public function index()
|
||||
{
|
||||
Yii::app()->loadHelper("admin/backupdb");
|
||||
$sDbName=_getDbName();
|
||||
$sFileName = 'LimeSurvey_'.$sDbName.'_dump_'.dateShift(date('Y-m-d H:i:s'), 'Y-m-d', Yii::app()->getConfig('timeadjust')).'.sql';
|
||||
$this->_outputHeaders($sFileName);
|
||||
outputDatabase();
|
||||
exit;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Send the headers so that it is shown as a download
|
||||
* @param string $sDbName Database Name
|
||||
*/
|
||||
private function _outputHeaders($sFileName)
|
||||
{
|
||||
header('Content-type: application/octet-stream');
|
||||
header('Content-Disposition: attachment; filename='.$sFileName);
|
||||
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
|
||||
}
|
||||
|
||||
}
|
174
sources/application/controllers/admin/emailtemplates.php
Normal file
174
sources/application/controllers/admin/emailtemplates.php
Normal file
|
@ -0,0 +1,174 @@
|
|||
<?php
|
||||
/*
|
||||
* LimeSurvey
|
||||
* Copyright (C) 2013 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.
|
||||
*
|
||||
*
|
||||
*/
|
||||
/**
|
||||
* emailtemplates
|
||||
*
|
||||
* @package LimeSurvey
|
||||
* @copyright 2011
|
||||
* @access public
|
||||
*/
|
||||
|
||||
class emailtemplates extends Survey_Common_Action {
|
||||
|
||||
/**
|
||||
* Load edit email template screen.
|
||||
* @param mixed $iSurveyId
|
||||
* @return
|
||||
*/
|
||||
function index($iSurveyId)
|
||||
{
|
||||
$clang = $this->getController()->lang;
|
||||
$iSurveyId = sanitize_int($iSurveyId);
|
||||
App()->getClientScript()->registerPackage('jquery-superfish');
|
||||
|
||||
Yii::app()->loadHelper('admin.htmleditor');
|
||||
Yii::app()->loadHelper('surveytranslator');
|
||||
|
||||
Yii::app()->session['FileManagerContext'] = "edit:emailsettings:{$iSurveyId}";
|
||||
initKcfinder();
|
||||
|
||||
if(isset($iSurveyId) && getEmailFormat($iSurveyId) == 'html')
|
||||
{
|
||||
$ishtml = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
$ishtml = false;
|
||||
}
|
||||
|
||||
$grplangs = Survey::model()->findByPk($iSurveyId)->additionalLanguages;
|
||||
$baselang = Survey::model()->findByPk($iSurveyId)->language;
|
||||
array_unshift($grplangs,$baselang);
|
||||
|
||||
$sEditScript = PrepareEditorScript(false, $this->getController());
|
||||
$aData['attrib'] = array();
|
||||
$aData['bplangs'] = array();
|
||||
$aData['defaulttexts'] = array();
|
||||
if ($ishtml)
|
||||
{
|
||||
$sEscapeMode='html';
|
||||
}
|
||||
else
|
||||
{
|
||||
$sEscapeMode='unescaped';
|
||||
}
|
||||
foreach ($grplangs as $key => $grouplang)
|
||||
{
|
||||
$aData['bplangs'][$key] = new limesurvey_lang($grouplang);
|
||||
$aData['attrib'][$key] = SurveyLanguageSetting::model()->find('surveyls_survey_id = :ssid AND surveyls_language = :ls', array(':ssid' => $iSurveyId, ':ls' => $grouplang));
|
||||
$aData['attrib'][$key]['attachments'] = unserialize($aData['attrib'][$key]['attachments']);
|
||||
$aData['defaulttexts'][$key] = templateDefaultTexts($aData['bplangs'][$key],$sEscapeMode);
|
||||
}
|
||||
|
||||
$aData['surveyid'] = $iSurveyId;
|
||||
$aData['ishtml'] = $ishtml;
|
||||
$aData['grplangs'] = $grplangs;
|
||||
$this->_renderWrappedTemplate('emailtemplates', array('output' => $sEditScript, 'emailtemplates_view'), $aData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Function responsible to process any change in email template.
|
||||
* @return
|
||||
*/
|
||||
function update($iSurveyId)
|
||||
{
|
||||
$uploadUrl = Yii::app()->getBaseUrl(true) . substr(Yii::app()->getConfig('uploadurl'),strlen(Yii::app()->getConfig('publicurl'))-1);
|
||||
// We need the real path since we check that the resolved file name starts with this path.
|
||||
$uploadDir = realpath(Yii::app()->getConfig('uploaddir'));
|
||||
$save=Yii::app()->request->getPost('save','');
|
||||
$clang = $this->getController()->lang;
|
||||
if (Permission::model()->hasSurveyPermission($iSurveyId, 'surveylocale','update'))
|
||||
{
|
||||
$languagelist = Survey::model()->findByPk($iSurveyId)->additionalLanguages;
|
||||
$languagelist[] = Survey::model()->findByPk($iSurveyId)->language;
|
||||
array_filter($languagelist);
|
||||
foreach ($languagelist as $langname)
|
||||
{
|
||||
if (isset($_POST['attachments'][$langname]))
|
||||
{
|
||||
foreach ($_POST['attachments'][$langname] as $template => &$attachments)
|
||||
{
|
||||
foreach ($attachments as $index => &$attachment)
|
||||
{
|
||||
// We again take the real path.
|
||||
$localName = realpath(urldecode(str_replace($uploadUrl, $uploadDir, $attachment['url'])));
|
||||
if ($localName !== false)
|
||||
{
|
||||
if (strpos($localName, $uploadDir) === 0)
|
||||
{
|
||||
$attachment['url'] = $localName;
|
||||
$attachment['size'] = filesize($localName);
|
||||
}
|
||||
else
|
||||
{
|
||||
unset($attachments[$index]);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
unset($attachments[$index]);
|
||||
}
|
||||
}
|
||||
unset($attachments);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
$_POST['attachments'][$langname] = array();
|
||||
}
|
||||
|
||||
$attributes = array(
|
||||
'surveyls_email_invite_subj' => $_POST['email_invitation_subj_'.$langname],
|
||||
'surveyls_email_invite' => $_POST['email_invitation_'.$langname],
|
||||
'surveyls_email_remind_subj' => $_POST['email_reminder_subj_'.$langname],
|
||||
'surveyls_email_remind' => $_POST['email_reminder_'.$langname],
|
||||
'surveyls_email_register_subj' => $_POST['email_registration_subj_'.$langname],
|
||||
'surveyls_email_register' => $_POST['email_registration_'.$langname],
|
||||
'surveyls_email_confirm_subj' => $_POST['email_confirmation_subj_'.$langname],
|
||||
'surveyls_email_confirm' => $_POST['email_confirmation_'.$langname],
|
||||
'email_admin_notification_subj' => $_POST['email_admin_notification_subj_'.$langname],
|
||||
'email_admin_notification' => $_POST['email_admin_notification_'.$langname],
|
||||
'email_admin_responses_subj' => $_POST['email_admin_detailed_notification_subj_'.$langname],
|
||||
'email_admin_responses' => $_POST['email_admin_detailed_notification_'.$langname],
|
||||
'attachments' => serialize($_POST['attachments'][$langname])
|
||||
);
|
||||
$usquery = SurveyLanguageSetting::model()->updateAll($attributes,'surveyls_survey_id = :ssid AND surveyls_language = :sl', array(':ssid' => $iSurveyId, ':sl' => $langname));
|
||||
}
|
||||
Yii::app()->session['flashmessage'] = $clang->gT("Email templates successfully saved.");
|
||||
}
|
||||
if($save=='saveclose')
|
||||
$this->getController()->redirect(array('admin/survey/sa/view/surveyid/'.$iSurveyId));
|
||||
else
|
||||
self::index($iSurveyId);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Renders template(s) wrapped in header and footer
|
||||
*
|
||||
* @param string $sAction Current action, the folder to fetch views from
|
||||
* @param string|array $aViewUrls View url(s)
|
||||
* @param array $aData Data to be passed on. Optional.
|
||||
*/
|
||||
protected function _renderWrappedTemplate($sAction = 'emailtemplates', $aViewUrls = array(), $aData = array())
|
||||
{
|
||||
App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . 'emailtemplates.js');
|
||||
|
||||
$aData['display']['menu_bars']['surveysummary'] = 'editemailtemplates';
|
||||
|
||||
parent::_renderWrappedTemplate($sAction, $aViewUrls, $aData);
|
||||
}
|
||||
|
||||
}
|
1123
sources/application/controllers/admin/export.php
Normal file
1123
sources/application/controllers/admin/export.php
Normal file
File diff suppressed because it is too large
Load diff
147
sources/application/controllers/admin/expressions.php
Normal file
147
sources/application/controllers/admin/expressions.php
Normal file
|
@ -0,0 +1,147 @@
|
|||
<?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.
|
||||
*
|
||||
*/
|
||||
class Expressions extends Survey_Common_Action {
|
||||
function index()
|
||||
{
|
||||
$aData=array();
|
||||
$needpermission=false;
|
||||
$aData['surveyid']=$surveyid=sanitize_int(Yii::app()->request->getQuery('sid'));
|
||||
$aData['sa']=$sa=sanitize_paranoid_string(Yii::app()->request->getQuery('sa','index'));
|
||||
if (($aData['sa']=='survey_logic_file' || $aData['sa']=='navigation_test') && $surveyid)
|
||||
{
|
||||
$needpermission=true;
|
||||
}
|
||||
if($needpermission && !Permission::model()->hasSurveyPermission($surveyid,'surveycontent','read'))
|
||||
{
|
||||
$clang = $this->getController()->lang;
|
||||
App()->getClientScript()->registerPackage('jquery-superfish');
|
||||
$message['title']= $clang->gT('Access denied!');
|
||||
$message['message']= $clang->gT('You do not have sufficient rights to access this page.');
|
||||
$message['class']= "error";
|
||||
$this->_renderWrappedTemplate('survey', array("message"=>$message), $aData);
|
||||
}
|
||||
else
|
||||
{
|
||||
App()->getClientScript()->registerPackage('jqueryui');
|
||||
App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts')."survey_runtime.js");
|
||||
App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts')."expressions/em_javascript.js");
|
||||
App()->getClientScript()->registerCssFile(Yii::app()->getConfig('adminstyleurl') . "adminstyle.css" );
|
||||
$this->_printOnLoad(Yii::app()->request->getQuery('sa', 'index'));
|
||||
$aData['pagetitle']="ExpressionManager: {$aData['sa']}";
|
||||
//header("Content-type: text/html; charset=UTF-8"); // needed for correct UTF-8 encoding
|
||||
if(isset($_GET['sa']))
|
||||
$this->test($aData['sa'],$aData);
|
||||
else
|
||||
$this->_renderWrappedTemplate('expressions', 'test_view', $aData);
|
||||
}
|
||||
}
|
||||
|
||||
protected function test($which,$aData)
|
||||
{
|
||||
$this->_renderWrappedTemplate('expressions', 'test/'.$which, $aData);
|
||||
//$this->getController()->render('/admin/expressions/test/'.$which);
|
||||
}
|
||||
|
||||
private function _printOnLoad($which)
|
||||
{
|
||||
switch ($which)
|
||||
{
|
||||
case 'relevance':
|
||||
App()->getClientScript()->registerScript("emscript", "ExprMgr_process_relevance_and_tailoring();", CClientScript::POS_LOAD);
|
||||
break;
|
||||
case 'unit':
|
||||
App()->getClientScript()->registerScript("emscript", "recompute();", CClientScript::POS_LOAD);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private function _printTitle($which)
|
||||
{
|
||||
switch ($which)
|
||||
{
|
||||
case 'index':
|
||||
return 'Test Suite';
|
||||
break;
|
||||
case 'relevance':
|
||||
return 'Unit Test Relevance';
|
||||
break;
|
||||
case 'stringspilt':
|
||||
return 'Unit Test String Splitter';
|
||||
break;
|
||||
case 'functions':
|
||||
return 'Available Functions';
|
||||
break;
|
||||
case 'data':
|
||||
return 'Current Data';
|
||||
break;
|
||||
case 'reset_syntax_error_log':
|
||||
return 'Reset Log of Syntax Errors';
|
||||
break;
|
||||
case 'tokenizer':
|
||||
return 'Unit Test Tokenizer';
|
||||
break;
|
||||
case 'unit':
|
||||
return 'Unit Test Core Evaluator';
|
||||
break;
|
||||
case 'conditions2relevance':
|
||||
return 'Preview Conditions to Relevance';
|
||||
break;
|
||||
case 'navigation_test':
|
||||
return 'Navigation Test';
|
||||
break;
|
||||
case 'reset_syntax_error_log.php':
|
||||
return 'Reset Log of Syntax Errors';
|
||||
break;
|
||||
case 'revert_upgrade_conditions2relevance':
|
||||
return 'Revert Upgrade Conditions to Relevance';
|
||||
break;
|
||||
case 'strings_with_expressions':
|
||||
return 'Test Evaluation of Strings Containing Expressions';
|
||||
break;
|
||||
case 'survey_logic_file':
|
||||
return 'Survey logic file';
|
||||
break;
|
||||
case 'syntax_errors':
|
||||
echo 'Show Log of Syntax Errors';
|
||||
break;
|
||||
case 'upgrade_conditions2relevance':
|
||||
return 'Upgrade Conditions to Relevance';
|
||||
break;
|
||||
case 'upgrade_relevance_location':
|
||||
return 'Upgrade Relevance Location';
|
||||
break;
|
||||
case 'usage':
|
||||
return 'Running Translation Log';
|
||||
break;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Renders template(s) wrapped in header and footer
|
||||
*
|
||||
* @param string $sAction Current action, the folder to fetch views from
|
||||
* @param string|array $aViewUrls View url(s)
|
||||
* @param array $aData Data to be passed on. Optional.
|
||||
*/
|
||||
protected function _renderWrappedTemplate($sAction = 'expressions', $aViewUrls = array(), $aData = array())
|
||||
{
|
||||
$aData['imageurl'] = Yii::app()->getConfig('adminimageurl');
|
||||
//$aData['display']['header']=false;
|
||||
$aData['display']['menu_bars'] = false;
|
||||
//$aData['display']['footer']= false;
|
||||
header("Content-type: text/html; charset=UTF-8"); // needed for correct UTF-8 encoding
|
||||
parent::_renderWrappedTemplate($sAction, $aViewUrls, $aData);
|
||||
}
|
||||
}
|
||||
/* End of file expressions.php */
|
||||
/* Location: ./application/controllers/admin/expressions.php */
|
288
sources/application/controllers/admin/globalsettings.php
Normal file
288
sources/application/controllers/admin/globalsettings.php
Normal file
|
@ -0,0 +1,288 @@
|
|||
<?php
|
||||
/*
|
||||
* 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.
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* GlobalSettings Controller
|
||||
*
|
||||
*
|
||||
* @package LimeSurvey
|
||||
* @subpackage Backend
|
||||
*/
|
||||
class GlobalSettings extends Survey_Common_Action
|
||||
{
|
||||
|
||||
function __construct($controller, $id)
|
||||
{
|
||||
parent::__construct($controller, $id);
|
||||
|
||||
if (!Permission::model()->hasGlobalPermission('settings','read')) {
|
||||
die();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows the index page
|
||||
*
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function index()
|
||||
{
|
||||
if (!empty($_POST['action'])) {
|
||||
$this->_saveSettings();
|
||||
}
|
||||
$this->_displaySettings();
|
||||
}
|
||||
|
||||
public function showphpinfo()
|
||||
{
|
||||
if (!Yii::app()->getConfig('demoMode')) {
|
||||
phpinfo();
|
||||
}
|
||||
}
|
||||
|
||||
public function updatecheck()
|
||||
{
|
||||
updateCheck();
|
||||
$this->getController()->redirect(array('admin/globalsettings'));
|
||||
}
|
||||
|
||||
private function _displaySettings()
|
||||
{
|
||||
Yii::app()->loadHelper('surveytranslator');
|
||||
|
||||
//save refurl from where global settings screen is called!
|
||||
$refurl = Yii::app()->getRequest()->getUrlReferrer();
|
||||
|
||||
// Some URLs are not to be allowed to refered back to.
|
||||
// These exceptions can be added to the $aReplacements array
|
||||
$aReplacements=array('admin/user/adduser'=>'admin/user/index',
|
||||
'admin/user/sa/adduser'=>'admin/user/sa/index',
|
||||
'admin/user/sa/setusertemplates'=>'admin/user/sa/index',
|
||||
'admin/user/setusertemplates'=>'admin/user/sa/index'
|
||||
|
||||
);
|
||||
$refurl= str_replace(array_keys($aReplacements),array_values($aReplacements),$refurl);
|
||||
Yii::app()->session['refurl'] = htmlspecialchars($refurl); //just to be safe!
|
||||
|
||||
$data['clang'] = $this->getController()->lang;
|
||||
$data['title'] = "hi";
|
||||
$data['message'] = "message";
|
||||
foreach ($this->_checkSettings() as $key => $row)
|
||||
{
|
||||
$data[$key] = $row;
|
||||
}
|
||||
$data['thisupdatecheckperiod'] = getGlobalSetting('updatecheckperiod');
|
||||
$data['sUpdateNotification'] = getGlobalSetting('updatenotification');
|
||||
Yii::app()->loadLibrary('Date_Time_Converter');
|
||||
$dateformatdetails = getDateFormatData(Yii::app()->session['dateformat']);
|
||||
$datetimeobj = new date_time_converter(dateShift(getGlobalSetting("updatelastcheck"),'Y-m-d H:i:s',getGlobalSetting('timeadjust')), 'Y-m-d H:i:s');
|
||||
$data['updatelastcheck']=$datetimeobj->convert($dateformatdetails['phpdate'] . " H:i:s");
|
||||
|
||||
$data['updateavailable'] = (getGlobalSetting("updateavailable") && Yii::app()->getConfig("updatable"));
|
||||
$data['updatable'] = Yii::app()->getConfig("updatable");
|
||||
$data['updateinfo'] = getGlobalSetting("updateinfo");
|
||||
$data['updatebuild'] = getGlobalSetting("updatebuild");
|
||||
$data['updateversion'] = getGlobalSetting("updateversion");
|
||||
$data['aUpdateVersions'] = json_decode(getGlobalSetting("updateversions"),true);
|
||||
$data['allLanguages'] = getLanguageData(false, Yii::app()->session['adminlang']);
|
||||
if (trim(Yii::app()->getConfig('restrictToLanguages')) == '') {
|
||||
$data['restrictToLanguages'] = array_keys($data['allLanguages']);
|
||||
$data['excludedLanguages'] = array();
|
||||
}
|
||||
else
|
||||
{
|
||||
$data['restrictToLanguages'] = explode(' ', trim(Yii::app()->getConfig('restrictToLanguages')));
|
||||
$data['excludedLanguages'] = array_diff(array_keys($data['allLanguages']), $data['restrictToLanguages']);
|
||||
}
|
||||
|
||||
$this->_renderWrappedTemplate('', 'globalSettings_view', $data);
|
||||
}
|
||||
|
||||
private function _saveSettings()
|
||||
{
|
||||
if ($_POST['action'] !== "globalsettingssave") {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Permission::model()->hasGlobalPermission('settings','update')) {
|
||||
$this->getController()->redirect(array('/admin'));
|
||||
}
|
||||
$clang = $this->getController()->lang;
|
||||
Yii::app()->loadHelper('surveytranslator');
|
||||
|
||||
$maxemails = $_POST['maxemails'];
|
||||
if (sanitize_int($_POST['maxemails']) < 1) {
|
||||
$maxemails = 1;
|
||||
}
|
||||
|
||||
$defaultlang = sanitize_languagecode($_POST['defaultlang']);
|
||||
$aRestrictToLanguages = explode(' ', sanitize_languagecodeS($_POST['restrictToLanguages']));
|
||||
if (!in_array($defaultlang,$aRestrictToLanguages)){ // Force default language in restrictToLanguages
|
||||
$aRestrictToLanguages[]=$defaultlang;
|
||||
}
|
||||
if (count(array_diff(array_keys(getLanguageData(false,Yii::app()->session['adminlang'])), $aRestrictToLanguages)) == 0) {
|
||||
$aRestrictToLanguages = '';
|
||||
} else {
|
||||
$aRestrictToLanguages = implode(' ', $aRestrictToLanguages);
|
||||
}
|
||||
|
||||
setGlobalSetting('defaultlang', $defaultlang);
|
||||
setGlobalSetting('restrictToLanguages', trim($aRestrictToLanguages));
|
||||
setGlobalSetting('sitename', strip_tags($_POST['sitename']));
|
||||
setGlobalSetting('updatecheckperiod', (int)($_POST['updatecheckperiod']));
|
||||
setGlobalSetting('updatenotification', strip_tags($_POST['updatenotification']));
|
||||
setGlobalSetting('defaulthtmleditormode', sanitize_paranoid_string($_POST['defaulthtmleditormode']));
|
||||
setGlobalSetting('defaultquestionselectormode', sanitize_paranoid_string($_POST['defaultquestionselectormode']));
|
||||
setGlobalSetting('defaulttemplateeditormode', sanitize_paranoid_string($_POST['defaulttemplateeditormode']));
|
||||
if (!Yii::app()->getConfig('demoMode'))
|
||||
{
|
||||
setGlobalSetting('defaulttemplate', sanitize_paranoid_string($_POST['defaulttemplate']));
|
||||
}
|
||||
setGlobalSetting('admintheme', sanitize_paranoid_string($_POST['admintheme']));
|
||||
setGlobalSetting('adminthemeiconsize', trim(file_get_contents(Yii::app()->getConfig("styledir").DIRECTORY_SEPARATOR.sanitize_paranoid_string($_POST['admintheme']).DIRECTORY_SEPARATOR.'iconsize')));
|
||||
setGlobalSetting('emailmethod', strip_tags($_POST['emailmethod']));
|
||||
setGlobalSetting('emailsmtphost', strip_tags(returnGlobal('emailsmtphost')));
|
||||
if (returnGlobal('emailsmtppassword') != 'somepassword') {
|
||||
setGlobalSetting('emailsmtppassword', strip_tags(returnGlobal('emailsmtppassword')));
|
||||
}
|
||||
setGlobalSetting('bounceaccounthost', strip_tags(returnGlobal('bounceaccounthost')));
|
||||
setGlobalSetting('bounceaccounttype', strip_tags(returnGlobal('bounceaccounttype')));
|
||||
setGlobalSetting('bounceencryption', strip_tags(returnGlobal('bounceencryption')));
|
||||
setGlobalSetting('bounceaccountuser', strip_tags(returnGlobal('bounceaccountuser')));
|
||||
|
||||
if (returnGlobal('bounceaccountpass') != 'enteredpassword') setGlobalSetting('bounceaccountpass', strip_tags(returnGlobal('bounceaccountpass')));
|
||||
|
||||
setGlobalSetting('emailsmtpssl', sanitize_paranoid_string(Yii::app()->request->getPost('emailsmtpssl','')));
|
||||
setGlobalSetting('emailsmtpdebug', sanitize_int(Yii::app()->request->getPost('emailsmtpdebug','0')));
|
||||
setGlobalSetting('emailsmtpuser', strip_tags(returnGlobal('emailsmtpuser')));
|
||||
setGlobalSetting('filterxsshtml', strip_tags($_POST['filterxsshtml']));
|
||||
$warning = '';
|
||||
// make sure emails are valid before saving them
|
||||
if (Yii::app()->request->getPost('siteadminbounce', '') == ''
|
||||
|| validateEmailAddress(Yii::app()->request->getPost('siteadminbounce'))) {
|
||||
setGlobalSetting('siteadminbounce', strip_tags(Yii::app()->request->getPost('siteadminbounce')));
|
||||
} else {
|
||||
$warning .= $clang->gT("Warning! Admin bounce email was not saved because it was not valid.").'<br/>';
|
||||
}
|
||||
if (Yii::app()->request->getPost('siteadminemail', '') == ''
|
||||
|| validateEmailAddress(Yii::app()->request->getPost('siteadminemail'))) {
|
||||
setGlobalSetting('siteadminemail', strip_tags(Yii::app()->request->getPost('siteadminemail')));
|
||||
} else {
|
||||
$warning .= $clang->gT("Warning! Admin email was not saved because it was not valid.").'<br/>';
|
||||
}
|
||||
setGlobalSetting('siteadminname', strip_tags($_POST['siteadminname']));
|
||||
setGlobalSetting('shownoanswer', sanitize_int($_POST['shownoanswer']));
|
||||
setGlobalSetting('showxquestions', ($_POST['showxquestions']));
|
||||
setGlobalSetting('showgroupinfo', ($_POST['showgroupinfo']));
|
||||
setGlobalSetting('showqnumcode', ($_POST['showqnumcode']));
|
||||
$repeatheadingstemp = (int)($_POST['repeatheadings']);
|
||||
if ($repeatheadingstemp == 0) $repeatheadingstemp = 25;
|
||||
setGlobalSetting('repeatheadings', $repeatheadingstemp);
|
||||
|
||||
setGlobalSetting('maxemails', sanitize_int($maxemails));
|
||||
$iSessionExpirationTime = (int)($_POST['iSessionExpirationTime']);
|
||||
if ($iSessionExpirationTime == 0) $iSessionExpirationTime = 7200;
|
||||
setGlobalSetting('iSessionExpirationTime', $iSessionExpirationTime);
|
||||
setGlobalSetting('ipInfoDbAPIKey', $_POST['ipInfoDbAPIKey']);
|
||||
setGlobalSetting('googleMapsAPIKey', $_POST['googleMapsAPIKey']);
|
||||
setGlobalSetting('googleanalyticsapikey',$_POST['googleanalyticsapikey']);
|
||||
setGlobalSetting('googletranslateapikey',$_POST['googletranslateapikey']);
|
||||
setGlobalSetting('force_ssl', $_POST['force_ssl']);
|
||||
setGlobalSetting('surveyPreview_require_Auth', $_POST['surveyPreview_require_Auth']);
|
||||
setGlobalSetting('RPCInterface', $_POST['RPCInterface']);
|
||||
setGlobalSetting('rpc_publish_api', (bool) $_POST['rpc_publish_api']);
|
||||
$savetime = ((float)$_POST['timeadjust'])*60 . ' minutes'; //makes sure it is a number, at least 0
|
||||
if ((substr($savetime, 0, 1) != '-') && (substr($savetime, 0, 1) != '+')) {
|
||||
$savetime = '+' . $savetime;
|
||||
}
|
||||
setGlobalSetting('timeadjust', $savetime);
|
||||
setGlobalSetting('usercontrolSameGroupPolicy', strip_tags($_POST['usercontrolSameGroupPolicy']));
|
||||
|
||||
Yii::app()->session['flashmessage'] = $warning.$clang->gT("Global settings were saved.");
|
||||
|
||||
$url = htmlspecialchars_decode(Yii::app()->session['refurl']);
|
||||
if($url){Yii::app()->getController()->redirect($url);}
|
||||
}
|
||||
|
||||
private function _checkSettings()
|
||||
{
|
||||
$surveycount = Survey::model()->count();
|
||||
|
||||
$activesurveycount = Survey::model()->active()->count();
|
||||
|
||||
$usercount = User::model()->count();
|
||||
|
||||
if ($activesurveycount == false) {
|
||||
$activesurveycount = 0;
|
||||
}
|
||||
if ($surveycount == false) {
|
||||
$surveycount = 0;
|
||||
}
|
||||
|
||||
$tablelist = Yii::app()->db->schema->getTableNames();
|
||||
foreach ($tablelist as $table)
|
||||
{
|
||||
if (strpos($table, Yii::app()->db->tablePrefix . "old_tokens_") !== false) {
|
||||
$oldtokenlist[] = $table;
|
||||
}
|
||||
elseif (strpos($table, Yii::app()->db->tablePrefix . "tokens_") !== false)
|
||||
{
|
||||
$tokenlist[] = $table;
|
||||
}
|
||||
elseif (strpos($table, Yii::app()->db->tablePrefix . "old_survey_") !== false)
|
||||
{
|
||||
$oldresultslist[] = $table;
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($oldresultslist) && is_array($oldresultslist)) {
|
||||
$deactivatedsurveys = count($oldresultslist);
|
||||
} else {
|
||||
$deactivatedsurveys = 0;
|
||||
}
|
||||
if (isset($oldtokenlist) && is_array($oldtokenlist)) {
|
||||
$deactivatedtokens = count($oldtokenlist);
|
||||
} else {
|
||||
$deactivatedtokens = 0;
|
||||
}
|
||||
if (isset($tokenlist) && is_array($tokenlist)) {
|
||||
$activetokens = count($tokenlist);
|
||||
} else {
|
||||
$activetokens = 0;
|
||||
}
|
||||
return array(
|
||||
'usercount' => $usercount,
|
||||
'surveycount' => $surveycount,
|
||||
'activesurveycount' => $activesurveycount,
|
||||
'deactivatedsurveys' => $deactivatedsurveys,
|
||||
'activetokens' => $activetokens,
|
||||
'deactivatedtokens' => $deactivatedtokens
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders template(s) wrapped in header and footer
|
||||
*
|
||||
* @param string $sAction Current action, the folder to fetch views from
|
||||
* @param string|array $aViewUrls View url(s)
|
||||
* @param array $aData Data to be passed on. Optional.
|
||||
*/
|
||||
protected function _renderWrappedTemplate($sAction = '', $aViewUrls = array(), $aData = array())
|
||||
{
|
||||
App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . "globalsettings.js");
|
||||
|
||||
parent::_renderWrappedTemplate($sAction, $aViewUrls, $aData);
|
||||
}
|
||||
}
|
67
sources/application/controllers/admin/htmleditor_pop.php
Normal file
67
sources/application/controllers/admin/htmleditor_pop.php
Normal file
|
@ -0,0 +1,67 @@
|
|||
<?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.
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
class htmleditor_pop extends Survey_Common_Action
|
||||
{
|
||||
|
||||
function index()
|
||||
{
|
||||
Yii::app()->loadHelper('admin/htmleditor');
|
||||
$ckLanguage = sTranslateLangCode2CK(Yii::app()->session['adminlang']);
|
||||
|
||||
$sFieldName = isset($_GET['name']) ? $_GET['name'] : 0;
|
||||
$sFieldText = isset($_GET['text']) ? $_GET['text'] : 0;
|
||||
$sFieldType = isset($_GET['type']) ? $_GET['type'] : 0;
|
||||
$sAction = isset($_GET['action']) ? $_GET['action'] : 0;
|
||||
$iSurveyId = isset($_GET['sid']) ? $_GET['sid'] : 0;
|
||||
$iGroupId = isset($_GET['gid']) ? $_GET['gid'] : 0;
|
||||
$iQuestionId = isset($_GET['qid']) ? $_GET['qid'] : 0;
|
||||
$sLanguage = isset($_GET['lang']) ? $_GET['lang'] : 0;
|
||||
$aData['clang'] = $this->getController()->lang;
|
||||
$aData['sFieldName'] = $sFieldName;
|
||||
if (get_magic_quotes_gpc())
|
||||
$aData['sFieldText'] = $sFieldText = stripslashes($sFieldText);
|
||||
else
|
||||
$aData['sFieldText'] = $sFieldText;
|
||||
|
||||
if (!$sFieldName || !$sFieldText)
|
||||
{
|
||||
$this->getController()->render('/admin/htmleditor/pop_nofields_view', $aData);
|
||||
}
|
||||
else
|
||||
{
|
||||
$aData['sFieldType'] = $sFieldType = preg_replace("/[^_.a-zA-Z0-9-]/", "", $sFieldType);
|
||||
$aData['sAction'] = preg_replace("/[^_.a-zA-Z0-9-]/", "", $sAction);
|
||||
$aData['iSurveyId'] = sanitize_int($iSurveyId);
|
||||
$aData['iGroupId'] = sanitize_int($iGroupId);
|
||||
$aData['iQuestionId'] = sanitize_int($iQuestionId);
|
||||
$aData['sControlIdEna'] = $sFieldName . '_popupctrlena';
|
||||
$aData['sControlIdDis'] = $sFieldName . '_popupctrldis';
|
||||
$aData['ckLanguage'] = $ckLanguage;
|
||||
|
||||
$aData['toolbarname'] = 'popup';
|
||||
$aData['htmlformatoption'] = '';
|
||||
|
||||
if (in_array($sFieldType, array('email-inv', 'email-reg', 'email-conf', 'email-rem')))
|
||||
{
|
||||
$aData['htmlformatoption'] = ',fullPage:true';
|
||||
}
|
||||
|
||||
$this->getController()->render('/admin/htmleditor/pop_editor_view', $aData);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
10
sources/application/controllers/admin/index.html
Normal file
10
sources/application/controllers/admin/index.html
Normal file
|
@ -0,0 +1,10 @@
|
|||
<html>
|
||||
<head>
|
||||
<title>403 Forbidden</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<p>Directory access is forbidden.</p>
|
||||
|
||||
</body>
|
||||
</html>
|
42
sources/application/controllers/admin/index.php
Normal file
42
sources/application/controllers/admin/index.php
Normal file
|
@ -0,0 +1,42 @@
|
|||
<?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.
|
||||
*
|
||||
*/
|
||||
class Index extends Survey_Common_Action
|
||||
{
|
||||
|
||||
public function run()
|
||||
{
|
||||
$clang = Yii::app()->lang;
|
||||
|
||||
if (Yii::app()->session['just_logged_in'])
|
||||
{
|
||||
$aViewUrls = array('message' => array(
|
||||
'title' => $clang->gT("Logged in"),
|
||||
'message' => Yii::app()->session['loginsummary']
|
||||
));
|
||||
unset(Yii::app()->session['just_logged_in'], Yii::app()->session['loginsummary']);
|
||||
|
||||
$this->_renderWrappedTemplate('super', $aViewUrls);
|
||||
}
|
||||
elseif (count(getSurveyList(true)) == 0)
|
||||
{
|
||||
$this->_renderWrappedTemplate('super', 'firststeps');
|
||||
}
|
||||
else
|
||||
{
|
||||
$this->getController()->redirect(array('admin/survey/sa/index'));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
452
sources/application/controllers/admin/labels.php
Normal file
452
sources/application/controllers/admin/labels.php
Normal file
|
@ -0,0 +1,452 @@
|
|||
<?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.
|
||||
*/
|
||||
|
||||
/**
|
||||
* labels
|
||||
*
|
||||
* @package LimeSurvey
|
||||
* @author
|
||||
* @copyright 2011
|
||||
* @access public
|
||||
*/
|
||||
class labels extends Survey_Common_Action
|
||||
{
|
||||
/**
|
||||
* routes to the correct subdir
|
||||
*
|
||||
* @access public
|
||||
* @param string $sa
|
||||
* @return void
|
||||
*/
|
||||
public function run($sa=null)
|
||||
{
|
||||
if ($sa == 'newlabelset' || $sa == 'editlabelset')
|
||||
$this->route('index', array('sa', 'lid'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Function responsible to import label resources from a '.zip' file.
|
||||
*
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function importlabelresources()
|
||||
{
|
||||
$clang = $this->getController()->lang;
|
||||
$lid = returnGlobal('lid');
|
||||
|
||||
if (!empty($lid))
|
||||
{
|
||||
if (Yii::app()->getConfig('demoMode'))
|
||||
$this->getController()->error($clang->gT("Demo mode only: Uploading files is disabled in this system."), $this->getController()->createUrl("admin/labels/sa/view/lid/{$lid}"));
|
||||
|
||||
// Create temporary directory
|
||||
// If dangerous content is unzipped
|
||||
// then no one will know the path
|
||||
$extractdir = $this->_tempdir(Yii::app()->getConfig('tempdir'));
|
||||
$zipfilename = $_FILES['the_file']['tmp_name'];
|
||||
$basedestdir = Yii::app()->getConfig('uploaddir') . "/labels";
|
||||
$destdir = $basedestdir . "/$lid/";
|
||||
|
||||
Yii::app()->loadLibrary('admin.pclzip');
|
||||
$zip = new PclZip($zipfilename);
|
||||
|
||||
if (!is_writeable($basedestdir))
|
||||
$this->getController()->error(sprintf($clang->gT("Incorrect permissions in your %s folder."), $basedestdir), $this->getController()->createUrl("admin/labels/sa/view/lid/{$lid}"));
|
||||
|
||||
if (!is_dir($destdir))
|
||||
mkdir($destdir);
|
||||
|
||||
$aImportedFilesInfo = array();
|
||||
$aErrorFilesInfo = array();
|
||||
|
||||
if (is_file($zipfilename))
|
||||
{
|
||||
if ($zip->extract($extractdir) <= 0)
|
||||
$this->getController()->error($clang->gT("This file is not a valid ZIP file archive. Import failed. " . $zip->errorInfo(true)), $this->getController()->createUrl("admin/labels/sa/view/lid/{$lid}"));
|
||||
|
||||
// now read tempdir and copy authorized files only
|
||||
$folders = array('flash', 'files', 'images');
|
||||
foreach ($folders as $folder)
|
||||
{
|
||||
list($_aImportedFilesInfo, $_aErrorFilesInfo) = $this->_filterImportedResources($extractdir . "/" . $folder, $destdir . $folder);
|
||||
$aImportedFilesInfo = array_merge($aImportedFilesInfo, $_aImportedFilesInfo);
|
||||
$aErrorFilesInfo = array_merge($aErrorFilesInfo, $_aErrorFilesInfo);
|
||||
}
|
||||
|
||||
// Deletes the temp directory
|
||||
rmdirr($extractdir);
|
||||
|
||||
// Delete the temporary file
|
||||
unlink($zipfilename);
|
||||
|
||||
if (is_null($aErrorFilesInfo) && is_null($aImportedFilesInfo))
|
||||
$this->getController()->error($clang->gT("This ZIP archive contains no valid Resources files. Import failed."), $this->getController()->createUrl("admin/labels/sa/view/lid/{$lid}"));
|
||||
}
|
||||
else
|
||||
$this->getController()->error(sprintf($clang->gT("An error occurred uploading your file. This may be caused by incorrect permissions in your %s folder."), $basedestdir), $this->getController()->createUrl("admin/labels/sa/view/lid/{$lid}"));
|
||||
|
||||
$aData = array(
|
||||
'aErrorFilesInfo' => $aErrorFilesInfo,
|
||||
'aImportedFilesInfo' => $aImportedFilesInfo,
|
||||
'lid' => $lid
|
||||
);
|
||||
|
||||
$this->_renderWrappedTemplate('labels', 'importlabelresources_view', $aData);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to import a label set
|
||||
*
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function import()
|
||||
{
|
||||
$clang = $this->getController()->lang;
|
||||
$action = returnGlobal('action');
|
||||
$aViewUrls = array();
|
||||
|
||||
if ($action == 'importlabels')
|
||||
{
|
||||
Yii::app()->loadHelper('admin/import');
|
||||
|
||||
$sFullFilepath = Yii::app()->getConfig('tempdir') . DIRECTORY_SEPARATOR . randomChars(20);
|
||||
$aPathInfo = pathinfo($_FILES['the_file']['name']);
|
||||
$sExtension = !empty($aPathInfo['extension']) ? $aPathInfo['extension'] : '';
|
||||
|
||||
if (!@move_uploaded_file($_FILES['the_file']['tmp_name'], $sFullFilepath))
|
||||
$this->getController()->error(sprintf($clang->gT("An error occurred uploading your file. This may be caused by incorrect permissions in your %s folder."), Yii::app()->getConfig('tempdir')));
|
||||
|
||||
$options['checkforduplicates'] = 'off';
|
||||
if (isset($_POST['checkforduplicates']))
|
||||
$options['checkforduplicates'] = $_POST['checkforduplicates'];
|
||||
|
||||
if (strtolower($sExtension) == 'csv')
|
||||
$aImportResults = CSVImportLabelset($sFullFilepath, $options);
|
||||
elseif (strtolower($sExtension) == 'lsl')
|
||||
$aImportResults = XMLImportLabelsets($sFullFilepath, $options);
|
||||
else
|
||||
$this->getController()->error($clang->gT("Uploaded label set file needs to have an .lsl extension."));
|
||||
|
||||
unlink($sFullFilepath);
|
||||
|
||||
$aViewUrls['import_view'][] = array('aImportResults' => $aImportResults);
|
||||
}
|
||||
|
||||
$this->_renderWrappedTemplate('labels', $aViewUrls);
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to load new/edit labelset screen.
|
||||
*
|
||||
* @access public
|
||||
* @param mixed $action
|
||||
* @param integer $lid
|
||||
* @return
|
||||
*/
|
||||
public function index($sa, $lid=0)
|
||||
{
|
||||
Yii::app()->loadHelper('surveytranslator');
|
||||
|
||||
$clang = $this->getController()->lang;
|
||||
$lid = sanitize_int($lid);
|
||||
$aViewUrls = array();
|
||||
|
||||
if (Permission::model()->hasGlobalPermission('labelsets','read'))
|
||||
{
|
||||
if ($sa == "editlabelset" && Permission::model()->hasGlobalPermission('labelsets','update'))
|
||||
{
|
||||
$result = LabelSet::model()->findAllByAttributes(array('lid' => $lid));
|
||||
foreach ($result as $row)
|
||||
{
|
||||
$row = $row->attributes;
|
||||
$lbname = $row['label_name'];
|
||||
$lblid = $row['lid'];
|
||||
$langids = $row['languages'];
|
||||
}
|
||||
$aData['lbname'] = $lbname;
|
||||
$aData['lblid'] = $lblid;
|
||||
}
|
||||
|
||||
$aData['action'] = $sa;
|
||||
$aData['lid'] = $lid;
|
||||
|
||||
if ($sa == "newlabelset" && Permission::model()->hasGlobalPermission('labelsets','create'))
|
||||
{
|
||||
$langids = Yii::app()->session['adminlang'];
|
||||
$tabitem = $clang->gT("Create new label set");
|
||||
}
|
||||
else
|
||||
$tabitem = $clang->gT("Edit label set");
|
||||
|
||||
$langidsarray = explode(" ", trim($langids)); // Make an array of it
|
||||
|
||||
if (isset($row['lid']))
|
||||
$panecookie = $row['lid'];
|
||||
else
|
||||
$panecookie = 'new';
|
||||
|
||||
$aData['langids'] = $langids;
|
||||
$aData['langidsarray'] = $langidsarray;
|
||||
$aData['panecookie'] = $panecookie;
|
||||
$aData['tabitem'] = $tabitem;
|
||||
|
||||
$aViewUrls['editlabel_view'][] = $aData;
|
||||
}
|
||||
|
||||
$this->_renderWrappedTemplate('labels', $aViewUrls, $aData);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to view a labelset.
|
||||
*
|
||||
* @access public
|
||||
* @param int $lid
|
||||
* @return void
|
||||
*/
|
||||
public function view($lid = 0)
|
||||
{
|
||||
// Escapes the id variable
|
||||
if ($lid != false)
|
||||
$lid = sanitize_int($lid);
|
||||
|
||||
Yii::app()->session['FileManagerContext'] = "edit:label:{$lid}";
|
||||
|
||||
// Gets the current language
|
||||
$clang = $this->getController()->lang;
|
||||
$action = 'labels';
|
||||
$aViewUrls = array();
|
||||
$aData = array();
|
||||
|
||||
// Includes some javascript files
|
||||
App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . 'labels.js');
|
||||
App()->getClientScript()->registerPackage('jquery-json');
|
||||
// Checks if user have the sufficient rights to manage the labels
|
||||
if (Permission::model()->hasGlobalPermission('labelsets','read'))
|
||||
{
|
||||
// Get a result containing labelset with the specified id
|
||||
$result = LabelSet::model()->findByAttributes(array('lid' => $lid));
|
||||
|
||||
// If there is label id in the variable $lid and there are labelset records in the database
|
||||
$labelset_exists = !empty($result);
|
||||
|
||||
if ($lid && $labelset_exists)
|
||||
{
|
||||
// Now recieve all labelset information and display it
|
||||
$aData['lid'] = $lid;
|
||||
$aData['clang'] = $clang;
|
||||
$aData['row'] = $result->attributes;
|
||||
|
||||
// Display a specific labelbar menu
|
||||
$aViewUrls['labelbar_view'][] = $aData;
|
||||
|
||||
$rwlabelset = $result;
|
||||
|
||||
// Make languages array from the current row
|
||||
$lslanguages = explode(" ", trim($result['languages']));
|
||||
|
||||
Yii::app()->loadHelper("admin/htmleditor");
|
||||
|
||||
$aViewUrls['output'] = PrepareEditorScript(false, $this->getController());
|
||||
|
||||
$criteria = new CDbCriteria;
|
||||
$criteria->select = 'max(sortorder) as maxsortorder, sortorder';
|
||||
$criteria->addCondition('lid = :lid');
|
||||
$criteria->addCondition('language = :language');
|
||||
$criteria->params = array(':lid' => $lid, ':language' => $lslanguages[0]);
|
||||
$criteria->group = 'sortorder';
|
||||
$maxresult = Label::model()->find($criteria);
|
||||
$maxsortorder = 1;
|
||||
if (!empty($maxresult))
|
||||
$maxsortorder = $maxresult->maxsortorder + 1;
|
||||
|
||||
$i = 0;
|
||||
Yii::app()->loadHelper("surveytranslator");
|
||||
$results = array();
|
||||
foreach ($lslanguages as $lslanguage)
|
||||
{
|
||||
$result = Label::model()->findAllByAttributes(array('lid' => $lid, 'language' => $lslanguage), array('order' => 'sortorder, code'));
|
||||
$criteria = new CDbCriteria;
|
||||
$criteria->order = 'sortorder, code';
|
||||
$criteria->condition = 'lid = :lid AND language = :language';
|
||||
$criteria->params = array(':lid' => $lid, ':language' => $lslanguage);
|
||||
$labelcount = Label::model()->count($criteria);
|
||||
|
||||
$results[$i] = array();
|
||||
|
||||
foreach ($result as $row)
|
||||
$results[$i][] = $row->attributes;
|
||||
|
||||
$i++;
|
||||
}
|
||||
|
||||
$aViewUrls['labelview_view'][] = array(
|
||||
'results' => $results,
|
||||
'lslanguages' => $lslanguages,
|
||||
'clang' => $clang,
|
||||
'lid' => $lid,
|
||||
'maxsortorder' => $maxsortorder,
|
||||
// 'msorow' => $maxresult->sortorder,
|
||||
'action' => $action,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
$this->_renderWrappedTemplate('labels', $aViewUrls, $aData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Process labels form data depending on $action.
|
||||
*
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function process()
|
||||
{
|
||||
if ( Permission::model()->hasGlobalPermission('labelsets','update'))
|
||||
{
|
||||
if (isset($_POST['method']) && get_magic_quotes_gpc())
|
||||
$_POST['method'] = stripslashes($_POST['method']);
|
||||
|
||||
$action = returnGlobal('action');
|
||||
Yii::app()->loadHelper('admin/label');
|
||||
$lid = returnGlobal('lid');
|
||||
|
||||
if ($action == "updateset")
|
||||
{
|
||||
updateset($lid);
|
||||
Yii::app()->session['flashmessage'] = Yii::app()->lang->gT("Label set properties sucessfully updated.");
|
||||
}
|
||||
if ($action == "insertlabelset")
|
||||
$lid = insertlabelset();
|
||||
if (($action == "modlabelsetanswers") || ($action == "ajaxmodlabelsetanswers"))
|
||||
modlabelsetanswers($lid);
|
||||
if ($action == "deletelabelset")
|
||||
if (deletelabelset($lid))
|
||||
{
|
||||
Yii::app()->session['flashmessage'] = Yii::app()->lang->gT("Label set sucessfully deleted.");
|
||||
$lid = 0;
|
||||
}
|
||||
|
||||
|
||||
if ($lid)
|
||||
$this->getController()->redirect(array("admin/labels/sa/view/lid/" . $lid));
|
||||
else
|
||||
$this->getController()->redirect(array("admin/labels/sa/view"));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Multi label export
|
||||
*
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function exportmulti()
|
||||
{
|
||||
App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . 'labels.js');
|
||||
$this->_renderWrappedTemplate('labels', 'exportmulti_view');
|
||||
}
|
||||
|
||||
public function getAllSets()
|
||||
{
|
||||
$results = LabelSet::model()->findAll();
|
||||
|
||||
$output = array();
|
||||
|
||||
foreach($results as $row)
|
||||
{
|
||||
$output[$row->lid] = $row->getAttribute('label_name');
|
||||
}
|
||||
|
||||
echo ls_json_encode($output);
|
||||
}
|
||||
|
||||
public function ajaxSets()
|
||||
{
|
||||
$lid = Yii::app()->getRequest()->getPost('lid');
|
||||
$answers = Yii::app()->getRequest()->getPost('answers');
|
||||
$code = Yii::app()->getRequest()->getPost('code');
|
||||
//Create new label set
|
||||
$language = "";
|
||||
foreach ($answers as $lang => $answer) {
|
||||
$language .= $lang." ";
|
||||
}
|
||||
$language = trim($language);
|
||||
if ($lid == 0)
|
||||
{
|
||||
$lset = new LabelSet;
|
||||
$lset->label_name = Yii::app()->getRequest()->getPost('laname');
|
||||
$lset->languages = $language;
|
||||
$lset->save();
|
||||
|
||||
$lid = getLastInsertID($lset->tableName());
|
||||
}
|
||||
else
|
||||
{
|
||||
Label::model()->deleteAll('lid = :lid', array(':lid' => $lid));
|
||||
}
|
||||
$res = 'ok'; //optimistic
|
||||
foreach($answers as $lang => $answer) {
|
||||
foreach ($answer as $key => $ans)
|
||||
{
|
||||
$label = new Label;
|
||||
$label->lid = $lid;
|
||||
$label->code = $code[$key];
|
||||
$label->title = $ans;
|
||||
$label->sortorder = $key;
|
||||
$label->language = $lang;
|
||||
if(!$label->save())
|
||||
$res = 'fail';
|
||||
}
|
||||
}
|
||||
echo ls_json_encode($res);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders template(s) wrapped in header and footer
|
||||
*
|
||||
* @param string $sAction Current action, the folder to fetch views from
|
||||
* @param string|array $aViewUrls View url(s)
|
||||
* @param array $aData Data to be passed on. Optional.
|
||||
*/
|
||||
protected function _renderWrappedTemplate($sAction = 'labels', $aViewUrls = array(), $aData = array())
|
||||
{
|
||||
if (!isset($aData['display']['menu_bars']['labels']) || $aData['display']['menu_bars']['labels'] != false)
|
||||
{
|
||||
if (empty($aData['labelsets']))
|
||||
{
|
||||
$aData['labelsets'] = getLabelSets();
|
||||
}
|
||||
|
||||
if (empty($aData['lid']))
|
||||
{
|
||||
$aData['lid'] = 0;
|
||||
}
|
||||
|
||||
$aViewUrls = (array) $aViewUrls;
|
||||
|
||||
array_unshift($aViewUrls, 'labelsetsbar_view');
|
||||
}
|
||||
|
||||
$aData['display']['menu_bars'] = false;
|
||||
|
||||
parent::_renderWrappedTemplate($sAction, $aViewUrls, $aData);
|
||||
}
|
||||
}
|
341
sources/application/controllers/admin/limereplacementfields.php
Normal file
341
sources/application/controllers/admin/limereplacementfields.php
Normal file
|
@ -0,0 +1,341 @@
|
|||
<?php
|
||||
/*
|
||||
* LimeSurvey
|
||||
* Copyright (C) 2013 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.
|
||||
*
|
||||
*/
|
||||
class limereplacementfields extends Survey_Common_Action
|
||||
{
|
||||
|
||||
public function index()
|
||||
{
|
||||
if (isset($_GET['surveyid'])) {
|
||||
$surveyid = sanitize_int($_GET['surveyid']);
|
||||
}
|
||||
if (isset($_GET['gid'])) {
|
||||
$gid = sanitize_int($_GET['gid']);
|
||||
}
|
||||
if (isset($_GET['qid'])) {
|
||||
$qid = sanitize_int($_GET['qid']);
|
||||
}
|
||||
if (isset($_GET['fieldtype'])) {
|
||||
$fieldtype = $_GET['fieldtype'];
|
||||
}
|
||||
if (isset($_GET['action'])) {
|
||||
$action = $_GET['action'];
|
||||
}
|
||||
|
||||
$clang = Yii::app()->lang;
|
||||
|
||||
if (!Yii::app()->session['loginID']) {
|
||||
die ("Unauthenticated Access Forbiden");
|
||||
}
|
||||
|
||||
list($replacementFields, $isInstertAnswerEnabled) = $this->_getReplacementFields($fieldtype, $surveyid);
|
||||
|
||||
if ($isInstertAnswerEnabled === true) {
|
||||
if (empty($surveyid)) {
|
||||
safeDie("No SID provided.");
|
||||
}
|
||||
|
||||
//2: Get all other questions that occur before this question that are pre-determined answer types
|
||||
$fieldmap = createFieldMap($surveyid,'full',false,false,getBaseLanguageFromSurveyID($surveyid));
|
||||
|
||||
$surveyInfo = getSurveyInfo($surveyid);
|
||||
$surveyformat = $surveyInfo['format']; // S, G, A
|
||||
|
||||
//Go through each question until we reach the current one
|
||||
//error_log(print_r($qrows,true));
|
||||
$questionlist = $this->_getQuestionList($action, $gid, $qid, $fieldmap, $fieldtype, $surveyformat);
|
||||
$childQuestions = $this->_getChildQuestions($questionlist);
|
||||
}
|
||||
|
||||
$data['countfields'] = count($replacementFields);
|
||||
$data['replFields'] = $replacementFields;
|
||||
$data['clang'] = $clang;
|
||||
if (isset($childQuestions)) {
|
||||
$data['cquestions'] = $childQuestions;
|
||||
}
|
||||
if (isset($surveyformat)) {
|
||||
$data['surveyformat'] = $surveyformat;
|
||||
}
|
||||
|
||||
$this->getController()->render('/admin/limeReplacementFields_view', $data);
|
||||
}
|
||||
|
||||
private function _getQuestionList($action, $gid, $qid, array $fieldmap, $questionType, $surveyformat)
|
||||
{
|
||||
$previousQuestion = null;
|
||||
$isPreviousPageQuestion = true;
|
||||
$questionList = array();
|
||||
|
||||
foreach ($fieldmap as $question)
|
||||
{
|
||||
if (empty($question['qid'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (is_null($qid) || $this->_shouldAddQuestion($action, $gid, $qid, $question, $previousQuestion)) {
|
||||
$isPreviousPageQuestion = $this->_addQuestionToList($action, $gid, $question, $questionType, $surveyformat, $isPreviousPageQuestion, $questionList);
|
||||
$previousQuestion = $question;
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
return $questionList;
|
||||
}
|
||||
|
||||
private function _shouldAddQuestion($action, $gid, $qid, array $question, $previousQuestion)
|
||||
{
|
||||
switch ($action)
|
||||
{
|
||||
case 'addgroup':
|
||||
return true;
|
||||
|
||||
case 'editgroup':
|
||||
case 'editgroup_desc':
|
||||
case 'translategroup':
|
||||
if (empty($gid)) {
|
||||
safeDie("No GID provided.");
|
||||
}
|
||||
|
||||
if ($question['gid'] == $gid) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
|
||||
case 'addquestion':
|
||||
if (empty($gid)) {
|
||||
safeDie("No GID provided.");
|
||||
}
|
||||
|
||||
if (!is_null($previousQuestion) && $previousQuestion['gid'] == $gid && $question['gid'] != $gid ) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
|
||||
case 'editanswer':
|
||||
case 'copyquestion':
|
||||
case 'editquestion':
|
||||
case 'translatequestion':
|
||||
case 'translateanswer':
|
||||
if (empty($gid)) {
|
||||
safeDie("No GID provided.");
|
||||
}
|
||||
if (empty($qid)) {
|
||||
safeDie("No QID provided.");
|
||||
}
|
||||
|
||||
if ($question['gid'] == $gid && $question['qid'] == $qid) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
case 'emailtemplates':
|
||||
// this is the case for email-conf
|
||||
return true;
|
||||
default:
|
||||
safeDie("No Action provided.");
|
||||
}
|
||||
}
|
||||
|
||||
private function _addQuestionToList($action, $gid, array $field, $questionType, $surveyformat, $isPreviousPageQuestion, &$questionList)
|
||||
{
|
||||
if ($action == 'tokens' && $questionType == 'email-conf' || $surveyformat == "S") {
|
||||
$isPreviousPageQuestion = true;
|
||||
}
|
||||
elseif ($surveyformat == "G")
|
||||
{
|
||||
if ($isPreviousPageQuestion === true) { // Last question was on a previous page
|
||||
if ($field["gid"] == $gid) { // This question is on same page
|
||||
$isPreviousPageQuestion = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
elseif ($surveyformat == "A")
|
||||
{
|
||||
$isPreviousPageQuestion = false;
|
||||
}
|
||||
|
||||
$questionList[] = array_merge($field, Array("previouspage" => $isPreviousPageQuestion));
|
||||
|
||||
return $isPreviousPageQuestion;
|
||||
}
|
||||
|
||||
private function _getChildQuestions(array $questions)
|
||||
{
|
||||
$cquestions = array();
|
||||
|
||||
foreach ($questions as $row)
|
||||
{
|
||||
$question = $row['question'];
|
||||
|
||||
if (isset($row['subquestion'])) {
|
||||
$question = "[{$row['subquestion']}] " . $question;
|
||||
}
|
||||
if (isset($row['subquestion1'])) {
|
||||
$question = "[{$row['subquestion1']}] " . $question;
|
||||
}
|
||||
if (isset($row['subquestion2'])) {
|
||||
$question = "[{$row['subquestion2']}] " . $question;
|
||||
}
|
||||
|
||||
$shortquestion = $row['title'] . ": " . flattenText($question);
|
||||
$cquestions[] = array($shortquestion, $row['qid'], $row['type'], $row['fieldname'], $row['previouspage']);
|
||||
}
|
||||
return $cquestions;
|
||||
}
|
||||
|
||||
private function _getReplacementFields($fieldtype, $surveyid)
|
||||
{
|
||||
$clang = Yii::app()->lang;
|
||||
$replFields = array();
|
||||
|
||||
switch ($fieldtype)
|
||||
{
|
||||
case 'survey-desc':
|
||||
case 'survey-welc':
|
||||
case 'survey-endtext':
|
||||
case 'edittitle': // for translation
|
||||
case 'editdescription': // for translation
|
||||
case 'editwelcome': // for translation
|
||||
case 'editend': // for translation
|
||||
$replFields[] = array('TOKEN:FIRSTNAME', $clang->gT("First name from token"));
|
||||
$replFields[] = array('TOKEN:LASTNAME', $clang->gT("Last name from token"));
|
||||
$replFields[] = array('TOKEN:EMAIL', $clang->gT("Email from the token"));
|
||||
$attributes = getTokenFieldsAndNames($surveyid, true);
|
||||
foreach ($attributes as $attributefield => $attributedescription)
|
||||
{
|
||||
$replFields[] = array('TOKEN:' . strtoupper($attributefield), sprintf($clang->gT("Token attribute: %s"), $attributedescription['description']));
|
||||
}
|
||||
$replFields[] = array('EXPIRY', $clang->gT("Survey expiration date"));
|
||||
return array($replFields, false);
|
||||
|
||||
case 'email-admin_notification':
|
||||
case 'email-admin_detailed_notification':
|
||||
$replFields[] = array('RELOADURL', $clang->gT("Reload URL"));
|
||||
$replFields[] = array('VIEWRESPONSEURL', $clang->gT("View response URL"));
|
||||
$replFields[] = array('EDITRESPONSEURL', $clang->gT("Edit response URL"));
|
||||
$replFields[] = array('STATISTICSURL', $clang->gT("Statistics URL"));
|
||||
$replFields[] = array('TOKEN', $clang->gT("Token code for this participant"));
|
||||
$replFields[] = array('TOKEN:FIRSTNAME', $clang->gT("First name from token"));
|
||||
$replFields[] = array('TOKEN:LASTNAME', $clang->gT("Last name from token"));
|
||||
$replFields[] = array('SURVEYNAME', $clang->gT("Name of the survey"));
|
||||
$replFields[] = array('SURVEYDESCRIPTION', $clang->gT("Description of the survey"));
|
||||
$attributes = getTokenFieldsAndNames($surveyid, true);
|
||||
foreach ($attributes as $attributefield => $attributedescription)
|
||||
{
|
||||
$replFields[] = array(strtoupper($attributefield), sprintf($clang->gT("Token attribute: %s"), $attributedescription['description']));
|
||||
}
|
||||
$replFields[] = array('ADMINNAME', $clang->gT("Name of the survey administrator"));
|
||||
$replFields[] = array('ADMINEMAIL', $clang->gT("Email address of the survey administrator"));
|
||||
return array($replFields, false);
|
||||
|
||||
case 'email-admin-resp':
|
||||
$replFields[] = array('RELOADURL', $clang->gT("Reload URL"));
|
||||
$replFields[] = array('VIEWRESPONSEURL', $clang->gT("View response URL"));
|
||||
$replFields[] = array('EDITRESPONSEURL', $clang->gT("Edit response URL"));
|
||||
$replFields[] = array('STATISTICSURL', $clang->gT("Statistics URL"));
|
||||
$replFields[] = array('ANSWERTABLE', $clang->gT("Answers from this response"));
|
||||
$replFields[] = array('TOKEN', $clang->gT("Token code for this participant"));
|
||||
$replFields[] = array('TOKEN:FIRSTNAME', $clang->gT("First name from token"));
|
||||
$replFields[] = array('TOKEN:LASTNAME', $clang->gT("Last name from token"));
|
||||
$replFields[] = array('SURVEYNAME', $clang->gT("Name of the survey"));
|
||||
$replFields[] = array('SURVEYDESCRIPTION', $clang->gT("Description of the survey"));
|
||||
$attributes = getTokenFieldsAndNames($surveyid, true);
|
||||
foreach ($attributes as $attributefield => $attributedescription)
|
||||
{
|
||||
$replFields[] = array(strtoupper($attributefield), sprintf($clang->gT("Token attribute: %s"), $attributedescription['description']));
|
||||
}
|
||||
$replFields[] = array('ADMINNAME', $clang->gT("Name of the survey administrator"));
|
||||
$replFields[] = array('ADMINEMAIL', $clang->gT("Email address of the survey administrator"));
|
||||
return array($replFields, false);
|
||||
|
||||
case 'email-invitation':
|
||||
case 'email-reminder':
|
||||
// these 2 fields are supported by email-inv and email-rem
|
||||
// but not email-reg for the moment
|
||||
$replFields[] = array('EMAIL', $clang->gT("Email from the token"));
|
||||
$replFields[] = array('TOKEN', $clang->gT("Token code for this participant"));
|
||||
$replFields[] = array('OPTOUTURL', $clang->gT("URL for a respondent to opt-out of this survey"));
|
||||
$replFields[] = array('OPTINURL', $clang->gT("URL for a respondent to opt-in to this survey"));
|
||||
case 'email-registration':
|
||||
$replFields[] = array('FIRSTNAME', $clang->gT("First name from token"));
|
||||
$replFields[] = array('LASTNAME', $clang->gT("Last name from token"));
|
||||
$replFields[] = array('SURVEYNAME', $clang->gT("Name of the survey"));
|
||||
$replFields[] = array('SURVEYDESCRIPTION', $clang->gT("Description of the survey"));
|
||||
$attributes = getTokenFieldsAndNames($surveyid, true);
|
||||
foreach ($attributes as $attributefield => $attributedescription)
|
||||
{
|
||||
$replFields[] = array(strtoupper($attributefield), sprintf($clang->gT("Token attribute: %s"), $attributedescription['description']));
|
||||
}
|
||||
$replFields[] = array('ADMINNAME', $clang->gT("Name of the survey administrator"));
|
||||
$replFields[] = array('ADMINEMAIL', $clang->gT("Email address of the survey administrator"));
|
||||
$replFields[] = array('SURVEYURL', $clang->gT("URL of the survey"));
|
||||
$replFields[] = array('EXPIRY', $clang->gT("Survey expiration date"));
|
||||
return array($replFields, false);
|
||||
|
||||
case 'email-confirmation':
|
||||
$replFields[] = array('TOKEN', $clang->gT("Token code for this participant"));
|
||||
$replFields[] = array('FIRSTNAME', $clang->gT("First name from token"));
|
||||
$replFields[] = array('LASTNAME', $clang->gT("Last name from token"));
|
||||
$replFields[] = array('SURVEYNAME', $clang->gT("Name of the survey"));
|
||||
$replFields[] = array('SURVEYDESCRIPTION', $clang->gT("Description of the survey"));
|
||||
$attributes = getTokenFieldsAndNames($surveyid, true);
|
||||
foreach ($attributes as $attributefield => $attributedescription)
|
||||
{
|
||||
$replFields[] = array(strtoupper($attributefield), sprintf($clang->gT("Token attribute: %s"), $attributedescription['description']));
|
||||
}
|
||||
$replFields[] = array('ADMINNAME', $clang->gT("Name of the survey administrator"));
|
||||
$replFields[] = array('ADMINEMAIL', $clang->gT("Email address of the survey administrator"));
|
||||
$replFields[] = array('SURVEYURL', $clang->gT("URL of the survey"));
|
||||
$replFields[] = array('EXPIRY', $clang->gT("Survey expiration date"));
|
||||
|
||||
// email-conf can accept insertans fields for non anonymous surveys
|
||||
if (isset($surveyid)) {
|
||||
$surveyInfo = getSurveyInfo($surveyid);
|
||||
if ($surveyInfo['anonymized'] == "N") {
|
||||
return array($replFields, true);
|
||||
}
|
||||
}
|
||||
return array($replFields, false);
|
||||
|
||||
case 'group-desc':
|
||||
case 'question-text':
|
||||
case 'question-help':
|
||||
case 'editgroup': // for translation
|
||||
case 'editgroup_desc': // for translation
|
||||
case 'editquestion': // for translation
|
||||
case 'editquestion_help': // for translation
|
||||
$replFields[] = array('TOKEN:FIRSTNAME', $clang->gT("First name from token"));
|
||||
$replFields[] = array('TOKEN:LASTNAME', $clang->gT("Last name from token"));
|
||||
$replFields[] = array('TOKEN:EMAIL', $clang->gT("Email from the token"));
|
||||
$replFields[] = array('SID', $clang->gT("This question's survey ID number"));
|
||||
$replFields[] = array('GID', $clang->gT("This question's group ID number"));
|
||||
$replFields[] = array('QID', $clang->gT("This question's question ID number"));
|
||||
$replFields[] = array('SGQ', $clang->gT("This question's SGQA code"));
|
||||
$attributes = getTokenFieldsAndNames($surveyid, true);
|
||||
foreach ($attributes as $attributefield => $attributedescription)
|
||||
{
|
||||
$replFields[] = array('TOKEN:' . strtoupper($attributefield), sprintf($clang->gT("Token attribute: %s"), $attributedescription['description']));
|
||||
}
|
||||
$replFields[] = array('EXPIRY', $clang->gT("Survey expiration date"));
|
||||
case 'editanswer':
|
||||
return array($replFields, true);
|
||||
|
||||
case 'assessment-text':
|
||||
$replFields[] = array('TOTAL', $clang->gT("Overall assessment score"));
|
||||
$replFields[] = array('PERC', $clang->gT("Assessment group score"));
|
||||
return array($replFields, false);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
1772
sources/application/controllers/admin/participantsaction.php
Normal file
1772
sources/application/controllers/admin/participantsaction.php
Normal file
File diff suppressed because it is too large
Load diff
1789
sources/application/controllers/admin/printablesurvey.php
Normal file
1789
sources/application/controllers/admin/printablesurvey.php
Normal file
File diff suppressed because it is too large
Load diff
416
sources/application/controllers/admin/questiongroups.php
Normal file
416
sources/application/controllers/admin/questiongroups.php
Normal file
|
@ -0,0 +1,416 @@
|
|||
<?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.
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* questiongroup
|
||||
*
|
||||
* @package LimeSurvey
|
||||
* @author
|
||||
* @copyright 2011
|
||||
* @access public
|
||||
*/
|
||||
class questiongroups extends Survey_Common_Action
|
||||
{
|
||||
|
||||
/**
|
||||
* questiongroup::import()
|
||||
* Function responsible to import a question group.
|
||||
*
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
function import()
|
||||
{
|
||||
$action = $_POST['action'];
|
||||
$surveyid = $_POST['sid'];
|
||||
$clang = $this->getController()->lang;
|
||||
|
||||
if ($action == 'importgroup')
|
||||
{
|
||||
$importgroup = "\n";
|
||||
$importgroup .= "\n";
|
||||
|
||||
$sFullFilepath = Yii::app()->getConfig('tempdir') . DIRECTORY_SEPARATOR . randomChars(20);
|
||||
$aPathInfo = pathinfo($_FILES['the_file']['name']);
|
||||
$sExtension = $aPathInfo['extension'];
|
||||
|
||||
if (!@move_uploaded_file($_FILES['the_file']['tmp_name'], $sFullFilepath))
|
||||
{
|
||||
$fatalerror = sprintf($clang->gT("An error occurred uploading your file. This may be caused by incorrect permissions in your %s folder."), $this->config->item('tempdir'));
|
||||
}
|
||||
|
||||
// validate that we have a SID
|
||||
if (!returnGlobal('sid'))
|
||||
$fatalerror .= $clang->gT("No SID (Survey) has been provided. Cannot import question.");
|
||||
|
||||
if (isset($fatalerror))
|
||||
{
|
||||
@unlink($sFullFilepath);
|
||||
$this->getController()->error($fatalerror);
|
||||
}
|
||||
|
||||
Yii::app()->loadHelper('admin/import');
|
||||
|
||||
// IF WE GOT THIS FAR, THEN THE FILE HAS BEEN UPLOADED SUCCESFULLY
|
||||
if (strtolower($sExtension) == 'csv')
|
||||
$aImportResults = CSVImportGroup($sFullFilepath, $surveyid);
|
||||
elseif (strtolower($sExtension) == 'lsg')
|
||||
$aImportResults = XMLImportGroup($sFullFilepath, $surveyid);
|
||||
else
|
||||
$this->getController()->error('Unknown file extension');
|
||||
LimeExpressionManager::SetDirtyFlag(); // so refreshes syntax highlighting
|
||||
fixLanguageConsistency($surveyid);
|
||||
|
||||
if (isset($aImportResults['fatalerror']))
|
||||
{
|
||||
unlink($sFullFilepath);
|
||||
$this->getController()->error($aImportResults['fatalerror']);
|
||||
}
|
||||
|
||||
unlink($sFullFilepath);
|
||||
|
||||
$aData['display'] = $importgroup;
|
||||
$aData['surveyid'] = $surveyid;
|
||||
$aData['aImportResults'] = $aImportResults;
|
||||
$aData['sExtension'] = $sExtension;
|
||||
//$aData['display']['menu_bars']['surveysummary'] = 'importgroup';
|
||||
|
||||
$this->_renderWrappedTemplate('survey/QuestionGroups', 'import_view', $aData);
|
||||
// TMSW Condition->Relevance: call LEM->ConvertConditionsToRelevance() after import
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* questiongroup::add()
|
||||
* Load add new question group screen.
|
||||
* @return
|
||||
*/
|
||||
function add($surveyid)
|
||||
{
|
||||
$surveyid = sanitize_int($surveyid);
|
||||
$aViewUrls = $aData = array();
|
||||
|
||||
if (Permission::model()->hasSurveyPermission($surveyid, 'surveycontent', 'read'))
|
||||
{
|
||||
$clang = $this->getController()->lang;
|
||||
|
||||
Yii::app()->session['FileManagerContext'] = "create:group:{$surveyid}";
|
||||
|
||||
Yii::app()->loadHelper('admin/htmleditor');
|
||||
Yii::app()->loadHelper('surveytranslator');
|
||||
$grplangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
|
||||
$baselang = Survey::model()->findByPk($surveyid)->language;
|
||||
$grplangs[] = $baselang;
|
||||
$grplangs = array_reverse($grplangs);
|
||||
App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . 'questiongroup.js');
|
||||
|
||||
$aData['display']['menu_bars']['surveysummary'] = 'addgroup';
|
||||
$aData['surveyid'] = $surveyid;
|
||||
$aData['action'] = $aData['display']['menu_bars']['gid_action'] = 'addgroup';
|
||||
$aData['grplangs'] = $grplangs;
|
||||
$aData['baselang'] = $baselang;
|
||||
|
||||
$this->_renderWrappedTemplate('survey/QuestionGroups', 'addGroup_view', $aData);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert the new group to the database
|
||||
*
|
||||
* @access public
|
||||
* @param int $surveyid
|
||||
* @return void
|
||||
*/
|
||||
public function insert($surveyid)
|
||||
{
|
||||
if (Permission::model()->hasSurveyPermission($surveyid, 'surveycontent', 'create'))
|
||||
{
|
||||
Yii::app()->loadHelper('surveytranslator');
|
||||
|
||||
$grplangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
|
||||
$baselang = Survey::model()->findByPk($surveyid)->language;
|
||||
|
||||
$grplangs[] = $baselang;
|
||||
$errorstring = '';
|
||||
foreach ($grplangs as $grouplang)
|
||||
if (empty($_POST['group_name_' . $grouplang]))
|
||||
$errorstring.= getLanguageNameFromCode($grouplang, false) . "\\n";
|
||||
|
||||
if ($errorstring != '')
|
||||
$this->getController()->redirect(array('admin/survey/sa/view/surveyid/' . $surveyid));
|
||||
|
||||
else
|
||||
{
|
||||
$first = true;
|
||||
foreach ($grplangs as $grouplang)
|
||||
{
|
||||
//Clean XSS
|
||||
$group_name = $_POST['group_name_' . $grouplang];
|
||||
$group_description = $_POST['description_' . $grouplang];
|
||||
|
||||
$group_name = html_entity_decode($group_name, ENT_QUOTES, "UTF-8");
|
||||
$group_description = html_entity_decode($group_description, ENT_QUOTES, "UTF-8");
|
||||
|
||||
// Fix bug with FCKEditor saving strange BR types
|
||||
$group_name = fixCKeditorText($group_name);
|
||||
$group_description = fixCKeditorText($group_description);
|
||||
|
||||
|
||||
if ($first)
|
||||
{
|
||||
$aData = array(
|
||||
'sid' => $surveyid,
|
||||
'group_name' => $group_name,
|
||||
'description' => $group_description,
|
||||
'group_order' => getMaxGroupOrder($surveyid),
|
||||
'language' => $grouplang,
|
||||
'randomization_group' => $_POST['randomization_group'],
|
||||
'grelevance' => $_POST['grelevance'],
|
||||
);
|
||||
|
||||
$group = new QuestionGroup;
|
||||
foreach ($aData as $k => $v)
|
||||
$group->$k = $v;
|
||||
$group->save();
|
||||
$groupid = $group->gid;
|
||||
$first = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
switchMSSQLIdentityInsert('groups',true);
|
||||
$aData = array(
|
||||
'gid' => $groupid,
|
||||
'sid' => $surveyid,
|
||||
'group_name' => $group_name,
|
||||
'description' => $group_description,
|
||||
'group_order' => getMaxGroupOrder($surveyid),
|
||||
'language' => $grouplang,
|
||||
'randomization_group' => $_POST['randomization_group']
|
||||
);
|
||||
|
||||
$group = new QuestionGroup;
|
||||
foreach ($aData as $k => $v)
|
||||
$group->$k = $v;
|
||||
$group->save();
|
||||
switchMSSQLIdentityInsert('groups',false);
|
||||
}
|
||||
}
|
||||
// This line sets the newly inserted group as the new group
|
||||
if (isset($groupid))
|
||||
$gid = $groupid;
|
||||
Yii::app()->session['flashmessage'] = Yii::app()->lang->gT("New question group was saved.");
|
||||
}
|
||||
$this->getController()->redirect(array('admin/survey/sa/view/surveyid/' . $surveyid . '/gid/' . $gid));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Action to delete a question group.
|
||||
*
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function delete($iSurveyId, $iGroupId)
|
||||
{
|
||||
$iSurveyId = sanitize_int($iSurveyId);
|
||||
|
||||
if (Permission::model()->hasSurveyPermission($iSurveyId, 'surveycontent', 'delete'))
|
||||
{
|
||||
LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyId);
|
||||
|
||||
$iGroupId = sanitize_int($iGroupId);
|
||||
$clang = $this->getController()->lang;
|
||||
|
||||
$iGroupsDeleted = QuestionGroup::deleteWithDependency($iGroupId, $iSurveyId);
|
||||
|
||||
if ($iGroupsDeleted > 0)
|
||||
{
|
||||
fixSortOrderGroups($iSurveyId);
|
||||
Yii::app()->setFlashMessage($clang->gT('The question group was deleted.'));
|
||||
}
|
||||
else
|
||||
Yii::app()->setFlashMessage($clang->gT('Group could not be deleted'),'error');
|
||||
LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyId);
|
||||
$this->getController()->redirect(array('admin/survey/sa/view/surveyid/' . $iSurveyId));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* questiongroup::edit()
|
||||
* Load editing of a question group screen.
|
||||
*
|
||||
* @access public
|
||||
* @param int $surveyid
|
||||
* @param int $gid
|
||||
* @return void
|
||||
*/
|
||||
public function edit($surveyid, $gid)
|
||||
{
|
||||
$clang = $this->getController()->lang;
|
||||
$surveyid = sanitize_int($surveyid);
|
||||
$gid = sanitize_int($gid);
|
||||
$aViewUrls = $aData = array();
|
||||
|
||||
if (Permission::model()->hasSurveyPermission($surveyid, 'surveycontent', 'read'))
|
||||
{
|
||||
Yii::app()->session['FileManagerContext'] = "edit:group:{$surveyid}";
|
||||
|
||||
Yii::app()->loadHelper('admin/htmleditor');
|
||||
Yii::app()->loadHelper('surveytranslator');
|
||||
|
||||
$aAdditionalLanguages = Survey::model()->findByPk($surveyid)->additionalLanguages;
|
||||
$aBaseLanguage = Survey::model()->findByPk($surveyid)->language;
|
||||
|
||||
$aLanguages = array_merge(array($aBaseLanguage), $aAdditionalLanguages);
|
||||
|
||||
$grplangs = array_flip($aLanguages);
|
||||
|
||||
// Check out the intgrity of the language versions of this group
|
||||
$egresult = QuestionGroup::model()->findAllByAttributes(array('sid' => $surveyid, 'gid' => $gid));
|
||||
foreach ($egresult as $esrow)
|
||||
{
|
||||
$esrow = $esrow->attributes;
|
||||
|
||||
// Language Exists, BUT ITS NOT ON THE SURVEY ANYMORE
|
||||
if (!in_array($esrow['language'], $aLanguages))
|
||||
{
|
||||
QuestionGroup::model()->deleteAllByAttributes(array('sid' => $surveyid, 'gid' => $gid, 'language' => $esrow['language']));
|
||||
}
|
||||
else
|
||||
{
|
||||
$grplangs[$esrow['language']] = 'exists';
|
||||
}
|
||||
|
||||
if ($esrow['language'] == $aBaseLanguage)
|
||||
$basesettings = $esrow;
|
||||
}
|
||||
|
||||
// Create groups in missing languages
|
||||
while (list($key, $value) = each($grplangs))
|
||||
{
|
||||
if ($value != 'exists')
|
||||
{
|
||||
$basesettings['language'] = $key;
|
||||
$group = new QuestionGroup;
|
||||
foreach ($basesettings as $k => $v)
|
||||
$group->$k = $v;
|
||||
switchMSSQLIdentityInsert('groups', true);
|
||||
$group->save();
|
||||
switchMSSQLIdentityInsert('groups', false);
|
||||
}
|
||||
}
|
||||
$first = true;
|
||||
foreach ($aLanguages as $sLanguage)
|
||||
{
|
||||
$oResult = QuestionGroup::model()->findByAttributes(array('sid' => $surveyid, 'gid' => $gid, 'language' => $sLanguage));
|
||||
$aData['aGroupData'][$sLanguage] = $oResult->attributes;
|
||||
$aTabTitles[$sLanguage] = getLanguageNameFromCode($sLanguage, false);
|
||||
if ($first)
|
||||
{
|
||||
$aTabTitles[$sLanguage].= ' (' . $clang->gT("Base language") . ')';
|
||||
$first = false;
|
||||
}
|
||||
}
|
||||
|
||||
$aData['action'] = $aData['display']['menu_bars']['gid_action'] = 'editgroup';
|
||||
$aData['surveyid'] = $surveyid;
|
||||
$aData['gid'] = $gid;
|
||||
$aData['tabtitles'] = $aTabTitles;
|
||||
$aData['aBaseLanguage'] = $aBaseLanguage;
|
||||
|
||||
$this->_renderWrappedTemplate('survey/QuestionGroups', 'editGroup_view', $aData);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides an interface for updating a group
|
||||
*
|
||||
* @access public
|
||||
* @param int $gid
|
||||
* @return void
|
||||
*/
|
||||
public function update($gid)
|
||||
{
|
||||
$gid = (int) $gid;
|
||||
|
||||
$group = QuestionGroup::model()->findByAttributes(array('gid' => $gid));
|
||||
$surveyid = $group->sid;
|
||||
|
||||
if (Permission::model()->hasSurveyPermission($surveyid, 'surveycontent', 'update'))
|
||||
{
|
||||
Yii::app()->loadHelper('surveytranslator');
|
||||
|
||||
$grplangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
|
||||
$baselang = Survey::model()->findByPk($surveyid)->language;
|
||||
|
||||
array_push($grplangs, $baselang);
|
||||
|
||||
foreach ($grplangs as $grplang)
|
||||
{
|
||||
if (isset($grplang) && $grplang != "")
|
||||
{
|
||||
$group_name = $_POST['group_name_' . $grplang];
|
||||
$group_description = $_POST['description_' . $grplang];
|
||||
|
||||
$group_name = html_entity_decode($group_name, ENT_QUOTES, "UTF-8");
|
||||
$group_description = html_entity_decode($group_description, ENT_QUOTES, "UTF-8");
|
||||
|
||||
// Fix bug with FCKEditor saving strange BR types
|
||||
$group_name = fixCKeditorText($group_name);
|
||||
$group_description = fixCKeditorText($group_description);
|
||||
|
||||
$aData = array(
|
||||
'group_name' => $group_name,
|
||||
'description' => $group_description,
|
||||
'randomization_group' => $_POST['randomization_group'],
|
||||
'grelevance' => $_POST['grelevance'],
|
||||
);
|
||||
$condition = array(
|
||||
'gid' => $gid,
|
||||
'sid' => $surveyid,
|
||||
'language' => $grplang
|
||||
);
|
||||
$group = QuestionGroup::model()->findByAttributes($condition);
|
||||
foreach ($aData as $k => $v)
|
||||
$group->$k = $v;
|
||||
$ugresult = $group->save();
|
||||
if ($ugresult)
|
||||
{
|
||||
$groupsummary = getGroupList($gid, $surveyid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Yii::app()->session['flashmessage'] = Yii::app()->lang->gT("Question group successfully saved.");
|
||||
$this->getController()->redirect(array('admin/survey/sa/view/surveyid/' . $surveyid . '/gid/' . $gid));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders template(s) wrapped in header and footer
|
||||
*
|
||||
* @param string $sAction Current action, the folder to fetch views from
|
||||
* @param string|array $aViewUrls View url(s)
|
||||
* @param array $aData Data to be passed on. Optional.
|
||||
*/
|
||||
protected function _renderWrappedTemplate($sAction = 'survey/QuestionGroups', $aViewUrls = array(), $aData = array())
|
||||
{
|
||||
App()->getClientScript()->registerPackage('jquery-superfish');
|
||||
parent::_renderWrappedTemplate($sAction, $aViewUrls, $aData);
|
||||
}
|
||||
}
|
1312
sources/application/controllers/admin/questions.php
Normal file
1312
sources/application/controllers/admin/questions.php
Normal file
File diff suppressed because it is too large
Load diff
562
sources/application/controllers/admin/quotas.php
Normal file
562
sources/application/controllers/admin/quotas.php
Normal file
|
@ -0,0 +1,562 @@
|
|||
<?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.
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* Quotas Controller
|
||||
*
|
||||
* This controller performs quota actions
|
||||
*
|
||||
* @package LimeSurvey
|
||||
* @subpackage Backend
|
||||
*/
|
||||
class quotas extends Survey_Common_Action
|
||||
{
|
||||
|
||||
function __construct($controller, $id)
|
||||
{
|
||||
parent::__construct($controller, $id);
|
||||
|
||||
// Load helpers
|
||||
Yii::app()->loadHelper('surveytranslator');
|
||||
// Sanitize/get globals/variables
|
||||
$_POST['quotamax'] = sanitize_int(Yii::app()->request->getPost('quotamax'));
|
||||
|
||||
if (empty($_POST['autoload_url']))
|
||||
{
|
||||
$_POST['autoload_url'] = 0;
|
||||
}
|
||||
|
||||
if (empty($_POST['quota_limit']) || !is_numeric(Yii::app()->request->getPost('quota_limit')) || Yii::app()->request->getPost('quota_limit') < 0)
|
||||
{
|
||||
$_POST['quota_limit'] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
private function _getData($iSurveyId)
|
||||
{
|
||||
// Set the variables in an array
|
||||
$aData['iSurveyId'] = $aData['surveyid'] = $iSurveyId;
|
||||
$aData['clang'] = $this->getController()->lang;
|
||||
$aData['sBaseLang'] = Survey::model()->findByPk($iSurveyId)->language;
|
||||
$aData['aLangs'] = Survey::model()->findByPk($iSurveyId)->additionalLanguages;
|
||||
array_unshift($aData['aLangs'], $aData['sBaseLang']);
|
||||
|
||||
$aData['action'] = $action = Yii::app()->request->getParam('action');
|
||||
if (!isset($action))
|
||||
$aData['action'] = 'quotas';
|
||||
|
||||
return $aData;
|
||||
}
|
||||
|
||||
private function _checkPermissions($iSurveyId, $sPermission)
|
||||
{
|
||||
$clang=$this->getController()->lang;
|
||||
if (!empty($sPermission) && !(Permission::model()->hasSurveyPermission($iSurveyId, 'quotas', $sPermission))) {
|
||||
Yii::app()->session['flashmessage'] = $clang->gT('Access denied!');
|
||||
$this->_redirectToIndex($iSurveyId);
|
||||
}
|
||||
}
|
||||
|
||||
function _redirectToIndex($iSurveyId)
|
||||
{
|
||||
$clang=$this->getController()->lang;
|
||||
if(Permission::model()->hasSurveyPermission($iSurveyId, 'quotas','read'))
|
||||
{
|
||||
$this->getController()->redirect($this->getController()->createUrl("/admin/quotas/sa/index/surveyid/$iSurveyId"));
|
||||
}
|
||||
else
|
||||
{
|
||||
Yii::app()->session['flashmessage'] = $clang->gT('Access denied!');
|
||||
$this->getController()->redirect($this->getController()->createUrl("admin/survey/sa/view/surveyid/$iSurveyId"));
|
||||
}
|
||||
}
|
||||
|
||||
function index($iSurveyId, $quickreport = false)
|
||||
{
|
||||
$iSurveyId = sanitize_int($iSurveyId);
|
||||
$this->_checkPermissions($iSurveyId, 'read');
|
||||
$aData = $this->_getData($iSurveyId);
|
||||
$aViewUrls = array();
|
||||
|
||||
if ($quickreport == false)
|
||||
{
|
||||
$aViewUrls[] = 'viewquotas_view';
|
||||
}
|
||||
|
||||
$clang = $aData['clang'];
|
||||
$totalquotas = 0;
|
||||
$totalcompleted = 0;
|
||||
$csvoutput = array();
|
||||
|
||||
$criteria = new CDbCriteria;
|
||||
$criteria->select = '*';
|
||||
$criteria->join = 'LEFT JOIN {{quota_languagesettings}} as qls ON (t.id = qls.quotals_quota_id)';
|
||||
$criteria->condition = 'sid=:survey AND quotals_language=:lang';
|
||||
$criteria->params = array(':survey' => $iSurveyId, ':lang' => $aData['sBaseLang']);
|
||||
$criteria->order = 'name';
|
||||
$aResult = Quota::model()->findAll($criteria);
|
||||
|
||||
//if there are quotas let's proceed
|
||||
if (count($aResult) > 0)
|
||||
{
|
||||
$aViewUrls['output'] = '';
|
||||
//loop through all quotas
|
||||
foreach ($aResult as $aQuotaListing)
|
||||
{
|
||||
$totalquotas += $aQuotaListing['qlimit'];
|
||||
$completed = getQuotaCompletedCount($iSurveyId, $aQuotaListing['id']);
|
||||
$highlight = ($completed >= $aQuotaListing['qlimit']) ? '' : "style='color: orange'"; //Incomplete quotas displayed in red
|
||||
$totalcompleted = $totalcompleted + $completed;
|
||||
$csvoutput[] = $aQuotaListing['name'] . "," . $aQuotaListing['qlimit'] . "," . $completed . "," . ($aQuotaListing['qlimit'] - $completed) . "\r\n";
|
||||
|
||||
if ($quickreport != false)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
$aData['quotalisting'] = $aQuotaListing;
|
||||
$aData['highlight'] = $highlight;
|
||||
$aData['completed'] = $completed;
|
||||
$aData['totalquotas'] = $totalquotas;
|
||||
$aData['totalcompleted'] = $totalcompleted;
|
||||
$aViewUrls['output'] .= $this->getController()->renderPartial("/admin/quotas/viewquotasrow_view", $aData, true);
|
||||
|
||||
//check how many sub-elements exist for a certain quota
|
||||
$aResults2 = QuotaMember::model()->findAllByAttributes(array('quota_id' => $aQuotaListing['id']));
|
||||
|
||||
//loop through all sub-parts
|
||||
foreach ($aResults2 as $aQuotaQuestions)
|
||||
{
|
||||
$aQuestionAnswers = self::getQuotaAnswers($aQuotaQuestions['qid'], $iSurveyId, $aQuotaListing['id']);
|
||||
$aData['question_answers'] = $aQuestionAnswers;
|
||||
$aData['quota_questions'] = $aQuotaQuestions;
|
||||
$aViewUrls['output'] .= $this->getController()->renderPartial('/admin/quotas/viewquotasrowsub_view', $aData, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// No quotas have been set for this survey
|
||||
$aViewUrls[] = 'viewquotasempty_view';
|
||||
}
|
||||
|
||||
$aData['totalquotas'] = $totalquotas;
|
||||
$aData['totalcompleted'] = $totalcompleted;
|
||||
|
||||
if ($quickreport == false)
|
||||
{
|
||||
$aViewUrls[] = 'viewquotasfooter_view';
|
||||
$this->_renderWrappedTemplate('quotas', $aViewUrls, $aData);
|
||||
}
|
||||
else
|
||||
{
|
||||
header("Content-Disposition: attachment; filename=results-survey" . $iSurveyId . ".csv");
|
||||
header("Content-type: text/comma-separated-values; charset=UTF-8");
|
||||
header("Pragma: public");
|
||||
echo $clang->gT("Quota name") . "," . $clang->gT("Limit") . "," . $clang->gT("Completed") . "," . $clang->gT("Remaining") . "\r\n";
|
||||
foreach ($csvoutput as $line)
|
||||
{
|
||||
echo $line;
|
||||
}
|
||||
die;
|
||||
}
|
||||
}
|
||||
|
||||
function insertquota($iSurveyId)
|
||||
{
|
||||
$iSurveyId = sanitize_int($iSurveyId);
|
||||
$this->_checkPermissions($iSurveyId, 'create');
|
||||
$aData = $this->_getData($iSurveyId);
|
||||
$aLangs = $aData['aLangs'];
|
||||
|
||||
$oQuota = new Quota;
|
||||
$oQuota->sid = $iSurveyId;
|
||||
$oQuota->name = Yii::app()->request->getPost('quota_name');
|
||||
$oQuota->qlimit = Yii::app()->request->getPost('quota_limit');
|
||||
$oQuota->action = Yii::app()->request->getPost('quota_action');
|
||||
$oQuota->autoload_url = Yii::app()->request->getPost('autoload_url');
|
||||
$oQuota->save();
|
||||
$iQuotaId = $oQuota->id;
|
||||
|
||||
//Iterate through each language, and make sure there is a quota message for it
|
||||
$sError = '';
|
||||
foreach ($aLangs as $sLang)
|
||||
{
|
||||
if (!$_POST['quotals_message_' . $sLang])
|
||||
{
|
||||
$sError .= getLanguageNameFromCode($sLang, false) . "\\n";
|
||||
}
|
||||
}
|
||||
if ($sError != '')
|
||||
{
|
||||
$aData['sShowError'] = $sError;
|
||||
}
|
||||
else
|
||||
//All the required quota messages exist, now we can insert this info into the database
|
||||
{
|
||||
|
||||
foreach ($aLangs as $sLang) //Iterate through each language
|
||||
{
|
||||
//Clean XSS - Automatically provided by CI input class
|
||||
$_POST['quotals_message_' . $sLang] = html_entity_decode($_POST['quotals_message_' . $sLang], ENT_QUOTES, "UTF-8");
|
||||
|
||||
// Fix bug with FCKEditor saving strange BR types
|
||||
$_POST['quotals_message_' . $sLang] = fixCKeditorText($_POST['quotals_message_' . $sLang]);
|
||||
|
||||
$oQuotaLanguageSettings = new QuotaLanguageSetting;
|
||||
$oQuotaLanguageSettings->quotals_quota_id = $iQuotaId;
|
||||
$oQuotaLanguageSettings->quotals_language = $sLang;
|
||||
$oQuotaLanguageSettings->quotals_name = Yii::app()->request->getPost('quota_name');
|
||||
$oQuotaLanguageSettings->quotals_message = $_POST['quotals_message_' . $sLang];
|
||||
$oQuotaLanguageSettings->quotals_url = $_POST['quotals_url_' . $sLang];
|
||||
$oQuotaLanguageSettings->quotals_urldescrip = $_POST['quotals_urldescrip_' . $sLang];
|
||||
$oQuotaLanguageSettings->save();
|
||||
}
|
||||
}
|
||||
|
||||
self::_redirectToIndex($iSurveyId);
|
||||
}
|
||||
|
||||
function modifyquota($iSurveyId)
|
||||
{
|
||||
$iSurveyId = sanitize_int($iSurveyId);
|
||||
$this->_checkPermissions($iSurveyId, 'update');
|
||||
$aData = $this->_getData($iSurveyId);
|
||||
$aLangs = $aData['aLangs'];
|
||||
|
||||
$oQuota = Quota::model()->findByPk(Yii::app()->request->getPost('quota_id'));
|
||||
$oQuota->name = Yii::app()->request->getPost('quota_name');
|
||||
$oQuota->qlimit = Yii::app()->request->getPost('quota_limit');
|
||||
$oQuota->action = Yii::app()->request->getPost('quota_action');
|
||||
$oQuota->autoload_url = Yii::app()->request->getPost('autoload_url');
|
||||
$oQuota->save();
|
||||
|
||||
//Iterate through each language posted, and make sure there is a quota message for it
|
||||
$sError = '';
|
||||
foreach ($aLangs as $sLang)
|
||||
{
|
||||
if (!$_POST['quotals_message_' . $sLang])
|
||||
{
|
||||
$sError.= getLanguageNameFromCode($sLang, false) . "\\n";
|
||||
}
|
||||
}
|
||||
if ($sError != '')
|
||||
{
|
||||
$aData['sShowError'] = $sError;
|
||||
}
|
||||
else
|
||||
//All the required quota messages exist, now we can insert this info into the database
|
||||
{
|
||||
|
||||
foreach ($aLangs as $sLang) //Iterate through each language
|
||||
{
|
||||
//Clean XSS - Automatically provided by CI
|
||||
$_POST['quotals_message_' . $sLang] = html_entity_decode($_POST['quotals_message_' . $sLang], ENT_QUOTES, "UTF-8");
|
||||
|
||||
// Fix bug with FCKEditor saving strange BR types
|
||||
$_POST['quotals_message_' . $sLang] = fixCKeditorText($_POST['quotals_message_' . $sLang]);
|
||||
|
||||
$oQuotaLanguageSettings = QuotaLanguageSetting::model()->findByAttributes(array('quotals_quota_id' => Yii::app()->request->getPost('quota_id'), 'quotals_language' => $sLang));
|
||||
$oQuotaLanguageSettings->quotals_name = Yii::app()->request->getPost('quota_name');
|
||||
$oQuotaLanguageSettings->quotals_message = $_POST['quotals_message_' . $sLang];
|
||||
$oQuotaLanguageSettings->quotals_url = $_POST['quotals_url_' . $sLang];
|
||||
$oQuotaLanguageSettings->quotals_urldescrip = $_POST['quotals_urldescrip_' . $sLang];
|
||||
$oQuotaLanguageSettings->save();
|
||||
}
|
||||
} //End insert language based components
|
||||
|
||||
self::_redirectToIndex($iSurveyId);
|
||||
}
|
||||
|
||||
function insertquotaanswer($iSurveyId)
|
||||
{
|
||||
$iSurveyId = sanitize_int($iSurveyId);
|
||||
$this->_checkPermissions($iSurveyId, 'update');
|
||||
|
||||
$oQuotaMembers = new QuotaMember('create'); // Trigger the 'create' rules
|
||||
$oQuotaMembers->sid = $iSurveyId;
|
||||
$oQuotaMembers->qid = Yii::app()->request->getPost('quota_qid');
|
||||
$oQuotaMembers->quota_id = Yii::app()->request->getPost('quota_id');
|
||||
$oQuotaMembers->code = Yii::app()->request->getPost('quota_anscode');
|
||||
if ($oQuotaMembers->save()) {
|
||||
if (!empty($_POST['createanother']))
|
||||
{
|
||||
$_POST['action'] = "quotas";
|
||||
$_POST['subaction'] = "new_answer";
|
||||
$sSubAction = "new_answer";
|
||||
self::new_answer($iSurveyId, $sSubAction);
|
||||
}
|
||||
else
|
||||
{
|
||||
self::_redirectToIndex($iSurveyId);
|
||||
}
|
||||
} else {
|
||||
// Save was not successful, redirect back
|
||||
$_POST['action'] = "quotas";
|
||||
$_POST['subaction'] = "new_answer";
|
||||
$sSubAction = "new_answer_two";
|
||||
self::new_answer($iSurveyId, $sSubAction);
|
||||
}
|
||||
}
|
||||
|
||||
function delans($iSurveyId)
|
||||
{
|
||||
$iSurveyId = sanitize_int($iSurveyId);
|
||||
$this->_checkPermissions($iSurveyId, 'update');
|
||||
|
||||
QuotaMember::model()->deleteAllByAttributes(array(
|
||||
'id' => Yii::app()->request->getPost('quota_member_id'),
|
||||
'qid' => Yii::app()->request->getPost('quota_qid'),
|
||||
'code' => Yii::app()->request->getPost('quota_anscode'),
|
||||
));
|
||||
|
||||
self::_redirectToIndex($iSurveyId);
|
||||
}
|
||||
|
||||
function delquota($iSurveyId)
|
||||
{
|
||||
$iSurveyId = sanitize_int($iSurveyId);
|
||||
$this->_checkPermissions($iSurveyId, 'delete');
|
||||
|
||||
Quota::model()->deleteByPk(Yii::app()->request->getPost('quota_id'));
|
||||
QuotaLanguageSetting::model()->deleteAllByAttributes(array('quotals_quota_id' => Yii::app()->request->getPost('quota_id')));
|
||||
QuotaMember::model()->deleteAllByAttributes(array('quota_id' => Yii::app()->request->getPost('quota_id')));
|
||||
|
||||
self::_redirectToIndex($iSurveyId);
|
||||
}
|
||||
|
||||
function editquota($iSurveyId)
|
||||
{
|
||||
$iSurveyId = sanitize_int($iSurveyId);
|
||||
$this->_checkPermissions($iSurveyId, 'update');
|
||||
$aData = $this->_getData($iSurveyId);
|
||||
$aLangs = $aData['aLangs'];
|
||||
$clang = $aData['clang'];
|
||||
$aViewUrls = array();
|
||||
|
||||
$aQuotaInfo = Quota::model()->findByPk(Yii::app()->request->getPost('quota_id'));
|
||||
$aData['quotainfo'] = $aQuotaInfo;
|
||||
|
||||
$first=true;
|
||||
foreach ($aLangs as $sLanguage)
|
||||
{
|
||||
$aTabTitles[$sLanguage] = getLanguageNameFromCode($sLanguage, false);
|
||||
if ($first)
|
||||
{
|
||||
$aTabTitles[$sLanguage].= ' (' . $clang->gT("Base language") . ')';
|
||||
$first = false;
|
||||
}
|
||||
$aData['langquotainfo'] = QuotaLanguageSetting::model()->findByAttributes(array('quotals_quota_id' => Yii::app()->request->getPost('quota_id'), 'quotals_language' => $sLanguage));
|
||||
$aData['lang'] = $sLanguage;
|
||||
$aTabContents[$sLanguage] = $this->getController()->renderPartial('/admin/quotas/editquotalang_view', $aData, true);
|
||||
}
|
||||
$aData['aTabTitles']=$aTabTitles;
|
||||
$aData['aTabContents']=$aTabContents;
|
||||
|
||||
$aViewUrls[] = 'editquota_view';
|
||||
|
||||
$this->_renderWrappedTemplate('quotas', $aViewUrls, $aData);
|
||||
}
|
||||
|
||||
function new_answer($iSurveyId, $sSubAction = 'new_answer')
|
||||
{
|
||||
$iSurveyId = sanitize_int($iSurveyId);
|
||||
$this->_checkPermissions($iSurveyId, 'update');
|
||||
$aData = $this->_getData($iSurveyId);
|
||||
$sBaseLang = $aData['sBaseLang'];
|
||||
$clang = $aData['clang'];
|
||||
$aViewUrls = array();
|
||||
|
||||
if (($sSubAction == "new_answer" || ($sSubAction == "new_answer_two" && !isset($_POST['quota_qid']))) && Permission::model()->hasSurveyPermission($iSurveyId, 'quotas', 'create'))
|
||||
{
|
||||
$result = Quota::model()->findAllByPk(Yii::app()->request->getPost('quota_id'));
|
||||
foreach ($result as $aQuotaDetails)
|
||||
{
|
||||
$quota_name = $aQuotaDetails['name'];
|
||||
}
|
||||
|
||||
$result = Question::model()->findAllByAttributes(array('type' => array('G', 'M', 'Y', 'A', 'B', 'I', 'L', 'O', '!'), 'sid' => $iSurveyId, 'language' => $sBaseLang, 'parent_qid' => 0));
|
||||
if (empty($result))
|
||||
{
|
||||
$aViewUrls[] = 'newanswererror_view';
|
||||
}
|
||||
else
|
||||
{
|
||||
$aData['newanswer_result'] = $result;
|
||||
$aData['quota_name'] = $quota_name;
|
||||
$aViewUrls[] = 'newanswer_view';
|
||||
}
|
||||
}
|
||||
|
||||
if ($sSubAction == "new_answer_two" && isset($_POST['quota_qid']) && Permission::model()->hasSurveyPermission($iSurveyId, 'quotas', 'create'))
|
||||
{
|
||||
$aResults = Quota::model()->findByPk(Yii::app()->request->getPost('quota_qid'));
|
||||
$sQuotaName = $aResults['name'];
|
||||
|
||||
$aQuestionAnswers = self::getQuotaAnswers(Yii::app()->request->getPost('quota_qid'), $iSurveyId, Yii::app()->request->getPost('quota_id'));
|
||||
$x = 0;
|
||||
|
||||
foreach ($aQuestionAnswers as $aQACheck)
|
||||
{
|
||||
if (isset($aQACheck['rowexists']))
|
||||
$x++;
|
||||
}
|
||||
|
||||
reset($aQuestionAnswers);
|
||||
$aData['question_answers'] = $aQuestionAnswers;
|
||||
$aData['x'] = $x;
|
||||
$aData['quota_name'] = $sQuotaName;
|
||||
$aViewUrls[] = 'newanswertwo_view';
|
||||
}
|
||||
|
||||
$this->_renderWrappedTemplate('quotas', $aViewUrls, $aData);
|
||||
}
|
||||
|
||||
function newquota($iSurveyId)
|
||||
{
|
||||
$iSurveyId = sanitize_int($iSurveyId);
|
||||
$this->_checkPermissions($iSurveyId, 'create');
|
||||
$aData = $this->_getData($iSurveyId);
|
||||
$clang = $aData['clang'];
|
||||
|
||||
$aData['thissurvey'] = getSurveyInfo($iSurveyId);
|
||||
$aData['langs'] = $aData['aLangs'];
|
||||
$aData['baselang'] = $aData['sBaseLang'];
|
||||
|
||||
$this->_renderWrappedTemplate('quotas', 'newquota_view', $aData);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param type $iQuestionId
|
||||
* @param type $iSurveyId
|
||||
* @param type $iQuotaId
|
||||
* @return array
|
||||
*/
|
||||
function getQuotaAnswers($iQuestionId, $iSurveyId, $iQuotaId)
|
||||
{
|
||||
$iQuestionId = sanitize_int($iQuestionId);
|
||||
$iSurveyId = sanitize_int($iSurveyId);
|
||||
$iQuotaId = sanitize_int($iQuotaId);
|
||||
$aData = $this->_getData($iSurveyId);
|
||||
$sBaseLang = $aData['sBaseLang'];
|
||||
$clang = $aData['clang'];
|
||||
$this->_checkPermissions($iSurveyId, 'read');
|
||||
$aQuestion = Question::model()->findByPk(array('qid' => $iQuestionId, 'language' => $sBaseLang));
|
||||
$aQuestionType = $aQuestion['type'];
|
||||
|
||||
if ($aQuestionType == 'M')
|
||||
{
|
||||
$aResults = Question::model()->findAllByAttributes(array('parent_qid' => $iQuestionId));
|
||||
$aAnswerList = array();
|
||||
|
||||
foreach($aResults as $aDbAnsList)
|
||||
{
|
||||
$tmparrayans = array('Title' => $aQuestion['title'], 'Display' => substr($aDbAnsList['question'], 0, 40), 'code' => $aDbAnsList['title']);
|
||||
$aAnswerList[$aDbAnsList['title']] = $tmparrayans;
|
||||
}
|
||||
} elseif ($aQuestionType == 'G')
|
||||
{
|
||||
$aAnswerList = array(
|
||||
'M' => array('Title' => $aQuestion['title'], 'Display' => $clang->gT("Male"), 'code' => 'M'),
|
||||
'F' => array('Title' => $aQuestion['title'], 'Display' => $clang->gT("Female"), 'code' => 'F'));
|
||||
} elseif ($aQuestionType == 'L' || $aQuestionType == 'O' || $aQuestionType == '!')
|
||||
{
|
||||
$aAnsResults = Answer::model()->findAllByAttributes(array('qid' => $iQuestionId));
|
||||
|
||||
$aAnswerList = array();
|
||||
|
||||
foreach ($aAnsResults as $aDbAnsList)
|
||||
{
|
||||
$aAnswerList[$aDbAnsList['code']] = array('Title' => $aQuestion['title'], 'Display' => substr($aDbAnsList['answer'], 0, 40), 'code' => $aDbAnsList['code']);
|
||||
}
|
||||
} elseif ($aQuestionType == 'A')
|
||||
{
|
||||
$aAnsResults = Question::model()->findAllByAttributes(array('parent_qid' => $iQuestionId));
|
||||
|
||||
$aAnswerList = array();
|
||||
|
||||
foreach ($aAnsResults as $aDbAnsList)
|
||||
{
|
||||
for ($x = 1; $x < 6; $x++)
|
||||
{
|
||||
$tmparrayans = array('Title' => $aQuestion['title'], 'Display' => substr($aDbAnsList['question'], 0, 40) . ' [' . $x . ']', 'code' => $aDbAnsList['title']);
|
||||
$aAnswerList[$aDbAnsList['title'] . "-" . $x] = $tmparrayans;
|
||||
}
|
||||
}
|
||||
} elseif ($aQuestionType == 'B')
|
||||
{
|
||||
$aAnsResults = Answer::model()->findAllByAttributes(array('qid' => $iQuestionId));
|
||||
|
||||
$aAnswerList = array();
|
||||
|
||||
foreach ($aAnsResults as $aDbAnsList)
|
||||
{
|
||||
for ($x = 1; $x < 11; $x++)
|
||||
{
|
||||
$tmparrayans = array('Title' => $aQuestion['title'], 'Display' => substr($aDbAnsList['answer'], 0, 40) . ' [' . $x . ']', 'code' => $aDbAnsList['code']);
|
||||
$aAnswerList[$aDbAnsList['code'] . "-" . $x] = $tmparrayans;
|
||||
}
|
||||
}
|
||||
} elseif ($aQuestionType == 'Y')
|
||||
{
|
||||
$aAnswerList = array(
|
||||
'Y' => array('Title' => $aQuestion['title'], 'Display' => $clang->gT("Yes"), 'code' => 'Y'),
|
||||
'N' => array('Title' => $aQuestion['title'], 'Display' => $clang->gT("No"), 'code' => 'N'));
|
||||
} elseif ($aQuestionType == 'I')
|
||||
{
|
||||
$slangs = Survey::model()->findByPk($iSurveyId)->additionalLanguages;
|
||||
array_unshift($slangs, $sBaseLang);
|
||||
|
||||
while (list($key, $value) = each($slangs))
|
||||
{
|
||||
$tmparrayans = array('Title' => $aQuestion['title'], 'Display' => getLanguageNameFromCode($value, false), $value);
|
||||
$aAnswerList[$value] = $tmparrayans;
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($aAnswerList))
|
||||
{
|
||||
return array();
|
||||
}
|
||||
else
|
||||
{
|
||||
// Now we mark answers already used in this quota as such
|
||||
$aExistsingAnswers = QuotaMember::model()->findAllByAttributes(array('sid' => $iSurveyId, 'qid' => $iQuestionId, 'quota_id' => $iQuotaId));
|
||||
foreach ($aExistsingAnswers as $aAnswerRow)
|
||||
{
|
||||
if (array_key_exists($aAnswerRow['code'], $aAnswerList))
|
||||
{
|
||||
$aAnswerList[$aAnswerRow['code']]['rowexists'] = '1';
|
||||
}
|
||||
}
|
||||
return $aAnswerList;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders template(s) wrapped in header and footer
|
||||
*
|
||||
* @param string $sAction Current action, the folder to fetch views from
|
||||
* @param string|array $aViewUrls View url(s)
|
||||
* @param array $aData Data to be passed on. Optional.
|
||||
*/
|
||||
protected function _renderWrappedTemplate($sAction = 'quotas', $aViewUrls = array(), $aData = array())
|
||||
{
|
||||
App()->getClientScript()->registerPackage('jquery-superfish');
|
||||
App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . '/quotas.js');
|
||||
parent::_renderWrappedTemplate($sAction, $aViewUrls, $aData);
|
||||
}
|
||||
|
||||
}
|
170
sources/application/controllers/admin/remotecontrol.php
Normal file
170
sources/application/controllers/admin/remotecontrol.php
Normal file
|
@ -0,0 +1,170 @@
|
|||
<?php
|
||||
|
||||
/*
|
||||
* 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.
|
||||
*
|
||||
*/
|
||||
|
||||
class remotecontrol extends Survey_Common_Action
|
||||
{
|
||||
/**
|
||||
* @var Zend_XmlRpc_Server
|
||||
*/
|
||||
protected $xmlrpc;
|
||||
|
||||
/**
|
||||
* This is the XML-RPC server routine
|
||||
*
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function run()
|
||||
{
|
||||
Yii::import('application.helpers.remotecontrol.*');
|
||||
$oHandler=new remotecontrol_handle($this->controller);
|
||||
$RPCType=Yii::app()->getConfig("RPCInterface");
|
||||
if (Yii::app()->getRequest()->isPostRequest) {
|
||||
if ($RPCType=='xml')
|
||||
{
|
||||
$cur_path = get_include_path();
|
||||
set_include_path($cur_path . PATH_SEPARATOR . APPPATH . 'helpers');
|
||||
// Yii::import was causing problems for some odd reason
|
||||
require_once('Zend/XmlRpc/Server.php');
|
||||
require_once('Zend/XmlRpc/Server/Exception.php');
|
||||
require_once('Zend/XmlRpc/Value/Exception.php');
|
||||
$this->xmlrpc = new Zend_XmlRpc_Server();
|
||||
$this->xmlrpc->sendArgumentsToAllMethods(false);
|
||||
Yii::import('application.libraries.LSZend_XmlRpc_Response_Http');
|
||||
$this->xmlrpc->setResponseClass('LSZend_XmlRpc_Response_Http');
|
||||
$this->xmlrpc->setClass($oHandler);
|
||||
/* @var LSZend_XmlRpc_Response_Http */
|
||||
$result = $this->xmlrpc->handle();
|
||||
$result->printXml();
|
||||
}
|
||||
elseif($RPCType=='json')
|
||||
{
|
||||
Yii::app()->loadLibrary('LSjsonRPCServer');
|
||||
if (!isset($_SERVER['CONTENT_TYPE']))
|
||||
{
|
||||
$serverContentType = explode(';', $_SERVER['HTTP_CONTENT_TYPE']);
|
||||
$_SERVER['CONTENT_TYPE'] = reset($serverContentType);
|
||||
}
|
||||
LSjsonRPCServer::handle($oHandler);
|
||||
}
|
||||
foreach (App()->log->routes as $route)
|
||||
{
|
||||
$route->enabled = $route->enabled && !($route instanceOf CWebLogRoute);
|
||||
}
|
||||
|
||||
exit;
|
||||
} else {
|
||||
// Disabled output of API methods for now
|
||||
if (Yii::app()->getConfig("rpc_publish_api") == true && in_array($RPCType, array('xml', 'json'))) {
|
||||
$reflector = new ReflectionObject($oHandler);
|
||||
foreach ($reflector->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
|
||||
/* @var $method ReflectionMethod */
|
||||
if (substr($method->getName(),0,1) !== '_') {
|
||||
$list[$method->getName()] = array(
|
||||
'description' => str_replace(array("\r", "\r\n", "\n"), "<br/>", $method->getDocComment()),
|
||||
'parameters' => $method->getParameters()
|
||||
);
|
||||
}
|
||||
}
|
||||
ksort($list);
|
||||
$aData['method'] = $RPCType;
|
||||
$aData['list'] = $list;
|
||||
$aData['display']['menu_bars'] = false; // Hide normal menu bar
|
||||
$this->_renderWrappedTemplate('remotecontrol', array('index_view'), $aData);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Simple procedure to test most RPC functions
|
||||
*
|
||||
*/
|
||||
public function test()
|
||||
{
|
||||
$RPCType=Yii::app()->getConfig("RPCInterface");
|
||||
$serverUrl = App()->createAbsoluteUrl('/admin/remotecontrol');
|
||||
$sFileToImport=dirname(Yii::app()->basePath).DIRECTORY_SEPARATOR.'docs'.DIRECTORY_SEPARATOR.'demosurveys'.DIRECTORY_SEPARATOR.'limesurvey2_sample_survey_english.lss';
|
||||
|
||||
if ($RPCType == 'xml') {
|
||||
require_once('Zend/XmlRpc/Client.php');
|
||||
$client = new Zend_XmlRpc_Client($serverUrl);
|
||||
} elseif ($RPCType == 'json') {
|
||||
Yii::app()->loadLibrary('jsonRPCClient');
|
||||
$client = new jsonRPCClient($serverUrl);
|
||||
}
|
||||
else die('RPC interface not activated in global settings');
|
||||
|
||||
|
||||
$sSessionKey= $client->call('get_session_key', array('admin','password'));
|
||||
if (is_array($sSessionKey)) {echo $sSessionKey['status']; die();}
|
||||
else
|
||||
{
|
||||
echo 'Retrieved session key'.'<br>';
|
||||
}
|
||||
|
||||
$sLSSData=base64_encode(file_get_contents($sFileToImport));
|
||||
$iSurveyID=$client->call('import_survey', array($sSessionKey, $sLSSData, 'lss','Test import by JSON_RPC',1000));
|
||||
echo 'Created new survey SID:'.$iSurveyID.'<br>';
|
||||
|
||||
$aResult=$client->call('activate_survey', array($sSessionKey, $iSurveyID));
|
||||
if ($aResult['status']=='OK')
|
||||
{
|
||||
echo 'Survey '.$iSurveyID.' successfully activated.<br>';
|
||||
}
|
||||
$aResult=$client->call('activate_tokens', array($sSessionKey, $iSurveyID,array(1,2)));
|
||||
if ($aResult['status']=='OK')
|
||||
{
|
||||
echo 'Tokens for Survey ID '.$iSurveyID.' successfully activated.<br>';
|
||||
}
|
||||
$aResult=$client->call('set_survey_properties', array($sSessionKey, $iSurveyID,array('faxto'=>'0800-LIMESURVEY')));
|
||||
if (!array_key_exists('status', $aResult))
|
||||
{
|
||||
echo 'Modified survey settings for survey '.$iSurveyID.'<br>';
|
||||
}
|
||||
$aResult=$client->call('add_language', array($sSessionKey, $iSurveyID,'ar'));
|
||||
if ($aResult['status']=='OK')
|
||||
{
|
||||
echo 'Added Arabian as additional language'.'<br>';
|
||||
}
|
||||
$aResult=$client->call('set_language_properties', array($sSessionKey, $iSurveyID,array('surveyls_welcometext'=>'An Arabian welcome text!'),'ar'));
|
||||
if ($aResult['status']=='OK')
|
||||
{
|
||||
echo 'Modified survey locale setting welcometext for Arabian in survey ID '.$iSurveyID.'<br>';
|
||||
}
|
||||
|
||||
$aResult=$client->call('delete_language', array($sSessionKey, $iSurveyID,'ar'));
|
||||
if ($aResult['status']=='OK')
|
||||
{
|
||||
echo 'Removed Arabian as additional language'.'<br>';
|
||||
}
|
||||
|
||||
//Very simple example to export responses as Excel file
|
||||
//$aResult=$client->call('export_responses', array($sSessionKey,$iSurveyID,'xls'));
|
||||
//$aResult=$client->call('export_responses', array($sSessionKey,$iSurveyID,'pdf'));
|
||||
//$aResult=$client->call('export_responses', array($sSessionKey,$iSurveyID,'doc'));
|
||||
$aResult=$client->call('export_responses', array($sSessionKey,$iSurveyID,'csv'));
|
||||
//file_put_contents('test.xls',base64_decode(chunk_split($aResult)));
|
||||
|
||||
$aResult=$client->call('delete_survey', array($sSessionKey, $iSurveyID));
|
||||
echo 'Deleted survey SID:'.$iSurveyID.'-'.$aResult['status'].'<br>';
|
||||
|
||||
// Release the session key - close the session
|
||||
$Result= $client->call('release_session_key', array($sSessionKey));
|
||||
echo 'Closed the session'.'<br>';
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
865
sources/application/controllers/admin/responses.php
Normal file
865
sources/application/controllers/admin/responses.php
Normal file
|
@ -0,0 +1,865 @@
|
|||
<?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.
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* Responses Controller
|
||||
*
|
||||
* This controller performs browse actions
|
||||
*
|
||||
* @package LimeSurvey
|
||||
* @subpackage Backend
|
||||
*/
|
||||
class responses extends Survey_Common_Action
|
||||
{
|
||||
|
||||
function __construct($controller, $id)
|
||||
{
|
||||
parent::__construct($controller, $id);
|
||||
|
||||
Yii::app()->loadHelper('surveytranslator');
|
||||
}
|
||||
|
||||
private function _getData($params)
|
||||
{
|
||||
if (is_numeric($params))
|
||||
{
|
||||
$iSurveyId = $params;
|
||||
}
|
||||
elseif (is_array($params))
|
||||
{
|
||||
extract($params);
|
||||
}
|
||||
$aData = array();
|
||||
// Set the variables in an array
|
||||
$aData['surveyid'] = $aData['iSurveyId'] = (int) $iSurveyId;
|
||||
if (!empty($iId))
|
||||
{
|
||||
$aData['iId'] = (int) $iId;
|
||||
}
|
||||
$aData['clang'] = $clang = $this->getController()->lang;
|
||||
$aData['imageurl'] = Yii::app()->getConfig('imageurl');
|
||||
$aData['action'] = Yii::app()->request->getParam('action');
|
||||
$aData['all']=Yii::app()->request->getParam('all');
|
||||
$thissurvey=getSurveyInfo($iSurveyId);
|
||||
if(!$thissurvey)// Already done in Survey_Common_Action
|
||||
{
|
||||
Yii::app()->session['flashmessage'] = $clang->gT("Invalid survey ID");
|
||||
$this->getController()->redirect(array("admin/index"));
|
||||
}
|
||||
elseif($thissurvey['active'] != 'Y')
|
||||
{
|
||||
Yii::app()->session['flashmessage'] = $clang->gT("This survey has not been activated. There are no results to browse.");
|
||||
$this->getController()->redirect(array("/admin/survey/sa/view/surveyid/{$iSurveyId}"));
|
||||
}
|
||||
|
||||
//OK. IF WE GOT THIS FAR, THEN THE SURVEY EXISTS AND IT IS ACTIVE, SO LETS GET TO WORK.
|
||||
|
||||
$aData['surveyinfo'] = $thissurvey;
|
||||
|
||||
if (Yii::app()->request->getParam('browselang'))
|
||||
{
|
||||
$aData['language'] = Yii::app()->request->getParam('browselang');
|
||||
$aData['languagelist'] = $languagelist = Survey::model()->findByPk($iSurveyId)->additionalLanguages;
|
||||
$aData['languagelist'][] = Survey::model()->findByPk($iSurveyId)->language;
|
||||
if (!in_array($aData['language'], $languagelist))
|
||||
{
|
||||
$aData['language'] = $thissurvey['language'];
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
$aData['language'] = $thissurvey['language'];
|
||||
}
|
||||
|
||||
$aData['qulanguage'] = Survey::model()->findByPk($iSurveyId)->language;
|
||||
|
||||
$aData['surveyoptions'] = '';
|
||||
$aData['browseoutput'] = '';
|
||||
|
||||
return $aData;
|
||||
}
|
||||
|
||||
public function view($iSurveyID, $iId, $sBrowseLang = '')
|
||||
{
|
||||
if(Permission::model()->hasSurveyPermission($iSurveyID,'responses','read'))
|
||||
{
|
||||
$aData = $this->_getData(array('iId' => $iId, 'iSurveyId' => $iSurveyID, 'browselang' => $sBrowseLang));
|
||||
$oBrowseLanguage = new Limesurvey_lang($aData['language']);
|
||||
|
||||
extract($aData);
|
||||
$clang = Yii::app()->lang;
|
||||
$aViewUrls = array();
|
||||
|
||||
$fncount = 0;
|
||||
$fieldmap = createFieldMap($iSurveyID, 'full', false, false, $aData['language']);
|
||||
|
||||
//add token to top of list if survey is not private
|
||||
if ($aData['surveyinfo']['anonymized'] == "N" && tableExists('tokens_' . $iSurveyID) && Permission::model()->hasSurveyPermission($iSurveyID,'tokens','read'))
|
||||
{
|
||||
$fnames[] = array("token", $clang->gT("Token ID"), 'code'=>'token');
|
||||
$fnames[] = array("firstname", $clang->gT("First name"), 'code'=>'firstname');// or token:firstname ?
|
||||
$fnames[] = array("lastname", $clang->gT("Last name"), 'code'=>'lastname');
|
||||
$fnames[] = array("email", $clang->gT("Email"), 'code'=>'email');
|
||||
}
|
||||
$fnames[] = array("submitdate", $clang->gT("Submission date"), $clang->gT("Completed"), "0", 'D','code'=>'submitdate');
|
||||
$fnames[] = array("completed", $clang->gT("Completed"), "0");
|
||||
|
||||
foreach ($fieldmap as $field)
|
||||
{
|
||||
if ($field['fieldname'] == 'lastpage' || $field['fieldname'] == 'submitdate')
|
||||
continue;
|
||||
if ($field['type'] == 'interview_time')
|
||||
continue;
|
||||
if ($field['type'] == 'page_time')
|
||||
continue;
|
||||
if ($field['type'] == 'answer_time')
|
||||
continue;
|
||||
|
||||
//$question = $field['question'];
|
||||
$question = viewHelper::getFieldText($field);
|
||||
|
||||
if ($field['type'] != "|")
|
||||
{
|
||||
$fnames[] = array($field['fieldname'], viewHelper::getFieldText($field),'code'=>viewHelper::getFieldCode($field,array('LEMcompat'=>true)));
|
||||
}
|
||||
elseif ($field['aid'] !== 'filecount')
|
||||
{
|
||||
$qidattributes = getQuestionAttributeValues($field['qid']);
|
||||
|
||||
for ($i = 0; $i < $qidattributes['max_num_of_files']; $i++)
|
||||
{
|
||||
$filenum=sprintf($clang->gT("File %s"),$i + 1);
|
||||
if ($qidattributes['show_title'] == 1)
|
||||
$fnames[] = array($field['fieldname'], "{$filenum} - {$question} (".$clang->gT('Title').")",'code'=>viewHelper::getFieldCode($field).'(title)', "type" => "|", "metadata" => "title", "index" => $i);
|
||||
|
||||
if ($qidattributes['show_comment'] == 1)
|
||||
$fnames[] = array($field['fieldname'], "{$filenum} - {$question} (".$clang->gT('Comment').")",'code'=>viewHelper::getFieldCode($field).'(comment)', "type" => "|", "metadata" => "comment", "index" => $i);
|
||||
|
||||
$fnames[] = array($field['fieldname'], "{$filenum} - {$question} (".$clang->gT('File name').")",'code'=>viewHelper::getFieldCode($field).'(name)', "type" => "|", "metadata" => "name", "index" => $i);
|
||||
$fnames[] = array($field['fieldname'], "{$filenum} - {$question} (".$clang->gT('File size').")",'code'=>viewHelper::getFieldCode($field).'(size)', "type" => "|", "metadata" => "size", "index" => $i);
|
||||
|
||||
//$fnames[] = array($field['fieldname'], "File ".($i+1)." - ".$field['question']." (extension)", "type"=>"|", "metadata"=>"ext", "index"=>$i);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
$fnames[] = array($field['fieldname'], $clang->gT("File count"));
|
||||
}
|
||||
}
|
||||
|
||||
$nfncount = count($fnames) - 1;
|
||||
if ($iId < 1)
|
||||
{
|
||||
$iId = 1;
|
||||
}
|
||||
|
||||
$exist = SurveyDynamic::model($iSurveyID)->exist($iId);
|
||||
$next = SurveyDynamic::model($iSurveyID)->next($iId,true);
|
||||
$previous = SurveyDynamic::model($iSurveyID)->previous($iId,true);
|
||||
$aData['exist'] = $exist;
|
||||
$aData['next'] = $next;
|
||||
$aData['previous'] = $previous;
|
||||
$aData['id'] = $iId;
|
||||
|
||||
$aViewUrls[] = 'browseidheader_view';
|
||||
if($exist)
|
||||
{
|
||||
$oPurifier=new CHtmlPurifier();
|
||||
//SHOW INDIVIDUAL RECORD
|
||||
$oCriteria = new CDbCriteria();
|
||||
if ($aData['surveyinfo']['anonymized'] == 'N' && tableExists("{{tokens_$iSurveyID}}}") && Permission::model()->hasSurveyPermission($iSurveyID,'tokens','read'))
|
||||
{
|
||||
$oCriteria = SurveyDynamic::model($iSurveyID)->addTokenCriteria($oCriteria);
|
||||
}
|
||||
// If admin ask an specific response, then show it
|
||||
// Don't add incompleteAnsFilterState
|
||||
# if (incompleteAnsFilterState() == 'incomplete')
|
||||
# $oCriteria->addCondition('submitdate = ' . mktime(0, 0, 0, 1, 1, 1980) . ' OR submitdate IS NULL');
|
||||
# elseif (incompleteAnsFilterState() == 'complete')
|
||||
# $oCriteria->addCondition('submitdate >= ' . mktime(0, 0, 0, 1, 1, 1980));
|
||||
$oCriteria->addCondition("id = {$iId}");
|
||||
$iIdresult = SurveyDynamic::model($iSurveyID)->findAllAsArray($oCriteria);
|
||||
foreach ($iIdresult as $iIdrow)
|
||||
{
|
||||
$iId = $iIdrow['id'];
|
||||
$rlanguage = $iIdrow['startlanguage'];
|
||||
}
|
||||
$next = SurveyDynamic::model($iSurveyID)->next($iId);
|
||||
$previous = SurveyDynamic::model($iSurveyID)->previous($iId);
|
||||
|
||||
if (isset($rlanguage))
|
||||
{
|
||||
$aData['rlanguage'] = $rlanguage;
|
||||
}
|
||||
foreach ($iIdresult as $iIdrow)
|
||||
{
|
||||
$highlight = false;
|
||||
for ($i = 0; $i < $nfncount + 1; $i++)
|
||||
{
|
||||
if ($fnames[$i][0] != 'completed' && is_null($iIdrow[$fnames[$i][0]]))
|
||||
{
|
||||
continue; // irrelevant, so don't show
|
||||
}
|
||||
$inserthighlight = '';
|
||||
if ($highlight)
|
||||
$inserthighlight = "class='highlight'";
|
||||
|
||||
if ($fnames[$i][0] == 'completed')
|
||||
{
|
||||
if ($iIdrow['submitdate'] == NULL || $iIdrow['submitdate'] == "N")
|
||||
{
|
||||
$answervalue = "N";
|
||||
}
|
||||
else
|
||||
{
|
||||
$answervalue = "Y";
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (isset($fnames[$i]['type']) && $fnames[$i]['type'] == "|")
|
||||
{
|
||||
$index = $fnames[$i]['index'];
|
||||
$metadata = $fnames[$i]['metadata'];
|
||||
$phparray = json_decode_ls($iIdrow[$fnames[$i][0]]);
|
||||
|
||||
if (isset($phparray[$index]))
|
||||
{
|
||||
if ($metadata === "size")
|
||||
$answervalue = rawurldecode(((int) ($phparray[$index][$metadata])) . " KB");
|
||||
else if ($metadata === "name")
|
||||
$answervalue = CHtml::link($oPurifier->purify(rawurldecode($phparray[$index][$metadata])), $this->getController()->createUrl("/admin/responses/sa/browse/fieldname/{$fnames[$i][0]}/id/{$iId}/surveyid/{$iSurveyID}",array('downloadindividualfile'=>$phparray[$index][$metadata])));
|
||||
else
|
||||
$answervalue = rawurldecode($phparray[$index][$metadata]);
|
||||
}
|
||||
else
|
||||
$answervalue = "";
|
||||
}
|
||||
else
|
||||
{
|
||||
$answervalue = htmlspecialchars(strip_tags(stripJavaScript(getExtendedAnswer($iSurveyID, $fnames[$i][0], $iIdrow[$fnames[$i][0]], $oBrowseLanguage))), ENT_QUOTES);
|
||||
}
|
||||
}
|
||||
$aData['answervalue'] = $answervalue;
|
||||
$aData['inserthighlight'] = $inserthighlight;
|
||||
$aData['fnames'] = $fnames;
|
||||
$aData['i'] = $i;
|
||||
$aViewUrls['browseidrow_view'][] = $aData;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Yii::app()->session['flashmessage'] = $clang->gT("This response ID is invalid.");
|
||||
}
|
||||
|
||||
$aViewUrls[] = 'browseidfooter_view';
|
||||
|
||||
$this->_renderWrappedTemplate('',$aViewUrls, $aData);
|
||||
}
|
||||
else
|
||||
{
|
||||
$clang = $this->getController()->lang;
|
||||
$aData['surveyid'] = $iSurveyID;
|
||||
App()->getClientScript()->registerPackage('jquery-superfish');
|
||||
$message['title']= $clang->gT('Access denied!');
|
||||
$message['message']= $clang->gT('You do not have sufficient rights to access this page.');
|
||||
$message['class']= "error";
|
||||
$this->_renderWrappedTemplate('survey', array("message"=>$message), $aData);
|
||||
}
|
||||
}
|
||||
|
||||
public function index($iSurveyID)
|
||||
{
|
||||
$aData = $this->_getData($iSurveyID);
|
||||
extract($aData);
|
||||
$aViewUrls = array();
|
||||
$oBrowseLanguage = new Limesurvey_lang($aData['language']);
|
||||
|
||||
/**
|
||||
* fnames is used as informational array
|
||||
* it containts
|
||||
* $fnames[] = array(<dbfieldname>, <some strange title>, <questiontext>, <group_id>, <questiontype>);
|
||||
*/
|
||||
if (Yii::app()->request->getPost('sql'))
|
||||
{
|
||||
$aViewUrls[] = 'browseallfiltered_view';
|
||||
}
|
||||
|
||||
$clang = $aData['clang'];
|
||||
$aData['num_total_answers'] = SurveyDynamic::model($iSurveyID)->count();
|
||||
$aData['num_completed_answers'] = SurveyDynamic::model($iSurveyID)->count('submitdate IS NOT NULL');
|
||||
if (tableExists('{{tokens_' . $iSurveyID . '}}') && Permission::model()->hasSurveyPermission($iSurveyID,'tokens','read'))
|
||||
{
|
||||
$aData['with_token']= Yii::app()->db->schema->getTable('{{tokens_' . $iSurveyID . '}}');
|
||||
$aData['tokeninfo'] = Token::model($iSurveyID)->summary();
|
||||
}
|
||||
|
||||
$aViewUrls[] = 'browseindex_view';
|
||||
$this->_renderWrappedTemplate('',$aViewUrls, $aData);
|
||||
}
|
||||
|
||||
|
||||
function browse($iSurveyID)
|
||||
{
|
||||
$aData = $this->_getData($iSurveyID);
|
||||
extract($aData);
|
||||
$aViewUrls = array();
|
||||
$oBrowseLanguage = new Limesurvey_lang($aData['language']);
|
||||
|
||||
$tokenRequest = Yii::app()->request->getParam('token', null);
|
||||
|
||||
//Delete Individual answer using inrow delete buttons/links - checked
|
||||
if (Yii::app()->request->getPost('deleteanswer') && Yii::app()->request->getPost('deleteanswer') != '' && Yii::app()->request->getPost('deleteanswer') != 'marked')
|
||||
{
|
||||
if(Permission::model()->hasSurveyPermission($iSurveyID,'responses','delete'))
|
||||
{
|
||||
$iResponseID = (int) Yii::app()->request->getPost('deleteanswer'); // sanitize the value
|
||||
Response::model($iSurveyID)->findByPk($iResponseID)->delete(true);
|
||||
// delete timings if savetimings is set
|
||||
if($aData['surveyinfo']['savetimings'] == "Y"){
|
||||
SurveyTimingDynamic::model($iSurveyID)->deleteByPk($iResponseID);
|
||||
}
|
||||
Yii::app()->session['flashmessage'] = sprintf(gT("Response ID %s was successfully deleted."),$iResponseID);
|
||||
}
|
||||
else
|
||||
{
|
||||
Yii::app()->session['flashmessage'] = gT("Access denied!",'js');
|
||||
}
|
||||
}
|
||||
// Marked responses -> deal with the whole batch of marked responses
|
||||
if (Yii::app()->request->getPost('markedresponses') && count(Yii::app()->request->getPost('markedresponses')) > 0)
|
||||
{
|
||||
// Delete the marked responses - checked
|
||||
if (Yii::app()->request->getPost('deleteanswer') && Yii::app()->request->getPost('deleteanswer') === 'marked')
|
||||
{
|
||||
if(Permission::model()->hasSurveyPermission($iSurveyID,'responses','delete'))
|
||||
{
|
||||
foreach (Response::model($iSurveyID)->findAllByPk(Yii::app()->request->getPost('markedresponses')) as $response)
|
||||
{
|
||||
$response->deleteFiles();
|
||||
// delete timings if savetimings is set
|
||||
/**
|
||||
* @todo Move this to the Response model.
|
||||
*/
|
||||
if($aData['surveyinfo']['savetimings'] == "Y"){
|
||||
SurveyTimingDynamic::model($iSurveyID)->deleteByPk($iResponseID);
|
||||
}
|
||||
}
|
||||
|
||||
Response::model($iSurveyID)->deleteByPk(Yii::app()->request->getPost('markedresponses'));
|
||||
|
||||
|
||||
Yii::app()->session['flashmessage'] = sprintf(ngT("%s response was successfully deleted.","%s responses were successfully deleted.",count(Yii::app()->request->getPost('markedresponses'))),count(Yii::app()->request->getPost('markedresponses')),'js');
|
||||
}
|
||||
else
|
||||
{
|
||||
Yii::app()->session['flashmessage'] = $clang->gT("Access denied!",'js');
|
||||
}
|
||||
}
|
||||
// Download all files for all marked responses - checked
|
||||
elseif (Yii::app()->request->getPost('downloadfile') && Yii::app()->request->getPost('downloadfile') === 'marked')
|
||||
{
|
||||
if(Permission::model()->hasSurveyPermission($iSurveyID,'responses','read'))
|
||||
{
|
||||
// Now, zip all the files in the filelist
|
||||
$zipfilename = "Responses_for_survey_{$iSurveyID}.zip";
|
||||
$this->_zipFiles($iSurveyID, Yii::app()->request->getPost('markedresponses'), $zipfilename);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Download all files for this entry - checked
|
||||
elseif (Yii::app()->request->getPost('downloadfile') && Yii::app()->request->getPost('downloadfile') != '' && Yii::app()->request->getPost('downloadfile') !== true)
|
||||
{
|
||||
if(Permission::model()->hasSurveyPermission($iSurveyID,'responses','read'))
|
||||
{
|
||||
// Now, zip all the files in the filelist
|
||||
$zipfilename = "Files_for_responses_" . Yii::app()->request->getPost('downloadfile') . ".zip";
|
||||
$this->_zipFiles($iSurveyID, Yii::app()->request->getPost('downloadfile'), $zipfilename);
|
||||
}
|
||||
}
|
||||
elseif (Yii::app()->request->getParam('downloadindividualfile') != '')
|
||||
{
|
||||
if(Permission::model()->hasSurveyPermission($iSurveyID,'responses','read'))
|
||||
{
|
||||
$iId = (int) Yii::app()->request->getParam('id');
|
||||
$downloadindividualfile = Yii::app()->request->getParam('downloadindividualfile');
|
||||
$fieldname = Yii::app()->request->getParam('fieldname');
|
||||
|
||||
$oRow = SurveyDynamic::model($iSurveyID)->findByAttributes(array('id' => $iId));
|
||||
$phparray = json_decode_ls($oRow->$fieldname);
|
||||
|
||||
for ($i = 0; $i < count($phparray); $i++)
|
||||
{
|
||||
if (rawurldecode($phparray[$i]['name']) == rawurldecode($downloadindividualfile))
|
||||
{
|
||||
$file = Yii::app()->getConfig('uploaddir') . "/surveys/" . $iSurveyID . "/files/" . $phparray[$i]['filename'];
|
||||
|
||||
if (file_exists($file))
|
||||
{
|
||||
@ob_clean();
|
||||
header('Content-Description: File Transfer');
|
||||
header('Content-Type: application/octet-stream');
|
||||
header('Content-Disposition: attachment; filename="' . rawurldecode($phparray[$i]['name']) . '"');
|
||||
header('Content-Transfer-Encoding: binary');
|
||||
header('Expires: 0');
|
||||
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
|
||||
header('Pragma: public');
|
||||
header('Content-Length: ' . filesize($file));
|
||||
readfile($file);
|
||||
exit;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* fnames is used as informational array
|
||||
* it containts
|
||||
* $fnames[] = array(<dbfieldname>, <some strange title>, <questiontext>, <group_id>, <questiontype>);
|
||||
*/
|
||||
if(Permission::model()->hasSurveyPermission($iSurveyID,'responses','read'))
|
||||
{
|
||||
if (Yii::app()->request->getPost('sql'))
|
||||
{
|
||||
$aViewUrls[] = 'browseallfiltered_view';
|
||||
}
|
||||
//add token to top of list if survey is not private
|
||||
if ($aData['surveyinfo']['anonymized'] == "N" && tableExists('tokens_' . $iSurveyID) ) //add token to top of list if survey is not private
|
||||
{
|
||||
if(Permission::model()->hasSurveyPermission($iSurveyID,'tokens','read'))
|
||||
{
|
||||
$fnames[] = array("token", $clang->gT("Token ID"), 'code'=>'token');
|
||||
$fnames[] = array("firstname", $clang->gT("First name"), 'code'=>'firstname');// or token:firstname ?
|
||||
$fnames[] = array("lastname", $clang->gT("Last name"), 'code'=>'lastname');
|
||||
$fnames[] = array("email", $clang->gT("Email"), 'code'=>'email');
|
||||
}
|
||||
}
|
||||
|
||||
$fnames[] = array("submitdate", $clang->gT("Completed"), $clang->gT("Completed"), "0", 'D');
|
||||
$fields = createFieldMap($iSurveyID, 'full', false, false, $aData['language']);
|
||||
|
||||
foreach ($fields as $fielddetails)
|
||||
{
|
||||
if ($fielddetails['fieldname'] == 'lastpage' || $fielddetails['fieldname'] == 'submitdate')
|
||||
continue;
|
||||
|
||||
$question = $fielddetails['question'];
|
||||
if ($fielddetails['type'] != "|")
|
||||
{
|
||||
if ($fielddetails['fieldname'] == 'lastpage' || $fielddetails['fieldname'] == 'submitdate' || $fielddetails['fieldname'] == 'token')
|
||||
continue;
|
||||
|
||||
// no headers for time data
|
||||
if ($fielddetails['type'] == 'interview_time')
|
||||
continue;
|
||||
if ($fielddetails['type'] == 'page_time')
|
||||
continue;
|
||||
if ($fielddetails['type'] == 'answer_time')
|
||||
continue;
|
||||
$fnames[] = array($fielddetails['fieldname'], viewHelper::getFieldText($fielddetails),'code'=>viewHelper::getFieldCode($fielddetails,array('LEMcompat'=>true)));
|
||||
}
|
||||
elseif ($fielddetails['aid'] !== 'filecount')
|
||||
{
|
||||
$qidattributes = getQuestionAttributeValues($fielddetails['qid']);
|
||||
for ($i = 0; $i < $qidattributes['max_num_of_files']; $i++)
|
||||
{
|
||||
$filenum=sprintf($clang->gT("File %s"),$i + 1);
|
||||
if ($qidattributes['show_title'] == 1)
|
||||
$fnames[] = array($fielddetails['fieldname'], "{$filenum} - {$question} (".$clang->gT('Title').")",'code'=>viewHelper::getFieldCode($fielddetails).'(title)', "type" => "|", "metadata" => "title", "index" => $i);
|
||||
if ($qidattributes['show_comment'] == 1)
|
||||
$fnames[] = array($fielddetails['fieldname'], "{$filenum} - {$question} (".$clang->gT('Comment').")",'code'=>viewHelper::getFieldCode($fielddetails).'(comment)', "type" => "|", "metadata" => "comment", "index" => $i);
|
||||
|
||||
$fnames[] = array($fielddetails['fieldname'], "{$filenum} - {$question} (".$clang->gT('File name').")",'code'=>viewHelper::getFieldCode($fielddetails).'(name)', "type" => "|", "metadata" => "name", "index" => $i);
|
||||
$fnames[] = array($fielddetails['fieldname'], "{$filenum} - {$question} (".$clang->gT('File size').")",'code'=>viewHelper::getFieldCode($fielddetails).'(size)', "type" => "|", "metadata" => "size", "index" => $i);
|
||||
|
||||
//$fnames[] = array($fielddetails['fieldname'], "File ".($i+1)." - ".$fielddetails['question']."(extension)", "type"=>"|", "metadata"=>"ext", "index"=>$i);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
$fnames[] = array($fielddetails['fieldname'], $clang->gT("File count"), 'code'=>viewHelper::getFieldCode($fielddetails));
|
||||
}
|
||||
}
|
||||
|
||||
$fncount = count($fnames);
|
||||
|
||||
$start = Yii::app()->request->getParam('start', 0);
|
||||
$limit = Yii::app()->request->getParam('limit', 50);
|
||||
$order = Yii::app()->request->getParam('order', 'asc');
|
||||
if(!$limit){$limit=50;}
|
||||
$oCriteria = new CDbCriteria;
|
||||
//Create the query
|
||||
if ($aData['surveyinfo']['anonymized'] == "N" && tableExists("{{tokens_{$iSurveyID}}}") && Permission::model()->hasSurveyPermission($iSurveyID,'tokens','read'))
|
||||
{
|
||||
$oCriteria = SurveyDynamic::model($iSurveyID)->addTokenCriteria($oCriteria);
|
||||
}
|
||||
|
||||
if (incompleteAnsFilterState() == "incomplete")
|
||||
{
|
||||
$oCriteria->addCondition("submitdate IS NULL");
|
||||
}
|
||||
elseif (incompleteAnsFilterState() == "complete")
|
||||
{
|
||||
$oCriteria->addCondition("submitdate IS NOT NULL");
|
||||
}
|
||||
|
||||
$dtcount = SurveyDynamic::model($iSurveyID)->count($oCriteria);// or die("Couldn't get response data<br />");
|
||||
|
||||
if ($limit > $dtcount)
|
||||
{
|
||||
$limit = $dtcount;
|
||||
}
|
||||
|
||||
//NOW LETS SHOW THE DATA
|
||||
if (Yii::app()->request->getPost('sql') && stripcslashes(Yii::app()->request->getPost('sql')) !== "" && Yii::app()->request->getPost('sql') != "NULL")
|
||||
$oCriteria->addCondition(stripcslashes(Yii::app()->request->getPost('sql')));
|
||||
|
||||
if (!is_null($tokenRequest)) {
|
||||
$oCriteria->addCondition('t.token = ' . Yii::app()->db->quoteValue($tokenRequest));
|
||||
}
|
||||
|
||||
$oCriteria->order = 'id ' . ($order == 'desc' ? 'desc' : 'asc');
|
||||
$oCriteria->offset = $start;
|
||||
$oCriteria->limit = $limit;
|
||||
|
||||
$dtresult = SurveyDynamic::model($iSurveyID)->findAllAsArray($oCriteria);
|
||||
|
||||
$dtcount2 = count($dtresult);
|
||||
$cells = $fncount + 1;
|
||||
// Fix start if order is desc, only if actual start is 0
|
||||
if($order == 'desc' && $start==0)
|
||||
{
|
||||
$start=$dtcount-count($dtresult);
|
||||
}
|
||||
|
||||
//CONTROL MENUBAR
|
||||
$last = $start - $limit;
|
||||
$next = $start + $limit;
|
||||
$end = $dtcount - $limit;
|
||||
if ($end < 0)
|
||||
{
|
||||
$end = 0;
|
||||
}
|
||||
if ($last < 0)
|
||||
{
|
||||
$last = 0;
|
||||
}
|
||||
if ($next >= $dtcount)
|
||||
{
|
||||
$next = $dtcount - $limit;
|
||||
}
|
||||
if ($end < 0)
|
||||
{
|
||||
$end = 0;
|
||||
}
|
||||
|
||||
$aData['dtcount2'] = $dtcount2;
|
||||
$aData['sCompletionStateValue']=incompleteAnsFilterState();
|
||||
|
||||
$aData['start'] = $start;
|
||||
$aData['limit'] = $limit;
|
||||
$aData['last'] = $last;
|
||||
$aData['next'] = $next;
|
||||
$aData['end'] = $end;
|
||||
$aData['fncount'] = $fncount;
|
||||
$aData['fnames'] = $fnames;
|
||||
$aData['bHasFileUploadQuestion'] = hasFileUploadQuestion($iSurveyID);
|
||||
|
||||
$aViewUrls[] = 'browseallheader_view';
|
||||
|
||||
$bgcc = 'even';
|
||||
foreach ($dtresult as $dtrow)
|
||||
{
|
||||
if ($bgcc == "even")
|
||||
{
|
||||
$bgcc = "odd";
|
||||
}
|
||||
else
|
||||
{
|
||||
$bgcc = "even";
|
||||
}
|
||||
$aData['dtrow'] = $dtrow;
|
||||
$aData['bgcc'] = $bgcc;
|
||||
$aData['oBrowseLanguage']=$oBrowseLanguage;
|
||||
$aViewUrls['browseallrow_view'][] = $aData;
|
||||
}
|
||||
|
||||
$aViewUrls[] = 'browseallfooter_view';
|
||||
$this->_renderWrappedTemplate('',$aViewUrls, $aData);
|
||||
}
|
||||
else
|
||||
{
|
||||
$clang = $this->getController()->lang;
|
||||
$aData['surveyid'] = $iSurveyID;
|
||||
App()->getClientScript()->registerPackage('jquery-superfish');
|
||||
$message['title']= $clang->gT('Access denied!');
|
||||
$message['message']= $clang->gT('You do not have sufficient rights to access this page.');
|
||||
$message['class']= "error";
|
||||
$this->_renderWrappedTemplate('survey', array("message"=>$message), $aData);
|
||||
}
|
||||
}
|
||||
|
||||
public function time($iSurveyID)
|
||||
{
|
||||
$aData = $this->_getData(array('iSurveyId' => $iSurveyID));
|
||||
extract($aData);
|
||||
$aViewUrls = array();
|
||||
|
||||
if ($aData['surveyinfo']['savetimings'] != "Y")
|
||||
die();
|
||||
|
||||
if (Yii::app()->request->getPost('deleteanswer') && Yii::app()->request->getPost('deleteanswer') != '' && Yii::app()->request->getPost('deleteanswer') != 'marked'
|
||||
&& Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'delete'))
|
||||
{
|
||||
$iResponseID=(int) Yii::app()->request->getPost('deleteanswer');
|
||||
SurveyDynamic::model($iSurveyID)->deleteByPk($iResponseID);
|
||||
SurveyTimingDynamic::model($iSurveyID)->deleteByPk($iResponseID);
|
||||
}
|
||||
|
||||
if (Yii::app()->request->getPost('markedresponses') && count(Yii::app()->request->getPost('markedresponses')) > 0)
|
||||
{
|
||||
if (Yii::app()->request->getPost('deleteanswer') && Yii::app()->request->getPost('deleteanswer') === 'marked' &&
|
||||
Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'delete'))
|
||||
{
|
||||
foreach (Yii::app()->request->getPost('markedresponses') as $iResponseID)
|
||||
{
|
||||
$iResponseID=(int) $iResponseID;
|
||||
SurveyDynamic::model($iSurveyID)->deleteByPk($iResponseID);
|
||||
SurveyTimingDynamic::model($iSurveyID)->deleteByPk($iResponseID);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$fields = createTimingsFieldMap($iSurveyID, 'full',true,false,$aData['language']);
|
||||
|
||||
$clang = $aData['clang'];
|
||||
foreach ($fields as $fielddetails)
|
||||
{
|
||||
// headers for answer id and time data
|
||||
if ($fielddetails['type'] == 'id')
|
||||
$fnames[] = array($fielddetails['fieldname'], $fielddetails['question']);
|
||||
if ($fielddetails['type'] == 'interview_time')
|
||||
$fnames[] = array($fielddetails['fieldname'], $clang->gT('Total time'));
|
||||
if ($fielddetails['type'] == 'page_time')
|
||||
$fnames[] = array($fielddetails['fieldname'], $clang->gT('Group') . ": " . $fielddetails['group_name']);
|
||||
if ($fielddetails['type'] == 'answer_time')
|
||||
$fnames[] = array($fielddetails['fieldname'], $clang->gT('Question') . ": " . $fielddetails['title']);
|
||||
}
|
||||
$fncount = count($fnames);
|
||||
|
||||
//NOW LETS CREATE A TABLE WITH THOSE HEADINGS
|
||||
foreach ($fnames as $fn)
|
||||
{
|
||||
if (!isset($currentgroup))
|
||||
{
|
||||
$currentgroup = $fn[1];
|
||||
$gbc = "oddrow";
|
||||
}
|
||||
if ($currentgroup != $fn[1])
|
||||
{
|
||||
$currentgroup = $fn[1];
|
||||
if ($gbc == "oddrow")
|
||||
{
|
||||
$gbc = "evenrow";
|
||||
}
|
||||
else
|
||||
{
|
||||
$gbc = "oddrow";
|
||||
}
|
||||
}
|
||||
}
|
||||
$aData['fnames'] = $fnames;
|
||||
$start = Yii::app()->request->getParam('start', 0);
|
||||
$limit = Yii::app()->request->getParam('limit', 50);
|
||||
if(!$limit){$limit=50;}
|
||||
//LETS COUNT THE DATA
|
||||
$oCriteria = new CdbCriteria();
|
||||
$oCriteria->select = 'tid';
|
||||
$oCriteria->join = "INNER JOIN {{survey_{$iSurveyID}}} s ON t.id=s.id";
|
||||
$oCriteria->condition = 'submitdate IS NOT NULL';
|
||||
$dtcount = SurveyTimingDynamic::model($iSurveyID)->count($oCriteria); // or die("Couldn't get response data");
|
||||
|
||||
if ($limit > $dtcount)
|
||||
{
|
||||
$limit = $dtcount;
|
||||
}
|
||||
|
||||
//NOW LETS SHOW THE DATA
|
||||
$oCriteria = new CdbCriteria();
|
||||
$oCriteria->join = "INNER JOIN {{survey_{$iSurveyID}}} s ON t.id=s.id";
|
||||
$oCriteria->condition = 'submitdate IS NOT NULL';
|
||||
$oCriteria->order = "s.id " . (Yii::app()->request->getParam('order') == 'desc' ? 'desc' : 'asc');
|
||||
$oCriteria->offset = $start;
|
||||
$oCriteria->limit = $limit;
|
||||
|
||||
$dtresult = SurveyTimingDynamic::model($iSurveyID)->findAllAsArray($oCriteria);
|
||||
$dtcount2 = count($dtresult);
|
||||
$cells = $fncount + 1;
|
||||
|
||||
//CONTROL MENUBAR
|
||||
$last = $start - $limit;
|
||||
$next = $start + $limit;
|
||||
$end = $dtcount - $limit;
|
||||
if ($end < 0)
|
||||
{
|
||||
$end = 0;
|
||||
}
|
||||
if ($last < 0)
|
||||
{
|
||||
$last = 0;
|
||||
}
|
||||
if ($next >= $dtcount)
|
||||
{
|
||||
$next = $dtcount - $limit;
|
||||
}
|
||||
if ($end < 0)
|
||||
{
|
||||
$end = 0;
|
||||
}
|
||||
|
||||
$aData['sCompletionStateValue']=incompleteAnsFilterState();
|
||||
$aData['start'] = $start;
|
||||
$aData['limit'] = $limit;
|
||||
$aData['last'] = $last;
|
||||
$aData['next'] = $next;
|
||||
$aData['end'] = $end;
|
||||
$aViewUrls[] = 'browsetimeheader_view';
|
||||
|
||||
$aData['fncount'] = $fncount;
|
||||
$bgcc = 'oddrow';
|
||||
|
||||
foreach ($dtresult as $dtrow)
|
||||
{
|
||||
if ($bgcc == "evenrow")
|
||||
{
|
||||
$bgcc = "oddrow";
|
||||
}
|
||||
else
|
||||
{
|
||||
$bgcc = "evenrow";
|
||||
}
|
||||
$browsedatafield=array();
|
||||
for ($i = 0; $i < $fncount; $i++)
|
||||
{
|
||||
$browsedatafield[$i] = $dtrow[$fnames[$i][0]];
|
||||
// seconds -> minutes & seconds
|
||||
if (strtolower(substr($fnames[$i][0], -4)) == "time")
|
||||
{
|
||||
$minutes = (int) ($browsedatafield[$i] / 60);
|
||||
$seconds = $browsedatafield[$i] % 60;
|
||||
$browsedatafield[$i] = '';
|
||||
if ($minutes > 0)
|
||||
$browsedatafield[$i] .= "$minutes min ";
|
||||
$browsedatafield[$i] .= "$seconds s";
|
||||
}
|
||||
}
|
||||
$aData['browsedatafield'] = $browsedatafield;
|
||||
$aData['bgcc'] = $bgcc;
|
||||
$aData['dtrow'] = $dtrow;
|
||||
$aViewUrls['browsetimerow_view'][] = $aData;
|
||||
}
|
||||
|
||||
//interview Time statistics
|
||||
$aData['statistics'] = SurveyTimingDynamic::model($iSurveyId)->statistics();
|
||||
$aData['num_total_answers'] = SurveyDynamic::model($iSurveyID)->count();
|
||||
$aData['num_completed_answers'] = SurveyDynamic::model($iSurveyID)->count('submitdate IS NOT NULL');
|
||||
$aViewUrls[] = 'browsetimefooter_view';
|
||||
$this->_renderWrappedTemplate('',$aViewUrls, $aData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Supply an array with the responseIds and all files will be added to the zip
|
||||
* and it will be be spit out on success
|
||||
*
|
||||
* @param array $responseIds
|
||||
* @param string $zipfilename
|
||||
* @param string $language
|
||||
* @return ZipArchive
|
||||
*/
|
||||
private function _zipFiles($iSurveyID, $responseIds, $zipfilename)
|
||||
{
|
||||
/**
|
||||
* @todo Move this to model.
|
||||
*/
|
||||
Yii::app()->loadLibrary('admin/pclzip');
|
||||
|
||||
$tmpdir = Yii::app()->getConfig('uploaddir') . DIRECTORY_SEPARATOR."surveys". DIRECTORY_SEPARATOR . $iSurveyID . DIRECTORY_SEPARATOR."files".DIRECTORY_SEPARATOR;
|
||||
|
||||
$filelist = array();
|
||||
$responses = Response::model($iSurveyID)->findAllByPk($responseIds);
|
||||
$filecount = 0;
|
||||
foreach ($responses as $response)
|
||||
{
|
||||
foreach ($response->getFiles() as $file)
|
||||
{
|
||||
$filecount++;
|
||||
/*
|
||||
* Now add the file to the archive, prefix files with responseid_index to keep them
|
||||
* unique. This way we can have 234_1_image1.gif, 234_2_image1.gif as it could be
|
||||
* files from a different source with the same name.
|
||||
*/
|
||||
if (file_exists($tmpdir . basename($file['filename'])))
|
||||
{
|
||||
$filelist[] = array(PCLZIP_ATT_FILE_NAME => $tmpdir . basename($file['filename']),
|
||||
PCLZIP_ATT_FILE_NEW_FULL_NAME => sprintf("%05s_%02s_%s", $response->id, $filecount, rawurldecode($file['name'])));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (count($filelist) > 0)
|
||||
{
|
||||
$zip = new PclZip($tmpdir . $zipfilename);
|
||||
if ($zip->create($filelist) === 0)
|
||||
{
|
||||
//Oops something has gone wrong!
|
||||
}
|
||||
|
||||
if (file_exists($tmpdir . '/' . $zipfilename))
|
||||
{
|
||||
@ob_clean();
|
||||
header('Content-Description: File Transfer');
|
||||
header('Content-Type: application/octet-stream');
|
||||
header('Content-Disposition: attachment; filename=' . basename($zipfilename));
|
||||
header('Content-Transfer-Encoding: binary');
|
||||
header('Expires: 0');
|
||||
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
|
||||
header('Pragma: public');
|
||||
header('Content-Length: ' . filesize($tmpdir . "/" . $zipfilename));
|
||||
readfile($tmpdir . '/' . $zipfilename);
|
||||
unlink($tmpdir . '/' . $zipfilename);
|
||||
exit;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders template(s) wrapped in header and footer
|
||||
*
|
||||
* @param string|array $aViewUrls View url(s)
|
||||
* @param array $aData Data to be passed on. Optional.
|
||||
*/
|
||||
protected function _renderWrappedTemplate($sAction='', $aViewUrls = array(), $aData = array())
|
||||
{
|
||||
App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . 'browse.js');
|
||||
|
||||
$aData['display']['menu_bars'] = false;
|
||||
$aData['display']['menu_bars']['browse'] = Yii::app()->lang->gT('Browse responses'); // browse is independent of the above
|
||||
|
||||
parent::_renderWrappedTemplate('responses', $aViewUrls, $aData);
|
||||
}
|
||||
|
||||
}
|
96
sources/application/controllers/admin/saved.php
Normal file
96
sources/application/controllers/admin/saved.php
Normal file
|
@ -0,0 +1,96 @@
|
|||
<?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.
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* Saved controller
|
||||
*
|
||||
* @package LimeSurvey
|
||||
* @copyright 2011
|
||||
* @access public
|
||||
*/
|
||||
class saved extends Survey_Common_Action
|
||||
{
|
||||
|
||||
public function view($iSurveyId)
|
||||
{
|
||||
$iSurveyId = sanitize_int($iSurveyId);
|
||||
$clang = $this->getController()->lang;
|
||||
$aViewUrls = array();
|
||||
|
||||
if (!Permission::model()->hasSurveyPermission($iSurveyId, 'responses', 'read'))
|
||||
{
|
||||
die();
|
||||
}
|
||||
|
||||
App()->getClientScript()->registerPackage('jquery-tablesorter');
|
||||
App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . 'saved.js');
|
||||
|
||||
$aThisSurvey = getSurveyInfo($iSurveyId);
|
||||
$aData['sSurveyName'] = $aThisSurvey['name'];
|
||||
$aData['iSurveyId'] = $iSurveyId;
|
||||
$aViewUrls[] = 'savedbar_view';
|
||||
$aViewUrls['savedlist_view'][] = $this->_showSavedList($iSurveyId);
|
||||
|
||||
$this->_renderWrappedTemplate('saved', $aViewUrls, $aData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Function responsible to delete saved responses.
|
||||
*/
|
||||
public function delete($iSurveyId, $iSurveyResponseId, $iSavedControlId)
|
||||
{
|
||||
$clang = $this->getController()->lang;
|
||||
|
||||
SavedControl::model()->deleteAllByAttributes(array('scid' => $iSavedControlId, 'sid' => $iSurveyId)) or die($clang->gT("Couldn't delete"));
|
||||
Yii::app()->db->createCommand()->delete("{{survey_".intval($iSurveyId)."}}", 'id=:id', array('id' => $iSurveyResponseId)) or die($clang->gT("Couldn't delete"));
|
||||
|
||||
$this->getController()->redirect(array("admin/saved/sa/view/surveyid/{$iSurveyId}"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders template(s) wrapped in header and footer
|
||||
*
|
||||
* @param string $sAction Current action, the folder to fetch views from
|
||||
* @param string|array $aViewUrls View url(s)
|
||||
* @param array $aData Data to be passed on. Optional.
|
||||
*/
|
||||
protected function _renderWrappedTemplate($sAction = 'saved', $aViewUrls = array(), $aData = array())
|
||||
{
|
||||
$aData['display']['menu_bars'] = false;
|
||||
parent::_renderWrappedTemplate($sAction, $aViewUrls, $aData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load saved list.
|
||||
* @param mixed $iSurveyId Survey id
|
||||
*/
|
||||
private function _showSavedList($iSurveyId)
|
||||
{
|
||||
$clang = $this->getController()->lang;
|
||||
$aResults = SavedControl::model()->findAll(array(
|
||||
'select' => array('scid', 'srid', 'identifier', 'ip', 'saved_date', 'email', 'access_code'),
|
||||
'condition' => 'sid=:sid',
|
||||
'order' => 'saved_date desc',
|
||||
'params' => array(':sid' => $iSurveyId),
|
||||
));
|
||||
|
||||
if (!empty($aResults))
|
||||
{
|
||||
return compact('aResults');
|
||||
}
|
||||
else
|
||||
{return array('aResults'=>array());}
|
||||
}
|
||||
|
||||
}
|
634
sources/application/controllers/admin/statistics.php
Normal file
634
sources/application/controllers/admin/statistics.php
Normal file
|
@ -0,0 +1,634 @@
|
|||
<?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.
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* Statistics Controller
|
||||
*
|
||||
* This controller performs statistics actions
|
||||
*
|
||||
* @package LimeSurvey
|
||||
* @subpackage Backend
|
||||
*/
|
||||
class statistics extends Survey_Common_Action {
|
||||
|
||||
function __construct($controller, $id)
|
||||
{
|
||||
parent::__construct($controller, $id);
|
||||
|
||||
Yii::app()->loadHelper("surveytranslator");
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*/
|
||||
public function run($surveyid = 0, $subaction = null)
|
||||
{
|
||||
$surveyid = sanitize_int($surveyid);
|
||||
//TODO: Convert question types to views
|
||||
$clang = $this->getController()->lang;
|
||||
|
||||
$imageurl = Yii::app()->getConfig("imageurl");
|
||||
$aData = array('clang' => $clang, 'imageurl' => $imageurl);
|
||||
$aData['sql']='';
|
||||
|
||||
/*
|
||||
* We need this later:
|
||||
* 1 - Array Dual Scale
|
||||
* 5 - 5 Point Choice
|
||||
* A - Array (5 Point Choice)
|
||||
* B - Array (10 Point Choice)
|
||||
* C - Array (Yes/No/Uncertain)
|
||||
* D - Date
|
||||
* E - Array (Increase, Same, Decrease)
|
||||
* F - Array (Flexible Labels)
|
||||
* G - Gender
|
||||
* H - Array (Flexible Labels) by Column
|
||||
* I - Language Switch
|
||||
* K - Multiple Numerical Input
|
||||
* L - List (Radio)
|
||||
* M - Multiple choice
|
||||
* N - Numerical Input
|
||||
* O - List With Comment
|
||||
* P - Multiple choice with comments
|
||||
* Q - Multiple Short Text
|
||||
* R - Ranking
|
||||
* S - Short Free Text
|
||||
* T - Long Free Text
|
||||
* U - Huge Free Text
|
||||
* X - Boilerplate Question
|
||||
* Y - Yes/No
|
||||
* ! - List (Dropdown)
|
||||
* : - Array (Flexible Labels) multiple drop down
|
||||
* ; - Array (Flexible Labels) multiple texts
|
||||
* | - File Upload
|
||||
|
||||
|
||||
Debugging help:
|
||||
echo '<script language="javascript" type="text/javascript">alert("HI");</script>';
|
||||
*/
|
||||
|
||||
//split up results to extend statistics -> NOT WORKING YET! DO NOT ENABLE THIS!
|
||||
$showcombinedresults = 0;
|
||||
|
||||
/*
|
||||
* this variable is used in the function shortencode() which cuts off a question/answer title
|
||||
* after $maxchars and shows the rest as tooltip
|
||||
*/
|
||||
$maxchars = 50;
|
||||
|
||||
//we collect all the output within this variable
|
||||
$statisticsoutput ='';
|
||||
|
||||
//output for chosing questions to cross query
|
||||
$cr_statisticsoutput = '';
|
||||
|
||||
// This gets all the 'to be shown questions' from the POST and puts these into an array
|
||||
$summary=returnGlobal('summary');
|
||||
$statlang=returnGlobal('statlang');
|
||||
|
||||
//if $summary isn't an array we create one
|
||||
if (isset($summary) && !is_array($summary)) {
|
||||
$summary = explode("+", $summary);
|
||||
}
|
||||
|
||||
//no survey ID? -> come and get one
|
||||
if (!isset($surveyid)) {$surveyid=returnGlobal('sid');}
|
||||
|
||||
//still no survey ID -> error
|
||||
$aData['surveyid'] = $surveyid;
|
||||
|
||||
|
||||
// Set language for questions and answers to base language of this survey
|
||||
$language = Survey::model()->findByPk($surveyid)->language;
|
||||
$aData['language'] = $language;
|
||||
|
||||
|
||||
//Call the javascript file
|
||||
App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . 'statistics.js');
|
||||
App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . 'json-js/json2.min.js');
|
||||
|
||||
$aData['display']['menu_bars']['browse'] = $clang->gT("Quick statistics");
|
||||
|
||||
//Select public language file
|
||||
$row = Survey::model()->find('sid = :sid', array(':sid' => $surveyid));
|
||||
|
||||
/*
|
||||
* check if there is a datestamp available for this survey
|
||||
* yes -> $datestamp="Y"
|
||||
* no -> $datestamp="N"
|
||||
*/
|
||||
$datestamp = $row->datestamp;
|
||||
|
||||
// 1: Get list of questions from survey
|
||||
|
||||
/*
|
||||
* We want to have the following data
|
||||
* a) "questions" -> all table namens, e.g.
|
||||
* qid
|
||||
* sid
|
||||
* gid
|
||||
* type
|
||||
* title
|
||||
* question
|
||||
* preg
|
||||
* help
|
||||
* other
|
||||
* mandatory
|
||||
* lid
|
||||
* lid1
|
||||
* question_order
|
||||
* language
|
||||
*
|
||||
* b) "groups" -> group_name + group_order *
|
||||
*/
|
||||
|
||||
//store all the data in $rows
|
||||
$rows = Question::model()->getQuestionList($surveyid, $language);
|
||||
|
||||
//SORT IN NATURAL ORDER!
|
||||
usort($rows, 'groupOrderThenQuestionOrder');
|
||||
|
||||
//put the question information into the filter array
|
||||
$filters = array();
|
||||
foreach ($rows as $row)
|
||||
{
|
||||
//store some column names in $filters array
|
||||
$filters[]=array($row['qid'],
|
||||
$row['gid'],
|
||||
$row['type'],
|
||||
$row['title'],
|
||||
$row['group_name'],
|
||||
flattenText($row['question']));
|
||||
}
|
||||
$aData['filters'] = $filters;
|
||||
|
||||
//var_dump($filters);
|
||||
// SHOW ID FIELD
|
||||
|
||||
$grapherror = false;
|
||||
$error = '';
|
||||
if (!function_exists("gd_info")) {
|
||||
$grapherror = true;
|
||||
$error.='<br />'.$clang->gT('You do not have the GD Library installed. Showing charts requires the GD library to function properly.');
|
||||
$error.='<br />'.$clang->gT('visit http://us2.php.net/manual/en/ref.image.php for more information').'<br />';
|
||||
}
|
||||
elseif (!function_exists("imageftbbox")) {
|
||||
$grapherror = true;
|
||||
$error.='<br />'.$clang->gT('You do not have the Freetype Library installed. Showing charts requires the Freetype library to function properly.');
|
||||
$error.='<br />'.$clang->gT('visit http://us2.php.net/manual/en/ref.image.php for more information').'<br />';
|
||||
}
|
||||
|
||||
if ($grapherror)
|
||||
{
|
||||
unset($_POST['usegraph']);
|
||||
}
|
||||
|
||||
|
||||
//pre-selection of filter forms
|
||||
if (incompleteAnsFilterState() == "complete")
|
||||
{
|
||||
$selecthide="selected='selected'";
|
||||
$selectshow="";
|
||||
$selectinc="";
|
||||
}
|
||||
elseif (incompleteAnsFilterState() == "incomplete")
|
||||
{
|
||||
$selecthide="";
|
||||
$selectshow="";
|
||||
$selectinc="selected='selected'";
|
||||
}
|
||||
else
|
||||
{
|
||||
$selecthide="";
|
||||
$selectshow="selected='selected'";
|
||||
$selectinc="";
|
||||
}
|
||||
$aData['selecthide'] = $selecthide;
|
||||
$aData['selectshow'] = $selectshow;
|
||||
$aData['selectinc'] = $selectinc;
|
||||
$aData['error'] = $error;
|
||||
|
||||
$survlangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
|
||||
$survlangs[] = Survey::model()->findByPk($surveyid)->language;
|
||||
$aData['survlangs'] = $survlangs;
|
||||
$aData['datestamp'] = $datestamp;
|
||||
|
||||
//if the survey contains timestamps you can filter by timestamp, too
|
||||
|
||||
//Output selector
|
||||
|
||||
//second row below options -> filter settings headline
|
||||
|
||||
$filterchoice_state=returnGlobal('filterchoice_state');
|
||||
$aData['filterchoice_state'] = $filterchoice_state;
|
||||
|
||||
|
||||
/*
|
||||
* let's go through the filter array which contains
|
||||
* ['qid'],
|
||||
['gid'],
|
||||
['type'],
|
||||
['title'],
|
||||
['group_name'],
|
||||
['question'],
|
||||
['lid'],
|
||||
['lid1']);
|
||||
*/
|
||||
|
||||
$currentgroup='';
|
||||
$counter = 0;
|
||||
foreach ($filters as $key1 => $flt)
|
||||
{
|
||||
//is there a previous question type set?
|
||||
|
||||
|
||||
/*
|
||||
* remember: $flt is structured like this
|
||||
* ['qid'],
|
||||
['gid'],
|
||||
['type'],
|
||||
['title'],
|
||||
['group_name'],
|
||||
['question'],
|
||||
['lid'],
|
||||
['lid1']);
|
||||
*/
|
||||
|
||||
//SGQ identifier
|
||||
|
||||
//full question title
|
||||
|
||||
/*
|
||||
* Check question type: This question types will be used (all others are separated in the if clause)
|
||||
* 5 - 5 Point Choice
|
||||
G - Gender
|
||||
I - Language Switch
|
||||
L - List (Radio)
|
||||
M - Multiple choice
|
||||
N - Numerical Input
|
||||
| - File Upload
|
||||
O - List With Comment
|
||||
P - Multiple choice with comments
|
||||
Y - Yes/No
|
||||
! - List (Dropdown) )
|
||||
*/
|
||||
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
//This section presents the filter list, in various different ways depending on the question type
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
//let's switch through the question type for each question
|
||||
switch ($flt[2])
|
||||
{
|
||||
case "K": // Multiple Numerical
|
||||
//get answers
|
||||
$result = Question::model()->getQuestionsForStatistics('title as code, question as answer', "parent_qid=$flt[0] AND language = '{$language}'", 'question_order');
|
||||
$aData['result'][$key1]['key1'] = $result;
|
||||
break;
|
||||
|
||||
|
||||
|
||||
case "Q": // Multiple Short Text
|
||||
|
||||
//get subqestions
|
||||
$result = Question::model()->getQuestionsForStatistics('title as code, question as answer', "parent_qid=$flt[0] AND language = '{$language}'", 'question_order');
|
||||
$aData['result'][$key1] = $result;
|
||||
break;
|
||||
|
||||
//----------------------- ARRAYS --------------------------
|
||||
|
||||
case "A": // ARRAY OF 5 POINT CHOICE QUESTIONS
|
||||
|
||||
//get answers
|
||||
$result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid=$flt[0] AND language = '{$language}'", 'question_order');
|
||||
$aData['result'][$key1] = $result;
|
||||
break;
|
||||
|
||||
|
||||
|
||||
//just like above only a different loop
|
||||
case "B": // ARRAY OF 10 POINT CHOICE QUESTIONS
|
||||
$result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid=$flt[0] AND language = '{$language}'", 'question_order');
|
||||
$aData['result'][$key1] = $result;
|
||||
break;
|
||||
|
||||
|
||||
|
||||
case "C": // ARRAY OF YES\No\$clang->gT("Uncertain") QUESTIONS
|
||||
//get answers
|
||||
$result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid=$flt[0] AND language = '{$language}'", 'question_order');
|
||||
$aData['result'][$key1] = $result;
|
||||
break;
|
||||
|
||||
|
||||
|
||||
//similiar to the above one
|
||||
case "E": // ARRAY OF Increase/Same/Decrease QUESTIONS
|
||||
$result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid=$flt[0] AND language = '{$language}'", 'question_order');
|
||||
$aData['result'][$key1] = $result;
|
||||
break;
|
||||
|
||||
case ";": //ARRAY (Multi Flex) (Text)
|
||||
$result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid=$flt[0] AND language = '{$language}' AND scale_id = 0", 'question_order');
|
||||
$aData['result'][$key1] = $result;
|
||||
foreach($result as $key => $row)
|
||||
{
|
||||
$fresult = Question::model()->getQuestionsForStatistics('title, question', "parent_qid=$flt[0] AND language = '{$language}' AND scale_id = 1", 'question_order');
|
||||
$aData['fresults'][$key1][$key] = $fresult;
|
||||
}
|
||||
break;
|
||||
|
||||
case ":": //ARRAY (Multi Flex) (Numbers)
|
||||
$result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid=$flt[0] AND language = '{$language}' AND scale_id = 0", 'question_order');
|
||||
$aData['result'][$key1] = $result;
|
||||
foreach($result as $row)
|
||||
{
|
||||
$fresult = Question::model()->getQuestionsForStatistics('*', "parent_qid=$flt[0] AND language = '{$language}' AND scale_id = 1", 'question_order, title');
|
||||
$aData['fresults'][$key1] = $fresult;
|
||||
}
|
||||
break;
|
||||
/*
|
||||
* For question type "F" and "H" you can use labels.
|
||||
* The only difference is that the labels are applied to column heading
|
||||
* or rows respectively
|
||||
*/
|
||||
case "F": // FlEXIBLE ARRAY
|
||||
case "H": // ARRAY (By Column)
|
||||
//Get answers. We always use the answer code because the label might be too long elsewise
|
||||
$result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid=$flt[0] AND language = '{$language}'", 'question_order');
|
||||
$aData['result'][$key1] = $result;
|
||||
|
||||
//check all the answers
|
||||
foreach($result as $row)
|
||||
{
|
||||
$fresult = Answer::model()->getQuestionsForStatistics('*', "qid=$flt[0] AND language = '{$language}'", 'sortorder, code');
|
||||
$aData['fresults'][$key1] = $fresult;
|
||||
}
|
||||
|
||||
//$statisticsoutput .= "\t\t\t\t<td>\n";
|
||||
$counter=0;
|
||||
break;
|
||||
|
||||
|
||||
|
||||
case "R": //RANKING
|
||||
//get some answers
|
||||
$result = Answer::model()->getQuestionsForStatistics('code, answer', "qid=$flt[0] AND language = '{$language}'", 'sortorder, answer');
|
||||
$aData['result'][$key1] = $result;
|
||||
break;
|
||||
|
||||
case "1": // MULTI SCALE
|
||||
|
||||
//get answers
|
||||
$result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid=$flt[0] AND language = '{$language}'", 'question_order');
|
||||
$aData['result'][$key1] = $result;
|
||||
//loop through answers
|
||||
foreach($result as $key => $row)
|
||||
{
|
||||
|
||||
//check if there is a dualscale_headerA/B
|
||||
$dshresult = QuestionAttribute::model()->getQuestionsForStatistics('value', "qid=$flt[0] AND attribute = 'dualscale_headerA'", '');
|
||||
$aData['dshresults'][$key1][$key] = $dshresult;
|
||||
|
||||
|
||||
$fresult = Answer::model()->getQuestionsForStatistics('*', "qid=$flt[0] AND language = '{$language}' AND scale_id = 0", 'sortorder, code');
|
||||
|
||||
$aData['fresults'][$key1][$key] = $fresult;
|
||||
|
||||
|
||||
$dshresult2 = QuestionAttribute::model()->getQuestionsForStatistics('value', "qid=$flt[0] AND attribute = 'dualscale_headerB'", '');
|
||||
$aData['dshresults2'][$key1][$key] = $dshresult2;
|
||||
}
|
||||
break;
|
||||
|
||||
case "P": //P - Multiple choice with comments
|
||||
case "M": //M - Multiple choice
|
||||
|
||||
//get answers
|
||||
$result = Question::model()->getQuestionsForStatistics('title, question', "parent_qid = $flt[0] AND language = '$language'", 'question_order');
|
||||
$aData['result'][$key1] = $result;
|
||||
break;
|
||||
|
||||
|
||||
/*
|
||||
* This question types use the default settings:
|
||||
* L - List (Radio)
|
||||
O - List With Comment
|
||||
P - Multiple choice with comments
|
||||
! - List (Dropdown)
|
||||
*/
|
||||
default:
|
||||
|
||||
//get answers
|
||||
$result = Answer::model()->getQuestionsForStatistics('code, answer', "qid=$flt[0] AND language = '$language'", 'sortorder, answer');
|
||||
$aData['result'][$key1] = $result;
|
||||
break;
|
||||
|
||||
} //end switch -> check question types and create filter forms
|
||||
|
||||
$currentgroup=$flt[1];
|
||||
|
||||
$counter++;
|
||||
|
||||
//temporary save the type of the previous question
|
||||
//used to adjust linebreaks
|
||||
$previousquestiontype = $flt[2];
|
||||
|
||||
}
|
||||
|
||||
// ----------------------------------- END FILTER FORM ---------------------------------------
|
||||
|
||||
Yii::app()->loadHelper('admin/statistics');
|
||||
$showtextinline=isset($_POST['showtextinline']) ? 1 : 0;
|
||||
$aData['showtextinline'] = $showtextinline;
|
||||
|
||||
//Show Summary results
|
||||
if (isset($summary) && $summary)
|
||||
{
|
||||
$usegraph=isset($_POST['usegraph']) ? 1 : 0;
|
||||
$aData['usegraph'] = $usegraph;
|
||||
$outputType = $_POST['outputtype'];
|
||||
|
||||
$helper = new statistics_helper();
|
||||
switch($outputType){
|
||||
case 'html':
|
||||
$statisticsoutput .= $helper->generate_statistics($surveyid,$summary,$summary,$usegraph,$outputType,'DD',$statlang);
|
||||
break;
|
||||
case 'pdf':
|
||||
$helper->generate_statistics($surveyid,$summary,$summary,$usegraph,$outputType,'I',$statlang);
|
||||
exit;
|
||||
break;
|
||||
case 'xls':
|
||||
$helper->generate_statistics($surveyid,$summary,$summary,$usegraph,$outputType,'DD',$statlang);
|
||||
exit;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
} //end if -> show summary results
|
||||
|
||||
$aData['sStatisticsLanguage']=$statlang;
|
||||
$aData['output'] = $statisticsoutput;
|
||||
$aData['summary'] = $summary;
|
||||
|
||||
$this->_renderWrappedTemplate('export', 'statistics_view', $aData);
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns a simple list of values in a particular column, that meet the requirements of the SQL
|
||||
*/
|
||||
function listcolumn($surveyid, $column, $sortby="", $sortmethod="", $sorttype="")
|
||||
{
|
||||
Yii::app()->loadHelper('admin/statistics');
|
||||
$helper = new statistics_helper();
|
||||
$aData['data']=$helper->_listcolumn($surveyid, $column, $sortby, $sortmethod, $sorttype);
|
||||
$aData['surveyid']=$surveyid;
|
||||
$aData['column']=$column;
|
||||
$aData['sortby']=$sortby;
|
||||
$aData['sortmethod']=$sortmethod;
|
||||
$aData['sorttype']=$sorttype;
|
||||
App()->getClientScript()->reset();
|
||||
$this->getController()->render('export/statistics_browse_view', $aData);
|
||||
}
|
||||
|
||||
|
||||
function graph()
|
||||
{
|
||||
Yii::app()->loadHelper('admin/statistics');
|
||||
Yii::app()->loadHelper("surveytranslator");
|
||||
|
||||
// Initialise PCHART
|
||||
require_once(Yii::app()->basePath . '/third_party/pchart/pchart/pChart.class');
|
||||
require_once(Yii::app()->basePath . '/third_party/pchart/pchart/pData.class');
|
||||
require_once(Yii::app()->basePath . '/third_party/pchart/pchart/pCache.class');
|
||||
|
||||
|
||||
Yii::import('application.third_party.ar-php.Arabic', true);
|
||||
|
||||
$tempdir = Yii::app()->getConfig("tempdir");
|
||||
$MyCache = new pCache($tempdir.'/');
|
||||
$aData['success'] = 1;
|
||||
$sStatisticsLanguage=sanitize_languagecode($_POST['sStatisticsLanguage']);
|
||||
$oStatisticsLanguage = new Limesurvey_lang($sStatisticsLanguage);
|
||||
|
||||
if (isset($_POST['cmd']) && isset($_POST['id'])) {
|
||||
list($qsid, $qgid, $qqid) = explode("X", substr($_POST['id'], 0), 3);
|
||||
if(!is_numeric(substr($qsid,0,1))) {
|
||||
// Strip first char when not numeric (probably T or D)
|
||||
$qsid=substr($qsid,1);
|
||||
}
|
||||
$aFieldmap=createFieldMap($qsid,'full',false,false,$sStatisticsLanguage);
|
||||
$qtype=$aFieldmap[$_POST['id']]['type'];
|
||||
$qqid=$aFieldmap[$_POST['id']]['qid'];
|
||||
$aattr = getQuestionAttributeValues($qqid);
|
||||
$field = substr($_POST['id'], 1);
|
||||
|
||||
switch ($_POST['cmd']) {
|
||||
case 'showmap':
|
||||
if (isset($aattr['location_mapservice'])) {
|
||||
|
||||
$aData['mapdata'] = array (
|
||||
"coord" => getQuestionMapData($field, $qsid),
|
||||
"zoom" => $aattr['location_mapzoom'],
|
||||
"width" => $aattr['location_mapwidth'],
|
||||
"height" => $aattr['location_mapheight']
|
||||
);
|
||||
QuestionAttribute::model()->setQuestionAttribute($qqid, 'statistics_showmap', 1);
|
||||
} else {
|
||||
$aData['success'] = 0;
|
||||
}
|
||||
break;
|
||||
case 'hidemap':
|
||||
if (isset($aattr['location_mapservice'])) {
|
||||
$aData['success'] = 1;
|
||||
QuestionAttribute::model()->setQuestionAttribute($qqid, 'statistics_showmap', 0);
|
||||
} else {
|
||||
$aData['success'] = 0;
|
||||
}
|
||||
break;
|
||||
case 'showgraph':
|
||||
if (isset($aattr['location_mapservice'])) {
|
||||
$aData['mapdata'] = array (
|
||||
"coord" => getQuestionMapData($field, $qsid),
|
||||
"zoom" => $aattr['location_mapzoom'],
|
||||
"width" => $aattr['location_mapwidth'],
|
||||
"height" => $aattr['location_mapheight']
|
||||
);
|
||||
}
|
||||
|
||||
$bChartType = $qtype != "M" && $qtype != "P" && $aattr["statistics_graphtype"] == "1";
|
||||
$adata = Yii::app()->session['stats'][$_POST['id']];
|
||||
$aData['chartdata'] = createChart($qqid, $qsid, $bChartType, $adata['lbl'], $adata['gdata'], $adata['grawdata'], $MyCache, $oStatisticsLanguage, $qtype);
|
||||
|
||||
|
||||
QuestionAttribute::model()->setQuestionAttribute($qqid, 'statistics_showgraph', 1);
|
||||
break;
|
||||
case 'hidegraph':
|
||||
QuestionAttribute::model()->setQuestionAttribute($qqid, 'statistics_showgraph', 0);
|
||||
break;
|
||||
case 'showbar':
|
||||
if ($qtype == "M" || $qtype == "P") {
|
||||
$aData['success'] = 0;
|
||||
break;
|
||||
}
|
||||
|
||||
QuestionAttribute::model()->setQuestionAttribute($qqid, 'statistics_graphtype', 0);
|
||||
|
||||
$adata = Yii::app()->session['stats'][$_POST['id']];
|
||||
$aData['chartdata'] = createChart($qqid, $qsid, 0, $adata['lbl'], $adata['gdata'], $adata['grawdata'], $MyCache, $oStatisticsLanguage, $qtype);
|
||||
|
||||
break;
|
||||
case 'showpie':
|
||||
|
||||
if ($qtype == "M" || $qtype == "P") {
|
||||
$aData['success'] = 0;
|
||||
break;
|
||||
}
|
||||
|
||||
QuestionAttribute::model()->setQuestionAttribute($qqid, 'statistics_graphtype', 1);
|
||||
|
||||
$adata = Yii::app()->session['stats'][$_POST['id']];
|
||||
$aData['chartdata'] = createChart($qqid, $qsid, 1, $adata['lbl'], $adata['gdata'], $adata['grawdata'], $MyCache, $oStatisticsLanguage, $qtype);
|
||||
|
||||
|
||||
break;
|
||||
default:
|
||||
$aData['success'] = 0;
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
$aData['success'] = 0;
|
||||
}
|
||||
|
||||
//$this->_renderWrappedTemplate('export', 'statistics_graph_view', $aData);
|
||||
$this->getController()->renderPartial('export/statistics_graph_view', $aData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders template(s) wrapped in header and footer
|
||||
*
|
||||
* @param string $sAction Current action, the folder to fetch views from
|
||||
* @param string|array $aViewUrls View url(s)
|
||||
* @param array $aData Data to be passed on. Optional.
|
||||
*/
|
||||
protected function _renderWrappedTemplate($sAction = 'export', $aViewUrls = array(), $aData = array())
|
||||
{
|
||||
parent::_renderWrappedTemplate($sAction, $aViewUrls, $aData);
|
||||
}
|
||||
|
||||
}
|
1645
sources/application/controllers/admin/surveyadmin.php
Normal file
1645
sources/application/controllers/admin/surveyadmin.php
Normal file
File diff suppressed because it is too large
Load diff
663
sources/application/controllers/admin/surveypermission.php
Normal file
663
sources/application/controllers/admin/surveypermission.php
Normal file
|
@ -0,0 +1,663 @@
|
|||
<?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.
|
||||
*/
|
||||
|
||||
/**
|
||||
* surveypermission
|
||||
*
|
||||
* @package LimeSurvey
|
||||
* @copyright 2011
|
||||
* @access public
|
||||
*/
|
||||
class surveypermission extends Survey_Common_Action {
|
||||
|
||||
/**
|
||||
* Load survey security screen.
|
||||
* @param mixed $surveyid
|
||||
* @return void
|
||||
*/
|
||||
function index($surveyid)
|
||||
{
|
||||
$aData['surveyid'] = $surveyid = sanitize_int($surveyid);
|
||||
$aViewUrls = array();
|
||||
$clang = Yii::app()->lang;
|
||||
$imageurl = Yii::app()->getConfig('adminimageurl');
|
||||
|
||||
if(Permission::model()->hasSurveyPermission($surveyid,'surveysecurity','read'))
|
||||
{
|
||||
$aBaseSurveyPermissions=Permission::model()->getSurveyBasePermissions();
|
||||
$userList=getUserList('onlyuidarray'); // Limit the user list for the samegrouppolicy
|
||||
App()->getClientScript()->registerPackage('jquery-tablesorter');
|
||||
App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . "surveypermissions.js");
|
||||
$surveysecurity ="<div class='header ui-widget-header'>".$clang->gT("Survey permissions")."</div>\n";
|
||||
$result2 = Permission::model()->getUserDetails($surveyid);
|
||||
if(count($result2) > 0)
|
||||
{
|
||||
$surveysecurity = ""
|
||||
. "<table class='surveysecurity'><thead>"
|
||||
. "<tr>\n"
|
||||
. "<th>".$clang->gT("Action")."</th>\n"
|
||||
. "<th>".$clang->gT("Username")."</th>\n"
|
||||
. "<th>".$clang->gT("User group")."</th>\n"
|
||||
. "<th>".$clang->gT("Full name")."</th>\n";
|
||||
foreach ($aBaseSurveyPermissions as $sPermission=>$aSubPermissions )
|
||||
{
|
||||
$surveysecurity.="<th><img src=\"{$imageurl}{$aSubPermissions['img']}_30.png\" alt=\"<span style='font-weight:bold;'>".$aSubPermissions['title']."</span><br />".$aSubPermissions['description']."\" /></th>\n";
|
||||
}
|
||||
$surveysecurity .= "</tr></thead>\n";
|
||||
|
||||
// Foot first
|
||||
|
||||
if (Yii::app()->getConfig('usercontrolSameGroupPolicy') == true)
|
||||
{
|
||||
$authorizedGroupsList = getUserGroupList(NULL,'simplegidarray');
|
||||
}
|
||||
|
||||
$surveysecurity .= "<tbody>\n";
|
||||
$row = 0;
|
||||
foreach ($result2 as $PermissionRow)
|
||||
{
|
||||
if(in_array($PermissionRow['uid'],$userList))
|
||||
{
|
||||
|
||||
$result3 = UserInGroup::model()->with('users')->findAll('users.uid = :uid',array(':uid' => $PermissionRow['uid']));
|
||||
foreach ($result3 as $resul3row)
|
||||
{
|
||||
if (Yii::app()->getConfig('usercontrolSameGroupPolicy') == false ||
|
||||
in_array($resul3row->ugid,$authorizedGroupsList))
|
||||
{
|
||||
$group_ids[] = $resul3row->ugid;
|
||||
}
|
||||
}
|
||||
|
||||
if(isset($group_ids) && $group_ids[0] != NULL)
|
||||
{
|
||||
$group_ids_query = implode(",", $group_ids);
|
||||
unset($group_ids);
|
||||
$result4 = UserGroup::model()->findAll("ugid IN ($group_ids_query)");
|
||||
|
||||
foreach ($result4 as $resul4row)
|
||||
{
|
||||
$group_names[] = $resul4row->name;
|
||||
}
|
||||
if(count($group_names) > 0)
|
||||
$group_names_query = implode(", ", $group_names);
|
||||
}
|
||||
// else {break;} //TODO Commented by lemeur
|
||||
$surveysecurity .= "<tr>\n";
|
||||
|
||||
$surveysecurity .= "<td>\n";
|
||||
|
||||
if(Permission::model()->hasSurveyPermission($surveyid,'surveysecurity','update'))
|
||||
{
|
||||
if($PermissionRow['uid']!=Yii::app()->user->getId() || Permission::model()->hasGlobalPermission('superadmin','read')) // Can not update own security
|
||||
{
|
||||
$surveysecurity .= CHtml::form(array("admin/surveypermission/sa/set/surveyid/{$surveyid}"), 'post', array('style'=>"display:inline;"))
|
||||
."<input type='image' src='{$imageurl}edit_16.png' alt='".$clang->gT("Edit permissions")."' />"
|
||||
."<input type='hidden' name='action' value='setsurveysecurity' />"
|
||||
."<input type='hidden' name='user' value='{$PermissionRow['users_name']}' />"
|
||||
."<input type='hidden' name='uid' value='{$PermissionRow['uid']}' />"
|
||||
."</form>\n";
|
||||
}
|
||||
}
|
||||
if(Permission::model()->hasSurveyPermission($surveyid,'surveysecurity','delete'))
|
||||
{
|
||||
$surveysecurity .= CHtml::form(array("admin/surveypermission/sa/delete/surveyid/{$surveyid}"), 'post', array('style'=>"display:inline;"))
|
||||
."<input type='image' src='{$imageurl}/token_delete.png' alt='".$clang->gT("Delete")."' onclick='return confirm(\"".$clang->gT("Are you sure you want to delete this entry?","js")."\")' />"
|
||||
."<input type='hidden' name='action' value='delsurveysecurity' />"
|
||||
."<input type='hidden' name='user' value='{$PermissionRow['users_name']}' />"
|
||||
."<input type='hidden' name='uid' value='{$PermissionRow['uid']}' />"
|
||||
."</form>";
|
||||
}
|
||||
|
||||
$surveysecurity .= "</td>\n";
|
||||
$surveysecurity .= "<td>{$PermissionRow['users_name']}</td>\n"
|
||||
. "<td>";
|
||||
|
||||
if(isset($group_names) > 0)
|
||||
{
|
||||
$surveysecurity .= $group_names_query;
|
||||
}
|
||||
else
|
||||
{
|
||||
$surveysecurity .= "---";
|
||||
}
|
||||
unset($group_names);
|
||||
|
||||
$surveysecurity .= "</td>\n"
|
||||
. "<td>\n{$PermissionRow['full_name']}</td>\n";
|
||||
|
||||
//Now show the permissions
|
||||
foreach ($aBaseSurveyPermissions as $sPKey=>$aPDetails) {
|
||||
unset($aPDetails['img']);
|
||||
unset($aPDetails['description']);
|
||||
unset($aPDetails['title']);
|
||||
$iCount=0;
|
||||
$iPermissionCount=0;
|
||||
foreach ($aPDetails as $sPDetailKey=>$sPDetailValue)
|
||||
{
|
||||
if ($sPDetailValue && Permission::model()->hasSurveyPermission($surveyid,$sPKey,$sPDetailKey,$PermissionRow['uid']) && !($sPKey=='survey' && $sPDetailKey=='read')) $iCount++;
|
||||
if ($sPDetailValue) $iPermissionCount++;
|
||||
}
|
||||
if ($sPKey=='survey') $iPermissionCount--;
|
||||
if ($iCount==$iPermissionCount) {
|
||||
$insert = "<div class=\"ui-icon ui-icon-check\"> </div>";
|
||||
}
|
||||
elseif ($iCount>0){
|
||||
$insert = "<div class=\"ui-icon ui-icon-check mixed\"> </div>";
|
||||
}
|
||||
else
|
||||
{
|
||||
$insert = "<div> </div>";
|
||||
}
|
||||
$surveysecurity .= "<td>\n$insert\n</td>\n";
|
||||
}
|
||||
|
||||
$surveysecurity .= "</tr>\n";
|
||||
$row++;
|
||||
}
|
||||
}
|
||||
$surveysecurity .= "</tbody>\n"
|
||||
. "</table>\n";
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
}
|
||||
if(Permission::model()->hasSurveyPermission($surveyid,'surveysecurity','create'))
|
||||
{
|
||||
$surveysecurity .= CHtml::form(array("admin/surveypermission/sa/adduser/surveyid/{$surveyid}"), 'post', array('class'=>"form44"))."<ul>\n"
|
||||
. "<li><label for='uidselect'>".$clang->gT("User").": </label><select id='uidselect' name='uid'>\n"
|
||||
. getSurveyUserList(false,false,$surveyid)
|
||||
. "</select>\n"
|
||||
. "<input style='width: 15em;' type='submit' value='".$clang->gT("Add user")."' onclick=\"if (document.getElementById('uidselect').value == -1) { alert('".$clang->gT("Please select a user first","js")."'); return false;}\"/>"
|
||||
. "<input type='hidden' name='action' value='addsurveysecurity' />"
|
||||
. "</li></ul></form>\n";
|
||||
|
||||
$surveysecurity .= CHtml::form(array("admin/surveypermission/sa/addusergroup/surveyid/{$surveyid}"), 'post', array('class'=>"form44"))."<ul><li>\n"
|
||||
. "<label for='ugidselect'>".$clang->gT("User group").": </label><select id='ugidselect' name='ugid'>\n"
|
||||
. getSurveyUserGroupList('htmloptions',$surveyid)
|
||||
. "</select>\n"
|
||||
. "<input style='width: 15em;' type='submit' value='".$clang->gT("Add user group")."' onclick=\"if (document.getElementById('ugidselect').value == -1) { alert('".$clang->gT("Please select a user group first","js")."'); return false;}\" />"
|
||||
. "<input type='hidden' name='action' value='addusergroupsurveysecurity' />\n"
|
||||
. "</li></ul></form>";
|
||||
}
|
||||
|
||||
$aViewUrls['output'] = $surveysecurity;
|
||||
}
|
||||
else
|
||||
{
|
||||
$this->getController()->error('Access denied');
|
||||
}
|
||||
|
||||
$this->_renderWrappedTemplate('authentication', $aViewUrls, $aData);
|
||||
}
|
||||
|
||||
/**
|
||||
* surveypermission::addusergroup()
|
||||
* Function responsible to add usergroup.
|
||||
* @param mixed $surveyid
|
||||
* @return void
|
||||
*/
|
||||
function addusergroup($surveyid)
|
||||
{
|
||||
$aData['surveyid'] = $surveyid = sanitize_int($surveyid);
|
||||
$aViewUrls = array();
|
||||
|
||||
$action = $_POST['action'];
|
||||
$clang = Yii::app()->lang;
|
||||
|
||||
$imageurl = Yii::app()->getConfig('imageurl');
|
||||
|
||||
$postusergroupid = !empty($_POST['ugid']) ? $_POST['ugid'] : false;
|
||||
|
||||
|
||||
if($action == "addusergroupsurveysecurity")
|
||||
{
|
||||
$addsummary = "<div class=\"header\">".$clang->gT("Add user group")."</div>\n";
|
||||
$addsummary .= "<div class=\"messagebox ui-corner-all\" >\n";
|
||||
|
||||
$result = Survey::model()->findAll('sid = :surveyid AND owner_id = :owner_id',array(':surveyid' => $surveyid, ':owner_id' => Yii::app()->session['loginID']));
|
||||
if( Permission::model()->hasSurveyPermission($surveyid, 'surveysecurity', 'create')
|
||||
&& in_array($postusergroupid,getSurveyUserGroupList('simpleugidarray',$surveyid))
|
||||
)
|
||||
{
|
||||
if($postusergroupid > 0){
|
||||
$result2 = User::model()->getCommonUID($surveyid, $postusergroupid); //Checked
|
||||
$result2 = $result2->readAll();
|
||||
if(count($result2) > 0)
|
||||
{
|
||||
foreach ($result2 as $row2 )
|
||||
{
|
||||
$uid_arr[] = $row2['uid'];
|
||||
$isrresult = Permission::model()->insertSomeRecords(array('entity_id' => $surveyid, 'entity'=>'survey', 'uid' => $row2['uid'], 'permission' => 'survey', 'read_p' => 1));
|
||||
if (!$isrresult) break;
|
||||
}
|
||||
|
||||
if($isrresult)
|
||||
{
|
||||
$addsummary .= "<div class=\"successheader\">".$clang->gT("User group added.")."</div>\n";
|
||||
Yii::app()->session['uids'] = $uid_arr;
|
||||
$addsummary .= "<br />"
|
||||
.CHtml::form(array("admin/surveypermission/sa/set/surveyid/{$surveyid}"), 'post')
|
||||
."<input type='submit' value='".$clang->gT("Set Survey Rights")."' />"
|
||||
."<input type='hidden' name='action' value='setusergroupsurveysecurity' />"
|
||||
."<input type='hidden' name='ugid' value='{$postusergroupid}' />"
|
||||
."</form>\n";
|
||||
}
|
||||
else
|
||||
{
|
||||
// Error while adding user to the database
|
||||
$addsummary .= "<div class=\"warningheader\">".$clang->gT("Failed to add user group.")."</div>\n";
|
||||
$addsummary .= "<br/><input type=\"submit\" onclick=\"window.open('".$this->getController()->createUrl('admin/surveypermission/sa/view/surveyid/'.$surveyid)."', '_top')\" value=\"".$clang->gT("Continue")."\"/>\n";
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// no user to add
|
||||
$addsummary .= "<div class=\"warningheader\">".$clang->gT("Failed to add user group.")."</div>\n";
|
||||
$addsummary .= "<br/><input type=\"submit\" onclick=\"window.open('".$this->getController()->createUrl('admin/surveypermission/sa/view/surveyid/'.$surveyid)."', '_top')\" value=\"".$clang->gT("Continue")."\"/>\n";
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
$addsummary .= "<div class=\"warningheader\">".$clang->gT("Failed to add user.")."</div>\n"
|
||||
. "<br />" . $clang->gT("No Username selected.")."<br />\n";
|
||||
$addsummary .= "<br/><input type=\"submit\" onclick=\"window.open('".$this->getController()->createUrl('admin/surveypermission/sa/view/surveyid/'.$surveyid)."', '_top')\" value=\"".$clang->gT("Continue")."\"/>\n";
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
$this->getController()->error('Access denied');
|
||||
}
|
||||
$addsummary .= "</div>\n";
|
||||
|
||||
$aViewUrls['output'] = $addsummary;
|
||||
}
|
||||
|
||||
$this->_renderWrappedTemplate('authentication', $aViewUrls, $aData);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* surveypermission::adduser()
|
||||
* Function responsible to add user.
|
||||
* @param mixed $surveyid
|
||||
* @return void
|
||||
*/
|
||||
function adduser($surveyid)
|
||||
{
|
||||
$aData['surveyid'] = $surveyid = sanitize_int($surveyid);
|
||||
$aViewUrls = array();
|
||||
|
||||
$action = $_POST['action'];
|
||||
|
||||
$clang = Yii::app()->lang;
|
||||
$imageurl = Yii::app()->getConfig('imageurl');
|
||||
$postuserid = $_POST['uid'];
|
||||
|
||||
if($action == "addsurveysecurity")
|
||||
{
|
||||
$addsummary = "<div class='header ui-widget-header'>".$clang->gT("Add user")."</div>\n";
|
||||
$addsummary .= "<div class=\"messagebox ui-corner-all\">\n";
|
||||
|
||||
$result = Survey::model()->findAll('sid = :sid AND owner_id = :owner_id AND owner_id != :postuserid',array(':sid' => $surveyid, ':owner_id' => Yii::app()->session['loginID'], ':postuserid' => $postuserid));
|
||||
if( Permission::model()->hasSurveyPermission($surveyid, 'surveysecurity', 'create')
|
||||
&& in_array($postuserid,getUserList('onlyuidarray'))
|
||||
)
|
||||
{
|
||||
|
||||
if($postuserid > 0){
|
||||
|
||||
$isrresult = Permission::model()->insertSomeRecords(array('entity_id' => $surveyid, 'entity'=>'survey', 'uid' => $postuserid, 'permission' => 'survey', 'read_p' => 1));
|
||||
|
||||
if($isrresult)
|
||||
{
|
||||
|
||||
$addsummary .= "<div class=\"successheader\">".$clang->gT("User added.")."</div>\n";
|
||||
$addsummary .= "<br />"
|
||||
.CHtml::form(array("admin/surveypermission/sa/set/surveyid/{$surveyid}"), 'post')
|
||||
."<input type='submit' value='".$clang->gT("Set survey permissions")."' />"
|
||||
."<input type='hidden' name='action' value='setsurveysecurity' />"
|
||||
."<input type='hidden' name='uid' value='{$postuserid}' />"
|
||||
."</form>\n";
|
||||
}
|
||||
else
|
||||
{
|
||||
// Username already exists.
|
||||
$addsummary .= "<div class=\"warningheader\">".$clang->gT("Failed to add user.")."</div>\n"
|
||||
. "<br />" . $clang->gT("Username already exists.")."<br />\n";
|
||||
$addsummary .= "<br/><input type=\"submit\" onclick=\"window.open('".$this->getController()->createUrl('admin/surveypermission/sa/view/surveyid/'.$surveyid)."', '_top')\" value=\"".$clang->gT("Continue")."\"/>\n";
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
$addsummary .= "<div class=\"warningheader\">".$clang->gT("Failed to add user.")."</div>\n"
|
||||
. "<br />" . $clang->gT("No Username selected.")."<br />\n";
|
||||
$addsummary .= "<br/><input type=\"submit\" onclick=\"window.open('".$this->getController()->createUrl('admin/surveypermission/sa/view/surveyid/'.$surveyid)."', '_top')\" value=\"".$clang->gT("Continue")."\"/>\n";
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
$this->getController()->error('Access denied');
|
||||
}
|
||||
|
||||
$addsummary .= "</div>\n";
|
||||
|
||||
$aViewUrls['output'] = $addsummary;
|
||||
}
|
||||
|
||||
$this->_renderWrappedTemplate('authentication', $aViewUrls, $aData);
|
||||
}
|
||||
|
||||
/**
|
||||
* surveypermission::set()
|
||||
* Function responsible to set permissions to a user/usergroup.
|
||||
* @param mixed $surveyid
|
||||
* @return void
|
||||
*/
|
||||
function set($surveyid)
|
||||
{
|
||||
$aData['surveyid'] = $surveyid = sanitize_int($surveyid);
|
||||
$aViewUrls = array();
|
||||
|
||||
$action = $_POST['action'];
|
||||
|
||||
$clang = Yii::app()->lang;
|
||||
$imageurl = Yii::app()->getConfig('adminimageurl');
|
||||
$postuserid = !empty($_POST['uid']) ? $_POST['uid'] : null;
|
||||
$postusergroupid = !empty($_POST['ugid']) ? $_POST['ugid'] : null;
|
||||
if($action == "setsurveysecurity")
|
||||
{
|
||||
if ( (!Permission::model()->hasGlobalPermission('superadmin','read') && Yii::app()->user->getId()==$postuserid) // User can not change own security (except superadmin)
|
||||
|| !in_array($postuserid,getUserList('onlyuidarray')) // User can not set user security if it can not see it
|
||||
)
|
||||
{
|
||||
$this->getController()->error('Access denied');
|
||||
}
|
||||
}
|
||||
elseif( $action == "setusergroupsurveysecurity" )
|
||||
{
|
||||
if ( !Permission::model()->hasGlobalPermission('superadmin','read') && !in_array($postusergroupid,getUserList('onlyuidarray')) ) // User can not change own security (except for superadmin ?)
|
||||
{
|
||||
$this->getController()->error('Access denied');
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Yii::app()->request->redirect(Yii::app()->getController()->createUrl('admin/surveypermission/sa/view', array('surveyid'=>$surveyid)));
|
||||
//$this->getController()->error('Unknow action');
|
||||
}
|
||||
|
||||
if( Permission::model()->hasSurveyPermission($surveyid, 'surveysecurity', 'update') )
|
||||
{
|
||||
App()->getClientScript()->registerPackage('jquery-tablesorter');
|
||||
App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . "surveypermissions.js");
|
||||
if ($action == "setsurveysecurity")
|
||||
{
|
||||
$query = "select users_name from {{users}} where uid=:uid";
|
||||
$resrow = Yii::app()->db->createCommand($query)->bindParam(":uid", $postuserid, PDO::PARAM_INT)->queryRow();
|
||||
$sUsername=$resrow['users_name'];
|
||||
$usersummary = "<div class='header ui-widget-header'>".sprintf($clang->gT("Edit survey permissions for user %s"),"<span style='font-style:italic'>".$sUsername."</span>")."</div>";
|
||||
}
|
||||
else
|
||||
{
|
||||
$resrow = UserGroup::model()->find('ugid = :ugid',array(':ugid' => $postusergroupid));
|
||||
$sUsergroupName=$resrow['name'];
|
||||
$usersummary = "<div class='header ui-widget-header'>".sprintf($clang->gT("Edit survey permissions for group %s"),"<span style='font-style:italic'>".$sUsergroupName."</span>")."</div>";
|
||||
}
|
||||
$usersummary .= "<br />"
|
||||
.CHtml::form(array("admin/surveypermission/sa/surveyright/surveyid/{$surveyid}"), 'post')
|
||||
. "<table style='margin:0 auto;' class='usersurveypermissions'><thead>\n";
|
||||
|
||||
$usersummary .= ""
|
||||
. "<tr><th></th><th>".$clang->gT("Permission")."</th>\n"
|
||||
. "<th><input type='button' id='btnToggleAdvanced' value='<<' /></th>\n"
|
||||
. "<th class='extended'>".$clang->gT("Create")."</th>\n"
|
||||
. "<th class='extended'>".$clang->gT("View/read")."</th>\n"
|
||||
. "<th class='extended'>".$clang->gT("Update")."</th>\n"
|
||||
. "<th class='extended'>".$clang->gT("Delete")."</th>\n"
|
||||
. "<th class='extended'>".$clang->gT("Import")."</th>\n"
|
||||
. "<th class='extended'>".$clang->gT("Export")."</th>\n"
|
||||
. "</tr></thead>\n";
|
||||
|
||||
//content
|
||||
|
||||
$aBasePermissions=Permission::model()->getSurveyBasePermissions();
|
||||
|
||||
$oddcolumn=false;
|
||||
foreach($aBasePermissions as $sPermissionKey=>$aCRUDPermissions)
|
||||
{
|
||||
$oddcolumn=!$oddcolumn;
|
||||
$usersummary .= "<tr><td><img src='{$imageurl}{$aCRUDPermissions['img']}_30.png' alt='{$aCRUDPermissions['description']}'/></td>";
|
||||
$usersummary .= "<td>{$aCRUDPermissions['title']}</td>";
|
||||
$usersummary .= "<td ><input type=\"checkbox\" class=\"markrow\" name='all_{$sPermissionKey}' /></td>";
|
||||
foreach ($aCRUDPermissions as $sCRUDKey=>$CRUDValue)
|
||||
{
|
||||
if (!in_array($sCRUDKey,array('create','read','update','delete','import','export'))) continue;
|
||||
$usersummary .= "<td class='extended'>";
|
||||
|
||||
if ($CRUDValue)
|
||||
{
|
||||
if (!($sPermissionKey=='survey' && $sCRUDKey=='read'))
|
||||
{
|
||||
$usersummary .= "<input type=\"checkbox\" class=\"checkboxbtn\" name='perm_{$sPermissionKey}_{$sCRUDKey}' ";
|
||||
if($action=='setsurveysecurity' && Permission::model()->hasSurveyPermission( $surveyid,$sPermissionKey,$sCRUDKey,$postuserid)) {
|
||||
$usersummary .= ' checked="checked" ';
|
||||
}
|
||||
$usersummary .=" />";
|
||||
}
|
||||
}
|
||||
$usersummary .= "</td>";
|
||||
}
|
||||
$usersummary .= "</tr>";
|
||||
}
|
||||
|
||||
$usersummary .= "\n</table>"
|
||||
."<p><input type='submit' value='".$clang->gT("Save Now")."' />"
|
||||
."<input type='hidden' name='perm_survey_read' value='1' />"
|
||||
."<input type='hidden' name='action' value='surveyrights' />";
|
||||
|
||||
if ($action=='setsurveysecurity')
|
||||
{
|
||||
$usersummary .="<input type='hidden' name='uid' value='{$postuserid}' />";
|
||||
}
|
||||
else
|
||||
{
|
||||
$usersummary .="<input type='hidden' name='ugid' value='{$postusergroupid}' />";
|
||||
}
|
||||
$usersummary .= "</form>\n";
|
||||
|
||||
$aViewUrls['output'] = $usersummary;
|
||||
}
|
||||
else
|
||||
{
|
||||
$this->getController()->error('Access denied');
|
||||
}
|
||||
|
||||
$this->_renderWrappedTemplate('authentication', $aViewUrls, $aData);
|
||||
}
|
||||
|
||||
/**
|
||||
* surveypermission::delete()
|
||||
* Function responsible to delete a user/usergroup.
|
||||
* @param mixed $surveyid
|
||||
* @return void
|
||||
*/
|
||||
function delete($surveyid)
|
||||
{
|
||||
|
||||
$aData['surveyid'] = $surveyid = sanitize_int($surveyid);
|
||||
$aViewUrls = array();
|
||||
|
||||
$action = $_POST['action'];
|
||||
|
||||
$clang = Yii::app()->lang;
|
||||
$imageurl = Yii::app()->getConfig('imageurl');
|
||||
$postuserid = !empty($_POST['uid']) ? $_POST['uid'] : false;
|
||||
$postusergroupid = !empty($_POST['gid']) ? $_POST['gid'] : false;// Not used
|
||||
|
||||
if($postuserid && !in_array($postuserid,getUserList('onlyuidarray')))
|
||||
{
|
||||
$this->getController()->error('Access denied');
|
||||
}
|
||||
elseif( $postusergroupid && !in_array($postusergroupid,getUserList('onlyuidarray')))
|
||||
{
|
||||
$this->getController()->error('Access denied');
|
||||
}
|
||||
|
||||
if($action == "delsurveysecurity")
|
||||
{
|
||||
$addsummary = "<div class=\"header\">".$clang->gT("Deleting User")."</div>\n";
|
||||
$addsummary .= "<div class=\"messagebox\">\n";
|
||||
|
||||
if( Permission::model()->hasSurveyPermission($surveyid, 'surveysecurity', 'delete') )
|
||||
{
|
||||
if (isset($postuserid))
|
||||
{
|
||||
$dbresult = Permission::model()->deleteAll('uid = :uid AND entity_id = :sid AND entity = :entity',array(':uid' => $postuserid, ':sid' => $surveyid, ':entity' => 'survey'));
|
||||
$addsummary .= "<br />".$clang->gT("Username").": ".sanitize_xss_string($_POST['user'])."<br /><br />\n";
|
||||
$addsummary .= "<div class=\"successheader\">".$clang->gT("Success!")."</div>\n";
|
||||
}
|
||||
else
|
||||
{
|
||||
$addsummary .= "<div class=\"warningheader\">".$clang->gT("Could not delete user. User was not supplied.")."</div>\n";
|
||||
}
|
||||
$addsummary .= "<br/><input type=\"submit\" onclick=\"window.open('".$this->getController()->createUrl('admin/surveypermission/sa/view/surveyid/'.$surveyid)."', '_top')\" value=\"".$clang->gT("Continue")."\"/>\n";
|
||||
}
|
||||
else
|
||||
{
|
||||
$this->getController()->error('Access denied');
|
||||
}
|
||||
$addsummary .= "</div>\n";
|
||||
|
||||
$aViewUrls['output'] = $addsummary;
|
||||
}
|
||||
|
||||
$this->_renderWrappedTemplate('authentication', $aViewUrls, $aData);
|
||||
}
|
||||
|
||||
/**
|
||||
* surveypermission::surveyright()
|
||||
* Function responsible to process setting of permission of a user/usergroup.
|
||||
* @param mixed $surveyid
|
||||
* @return void
|
||||
*/
|
||||
function surveyright($surveyid)
|
||||
{
|
||||
$aData['surveyid'] = $surveyid = sanitize_int($surveyid);
|
||||
$aViewUrls = array();
|
||||
|
||||
$action = $_POST['action'];
|
||||
$clang = Yii::app()->lang;
|
||||
$imageurl = Yii::app()->getConfig('imageurl');
|
||||
$postuserid = !empty($_POST['uid']) ? $_POST['uid'] : false;
|
||||
$postusergroupid = !empty($_POST['ugid']) ? $_POST['ugid'] : false;
|
||||
|
||||
if($postuserid && !in_array($postuserid,getUserList('onlyuidarray')))
|
||||
{
|
||||
$this->getController()->error('Access denied');
|
||||
}
|
||||
elseif( $postusergroupid && !in_array($postusergroupid,getUserGroupList(null, 'simplegidarray')))
|
||||
{
|
||||
$this->getController()->error('Access denied');
|
||||
}
|
||||
|
||||
if ($action == "surveyrights" && Permission::model()->hasSurveyPermission($surveyid, 'surveysecurity', 'update'))
|
||||
{
|
||||
$addsummary = "<div class='header ui-widget-header'>".$clang->gT("Edit survey permissions")."</div>\n";
|
||||
$addsummary .= "<div class='messagebox ui-corner-all'>\n";
|
||||
$where = ' ';
|
||||
if($postuserid){
|
||||
if (!Permission::model()->hasGlobalPermission('superadmin','read'))
|
||||
{
|
||||
$where .= "sid = :surveyid AND owner_id != :postuserid AND owner_id = :owner_id";
|
||||
$resrow = Survey::model()->find($where,array(':surveyid' => $surveyid, ':owner_id' => Yii::app()->session['loginID'], ':postuserid' => $postuserid));
|
||||
}
|
||||
}
|
||||
else{
|
||||
$where .= "sid = :sid";
|
||||
$resrow = Survey::model()->find($where,array(':sid' => $surveyid));
|
||||
$iOwnerID=$resrow['owner_id'];
|
||||
}
|
||||
|
||||
$aBaseSurveyPermissions = Permission::model()->getSurveyBasePermissions();
|
||||
$aPermissions=array();
|
||||
foreach ($aBaseSurveyPermissions as $sPermissionKey=>$aCRUDPermissions)
|
||||
{
|
||||
foreach ($aCRUDPermissions as $sCRUDKey=>$CRUDValue)
|
||||
{
|
||||
if (!in_array($sCRUDKey,array('create','read','update','delete','import','export'))) continue;
|
||||
|
||||
if ($CRUDValue)
|
||||
{
|
||||
if(isset($_POST["perm_{$sPermissionKey}_{$sCRUDKey}"])){
|
||||
$aPermissions[$sPermissionKey][$sCRUDKey]=1;
|
||||
}
|
||||
else
|
||||
{
|
||||
$aPermissions[$sPermissionKey][$sCRUDKey]=0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($postusergroupid) && $postusergroupid>0)
|
||||
{
|
||||
$oResult = UserInGroup::model()->findAll('ugid = :ugid AND uid <> :uid AND uid <> :iOwnerID',array(':ugid' => $postusergroupid, ':uid' => Yii::app()->session['loginID'], ':iOwnerID' => $iOwnerID));
|
||||
if(count($oResult) > 0)
|
||||
{
|
||||
foreach ($oResult as $aRow)
|
||||
{
|
||||
Permission::model()->setPermissions($aRow->uid, $surveyid, 'survey', $aPermissions);
|
||||
}
|
||||
$addsummary .= "<div class=\"successheader\">".$clang->gT("Survey permissions for all users in this group were successfully updated.")."</div>\n";
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (Permission::model()->setPermissions($postuserid, $surveyid, 'survey', $aPermissions))
|
||||
{
|
||||
$addsummary .= "<div class=\"successheader\">".$clang->gT("Survey permissions were successfully updated.")."</div>\n";
|
||||
}
|
||||
else
|
||||
{
|
||||
$addsummary .= "<div class=\"warningheader\">".$clang->gT("Failed to update survey permissions!")."</div>\n";
|
||||
}
|
||||
|
||||
}
|
||||
$addsummary .= "<br/><input type=\"submit\" onclick=\"window.open('".$this->getController()->createUrl('admin/surveypermission/sa/view/surveyid/'.$surveyid)."', '_top')\" value=\"".$clang->gT("Continue")."\"/>\n";
|
||||
$addsummary .= "</div>\n";
|
||||
$aViewUrls['output'] = $addsummary;
|
||||
}
|
||||
else
|
||||
{
|
||||
$this->getController()->error('Access denied');
|
||||
}
|
||||
|
||||
$this->_renderWrappedTemplate('authentication', $aViewUrls, $aData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders template(s) wrapped in header and footer
|
||||
*
|
||||
* @param string $sAction Current action, the folder to fetch views from
|
||||
* @param string|array $aViewUrls View url(s)
|
||||
* @param array $aData Data to be passed on. Optional.
|
||||
*/
|
||||
protected function _renderWrappedTemplate($sAction = 'authentication', $aViewUrls = array(), $aData = array())
|
||||
{
|
||||
App()->getClientScript()->registerPackage('jquery-superfish');
|
||||
parent::_renderWrappedTemplate($sAction, $aViewUrls, $aData);
|
||||
}
|
||||
|
||||
}
|
1274
sources/application/controllers/admin/templates.php
Normal file
1274
sources/application/controllers/admin/templates.php
Normal file
File diff suppressed because it is too large
Load diff
2485
sources/application/controllers/admin/tokens.php
Normal file
2485
sources/application/controllers/admin/tokens.php
Normal file
File diff suppressed because it is too large
Load diff
1096
sources/application/controllers/admin/translate.php
Normal file
1096
sources/application/controllers/admin/translate.php
Normal file
File diff suppressed because it is too large
Load diff
626
sources/application/controllers/admin/update.php
Normal file
626
sources/application/controllers/admin/update.php
Normal file
|
@ -0,0 +1,626 @@
|
|||
<?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.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Update Controller
|
||||
*
|
||||
* This controller performs updates
|
||||
*
|
||||
* @package LimeSurvey
|
||||
* @subpackage Backend
|
||||
*/
|
||||
class update extends Survey_Common_Action
|
||||
{
|
||||
|
||||
/**
|
||||
* Returns the supported protocol extension (https/http)
|
||||
*
|
||||
*/
|
||||
private function getProtocol()
|
||||
{
|
||||
if(!function_exists("extension_loaded") || !extension_loaded("openssl"))
|
||||
{
|
||||
return 'http://';
|
||||
}
|
||||
return 'https://';
|
||||
}
|
||||
|
||||
/**
|
||||
* Default Controller Action
|
||||
*/
|
||||
function index($sSubAction = null)
|
||||
{
|
||||
updateCheck();
|
||||
$this->_RunUpdaterUpdate();
|
||||
Yii::import('application.libraries.admin.http.httpRequestIt');
|
||||
|
||||
$clang = $this->getController()->lang;
|
||||
$iCurrentBuildnumber = Yii::app()->getConfig("buildnumber");
|
||||
$tempdir = Yii::app()->getConfig("tempdir");
|
||||
$iDestinationBuild = Yii::app()->request->getParam('build',getGlobalSetting("updatebuild"));
|
||||
|
||||
$aUpdateVersions = json_decode(getGlobalSetting("updateversions"),true);
|
||||
foreach($aUpdateVersions as $sBranch=>$aUpdateVersion)
|
||||
{
|
||||
if ($aUpdateVersion['build']==$iDestinationBuild)
|
||||
{
|
||||
setGlobalSetting('updatebuild',$aUpdateVersion['build']);
|
||||
setGlobalSetting('updateversion',$aUpdateVersion['versionnumber']);
|
||||
}
|
||||
}
|
||||
|
||||
$error = false;
|
||||
|
||||
if (!is_writable($tempdir)) {
|
||||
$error = true;
|
||||
}
|
||||
if (!is_writable(APPPATH . 'config/version.php')) {
|
||||
$error = true;
|
||||
}
|
||||
|
||||
list($httperror, $changelog, $cookies) = $this->_getChangelog($iCurrentBuildnumber, $iDestinationBuild);
|
||||
|
||||
$aData['error'] = $error;
|
||||
$aData['tempdir'] = $tempdir;
|
||||
$aData['changelog'] = isset($changelog) ? $changelog : '';
|
||||
$aData['httperror'] = isset($httperror) ? $httperror : '';
|
||||
|
||||
$this->_renderWrappedTemplate('update', 'update', $aData);
|
||||
}
|
||||
|
||||
private function _getChangedFiles($buildnumber, $updaterversion)
|
||||
{
|
||||
Yii::import('application.libraries.admin.http.httpRequestIt');
|
||||
$http = new httpRequestIt;
|
||||
$httperror = $this->_requestChangedFiles($http, $buildnumber, $updaterversion);
|
||||
|
||||
if ($httperror != '') {
|
||||
return array($httperror, null);
|
||||
}
|
||||
return $this->_readChangelog($http);
|
||||
}
|
||||
|
||||
private function _getChangelog($buildnumber, $updaterversion)
|
||||
{
|
||||
Yii::import('application.libraries.admin.http.httpRequestIt');
|
||||
$http = new httpRequestIt;
|
||||
$httperror = $this->_requestChangelog($http, $buildnumber, $updaterversion);
|
||||
|
||||
if ($httperror != '') {
|
||||
return array($httperror, null);
|
||||
}
|
||||
return $this->_readChangelog($http);
|
||||
}
|
||||
|
||||
private function _readChangelog(httpRequestIt $http)
|
||||
{
|
||||
$szLines = '';
|
||||
$szResponse = '';
|
||||
for (; ;) {
|
||||
$httperror = $http->ReadReplyBody($szLines, 10000);
|
||||
if ($httperror != "" || strlen($szLines) == 0) {
|
||||
$changelog = json_decode($szResponse, true);
|
||||
$http->SaveCookies($cookies);
|
||||
return array($httperror, $changelog, $cookies);
|
||||
}
|
||||
$szResponse .= $szLines;
|
||||
}
|
||||
}
|
||||
|
||||
private function _requestChangelog(httpRequestIt $http, $buildnumber, $updaterversion)
|
||||
{
|
||||
$http->proxy_host_name = Yii::app()->getConfig("proxy_host_name","");
|
||||
$http->proxy_host_port = Yii::app()->getConfig("proxy_host_port",80);
|
||||
$http->timeout = 0;
|
||||
$http->data_timeout = 0;
|
||||
$http->user_agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)';
|
||||
$http->GetRequestArguments($this->getProtocol().'update.limesurvey.org/updates/changelog/' . $buildnumber . '/' . $updaterversion , $arguments);
|
||||
|
||||
$http->Open($arguments);
|
||||
|
||||
return $http->SendRequest($arguments);
|
||||
}
|
||||
|
||||
private function _requestChangedFiles(httpRequestIt $http, $buildnumber, $updaterversion)
|
||||
{
|
||||
$http->proxy_host_name = Yii::app()->getConfig("proxy_host_name","");
|
||||
$http->proxy_host_port = Yii::app()->getConfig("proxy_host_port",80);
|
||||
$http->timeout = 0;
|
||||
$http->data_timeout = 0;
|
||||
$http->user_agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)';
|
||||
$http->GetRequestArguments($this->getProtocol().'update.limesurvey.org/updates/update/' . $buildnumber . '/' . $updaterversion , $arguments);
|
||||
|
||||
$http->Open($arguments);
|
||||
|
||||
return $http->SendRequest($arguments);
|
||||
}
|
||||
|
||||
function step2()
|
||||
{
|
||||
|
||||
$clang = $this->getController()->lang;
|
||||
$buildnumber = Yii::app()->getConfig("buildnumber");
|
||||
$updatebuild = getGlobalSetting("updatebuild");
|
||||
|
||||
list($error, $updateinfo, $cookies) = $this->_getChangedFiles($buildnumber, $updatebuild);
|
||||
$aData = $this->_getFileStatus($updateinfo);
|
||||
$aReadOnlyFiles=array_unique($aData['readonlyfiles']);
|
||||
sort($aReadOnlyFiles);
|
||||
$aData['readonlyfiles']=$aReadOnlyFiles;
|
||||
Yii::app()->session['updateinfo'] = $updateinfo;
|
||||
Yii::app()->session['updatesession'] = $cookies;
|
||||
|
||||
$aData['error'] = $error;
|
||||
$aData['updateinfo'] = $updateinfo;
|
||||
$this->_renderWrappedTemplate('update', 'step2', $aData);
|
||||
}
|
||||
|
||||
private function _getFileStatus($updateinfo)
|
||||
{
|
||||
// okay, updateinfo now contains all necessary updateinformation
|
||||
// Now check if the existing files have the mentioned checksum
|
||||
|
||||
if (!isset($updateinfo['files'])) {
|
||||
return array();
|
||||
}
|
||||
|
||||
$rootdir = Yii::app()->getConfig("rootdir");
|
||||
$existingfiles = array();
|
||||
$modifiedfiles = array();
|
||||
$readonlyfiles = array();
|
||||
|
||||
foreach ($updateinfo['files'] as $afile)
|
||||
{
|
||||
$this->_checkFile($afile, $rootdir, $readonlyfiles, $existingfiles, $modifiedfiles);
|
||||
}
|
||||
return array('readonlyfiles'=>$readonlyfiles,
|
||||
'modifiedfiles'=>$modifiedfiles,
|
||||
'existingfiles'=>$existingfiles)
|
||||
;
|
||||
}
|
||||
|
||||
private function _checkFile($file, $rootdir, &$readonlyfiles, &$existingfiles, &$modifiedfiles)
|
||||
{
|
||||
$this->_checkReadOnlyFile($file, $rootdir, $readonlyfiles);
|
||||
|
||||
|
||||
if ($file['type'] == 'A' && file_exists($rootdir . $file['file'])) {
|
||||
//A new file, check if this already exists
|
||||
$existingfiles[] = $file;
|
||||
}
|
||||
elseif (($file['type'] == 'D' || $file['type'] == 'M') && is_file($rootdir . $file['file']) && sha1_file($rootdir . $file['file']) != $file['checksum']) {
|
||||
// A deleted or modified file - check if it is unmodified
|
||||
$modifiedfiles[] = $file;
|
||||
}
|
||||
}
|
||||
|
||||
private function _checkReadOnlyFile($file, $rootdir, &$readonlyfiles)
|
||||
{
|
||||
if ($file['type'] == 'A' && !file_exists($rootdir . $file['file']) || ($file['type'] == 'D' && file_exists($rootdir . $file['file']))) {
|
||||
$searchpath = $rootdir . $file['file'];
|
||||
$is_writable = is_writable(dirname($searchpath));
|
||||
while (!$is_writable && strlen($searchpath) > strlen($rootdir))
|
||||
{
|
||||
$searchpath = dirname($searchpath);
|
||||
if (file_exists($searchpath)) {
|
||||
$is_writable = is_writable($searchpath);
|
||||
break;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
if (!$is_writable) {
|
||||
$readonlyfiles[] = $searchpath;
|
||||
}
|
||||
}
|
||||
elseif (file_exists($rootdir . $file['file']) && !is_writable($rootdir . $file['file'])) {
|
||||
$readonlyfiles[] = $rootdir . $file['file'];
|
||||
}
|
||||
}
|
||||
|
||||
function step3()
|
||||
{
|
||||
$clang = $this->getController()->lang;
|
||||
$buildnumber = Yii::app()->getConfig("buildnumber");
|
||||
$tempdir = Yii::app()->getConfig("tempdir");
|
||||
$updatebuild = getGlobalSetting("updatebuild");
|
||||
//$_POST=$this->input->post();
|
||||
$rootdir = Yii::app()->getConfig("rootdir");
|
||||
$publicdir = Yii::app()->getConfig("publicdir");
|
||||
$tempdir = Yii::app()->getConfig("tempdir");
|
||||
$aDatabasetype = Yii::app()->db->getDriverName();
|
||||
$aData = array('clang' => $clang);
|
||||
// Request the list with changed files from the server
|
||||
|
||||
if (!isset( Yii::app()->session['updateinfo']))
|
||||
{
|
||||
if ($updateinfo['error']==1)
|
||||
{
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
$updateinfo=Yii::app()->session['updateinfo'];
|
||||
}
|
||||
|
||||
$aData['updateinfo'] = $updateinfo;
|
||||
|
||||
// okay, updateinfo now contains all necessary updateinformation
|
||||
// Create DB and file backups now
|
||||
|
||||
$basefilename = dateShift(date("Y-m-d H:i:s"), "Y-m-d", Yii::app()->getConfig('timeadjust')).'_'.md5(uniqid(rand(), true));
|
||||
//Now create a backup of the files to be delete or modified
|
||||
|
||||
$filestozip=array();
|
||||
|
||||
foreach ($updateinfo['files'] as $file)
|
||||
{
|
||||
if (is_file($publicdir.$file['file'])===true) // Sort out directories
|
||||
{
|
||||
$filestozip[]=$publicdir.$file['file'];
|
||||
}
|
||||
}
|
||||
|
||||
Yii::app()->loadLibrary("admin/pclzip");
|
||||
$archive = new PclZip($tempdir.DIRECTORY_SEPARATOR.'LimeSurvey_files_backup_'.$basefilename.'.zip');
|
||||
|
||||
$v_list = $archive->add($filestozip, PCLZIP_OPT_REMOVE_PATH, $publicdir);
|
||||
|
||||
if ($v_list == 0) {
|
||||
$aFileBackup= array('class'=>'error','text'=>sprintf($clang->gT("Error on file backup: %s"),$archive->errorInfo(true)));
|
||||
}
|
||||
else{
|
||||
$aFileBackup= array('class'=>'success','text'=>sprintf($clang->gT("File backup created: %s"),$tempdir.DIRECTORY_SEPARATOR.'LimeSurvey_files_backup_'.$basefilename.'.zip'));
|
||||
}
|
||||
$aData['aFileBackup']=$aFileBackup;
|
||||
|
||||
$aData['databasetype'] = $aDatabasetype;
|
||||
|
||||
//TODO: Yii provides no function to backup the database. To be done after dumpdb is ported
|
||||
if (in_array($aDatabasetype, array('mysql', 'mysqli')))
|
||||
{
|
||||
if ((in_array($aDatabasetype, array('mysql', 'mysqli'))) && Yii::app()->getConfig('demoMode') != true) {
|
||||
Yii::app()->loadHelper("admin/backupdb");
|
||||
$sfilename = $tempdir.DIRECTORY_SEPARATOR."backup_db_".randomChars(20)."_".dateShift(date("Y-m-d H:i:s"), "Y-m-d", Yii::app()->getConfig('timeadjust')).".sql";
|
||||
$dfilename = $tempdir.DIRECTORY_SEPARATOR."LimeSurvey_database_backup_".$basefilename.".sql.gz";
|
||||
|
||||
outputDatabase('',false,$sfilename);
|
||||
// Before try to zip: test size of file
|
||||
if( is_file($sfilename) && filesize($sfilename))
|
||||
{
|
||||
$archive = new PclZip($dfilename);
|
||||
$v_list = $archive->add(array($sfilename), PCLZIP_OPT_REMOVE_PATH, $tempdir,PCLZIP_OPT_ADD_TEMP_FILE_ON);
|
||||
unlink($sfilename);
|
||||
if ($v_list == 0) {// Unknow reason because backup of DB work ?
|
||||
$aSQLBackup=array('class'=>'warning','text'=>$clang->gT("Unable to backup your database for unknow reason. Before proceeding please backup your database using a backup tool!"));
|
||||
}
|
||||
else
|
||||
{
|
||||
$aSQLBackup=array('class'=>'success','text'=>sprintf($clang->gT('DB backup created: %s'),htmlspecialchars($dfilename)));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
$aSQLBackup=array('class'=>'warning','text'=>$clang->gT("Unable to backup your database for unknow reason. Before proceeding please backup your database using a backup tool!"));
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
$aSQLBackup=array('class'=>'warning','text'=>$clang->gT('Database backup functionality is currently not available for your database type. Before proceeding please backup your database using a backup tool!'));
|
||||
}
|
||||
$aData['aSQLBackup']=$aSQLBackup;
|
||||
if($aFileBackup['class']=="success" && $aSQLBackup['class']=="success") {
|
||||
$aData['result']="success";
|
||||
}elseif($aFileBackup['class']=="error" || $aSQLBackup['class']=="error") {
|
||||
$aData['result']="error";
|
||||
}else{
|
||||
$aData['result']="warning";
|
||||
}
|
||||
$this->_renderWrappedTemplate('update', 'step3', $aData);
|
||||
}
|
||||
|
||||
|
||||
function step4()
|
||||
{
|
||||
$clang = $this->getController()->lang;
|
||||
$buildnumber = Yii::app()->getConfig("buildnumber");
|
||||
$tempdir = Yii::app()->getConfig("tempdir");
|
||||
$updatebuild = getGlobalSetting("updatebuild");
|
||||
|
||||
$rootdir = Yii::app()->getConfig("rootdir");
|
||||
$publicdir = Yii::app()->getConfig("publicdir");
|
||||
$tempdir = Yii::app()->getConfig("tempdir");
|
||||
$aDatabasetype = Yii::app()->db->getDriverName();
|
||||
// Request the list with changed files from the server
|
||||
$aData = array();
|
||||
|
||||
if (!isset( Yii::app()->session['updateinfo']))
|
||||
{
|
||||
if ($updateinfo['error']==1)
|
||||
{
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
$updateinfo=Yii::app()->session['updateinfo'];
|
||||
}
|
||||
// this is the last step - Download the zip file, unpack it and replace files accordingly
|
||||
// Create DB and file backups now
|
||||
|
||||
$downloaderror=false;
|
||||
Yii::import('application.libraries.admin.http.httpRequestIt');
|
||||
$http=new httpRequestIt;
|
||||
|
||||
$http->proxy_host_name = Yii::app()->getConfig("proxy_host_name","");
|
||||
$http->proxy_host_port = Yii::app()->getConfig("proxy_host_port",80);
|
||||
|
||||
// Allow redirects
|
||||
$http->follow_redirect=1;
|
||||
/* Connection timeout */
|
||||
$http->timeout=0;
|
||||
/* Data transfer timeout */
|
||||
$http->data_timeout=0;
|
||||
$http->user_agent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)";
|
||||
$http->GetRequestArguments($this->getProtocol()."update.limesurvey.org/updates/download/{$updateinfo['downloadid']}",$arguments);
|
||||
$http->RestoreCookies(Yii::app()->session['updatesession']);
|
||||
|
||||
$error=$http->Open($arguments);
|
||||
$error=$http->SendRequest($arguments);
|
||||
$http->ReadReplyHeaders($headers);
|
||||
if ($headers['content-type']=='text/html')
|
||||
{
|
||||
@unlink($tempdir.'/update.zip');
|
||||
}
|
||||
else if($error=='') {
|
||||
$body='';
|
||||
$pFile = fopen($tempdir.'/update.zip', 'w');
|
||||
for(;;){
|
||||
$error = $http->ReadReplyBody($body,100000);
|
||||
if($error != "" || strlen($body)==0) break;
|
||||
fwrite($pFile, $body);
|
||||
}
|
||||
fclose($pFile);
|
||||
}
|
||||
else
|
||||
{
|
||||
print( $error );
|
||||
}
|
||||
|
||||
//Now unzip the new files over the existing ones.
|
||||
$new_files = false;
|
||||
if (file_exists($tempdir.'/update.zip')){
|
||||
Yii::app()->loadLibrary("admin/pclzip");
|
||||
$archive = new PclZip($tempdir.'/update.zip');
|
||||
if ($archive->extract(PCLZIP_OPT_PATH, $rootdir.'/', PCLZIP_OPT_REPLACE_NEWER)== 0) {
|
||||
die("Error : ".$archive->errorInfo(true));
|
||||
}
|
||||
else
|
||||
{
|
||||
$new_files = true;
|
||||
unlink($tempdir.'/update.zip');
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
$downloaderror=true;
|
||||
}
|
||||
|
||||
// Now remove all files that are to be deleted according to update process
|
||||
// This happens after unzipping
|
||||
foreach ($updateinfo['files'] as $afile)
|
||||
{
|
||||
if ($afile['type']=='D' && file_exists($rootdir.$afile['file']))
|
||||
{
|
||||
if (is_file($rootdir.$afile['file']))
|
||||
{
|
||||
@unlink($rootdir.$afile['file']);
|
||||
}
|
||||
else{
|
||||
rmdirr($rootdir.$afile['file']);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
$aData['new_files'] = $new_files;
|
||||
$aData['downloaderror'] = $downloaderror;
|
||||
|
||||
// PclTraceDisplay();
|
||||
|
||||
// Now we have to update version.php
|
||||
if (!$downloaderror)
|
||||
{
|
||||
@ini_set('auto_detect_line_endings', true);
|
||||
$versionlines=file($rootdir.'/application/config/version.php');
|
||||
$handle = fopen($rootdir.'/application/config/version.php', "w");
|
||||
foreach ($versionlines as $line)
|
||||
{
|
||||
if(strpos($line,'buildnumber')!==false)
|
||||
{
|
||||
$line='$config[\'buildnumber\'] = '.Yii::app()->session['updateinfo']['toversion'].';'."\r\n";
|
||||
}
|
||||
fwrite($handle,$line);
|
||||
}
|
||||
fclose($handle);
|
||||
}
|
||||
setGlobalSetting('updateavailable','0');
|
||||
setGlobalSetting('updatebuild','');
|
||||
setGlobalSetting('updateversions','');
|
||||
// We redirect here because the files might have been overwritten earlier
|
||||
// and classes may have been changed that would be needed in the view
|
||||
Yii::app()->session['installlstep4b']=$aData;
|
||||
Yii::app()->getController()->redirect(array('/admin/update/sa/step4b'));
|
||||
}
|
||||
|
||||
|
||||
function step4b()
|
||||
{
|
||||
if (!isset(Yii::app()->session['installlstep4b'])) die();
|
||||
$aData=Yii::app()->session['installlstep4b'];
|
||||
unset (Yii::app()->session['installlstep4b']);
|
||||
$this->_renderWrappedTemplate('update', 'step4', $aData);
|
||||
}
|
||||
|
||||
private function _RunUpdaterUpdate()
|
||||
{
|
||||
$clang = $this->getController()->lang;
|
||||
$versionnumber = Yii::app()->getConfig("versionnumber");
|
||||
$buildnumber = Yii::app()->getConfig("buildnumber");
|
||||
$tempdir = Yii::app()->getConfig("tempdir");
|
||||
|
||||
Yii::import('application.libraries.admin.http.httpRequestIt');
|
||||
$oHTTPRequest=new httpRequestIt;
|
||||
|
||||
$oHTTPRequest->proxy_host_name = Yii::app()->getConfig("proxy_host_name","");
|
||||
$oHTTPRequest->proxy_host_port = Yii::app()->getConfig("proxy_host_port",80);
|
||||
|
||||
/* Connection timeout */
|
||||
$oHTTPRequest->timeout=0;
|
||||
/* Data transfer timeout */
|
||||
$oHTTPRequest->data_timeout=0;
|
||||
$oHTTPRequest->user_agent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)";
|
||||
$oHTTPRequest->GetRequestArguments($this->getProtocol()."update.limesurvey.org?updaterbuild={$buildnumber}",$arguments);
|
||||
|
||||
$updateinfo=false;
|
||||
$error=$oHTTPRequest->Open($arguments);
|
||||
$error=$oHTTPRequest->SendRequest($arguments);
|
||||
|
||||
$oHTTPRequest->ReadReplyHeaders($headers);
|
||||
|
||||
|
||||
if($error=="") {
|
||||
$body=''; $full_body='';
|
||||
for(;;){
|
||||
$error = $oHTTPRequest->ReadReplyBody($body,10000);
|
||||
if($error != "" || strlen($body)==0) break;
|
||||
$full_body .= $body;
|
||||
}
|
||||
$updateinfo=json_decode($full_body,true);
|
||||
if ($oHTTPRequest->response_status!='200')
|
||||
{
|
||||
$updateinfo['errorcode']=$oHTTPRequest->response_status;
|
||||
$updateinfo['errorhtml']=$full_body;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
$updateinfo['errorcode']=$error;
|
||||
$updateinfo['errorhtml']=$error;
|
||||
}
|
||||
unset( $oHTTPRequest );
|
||||
if ((int)$updateinfo['UpdaterRevision']<=$buildnumber)
|
||||
{
|
||||
// There is no newer updater version on the server
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!is_writable($tempdir) || !is_writable(APPPATH.DIRECTORY_SEPARATOR.'controllers'.DIRECTORY_SEPARATOR.'admin'.DIRECTORY_SEPARATOR.'update.php'))
|
||||
{
|
||||
$error=true;
|
||||
}
|
||||
|
||||
// Download the zip file, unpack it and replace the updater file accordingly
|
||||
// Create DB and file backups now
|
||||
|
||||
$downloaderror=false;
|
||||
Yii::import('application.libraries.admin.http.httpRequestIt');
|
||||
$oHTTPRequest=new httpRequestIt;
|
||||
|
||||
$oHTTPRequest->proxy_host_name = Yii::app()->getConfig("proxy_host_name","");
|
||||
$oHTTPRequest->proxy_host_port = Yii::app()->getConfig("proxy_host_port",80);
|
||||
|
||||
// Allow redirects
|
||||
$oHTTPRequest->follow_redirect=1;
|
||||
/* Connection timeout */
|
||||
$oHTTPRequest->timeout=0;
|
||||
/* Data transfer timeout */
|
||||
$oHTTPRequest->data_timeout=0;
|
||||
$oHTTPRequest->user_agent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)";
|
||||
$oHTTPRequest->GetRequestArguments($this->getProtocol()."update.limesurvey.org/updates/downloadupdater/{$updateinfo['UpdaterRevision']}",$arguments);
|
||||
|
||||
$oHTTPRequesterror=$oHTTPRequest->Open($arguments);
|
||||
$oHTTPRequesterror=$oHTTPRequest->SendRequest($arguments);
|
||||
$oHTTPRequest->ReadReplyHeaders($headers);
|
||||
if ($headers['content-type']=='text/html')
|
||||
{
|
||||
@unlink($tempdir.'/updater.zip');
|
||||
}
|
||||
elseif($oHTTPRequesterror=='') {
|
||||
$body=''; $full_body='';
|
||||
for(;;){
|
||||
$oHTTPRequesterror = $oHTTPRequest->ReadReplyBody($body,100000);
|
||||
if($oHTTPRequesterror != "" || strlen($body)==0) break;
|
||||
$full_body .= $body;
|
||||
}
|
||||
file_put_contents($tempdir.'/updater.zip',$full_body);
|
||||
}
|
||||
$aData['httperror'] = $oHTTPRequesterror;
|
||||
|
||||
//Now unzip the new updater over the existing ones.
|
||||
if (file_exists($tempdir.'/updater.zip')){
|
||||
Yii::app()->loadLibrary("admin/pclzip",array('p_zipname' => $tempdir.'/updater.zip'));
|
||||
$archive = new PclZip(array('p_zipname' => $tempdir.'/updater.zip'));
|
||||
if ($archive->extract(PCLZIP_OPT_PATH, APPPATH.'/controllers/admin/', PCLZIP_OPT_REPLACE_NEWER)== 0) {
|
||||
die("Error : ".$archive->errorInfo(true));
|
||||
}
|
||||
else
|
||||
{
|
||||
unlink($tempdir.'/updater.zip');
|
||||
}
|
||||
$updater_exists = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
$updater_exists = false;
|
||||
$error=true;
|
||||
}
|
||||
$aData['updater_exists'] = $updater_exists;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update database
|
||||
*/
|
||||
function db($continue = null)
|
||||
{
|
||||
$clang = $this->getController()->lang;
|
||||
Yii::app()->loadHelper("update/update");
|
||||
if(isset($continue) && $continue=="yes")
|
||||
{
|
||||
$aViewUrls['output'] = CheckForDBUpgrades($continue);
|
||||
updateCheck();
|
||||
$aData['display']['header'] = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
$aData['display']['header'] = true;
|
||||
$aViewUrls['output'] = CheckForDBUpgrades();
|
||||
}
|
||||
|
||||
$this->_renderWrappedTemplate('update', $aViewUrls, $aData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders template(s) wrapped in header and footer
|
||||
*
|
||||
* @param string $sAction Current action, the folder to fetch views from
|
||||
* @param string|array $aViewUrls View url(s)
|
||||
* @param array $aData Data to be passed on. Optional.
|
||||
*/
|
||||
protected function _renderWrappedTemplate($sAction = 'update', $aViewUrls = array(), $aData = array())
|
||||
{
|
||||
$aData['display']['menu_bars'] = false;
|
||||
parent::_renderWrappedTemplate($sAction, $aViewUrls, $aData);
|
||||
}
|
||||
|
||||
}
|
767
sources/application/controllers/admin/useraction.php
Normal file
767
sources/application/controllers/admin/useraction.php
Normal file
|
@ -0,0 +1,767 @@
|
|||
<?php
|
||||
|
||||
if (!defined('BASEPATH'))
|
||||
exit('No direct script access allowed');
|
||||
/*
|
||||
* LimeSurvey
|
||||
* Copyright (C) 2013 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.
|
||||
*/
|
||||
|
||||
/**
|
||||
* User Controller
|
||||
*
|
||||
* This controller performs user actions
|
||||
*
|
||||
* @package LimeSurvey
|
||||
* @subpackage Backend
|
||||
*/
|
||||
class UserAction extends Survey_Common_Action
|
||||
{
|
||||
|
||||
function __construct($controller, $id)
|
||||
{
|
||||
parent::__construct($controller, $id);
|
||||
|
||||
Yii::app()->loadHelper('database');
|
||||
}
|
||||
|
||||
/**
|
||||
* Show users table
|
||||
*/
|
||||
public function index()
|
||||
{
|
||||
App()->getClientScript()->registerPackage('jquery-tablesorter');
|
||||
App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts').'users.js');
|
||||
|
||||
$userlist = getUserList();
|
||||
$usrhimself = $userlist[0];
|
||||
unset($userlist[0]);
|
||||
|
||||
if (Permission::model()->hasGlobalPermission('superadmin','read')) {
|
||||
$noofsurveys = Survey::model()->countByAttributes(array("owner_id" => $usrhimself['uid']));
|
||||
$aData['noofsurveys'] = $noofsurveys;
|
||||
}
|
||||
$aData['row'] = 0;
|
||||
if (isset($usrhimself['parent_id']) && $usrhimself['parent_id'] != 0)
|
||||
{
|
||||
$aData['row'] = User::model()->findByAttributes(array('uid' => $usrhimself['parent_id']))->users_name;
|
||||
}
|
||||
|
||||
|
||||
$aData['usrhimself'] = $usrhimself;
|
||||
// other users
|
||||
$aData['usr_arr'] = $userlist;
|
||||
$noofsurveyslist = array();
|
||||
|
||||
//This loops through for each user and checks the amount of surveys against them.
|
||||
for ($i = 1; $i <= count($userlist); $i++)
|
||||
$noofsurveyslist[$i] = $this->_getSurveyCountForUser($userlist[$i]);
|
||||
|
||||
$aData['imageurl'] = Yii::app()->getConfig("adminimageurl");
|
||||
$aData['noofsurveyslist'] = $noofsurveyslist;
|
||||
|
||||
$this->_renderWrappedTemplate('user', 'editusers', $aData);
|
||||
}
|
||||
|
||||
private function _getSurveyCountForUser(array $user)
|
||||
{
|
||||
return Survey::model()->countByAttributes(array('owner_id' => $user['uid']));
|
||||
}
|
||||
|
||||
function adduser()
|
||||
{
|
||||
$clang = Yii::app()->lang;
|
||||
if (!Permission::model()->hasGlobalPermission('users','create')) {
|
||||
Yii::app()->setFlashMessage($clang->gT("You do not have sufficient rights to access this page."),'error');
|
||||
$this->getController()->redirect(array("admin/user/sa/index"));
|
||||
}
|
||||
$new_user = flattenText(Yii::app()->request->getPost('new_user'), false, true);
|
||||
$new_email = flattenText(Yii::app()->request->getPost('new_email'), false, true);
|
||||
$new_full_name = flattenText(Yii::app()->request->getPost('new_full_name'), false, true);
|
||||
$aViewUrls = array();
|
||||
$valid_email = true;
|
||||
if (!validateEmailAddress($new_email)) {
|
||||
$valid_email = false;
|
||||
$aViewUrls['message'] = array('title' => $clang->gT("Failed to add user"), 'message' => $clang->gT("The email address is not valid."), 'class'=> 'warningheader');
|
||||
}
|
||||
if (empty($new_user)) {
|
||||
$aViewUrls['message'] = array('title' => $clang->gT("Failed to add user"), 'message' => $clang->gT("A username was not supplied or the username is invalid."), 'class'=> 'warningheader');
|
||||
}
|
||||
elseif (User::model()->find("users_name=:users_name",array(':users_name'=>$new_user))) {
|
||||
$aViewUrls['message'] = array('title' => $clang->gT("Failed to add user"), 'message' => $clang->gT("The username already exists."), 'class'=> 'warningheader');
|
||||
}
|
||||
elseif ($valid_email)
|
||||
{
|
||||
$new_pass = createPassword();
|
||||
$iNewUID = User::model()->insertUser($new_user, $new_pass, $new_full_name, Yii::app()->session['loginID'], $new_email);
|
||||
|
||||
if ($iNewUID) {
|
||||
// add default template to template rights for user
|
||||
Permission::model()->insertSomeRecords(array('uid' => $iNewUID, 'permission' => Yii::app()->getConfig("defaulttemplate"), 'entity'=>'template', 'read_p' => 1, 'entity_id'=>0));
|
||||
// add new user to userlist
|
||||
$sresult = User::model()->getAllRecords(array('uid' => $iNewUID));
|
||||
$srow = count($sresult);
|
||||
$userlist = getUserList();
|
||||
array_push($userlist, array("user" => $srow['users_name'], "uid" => $srow['uid'], "email" => $srow['email'],
|
||||
"password" => $srow["password"], "parent_id" => $srow['parent_id'], // "level"=>$level,
|
||||
"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']));
|
||||
|
||||
// send Mail
|
||||
$body = sprintf($clang->gT("Hello %s,"), $new_full_name) . "<br /><br />\n";
|
||||
$body .= sprintf($clang->gT("this is an automated email to notify that a user has been created for you on the site '%s'."), Yii::app()->getConfig("sitename")) . "<br /><br />\n";
|
||||
$body .= $clang->gT("You can use now the following credentials to log into the site:") . "<br />\n";
|
||||
$body .= $clang->gT("Username") . ": " . $new_user . "<br />\n";
|
||||
if (Yii::app()->getConfig("auth_webserver") === false) { // authent is not delegated to web server
|
||||
// send password (if authorized by config)
|
||||
if (Yii::app()->getConfig("display_user_password_in_email") === true) {
|
||||
$body .= $clang->gT("Password") . ": " . $new_pass . "<br />\n";
|
||||
}
|
||||
else
|
||||
{
|
||||
$body .= $clang->gT("Password") . ": " . $clang->gT("Please contact your LimeSurvey administrator for your password.") . "<br />\n";
|
||||
}
|
||||
}
|
||||
|
||||
$body .= "<a href='" . $this->getController()->createAbsoluteUrl("/admin") . "'>" . $clang->gT("Click here to log in.") . "</a><br /><br />\n";
|
||||
$body .= sprintf($clang->gT('If you have any questions regarding this mail please do not hesitate to contact the site administrator at %s. Thank you!'), Yii::app()->getConfig("siteadminemail")) . "<br />\n";
|
||||
|
||||
$subject = sprintf($clang->gT("User registration at '%s'", "unescaped"), Yii::app()->getConfig("sitename"));
|
||||
$to = $new_user . " <$new_email>";
|
||||
$from = Yii::app()->getConfig("siteadminname") . " <" . Yii::app()->getConfig("siteadminemail") . ">";
|
||||
$extra = '';
|
||||
$classMsg = '';
|
||||
if (SendEmailMessage($body, $subject, $to, $from, Yii::app()->getConfig("sitename"), true, Yii::app()->getConfig("siteadminbounce"))) {
|
||||
$extra .= "<br />" . $clang->gT("Username") . ": $new_user<br />" . $clang->gT("Email") . ": $new_email<br />";
|
||||
$extra .= "<br />" . $clang->gT("An email with a generated password was sent to the user.");
|
||||
$classMsg = 'successheader';
|
||||
$sHeader= $clang->gT("Success");
|
||||
}
|
||||
else
|
||||
{
|
||||
// has to be sent again or no other way
|
||||
$tmp = str_replace("{NAME}", "<strong>" . $new_user . "</strong>", $clang->gT("Email to {NAME} ({EMAIL}) failed."));
|
||||
$extra .= "<br />" . str_replace("{EMAIL}", $new_email, $tmp) . "<br />";
|
||||
$classMsg = 'warningheader';
|
||||
$sHeader= $clang->gT("Warning");
|
||||
}
|
||||
|
||||
$aViewUrls['mboxwithredirect'][] = $this->_messageBoxWithRedirect($clang->gT("Add user"), $sHeader, $classMsg, $extra,
|
||||
$this->getController()->createUrl("admin/user/sa/setuserpermissions"), $clang->gT("Set user permissions"),
|
||||
array('action' => 'setuserpermissions', 'user' => $new_user, 'uid' => $iNewUID));
|
||||
}
|
||||
else
|
||||
{
|
||||
$aViewUrls['mboxwithredirect'][] = $this->_messageBoxWithRedirect($clang->gT("Failed to add user"), $clang->gT("The user name already exists."), 'warningheader');
|
||||
}
|
||||
}
|
||||
|
||||
$this->_renderWrappedTemplate('user', $aViewUrls);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete user
|
||||
*/
|
||||
function deluser()
|
||||
{
|
||||
$clang = Yii::app()->lang;
|
||||
if (!Permission::model()->hasGlobalPermission('superadmin','read') && !Permission::model()->hasGlobalPermission('users','delete')) {
|
||||
Yii::app()->setFlashMessage($clang->gT("You do not have sufficient rights to access this page."),'error');
|
||||
$this->getController()->redirect(array("admin/user/sa/index"));
|
||||
}
|
||||
$action = Yii::app()->request->getPost("action");
|
||||
$aViewUrls = array();
|
||||
|
||||
// CAN'T DELETE ORIGINAL SUPERADMIN (with findByAttributes : found the first user without parent)
|
||||
$oInitialAdmin = User::model()->findByAttributes(array('parent_id' => 0));
|
||||
|
||||
$postuserid = (int) Yii::app()->request->getPost("uid");
|
||||
$postuser = flattenText(Yii::app()->request->getPost("user"));
|
||||
if ($oInitialAdmin && $oInitialAdmin->uid == $postuserid) // it's the original superadmin !!!
|
||||
{
|
||||
Yii::app()->setFlashMessage($clang->gT("Initial Superadmin cannot be deleted!"),'error');
|
||||
$this->getController()->redirect(array("admin/user/sa/index"));
|
||||
}
|
||||
else
|
||||
{
|
||||
if ($postuserid)
|
||||
{
|
||||
$sresultcount = 0; // 1 if I am parent of $postuserid
|
||||
if (!Permission::model()->hasGlobalPermission('superadmin','read'))
|
||||
{
|
||||
$sresult = User::model()->findAllByAttributes(array('parent_id' => $postuserid, 'parent_id' => Yii::app()->session['loginID']));
|
||||
$sresultcount = count($sresult);
|
||||
}
|
||||
|
||||
if (Permission::model()->hasGlobalPermission('superadmin','read') || $sresultcount > 0 || $postuserid == Yii::app()->session['loginID'])
|
||||
{
|
||||
$transfer_surveys_to = 0;
|
||||
$ownerUser = User::model()->findAll();
|
||||
$aData['users'] = $ownerUser;
|
||||
|
||||
$current_user = Yii::app()->session['loginID'];
|
||||
if (count($ownerUser) == 2) {
|
||||
$action = "finaldeluser";
|
||||
foreach ($ownerUser as &$user)
|
||||
{
|
||||
if ($postuserid != $user['uid'])
|
||||
$transfer_surveys_to = $user['uid'];
|
||||
}
|
||||
}
|
||||
|
||||
$ownerUser = Survey::model()->findAllByAttributes(array('owner_id' => $postuserid));
|
||||
if (count($ownerUser) == 0) {
|
||||
$action = "finaldeluser";
|
||||
}
|
||||
|
||||
if ($action == "finaldeluser")
|
||||
{
|
||||
$aViewUrls=$this->deleteFinalUser($ownerUser, $transfer_surveys_to);
|
||||
}
|
||||
else
|
||||
{
|
||||
$aData['postuserid'] = $postuserid;
|
||||
$aData['postuser'] = $postuser;
|
||||
$aData['current_user'] = $current_user;
|
||||
|
||||
$aViewUrls['deluser'][] = $aData;
|
||||
$this->_renderWrappedTemplate('user', $aViewUrls);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Yii::app()->setFlashMessage($clang->gT("You do not have sufficient rights to access this page."),'error');
|
||||
$this->getController()->redirect(array("admin/user/sa/index"));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Yii::app()->setFlashMessage($clang->gT("Could not delete user. User was not supplied."),'error');
|
||||
$this->getController()->redirect(array("admin/user/sa/index"));
|
||||
}
|
||||
}
|
||||
|
||||
return $aViewUrls;
|
||||
}
|
||||
|
||||
function deleteFinalUser($result, $transfer_surveys_to)
|
||||
{
|
||||
$clang = Yii::app()->lang;
|
||||
$postuserid = (int) Yii::app()->request->getPost("uid");
|
||||
$postuser = flattenText(Yii::app()->request->getPost("user"));
|
||||
// Never delete initial admin (with findByAttributes : found the first user without parent)
|
||||
$oInitialAdmin = User::model()->findByAttributes(array('parent_id' => 0));
|
||||
if ($oInitialAdmin && $oInitialAdmin->uid == $postuserid) // it's the original superadmin !!!
|
||||
{
|
||||
Yii::app()->setFlashMessage($clang->gT("Initial Superadmin cannot be deleted!"),'error');
|
||||
$this->getController()->redirect(array("admin/user/sa/index"));
|
||||
}
|
||||
if (isset($_POST['transfer_surveys_to'])) {
|
||||
$transfer_surveys_to = sanitize_int(Yii::app()->request->getPost("transfer_surveys_to"));
|
||||
}
|
||||
if ($transfer_surveys_to > 0) {
|
||||
$iSurveysTransferred = Survey::model()->updateAll(array('owner_id' => $transfer_surveys_to), 'owner_id='.$postuserid);
|
||||
}
|
||||
$sresult = User::model()->findByAttributes(array('uid' => $postuserid));
|
||||
$fields = $sresult;
|
||||
if (isset($fields['parent_id'])) {
|
||||
$uresult = User::model()->updateAll(array('parent_id' => $fields['parent_id']), 'parent_id='.$postuserid);
|
||||
}
|
||||
|
||||
//DELETE USER FROM TABLE
|
||||
$dresult = User::model()->deleteUser($postuserid);
|
||||
|
||||
// Delete user rights
|
||||
$dresult = Permission::model()->deleteAllByAttributes(array('uid' => $postuserid));
|
||||
|
||||
if ($postuserid == Yii::app()->session['loginID'])
|
||||
{
|
||||
session_destroy(); // user deleted himself
|
||||
$this->getController()->redirect(array("admin/authentication/sa/logout"));
|
||||
die();
|
||||
}
|
||||
|
||||
$extra = "<br />" . sprintf($clang->gT("User '%s' was successfully deleted."),$postuser)."<br /><br />\n";
|
||||
if ($transfer_surveys_to > 0 && $iSurveysTransferred>0) {
|
||||
$user = User::model()->findByPk($transfer_surveys_to);
|
||||
$sTransferred_to = $user->users_name;
|
||||
//$sTransferred_to = $this->getController()->_getUserNameFromUid($transfer_surveys_to);
|
||||
$extra = sprintf($clang->gT("All of the user's surveys were transferred to %s."), $sTransferred_to);
|
||||
}
|
||||
|
||||
$aViewUrls['mboxwithredirect'][] = $this->_messageBoxWithRedirect("", $clang->gT("Success!"), "successheader", $extra);
|
||||
$this->_renderWrappedTemplate('user', $aViewUrls);
|
||||
}
|
||||
|
||||
/**
|
||||
* Modify User
|
||||
*/
|
||||
function modifyuser()
|
||||
{
|
||||
if (isset($_POST['uid'])) {
|
||||
$postuserid = (int) Yii::app()->request->getPost("uid");
|
||||
$sresult = User::model()->findAllByAttributes(array('uid' => $postuserid, 'parent_id' => Yii::app()->session['loginID']));
|
||||
$sresultcount = count($sresult);
|
||||
|
||||
|
||||
if (Permission::model()->hasGlobalPermission('superadmin','read') || Yii::app()->session['loginID'] == $postuserid ||
|
||||
(Permission::model()->hasGlobalPermission('users','update') && $sresultcount > 0) )
|
||||
{
|
||||
$sresult = User::model()->parentAndUser($postuserid);
|
||||
$aData['mur'] = $sresult;
|
||||
|
||||
$this->_renderWrappedTemplate('user', 'modifyuser', $aData);
|
||||
return;
|
||||
}
|
||||
else
|
||||
{
|
||||
Yii::app()->setFlashMessage(Yii::app()->lang->gT("You do not have sufficient rights to access this page."),'error');
|
||||
$this->getController()->redirect(array("admin/user/sa/index"));
|
||||
}
|
||||
}
|
||||
Yii::app()->setFlashMessage(Yii::app()->lang->gT("You do not have sufficient rights to access this page."),'error');
|
||||
$this->getController()->redirect(array("admin/user/sa/index"));
|
||||
//echo accessDenied('modifyuser');
|
||||
//die();
|
||||
}
|
||||
|
||||
/**
|
||||
* Modify User POST
|
||||
*/
|
||||
function moduser()
|
||||
{
|
||||
$clang = Yii::app()->lang;
|
||||
$postuserid = (int) Yii::app()->request->getPost("uid");
|
||||
$postuser = flattenText(Yii::app()->request->getPost("user"));
|
||||
$postemail = flattenText(Yii::app()->request->getPost("email"));
|
||||
$postfull_name = flattenText(Yii::app()->request->getPost("full_name"));
|
||||
$display_user_password_in_html = Yii::app()->getConfig("display_user_password_in_html");
|
||||
$addsummary = '';
|
||||
$aViewUrls = array();
|
||||
|
||||
$sresult = User::model()->findAllByAttributes(array('uid' => $postuserid, 'parent_id' => Yii::app()->session['loginID']));
|
||||
$sresultcount = count($sresult);
|
||||
|
||||
if ((Permission::model()->hasGlobalPermission('superadmin','read') || $postuserid == Yii::app()->session['loginID'] ||
|
||||
($sresultcount > 0 && Permission::model()->hasGlobalPermission('users','update'))) && !(Yii::app()->getConfig("demoMode") == true && $postuserid == 1)
|
||||
)
|
||||
{
|
||||
$users_name = html_entity_decode($postuser, ENT_QUOTES, 'UTF-8');
|
||||
$email = html_entity_decode($postemail, ENT_QUOTES, 'UTF-8');
|
||||
$sPassword = html_entity_decode(Yii::app()->request->getPost('pass'), ENT_QUOTES, 'UTF-8');
|
||||
if ($sPassword == '%%unchanged%%')
|
||||
$sPassword = '';
|
||||
$full_name = html_entity_decode($postfull_name, ENT_QUOTES, 'UTF-8');
|
||||
|
||||
if (!validateEmailAddress($email)) {
|
||||
$aViewUrls['mboxwithredirect'][] = $this->_messageBoxWithRedirect($clang->gT("Editing user"), $clang->gT("Could not modify user data."), "warningheader", $clang->gT("Email address is not valid."),
|
||||
$this->getController()->createUrl('admin/user/modifyuser'), $clang->gT("Back"), array('uid' => $postuserid));
|
||||
}
|
||||
else
|
||||
{
|
||||
$oRecord = User::model()->findByPk($postuserid);
|
||||
$oRecord->email= $this->escape($email);
|
||||
$oRecord->full_name= $this->escape($full_name);
|
||||
if (!empty($sPassword))
|
||||
{
|
||||
$oRecord->password= hash('sha256', $sPassword);
|
||||
}
|
||||
$uresult = $oRecord->save(); // store result of save in uresult
|
||||
|
||||
if (empty($sPassword)) {
|
||||
$extra = $clang->gT("Username") . ": {$oRecord->users_name}<br />" . $clang->gT("Password") . ": (" . $clang->gT("Unchanged") . ")<br />\n";
|
||||
$aViewUrls['mboxwithredirect'][] = $this->_messageBoxWithRedirect($clang->gT("Editing user"), $clang->gT("Success!"), "successheader", $extra);
|
||||
}
|
||||
elseif ($uresult && !empty($sPassword)) // When saved successfully
|
||||
{
|
||||
if ($sPassword != 'password')
|
||||
Yii::app()->session['pw_notify'] = FALSE;
|
||||
if ($sPassword == 'password')
|
||||
Yii::app()->session['pw_notify'] = TRUE;
|
||||
|
||||
if ($display_user_password_in_html === true) {
|
||||
$displayedPwd = htmlentities($sPassword);
|
||||
}
|
||||
else
|
||||
{
|
||||
$displayedPwd = preg_replace('/./', '*', $sPassword);
|
||||
}
|
||||
|
||||
$extra = $clang->gT("Username") . ": {$oRecord->users_name}<br />" . $clang->gT("Password") . ": {$displayedPwd}<br />\n";
|
||||
$aViewUrls['mboxwithredirect'][] = $this->_messageBoxWithRedirect($clang->gT("Editing user"), $clang->gT("Success!"), "successheader", $extra);
|
||||
}
|
||||
else
|
||||
{ //Saving the user failed for some reason, message about email is not helpful here
|
||||
// Username and/or email adress already exists.
|
||||
$aViewUrls['mboxwithredirect'][] = $this->_messageBoxWithRedirect($clang->gT("Editing user"), $clang->gT("Could not modify user data."), 'warningheader');
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Yii::app()->setFlashMessage(Yii::app()->lang->gT("You do not have sufficient rights to access this page."),'error');
|
||||
}
|
||||
$this->_renderWrappedTemplate('user', $aViewUrls);
|
||||
}
|
||||
|
||||
|
||||
function savepermissions()
|
||||
{
|
||||
$clang = Yii::app()->lang;
|
||||
$iUserID=(int)App()->request->getPost('uid');
|
||||
// A user may not modify his own permissions
|
||||
if (Yii::app()->session['loginID']==$iUserID) {
|
||||
Yii::app()->setFlashMessage($clang->gT("You are not allowed to edit your own user permissions."),"error");
|
||||
$this->getController()->redirect(array("admin/user/sa/index"));
|
||||
}
|
||||
// Can not update initial superadmin permissions (with findByAttributes : found the first user without parent)
|
||||
$oInitialAdmin = User::model()->findByAttributes(array('parent_id' => 0));
|
||||
if ($oInitialAdmin && $oInitialAdmin->uid == $iUserID) // it's the original superadmin !!!
|
||||
{
|
||||
Yii::app()->setFlashMessage($clang->gT("Initial Superadmin permissions cannot be updated!"),'error');
|
||||
$this->getController()->redirect(array("admin/user/sa/index"));
|
||||
}
|
||||
$aBaseUserPermissions = Permission::model()->getGlobalBasePermissions();
|
||||
|
||||
$aPermissions=array();
|
||||
foreach ($aBaseUserPermissions as $sPermissionKey=>$aCRUDPermissions)
|
||||
{
|
||||
foreach ($aCRUDPermissions as $sCRUDKey=>$CRUDValue)
|
||||
{
|
||||
if (!in_array($sCRUDKey,array('create','read','update','delete','import','export'))) continue;
|
||||
|
||||
if ($CRUDValue)
|
||||
{
|
||||
if(isset($_POST["perm_{$sPermissionKey}_{$sCRUDKey}"])){
|
||||
$aPermissions[$sPermissionKey][$sCRUDKey]=1;
|
||||
}
|
||||
else
|
||||
{
|
||||
$aPermissions[$sPermissionKey][$sCRUDKey]=0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (Permission::model()->setPermissions($iUserID, 0, 'global', $aPermissions))
|
||||
{
|
||||
Yii::app()->session['flashmessage'] = $clang->gT("Permissions were successfully updated.");
|
||||
$this->getController()->redirect(array("admin/user/sa/index"));
|
||||
}
|
||||
else
|
||||
{
|
||||
Yii::app()->session['flashmessage'] = $clang->gT("There was a problem updating the user permissions.");
|
||||
$this->getController()->redirect(array("admin/user/sa/index"));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
function setuserpermissions()
|
||||
{
|
||||
$iUserID = (int) Yii::app()->request->getPost('uid');
|
||||
// Can not update initial superadmin permissions (with findByAttributes : found the first user without parent)
|
||||
$oInitialAdmin = User::model()->findByAttributes(array('parent_id' => 0));
|
||||
if ($oInitialAdmin && $oInitialAdmin->uid == $iUserID) // it's the original superadmin !!!
|
||||
{
|
||||
Yii::app()->setFlashMessage(Yii::app()->lang->gT("Initial Superadmin permissions cannot be updated!"),'error');
|
||||
$this->getController()->redirect(array("admin/user/sa/index"));
|
||||
}
|
||||
$aBaseUserPermissions = Permission::model()->getGlobalBasePermissions();
|
||||
if ($iUserID) {//Never update 1st admin
|
||||
if(Permission::model()->hasGlobalPermission('superadmin','read'))
|
||||
$oUser = User::model()->findByAttributes(array('uid' => $iUserID));
|
||||
else
|
||||
$oUser = User::model()->findByAttributes(array('uid' => $iUserID, 'parent_id' => Yii::app()->session['loginID']));
|
||||
}
|
||||
// Check permissions
|
||||
$aBasePermissions=Permission::model()->getGlobalBasePermissions();
|
||||
if (!Permission::model()->hasGlobalPermission('superadmin','read')) // if not superadmin filter the available permissions as no admin may give more permissions than he owns
|
||||
{
|
||||
Yii::app()->session['flashmessage'] = Yii::app()->lang->gT("Note: You can only give limited permissions to other users because your own permissions are limited, too.");
|
||||
$aFilteredPermissions=array();
|
||||
foreach ($aBasePermissions as $PermissionName=>$aPermission)
|
||||
{
|
||||
foreach ($aPermission as $sPermissionKey=>&$sPermissionValue)
|
||||
{
|
||||
if ($sPermissionKey!='title' && $sPermissionKey!='img' && !Permission::model()->hasGlobalPermission($PermissionName, $sPermissionKey)) $sPermissionValue=false;
|
||||
}
|
||||
// Only show a row for that permission if there is at least one permission he may give to other users
|
||||
if ($aPermission['create'] || $aPermission['read'] || $aPermission['update'] || $aPermission['delete'] || $aPermission['import'] || $aPermission['export'])
|
||||
{
|
||||
$aFilteredPermissions[$PermissionName]=$aPermission;
|
||||
}
|
||||
}
|
||||
$aBasePermissions=$aFilteredPermissions;
|
||||
}
|
||||
|
||||
if ($oUser && (Permission::model()->hasGlobalPermission('superadmin','read') || Permission::model()->hasGlobalPermission('users','update') && Yii::app()->session['loginID'] != $iUserID) )
|
||||
{
|
||||
// Only the original superadmin (UID 1) may create new superadmins
|
||||
if (Yii::app()->session['loginID']!=1)
|
||||
{
|
||||
unset($aBasePermissions['superadmin']);
|
||||
}
|
||||
$aData['aBasePermissions']=$aBasePermissions;
|
||||
$data['sImageURL'] = Yii::app()->getConfig("imageurl");
|
||||
|
||||
$aData['oUser'] =$oUser;
|
||||
App()->getClientScript()->registerPackage('jquery-tablesorter');
|
||||
App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . "userpermissions.js");
|
||||
$this->_renderWrappedTemplate('user', 'setuserpermissions', $aData);
|
||||
}
|
||||
else
|
||||
{
|
||||
Yii::app()->setFlashMessage(Yii::app()->lang->gT("You do not have sufficient rights to access this page."),'error');
|
||||
$this->getController()->redirect(array("admin/user/sa/index"));
|
||||
}
|
||||
}
|
||||
|
||||
function setusertemplates()
|
||||
{
|
||||
App()->getClientScript()->registerPackage('jquery-tablesorter');
|
||||
App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts') . 'users.js');
|
||||
$postuserid = (int) Yii::app()->request->getPost("uid");
|
||||
$aData['postuser'] = flattenText(Yii::app()->request->getPost("user"));
|
||||
$aData['postemail'] = flattenText(Yii::app()->request->getPost("email"));
|
||||
$aData['postuserid'] = $postuserid;
|
||||
$aData['postfull_name'] = flattenText(Yii::app()->request->getPost("full_name"));
|
||||
$this->_refreshtemplates();
|
||||
$templaterights=array();
|
||||
foreach (getUserList() as $usr)
|
||||
{
|
||||
if ($usr['uid'] == $postuserid)
|
||||
{
|
||||
$trights = Permission::model()->findAllByAttributes(array('uid' => $usr['uid'],'entity'=>'template'));
|
||||
foreach ($trights as $srow)
|
||||
{
|
||||
$templaterights[$srow["permission"]] = array("use"=>$srow["read_p"]);
|
||||
}
|
||||
$templates = Template::model()->findAll();
|
||||
$aData['list'][] = array('templaterights'=>$templaterights,'templates'=>$templates);
|
||||
}
|
||||
}
|
||||
$this->_renderWrappedTemplate('user', 'setusertemplates', $aData);
|
||||
}
|
||||
|
||||
function usertemplates()
|
||||
{
|
||||
$clang = Yii::app()->lang;
|
||||
$postuserid = (int) Yii::app()->request->getPost('uid');
|
||||
|
||||
// SUPERADMINS AND MANAGE_TEMPLATE USERS CAN SET THESE RIGHTS
|
||||
if (Permission::model()->hasGlobalPermission('superadmin','read') || Permission::model()->hasGlobalPermission('templates','update'))
|
||||
{
|
||||
$aTemplatePermissions = array();
|
||||
$tresult = Template::model()->findAll();
|
||||
$postvalue= array_flip($_POST);
|
||||
foreach ($tresult as $trow)
|
||||
{
|
||||
if (isset($postvalue[$trow["folder"] . "_use"]))
|
||||
$aTemplatePermissions[$trow["folder"]] = 1;
|
||||
else
|
||||
$aTemplatePermissions[$trow["folder"]] = 0;
|
||||
}
|
||||
foreach ($aTemplatePermissions as $key => $value)
|
||||
{
|
||||
$oPermission = Permission::model()->findByAttributes(array('permission' => $key, 'uid' => $postuserid, 'entity'=>'template'));
|
||||
if (empty($oPermission))
|
||||
{
|
||||
$oPermission = new Permission;
|
||||
$oPermission->uid = $postuserid;
|
||||
$oPermission->permission = $key;
|
||||
$oPermission->entity='template';
|
||||
$oPermission->entity_id=0;
|
||||
}
|
||||
$oPermission->read_p = $value;
|
||||
$uresult = $oPermission->save();
|
||||
}
|
||||
if ($uresult !== false) {
|
||||
Yii::app()->setFlashMessage($clang->gT("Template permissions were updated successfully."));
|
||||
}
|
||||
else
|
||||
{
|
||||
Yii::app()->setFlashMessage($clang->gT("Error while updating template permissions."),'error');
|
||||
}
|
||||
$this->getController()->redirect(array("admin/user/sa/index"));
|
||||
}
|
||||
else
|
||||
{
|
||||
Yii::app()->setFlashMessage($clang->gT("You do not have sufficient rights to access this page."),'error');
|
||||
$this->getController()->redirect(array("admin/user/sa/index"));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Manage user personal settings
|
||||
*/
|
||||
function personalsettings()
|
||||
{
|
||||
|
||||
// Save Data
|
||||
if (Yii::app()->request->getPost("action")) {
|
||||
$aData = array(
|
||||
'lang' => Yii::app()->request->getPost('lang'),
|
||||
'dateformat' => Yii::app()->request->getPost('dateformat'),
|
||||
'htmleditormode' => Yii::app()->request->getPost('htmleditormode'),
|
||||
'questionselectormode' => Yii::app()->request->getPost('questionselectormode'),
|
||||
'templateeditormode' => Yii::app()->request->getPost('templateeditormode')
|
||||
);
|
||||
|
||||
$uresult = User::model()->updateByPk(Yii::app()->session['loginID'], $aData);
|
||||
|
||||
if (Yii::app()->request->getPost('lang')=='auto')
|
||||
{
|
||||
$sLanguage= getBrowserLanguage();
|
||||
}
|
||||
else
|
||||
{
|
||||
$sLanguage=Yii::app()->request->getPost('lang');
|
||||
}
|
||||
|
||||
Yii::app()->session['adminlang'] = $sLanguage;
|
||||
Yii::app()->lang=new limesurvey_lang($sLanguage);
|
||||
$clang = Yii::app()->lang;
|
||||
|
||||
Yii::app()->session['htmleditormode'] = Yii::app()->request->getPost('htmleditormode');
|
||||
Yii::app()->session['questionselectormode'] = Yii::app()->request->getPost('questionselectormode');
|
||||
Yii::app()->session['templateeditormode'] = Yii::app()->request->getPost('templateeditormode');
|
||||
Yii::app()->session['dateformat'] = Yii::app()->request->getPost('dateformat');
|
||||
Yii::app()->session['flashmessage'] = $clang->gT("Your personal settings were successfully saved.");
|
||||
}
|
||||
|
||||
// Get user lang
|
||||
$user = User::model()->findByPk(Yii::app()->session['loginID']);
|
||||
$aData['sSavedLanguage'] = $user->lang;
|
||||
|
||||
// Render personal settings view
|
||||
$this->_renderWrappedTemplate('user', 'personalsettings', $aData);
|
||||
}
|
||||
|
||||
private function _getUserNameFromUid($uid)
|
||||
{
|
||||
$uid = sanitize_int($uid);
|
||||
$result = User::model()->findByPk($uid);
|
||||
|
||||
if (!empty($result)) {
|
||||
return $result->users_name;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private function _refreshtemplates()
|
||||
{
|
||||
$template_a = getTemplateList();
|
||||
foreach ($template_a as $tp => $fullpath)
|
||||
{
|
||||
// check for each folder if there is already an entry in the database
|
||||
// if not create it with current user as creator (user with rights "create user" can assign template rights)
|
||||
$result = Template::model()->findByPk($tp);
|
||||
|
||||
if (count($result) == 0) {
|
||||
$post = new Template;
|
||||
$post->folder = $tp;
|
||||
$post->creator = Yii::app()->session['loginID'];
|
||||
$post->save();
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private function escape($str)
|
||||
{
|
||||
if (is_string($str)) {
|
||||
$str = $this->escape_str($str);
|
||||
}
|
||||
elseif (is_bool($str))
|
||||
{
|
||||
$str = ($str === true) ? 1 : 0;
|
||||
}
|
||||
elseif (is_null($str))
|
||||
{
|
||||
$str = 'NULL';
|
||||
}
|
||||
|
||||
return $str;
|
||||
}
|
||||
|
||||
private function escape_str($str, $like = FALSE)
|
||||
{
|
||||
if (is_array($str)) {
|
||||
foreach ($str as $key => $val)
|
||||
{
|
||||
$str[$key] = $this->escape_str($val, $like);
|
||||
}
|
||||
|
||||
return $str;
|
||||
}
|
||||
|
||||
// Escape single quotes
|
||||
$str = str_replace("'", "''", $this->remove_invisible_characters($str));
|
||||
|
||||
return $str;
|
||||
}
|
||||
|
||||
private function remove_invisible_characters($str, $url_encoded = TRUE)
|
||||
{
|
||||
$non_displayables = array();
|
||||
|
||||
// every control character except newline (dec 10)
|
||||
// carriage return (dec 13), and horizontal tab (dec 09)
|
||||
|
||||
if ($url_encoded) {
|
||||
$non_displayables[] = '/%0[0-8bcef]/'; // url encoded 00-08, 11, 12, 14, 15
|
||||
$non_displayables[] = '/%1[0-9a-f]/'; // url encoded 16-31
|
||||
}
|
||||
|
||||
$non_displayables[] = '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S'; // 00-08, 11, 12, 14-31, 127
|
||||
|
||||
do
|
||||
{
|
||||
$str = preg_replace($non_displayables, '', $str, -1, $count);
|
||||
} while ($count);
|
||||
|
||||
return $str;
|
||||
}
|
||||
|
||||
private function _messageBoxWithRedirect($title, $message, $classMsg, $extra = "", $url = "", $urlText = "", $hiddenVars = array(), $classMbTitle = "header ui-widget-header")
|
||||
{
|
||||
$clang = Yii::app()->lang;
|
||||
$url = (!empty($url)) ? $url : $this->getController()->createUrl('admin/user/index');
|
||||
$urlText = (!empty($urlText)) ? $urlText : $clang->gT("Continue");
|
||||
|
||||
$aData['title'] = $title;
|
||||
$aData['message'] = $message;
|
||||
$aData['url'] = $url;
|
||||
$aData['urlText'] = $urlText;
|
||||
$aData['classMsg'] = $classMsg;
|
||||
$aData['classMbTitle'] = $classMbTitle;
|
||||
$aData['extra'] = $extra;
|
||||
$aData['hiddenVars'] = $hiddenVars;
|
||||
|
||||
return $aData;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders template(s) wrapped in header and footer
|
||||
*
|
||||
* @param string $sAction Current action, the folder to fetch views from
|
||||
* @param string|array $aViewUrls View url(s)
|
||||
* @param array $aData Data to be passed on. Optional.
|
||||
*/
|
||||
protected function _renderWrappedTemplate($sAction = 'user', $aViewUrls = array(), $aData = array())
|
||||
{
|
||||
parent::_renderWrappedTemplate($sAction, $aViewUrls, $aData);
|
||||
}
|
||||
|
||||
}
|
409
sources/application/controllers/admin/usergroups.php
Normal file
409
sources/application/controllers/admin/usergroups.php
Normal file
|
@ -0,0 +1,409 @@
|
|||
<?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.
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* Usergroups
|
||||
*
|
||||
* @package LimeSurvey
|
||||
* @author
|
||||
* @copyright 2011
|
||||
* @access public
|
||||
*/
|
||||
|
||||
class Usergroups extends Survey_Common_Action
|
||||
{
|
||||
|
||||
/**
|
||||
* Usergroups::mail()
|
||||
* Function responsible to send an e-mail to a user group.
|
||||
* @param mixed $ugid
|
||||
* @return void
|
||||
*/
|
||||
public function mail($ugid)
|
||||
{
|
||||
|
||||
$ugid = sanitize_int($ugid);
|
||||
$clang = Yii::app()->lang;
|
||||
|
||||
$action = Yii::app()->request->getPost("action");
|
||||
|
||||
if ($action == "mailsendusergroup") {
|
||||
|
||||
// user must be in user group or superadmin
|
||||
$result = UserInGroup::model()->findAllByPk(array('ugid' => $ugid, 'uid' => Yii::app()->session['loginID']));
|
||||
if (count($result) > 0 || Permission::model()->hasGlobalPermission('superadmin','read'))
|
||||
{
|
||||
$criteria = new CDbCriteria;
|
||||
$criteria->compare('ugid',$ugid)->addNotInCondition('users.uid',array(Yii::app()->session['loginID']));
|
||||
$eguresult = UserInGroup::model()->with('users')->findAll($criteria);
|
||||
//die('me');
|
||||
$to = array();
|
||||
|
||||
foreach ($eguresult as $egurow)
|
||||
{
|
||||
$to[] = $egurow->users->users_name . ' <' . $egurow->users->email . '>';
|
||||
}
|
||||
|
||||
$from_user_result = User::model()->findByPk(Yii::app()->session['loginID']);
|
||||
$from_user_row = $from_user_result;
|
||||
|
||||
if ($from_user_row->full_name) {
|
||||
$from = $from_user_row->full_name;
|
||||
$from .= ' <';
|
||||
$from .= $from_user_row->email . '> ';
|
||||
}
|
||||
else
|
||||
{
|
||||
$from = $from_user_row->users_name . ' <' . $from_user_row->email . '> ';
|
||||
}
|
||||
|
||||
$body = $_POST['body'];
|
||||
$subject = $_POST['subject'];
|
||||
|
||||
if (isset($_POST['copymail']) && $_POST['copymail'] == 1) {
|
||||
$to[] = $from;
|
||||
}
|
||||
$body = str_replace("\n.", "\n..", $body);
|
||||
$body = wordwrap($body, 70);
|
||||
|
||||
|
||||
//echo $body . '-'.$subject .'-'.'<pre>'.htmlspecialchars($to).'</pre>'.'-'.$from;
|
||||
if (SendEmailMessage($body, $subject, $to, $from, '')) {
|
||||
list($aViewUrls, $aData) = $this->index($ugid, array("type" => "success", "message" => "Message(s) sent successfully!"));
|
||||
}
|
||||
else
|
||||
{
|
||||
global $maildebug;
|
||||
global $debug;
|
||||
global $maildebugbody;
|
||||
//$maildebug = (isset($maildebug)) ? $maildebug : "Their was a unknown error in the mailing part :)";
|
||||
//$debug = (isset($debug)) ? $debug : 9;
|
||||
//$maildebugbody = (isset($maildebugbody)) ? $maildebugbody : 'an unknown error accourd';
|
||||
$headercfg["type"] = "warning";
|
||||
$headercfg["message"] = sprintf($clang->gT("Email to %s failed. Error Message:"), $to) . " " . $maildebug;
|
||||
list($aViewUrls, $aData) = $this->index($ugid, $headercfg);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
die();
|
||||
}
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
$where = array('and', 'a.ugid =' . $ugid, 'uid =' . Yii::app()->session['loginID']);
|
||||
$join = array('where' => "{{user_in_groups}} AS b", 'on' => 'a.ugid = b.ugid');
|
||||
$result = UserGroup::model()->join(array('a.ugid', 'a.name', 'a.owner_id', 'b.uid'), "{{user_groups}} AS a", $where, $join, 'name');
|
||||
|
||||
$crow = $result;
|
||||
$aData['ugid'] = $ugid;
|
||||
|
||||
$aViewUrls = 'mailUserGroup_view';
|
||||
}
|
||||
|
||||
$this->_renderWrappedTemplate('usergroup', $aViewUrls, $aData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Usergroups::delete()
|
||||
* Function responsible to delete a user group.
|
||||
* @return void
|
||||
*/
|
||||
public function delete($ugid)
|
||||
{
|
||||
$clang = Yii::app()->lang;
|
||||
$aViewUrls = array();
|
||||
$aData = array();
|
||||
|
||||
if (Permission::model()->hasGlobalPermission('usergroups','delete')) {
|
||||
|
||||
if (!empty($ugid) && ($ugid > -1)) {
|
||||
$result = UserGroup::model()->requestEditGroup($ugid, Yii::app()->session["loginID"]);
|
||||
if ($result->count() > 0) { // OK - AR count
|
||||
$delquery_result = UserGroup::model()->deleteGroup($ugid, Yii::app()->session["loginID"]);
|
||||
|
||||
if ($delquery_result) //Checked)
|
||||
{
|
||||
list($aViewUrls, $aData) = $this->index(false, array("type" => "success", "message" => $clang->gT("Success!")));
|
||||
}
|
||||
else
|
||||
{
|
||||
list($aViewUrls, $aData) = $this->index(false, array("type" => "warning", "message" => $clang->gT("Could not delete user group.")));
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
list($aViewUrls, $aData) = $this->index($ugid, array("type" => "warning", "message" => $clang->gT("Could not delete user group. No group selected.")));
|
||||
}
|
||||
}
|
||||
|
||||
$this->_renderWrappedTemplate('usergroup', $aViewUrls, $aData);
|
||||
}
|
||||
|
||||
|
||||
public function add()
|
||||
{
|
||||
$clang = Yii::app()->lang;
|
||||
|
||||
$action = (isset($_POST['action'])) ? $_POST['action'] : '';
|
||||
$aData = array();
|
||||
|
||||
if (Permission::model()->hasGlobalPermission('usergroups','create')) {
|
||||
|
||||
if ($action == "usergroupindb") {
|
||||
$db_group_name = flattenText($_POST['group_name'],false,true,'UTF-8',true);
|
||||
$db_group_description = $_POST['group_description'];
|
||||
|
||||
if (isset($db_group_name) && strlen($db_group_name) > 0) {
|
||||
if (strlen($db_group_name) > 21) {
|
||||
list($aViewUrls, $aData) = $this->index(false, array("type" => "warning", "message" => $clang->gT("Failed to add group! Group name length more than 20 characters.")));
|
||||
}
|
||||
elseif (UserGroup::model()->find("name=:groupName", array(':groupName'=>$db_group_name))) {
|
||||
list($aViewUrls, $aData) = $this->index(false, array("type" => "warning", "message" => $clang->gT("Failed to add group! Group already exists.")));
|
||||
}
|
||||
else
|
||||
{
|
||||
$ugid = UserGroup::model()->addGroup($db_group_name, $db_group_description);
|
||||
Yii::app()->session['flashmessage'] = $clang->gT("User group successfully added!");
|
||||
list($aViewUrls, $aData) = $this->index($ugid, true);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
list($aViewUrls, $aData) = $this->index(false, array("type" => "warning", "message" => $clang->gT("Failed to add group! Group Name was not supplied.")));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
$aViewUrls = 'addUserGroup_view';
|
||||
}
|
||||
}
|
||||
|
||||
$this->_renderWrappedTemplate('usergroup', $aViewUrls, $aData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Usergroups::edit()
|
||||
* Load edit user group screen.
|
||||
* @param mixed $ugid
|
||||
* @return void
|
||||
*/
|
||||
function edit($ugid)
|
||||
{
|
||||
$ugid = (int)$ugid;
|
||||
$clang = Yii::app()->lang;
|
||||
$action = (isset($_POST['action'])) ? $_POST['action'] : '';
|
||||
if (Permission::model()->hasGlobalPermission('usergroups','update')) {
|
||||
if ($action == "editusergroupindb") {
|
||||
|
||||
$ugid = (int)$_POST['ugid'];
|
||||
|
||||
$db_name = $_POST['name'];
|
||||
$db_description = $_POST['description'];
|
||||
if (UserGroup::model()->updateGroup($db_name, $db_description, $ugid)) {
|
||||
Yii::app()->session['flashmessage'] = $clang->gT("User group successfully saved!");
|
||||
$aData['ugid'] = $ugid;
|
||||
$this->getController()->redirect(array('admin/usergroups/sa/view/ugid/'.$ugid));
|
||||
}
|
||||
else
|
||||
{
|
||||
Yii::app()->session['flashmessage'] = $clang->gT("Failed to edit user group!");
|
||||
$this->getController()->redirect(array('admin/usergroups/sa/edit/ugid/'.$ugid));
|
||||
}
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
$result = UserGroup::model()->requestEditGroup($ugid, Yii::app()->session['loginID']);
|
||||
$aData['esrow'] = $result;
|
||||
$aData['ugid'] = $result->ugid;
|
||||
$aViewUrls = 'editUserGroup_view';
|
||||
}
|
||||
}
|
||||
|
||||
$this->_renderWrappedTemplate('usergroup', 'editUserGroup_view', $aData);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Load viewing of a user group screen.
|
||||
* @param bool $ugid
|
||||
* @param array|bool $header (type=success, warning)(message=localized message)
|
||||
* @return void
|
||||
*/
|
||||
public function index($ugid = false, $header = false)
|
||||
{
|
||||
if ($ugid != false)
|
||||
$ugid = (int)$ugid;
|
||||
|
||||
if (!empty($header))
|
||||
$aData['headercfg'] = $header;
|
||||
else
|
||||
$aData = array();
|
||||
|
||||
$aViewUrls = array();
|
||||
$aData['ugid'] = $ugid;
|
||||
$aData['imageurl'] = Yii::app()->getConfig("adminimageurl");
|
||||
$clang = Yii::app()->lang;
|
||||
|
||||
if (Yii::app()->session['loginID']) {
|
||||
|
||||
if ($ugid) {
|
||||
$ugid = sanitize_int($ugid);
|
||||
$aData["usergroupid"] = $ugid;
|
||||
$result = UserGroup::model()->requestViewGroup($ugid, Yii::app()->session["loginID"]);
|
||||
$crow = $result[0];
|
||||
if ($result) {
|
||||
$aData["groupfound"] = true;
|
||||
$aData["groupname"] = $crow['name'];
|
||||
if (!empty($crow['description']))
|
||||
$aData["usergroupdescription"] = $crow['description'];
|
||||
else
|
||||
$aData["usergroupdescription"] = "";
|
||||
}
|
||||
//$this->user_in_groups_model = new User_in_groups;
|
||||
$eguquery = "SELECT * FROM {{user_in_groups}} AS a INNER JOIN {{users}} AS b ON a.uid = b.uid WHERE ugid = " . $ugid . " ORDER BY b.users_name";
|
||||
$eguresult = dbExecuteAssoc($eguquery);
|
||||
$aUserInGroupsResult = $eguresult->readAll();
|
||||
$query2 = "SELECT ugid FROM {{user_groups}} WHERE ugid = " . $ugid . " AND owner_id = " . Yii::app()->session['loginID'];
|
||||
$result2 = dbSelectLimitAssoc($query2, 1);
|
||||
$row2 = $result2->readAll();
|
||||
$row = 1;
|
||||
$userloop = array();
|
||||
$bgcc = "oddrow";
|
||||
foreach ($aUserInGroupsResult as $egurow)
|
||||
{
|
||||
if ($bgcc == "evenrow") {
|
||||
$bgcc = "oddrow";
|
||||
} else {
|
||||
$bgcc = "evenrow";
|
||||
}
|
||||
$userloop[$row]["userid"] = $egurow['uid'];
|
||||
|
||||
// output users
|
||||
$userloop[$row]["rowclass"] = $bgcc;
|
||||
if (Permission::model()->hasGlobalPermission('superadmin','update')) {
|
||||
$userloop[$row]["displayactions"] = true;
|
||||
} else {
|
||||
$userloop[$row]["displayactions"] = false;
|
||||
}
|
||||
|
||||
$userloop[$row]["username"] = $egurow['users_name'];
|
||||
$userloop[$row]["email"] = $egurow['email'];
|
||||
|
||||
$row++;
|
||||
}
|
||||
$aData["userloop"] = $userloop;
|
||||
if (isset($row2[0]['ugid'])) {
|
||||
$aData["useradddialog"] = true;
|
||||
$aData["useraddusers"] = getGroupUserList($ugid, 'optionlist');
|
||||
$aData["useraddurl"] = "";
|
||||
}
|
||||
}
|
||||
|
||||
$aViewUrls[] = 'viewUserGroup_view';
|
||||
}
|
||||
|
||||
if (!empty($header))
|
||||
{
|
||||
return array($aViewUrls, $aData);
|
||||
}
|
||||
else
|
||||
{
|
||||
$this->_renderWrappedTemplate('usergroup', $aViewUrls, $aData);
|
||||
}
|
||||
}
|
||||
|
||||
function user($ugid, $action = 'add')
|
||||
{
|
||||
if (!Permission::model()->hasGlobalPermission('usergroups','read') || !in_array($action, array('add', 'remove')))
|
||||
{
|
||||
die('access denied');
|
||||
}
|
||||
|
||||
$clang = Yii::app()->lang;
|
||||
$uid = (int) Yii::app()->request->getPost('uid');
|
||||
|
||||
$group = UserGroup::model()->findByAttributes(array('ugid' => $ugid, 'owner_id' => Yii::app()->session['loginID']));
|
||||
|
||||
if (empty($group))
|
||||
{
|
||||
list($aViewUrls, $aData) = $this->index(0, array('type' => 'warning', 'message' => $clang->gT('Failed.') . '<br />' . $clang->gT('Group not found.')));
|
||||
}
|
||||
else
|
||||
{
|
||||
if ($uid > 0 && User::model()->findByPk($uid))
|
||||
{
|
||||
if ($group->owner_id == $uid)
|
||||
{
|
||||
list($aViewUrls, $aData) = $this->index($ugid, array('type' => 'warning', 'message' => $clang->gT('Failed.') . '<br />' . $clang->gT('You can not add or remove the group owner from the group.')));
|
||||
}
|
||||
|
||||
$user_in_group = UserInGroup::model()->findByPk(array('ugid' => $ugid, 'uid' => $uid));
|
||||
|
||||
switch ($action)
|
||||
{
|
||||
case 'add' :
|
||||
if (empty($user_in_group) && UserInGroup::model()->insertRecords(array('ugid' => $ugid, 'uid' => $uid)))
|
||||
{
|
||||
list($aViewUrls, $aData) = $this->index($ugid, array('type' => 'success', 'message' => $clang->gT('User added.')));
|
||||
}
|
||||
else
|
||||
{
|
||||
list($aViewUrls, $aData) = $this->index($ugid, array('type' => 'warning', 'message' => $clang->gT('Failed to add user.') . '<br />' . $clang->gT('User already exists in the group.')));
|
||||
}
|
||||
|
||||
break;
|
||||
case 'remove' :
|
||||
if (!empty($user_in_group) && UserInGroup::model()->deleteByPk(array('ugid' => $ugid, 'uid' => $uid)))
|
||||
{
|
||||
list($aViewUrls, $aData) = $this->index($ugid, array('type' => 'success', 'message' => $clang->gT('User removed.')));
|
||||
}
|
||||
else
|
||||
{
|
||||
list($aViewUrls, $aData) = $this->index($ugid, array('type' => 'warning', 'message' => $clang->gT('Failed to remove user.') . '<br />' . $clang->gT('User does not exist in the group.')));
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
list($aViewUrls, $aData) = $this->index($ugid, array('type' => 'warning', 'message' => $clang->gT('Failed.') . '<br />' . $clang->gT('User not found.')));
|
||||
}
|
||||
}
|
||||
|
||||
$this->_renderWrappedTemplate('usergroup', $aViewUrls, $aData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders template(s) wrapped in header and footer
|
||||
*
|
||||
* @param string $sAction Current action, the folder to fetch views from
|
||||
* @param string|array $aViewUrls View url(s)
|
||||
* @param array $aData Data to be passed on. Optional.
|
||||
*/
|
||||
protected function _renderWrappedTemplate($sAction = 'usergroup', $aViewUrls = array(), $aData = array())
|
||||
{
|
||||
App()->getClientScript()->registerCssFile(Yii::app()->getConfig('adminstyleurl')."superfish.css");
|
||||
App()->getClientScript()->registerPackage('jquery-tablesorter');
|
||||
App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('adminscripts').'users.js');
|
||||
|
||||
$aData['display']['menu_bars']['user_group'] = true;
|
||||
|
||||
parent::_renderWrappedTemplate($sAction, $aViewUrls, $aData);
|
||||
}
|
||||
}
|
10
sources/application/controllers/index.html
Normal file
10
sources/application/controllers/index.html
Normal file
|
@ -0,0 +1,10 @@
|
|||
<html>
|
||||
<head>
|
||||
<title>403 Forbidden</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<p>Directory access is forbidden.</p>
|
||||
|
||||
</body>
|
||||
</html>
|
706
sources/application/controllers/survey/index.php
Normal file
706
sources/application/controllers/survey/index.php
Normal file
|
@ -0,0 +1,706 @@
|
|||
<?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.
|
||||
*/
|
||||
|
||||
class index extends CAction {
|
||||
|
||||
public function run()
|
||||
{
|
||||
/*
|
||||
* Instead of manually rendering scripts after this function returns we
|
||||
* use the callback. This ensures that scripts are always rendered, even
|
||||
* if we call exit at some point in the code. (Which we shouldn't, but
|
||||
* it happens.)
|
||||
*/
|
||||
// Ensure to set some var, but script are replaced in SurveyRuntimeHelper
|
||||
$aLSJavascriptVar=array();
|
||||
$aLSJavascriptVar['bFixNumAuto']=(int)(bool)Yii::app()->getConfig('bFixNumAuto',1);
|
||||
$aLSJavascriptVar['bNumRealValue']=(int)(bool)Yii::app()->getConfig('bNumRealValue',0);
|
||||
$aLangData=getLanguageData();
|
||||
$aRadix=getRadixPointData($aLangData[ Yii::app()->getConfig('defaultlang')]['radixpoint']);
|
||||
$aLSJavascriptVar['sLEMradix']=$aRadix['separator'];
|
||||
$sLSJavascriptVar="LSvar=".json_encode($aLSJavascriptVar) . ';';
|
||||
App()->clientScript->registerScript('sLSJavascriptVar',$sLSJavascriptVar,CClientScript::POS_HEAD);
|
||||
App()->clientScript->registerScript('setJsVar',"setJsVar();",CClientScript::POS_BEGIN);// Ensure all js var is set before rendering the page (User can click before $.ready)
|
||||
|
||||
App()->getClientScript()->registerPackage('jqueryui');
|
||||
App()->getClientScript()->registerPackage('jquery-touch-punch');
|
||||
App()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts')."survey_runtime.js");
|
||||
useFirebug();
|
||||
|
||||
ob_start(function($buffer, $phase) {
|
||||
App()->getClientScript()->render($buffer);
|
||||
App()->getClientScript()->reset();
|
||||
return $buffer;
|
||||
});
|
||||
ob_implicit_flush(false);
|
||||
$this->action();
|
||||
ob_flush();
|
||||
}
|
||||
|
||||
function action()
|
||||
{
|
||||
global $surveyid;
|
||||
global $thissurvey, $thisstep;
|
||||
global $clienttoken, $tokensexist, $token;
|
||||
global $clang;
|
||||
$clang = Yii::app()->lang;
|
||||
// only attempt to change session lifetime if using a DB backend
|
||||
// with file based sessions, it's up to the admin to configure maxlifetime
|
||||
if(isset(Yii::app()->session->connectionID)) {
|
||||
@ini_set('session.gc_maxlifetime', Yii::app()->getConfig('iSessionExpirationTime'));
|
||||
}
|
||||
|
||||
$this->_loadRequiredHelpersAndLibraries();
|
||||
|
||||
$param = $this->_getParameters(func_get_args(), $_POST);
|
||||
|
||||
$surveyid = $param['sid'];
|
||||
Yii::app()->setConfig('surveyID',$surveyid);
|
||||
$thisstep = $param['thisstep'];
|
||||
$move=getMove();
|
||||
Yii::app()->setConfig('move',$move);
|
||||
$clienttoken = $param['token'];
|
||||
$standardtemplaterootdir = Yii::app()->getConfig('standardtemplaterootdir');
|
||||
if (is_null($thissurvey) && !is_null($surveyid)) $thissurvey = getSurveyInfo($surveyid);
|
||||
|
||||
// unused vars in this method (used in methods using compacted method vars)
|
||||
@$loadname = $param['loadname'];
|
||||
@$loadpass = $param['loadpass'];
|
||||
$sitename = Yii::app()->getConfig('sitename');
|
||||
|
||||
if (isset($param['newtest']) && $param['newtest'] == "Y")
|
||||
{
|
||||
killSurveySession($surveyid);
|
||||
}
|
||||
|
||||
$surveyExists=($surveyid && Survey::model()->findByPk($surveyid));
|
||||
$isSurveyActive=($surveyExists && Survey::model()->findByPk($surveyid)->active=="Y");
|
||||
|
||||
// collect all data in this method to pass on later
|
||||
$redata = compact(array_keys(get_defined_vars()));
|
||||
|
||||
$clang = $this->_loadLimesurveyLang($surveyid);
|
||||
|
||||
if ( $this->_isClientTokenDifferentFromSessionToken($clienttoken,$surveyid) )
|
||||
{
|
||||
$sReloadUrl=$this->getController()->createUrl("/survey/index/sid/{$surveyid}",array('token'=>$clienttoken,'lang'=>$clang->langcode,'newtest'=>'Y'));
|
||||
$asMessage = array(
|
||||
$clang->gT('Token mismatch'),
|
||||
$clang->gT('The token you provided doesn\'t match the one in your session.'),
|
||||
"<a class='reloadlink newsurvey' href={$sReloadUrl}>".$clang->gT("Click here to start the survey.")."</a>"
|
||||
);
|
||||
$this->_createNewUserSessionAndRedirect($surveyid, $redata, __LINE__, $asMessage);
|
||||
}
|
||||
|
||||
if ( $this->_isSurveyFinished($surveyid) && ($thissurvey['alloweditaftercompletion'] != 'Y' || $thissurvey['tokenanswerspersistence'] != 'Y')) // No test for response update
|
||||
{
|
||||
$aReloadUrlParam=array('lang'=>$clang->langcode,'newtest'=>'Y');
|
||||
if($clienttoken){$aReloadUrlParam['token']=$clienttoken;}
|
||||
$sReloadUrl=$this->getController()->createUrl("/survey/index/sid/{$surveyid}",$aReloadUrlParam);
|
||||
$asMessage = array(
|
||||
$clang->gT('Previous session is set to be finished.'),
|
||||
$clang->gT('Your browser reports that it was used previously to answer this survey. We are resetting the session so that you can start from the beginning.'),
|
||||
"<a class='reloadlink newsurvey' href={$sReloadUrl}>".$clang->gT("Click here to start the survey.")."</a>"
|
||||
);
|
||||
$this->_createNewUserSessionAndRedirect($surveyid, $redata, __LINE__, $asMessage);
|
||||
}
|
||||
|
||||
$previewmode=false;
|
||||
if (isset($param['action']) && (in_array($param['action'],array('previewgroup','previewquestion'))))
|
||||
{
|
||||
if(!$this->_canUserPreviewSurvey($surveyid))
|
||||
{
|
||||
$asMessage = array(
|
||||
$clang->gT('Error'),
|
||||
$clang->gT("We are sorry but you don't have permissions to do this.")
|
||||
);
|
||||
$this->_niceExit($redata, __LINE__, null, $asMessage);
|
||||
}
|
||||
else
|
||||
{
|
||||
if((intval($param['qid']) && $param['action']=='previewquestion')) $previewmode='question';
|
||||
if((intval($param['gid']) && $param['action']=='previewgroup')) $previewmode='group';
|
||||
}
|
||||
}
|
||||
Yii::app()->setConfig('previewmode',$previewmode);
|
||||
if ( $this->_surveyCantBeViewedWithCurrentPreviewAccess($surveyid, $isSurveyActive, $surveyExists) )
|
||||
{
|
||||
$bPreviewRight = $this->_userHasPreviewAccessSession($surveyid);
|
||||
|
||||
if ($bPreviewRight === false)
|
||||
{
|
||||
$asMessage = array(
|
||||
$clang->gT("Error"),
|
||||
$clang->gT("We are sorry but you don't have permissions to do this."),
|
||||
sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$thissurvey['adminname'],$thissurvey['adminemail'])
|
||||
);
|
||||
$this->_niceExit($redata, __LINE__, null, $asMessage);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// TODO can this be moved to the top?
|
||||
// (Used to be global, used in ExpressionManager, merged into amVars. If not filled in === '')
|
||||
// can this be added in the first computation of $redata?
|
||||
if (isset($_SESSION['survey_'.$surveyid]['srid']))
|
||||
{
|
||||
$saved_id = $_SESSION['survey_'.$surveyid]['srid'];
|
||||
}
|
||||
// recompute $redata since $saved_id used to be a global
|
||||
$redata = compact(array_keys(get_defined_vars()));
|
||||
|
||||
|
||||
if ( $this->_didSessionTimeOut($surveyid) )
|
||||
{
|
||||
// @TODO is this still required ?
|
||||
$asMessage = array(
|
||||
$clang->gT("Error"),
|
||||
$clang->gT("We are sorry but your session has expired."),
|
||||
$clang->gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection."),
|
||||
sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$thissurvey['adminname'],$thissurvey['adminemail'])
|
||||
);
|
||||
$this->_niceExit($redata, __LINE__, null, $asMessage);
|
||||
};
|
||||
|
||||
// Set the language of the survey, either from POST, GET parameter of session var
|
||||
// Keep the old value, because SetSurveyLanguage update $_SESSION
|
||||
$sOldLang=isset($_SESSION['survey_'.$surveyid]['s_lang'])?$_SESSION['survey_'.$surveyid]['s_lang']:"";// Keep the old value, because SetSurveyLanguage update $_SESSION
|
||||
if (!empty($param['lang']))
|
||||
{
|
||||
$sDisplayLanguage = $param['lang'];// $param take lang from returnGlobal and returnGlobal sanitize langagecode
|
||||
}
|
||||
elseif (isset($_SESSION['survey_'.$surveyid]['s_lang']))
|
||||
{
|
||||
$sDisplayLanguage = $_SESSION['survey_'.$surveyid]['s_lang'];
|
||||
}
|
||||
else
|
||||
{
|
||||
$sDisplayLanguage=Yii::app()->getConfig('defaultlang');
|
||||
}
|
||||
|
||||
//CHECK FOR REQUIRED INFORMATION (sid)
|
||||
if ($surveyid && $surveyExists)
|
||||
{
|
||||
LimeExpressionManager::SetSurveyId($surveyid); // must be called early - it clears internal cache if a new survey is being used
|
||||
$clang = SetSurveyLanguage( $surveyid, $sDisplayLanguage);
|
||||
if($previewmode) LimeExpressionManager::SetPreviewMode($previewmode);
|
||||
if ($clang->langcode != $sOldLang) // Update the Session var only if needed
|
||||
{
|
||||
UpdateGroupList($surveyid, $clang->langcode); // to refresh the language strings in the group list session variable
|
||||
UpdateFieldArray(); // to refresh question titles and question text
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new CHttpException(404, "The survey in which you are trying to participate does not seem to exist. It may have been deleted or the link you were given is outdated or incorrect.");
|
||||
}
|
||||
|
||||
// Get token
|
||||
if (!isset($token))
|
||||
{
|
||||
$token=$clienttoken;
|
||||
}
|
||||
|
||||
//GET BASIC INFORMATION ABOUT THIS SURVEY
|
||||
$thissurvey=getSurveyInfo($surveyid, $_SESSION['survey_'.$surveyid]['s_lang']);
|
||||
|
||||
$event = new PluginEvent('beforeSurveyPage');
|
||||
$event->set('surveyId', $surveyid);
|
||||
App()->getPluginManager()->dispatchEvent($event);
|
||||
if (!is_null($event->get('template')))
|
||||
{
|
||||
$thissurvey['templatedir'] = $event->get('template');
|
||||
}
|
||||
|
||||
//SEE IF SURVEY USES TOKENS
|
||||
if ($surveyExists == 1 && tableExists('{{tokens_'.$thissurvey['sid'].'}}'))
|
||||
{
|
||||
$tokensexist = 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
$tokensexist = 0;
|
||||
unset($_POST['token']);
|
||||
unset($param['token']);
|
||||
unset($token);
|
||||
unset($clienttoken);
|
||||
}
|
||||
|
||||
//SET THE TEMPLATE DIRECTORY
|
||||
|
||||
$thistpl = getTemplatePath($thissurvey['templatedir']);
|
||||
|
||||
|
||||
$timeadjust = Yii::app()->getConfig("timeadjust");
|
||||
//MAKE SURE SURVEY HASN'T EXPIRED
|
||||
if ($thissurvey['expiry']!='' and dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust)>$thissurvey['expiry'] && $thissurvey['active']!='N' && !$previewmode)
|
||||
{
|
||||
$redata = compact(array_keys(get_defined_vars()));
|
||||
$asMessage = array(
|
||||
$clang->gT("Error"),
|
||||
$clang->gT("This survey is no longer available."),
|
||||
sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$thissurvey['adminname'],$thissurvey['adminemail'])
|
||||
);
|
||||
|
||||
$this->_niceExit($redata, __LINE__, $thissurvey['templatedir'], $asMessage);
|
||||
}
|
||||
|
||||
//MAKE SURE SURVEY IS ALREADY VALID
|
||||
if ($thissurvey['startdate']!='' and dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust)<$thissurvey['startdate'] && $thissurvey['active']!='N' && !$previewmode)
|
||||
{
|
||||
$redata = compact(array_keys(get_defined_vars()));
|
||||
$asMessage = array(
|
||||
$clang->gT("Error"),
|
||||
$clang->gT("This survey is not yet started."),
|
||||
sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$thissurvey['adminname'],$thissurvey['adminemail'])
|
||||
);
|
||||
|
||||
$this->_niceExit($redata, __LINE__, $thissurvey['templatedir'], $asMessage);
|
||||
}
|
||||
|
||||
//CHECK FOR PREVIOUSLY COMPLETED COOKIE
|
||||
//If cookies are being used, and this survey has been completed, a cookie called "PHPSID[sid]STATUS" will exist (ie: SID6STATUS) and will have a value of "COMPLETE"
|
||||
$sCookieName="LS_".$surveyid."_STATUS";
|
||||
if (isset($_COOKIE[$sCookieName]) && $_COOKIE[$sCookieName] == "COMPLETE" && $thissurvey['usecookie'] == "Y" && $tokensexist != 1 && (!isset($param['newtest']) || $param['newtest'] != "Y"))
|
||||
{
|
||||
$redata = compact(array_keys(get_defined_vars()));
|
||||
$asMessage = array(
|
||||
$clang->gT("Error"),
|
||||
$clang->gT("You have already completed this survey."),
|
||||
sprintf($clang->gT("Please contact %s ( %s ) for further assistance."),$thissurvey['adminname'],$thissurvey['adminemail'])
|
||||
);
|
||||
|
||||
$this->_niceExit($redata, __LINE__, $thissurvey['templatedir'], $asMessage);
|
||||
}
|
||||
|
||||
//LOAD SAVED SURVEY
|
||||
if (Yii::app()->request->getParam('loadall') == "reload")
|
||||
{
|
||||
$errormsg="";
|
||||
$sLoadName=Yii::app()->request->getParam('loadname');
|
||||
$sLoadPass=Yii::app()->request->getParam('loadpass');
|
||||
if ( isset($sLoadName) && !$sLoadName)
|
||||
{
|
||||
$errormsg .= $clang->gT("You did not provide a name")."<br />\n";
|
||||
}
|
||||
if ( isset($sLoadPass) && !$sLoadPass)
|
||||
{
|
||||
$errormsg .= $clang->gT("You did not provide a password")."<br />\n";
|
||||
}
|
||||
|
||||
// if security question answer is incorrect
|
||||
// Not called if scid is set in GET params (when using email save/reload reminder URL)
|
||||
if (function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen',$thissurvey['usecaptcha']) && is_null(Yii::app()->request->getQuery('scid')))
|
||||
{
|
||||
$sLoadSecurity=Yii::app()->request->getPost('loadsecurity');
|
||||
if(empty($sLoadSecurity))
|
||||
{
|
||||
$errormsg .= $clang->gT("You did not answer to the security question.")."<br />\n";
|
||||
}
|
||||
elseif ( (!isset($_SESSION['survey_'.$surveyid]['secanswer']) || $sLoadSecurity != $_SESSION['survey_'.$surveyid]['secanswer']) )
|
||||
{
|
||||
$errormsg .= $clang->gT("The answer to the security question is incorrect.")."<br />\n";
|
||||
}
|
||||
}
|
||||
|
||||
$_SESSION['survey_'.$surveyid]['holdname'] = $sLoadName;
|
||||
$_SESSION['survey_'.$surveyid]['holdpass'] = $sLoadPass;
|
||||
|
||||
if ($errormsg == "") {
|
||||
LimeExpressionManager::SetDirtyFlag();
|
||||
buildsurveysession($surveyid);
|
||||
if (loadanswers()){
|
||||
Yii::app()->setConfig('move','movenext');
|
||||
$move = "movenext";// 140113 : deprecated ?
|
||||
} else {
|
||||
$errormsg .= $clang->gT("There is no matching saved survey");
|
||||
}
|
||||
}
|
||||
if ($errormsg) {
|
||||
Yii::app()->setConfig('move',"loadall");// Show loading form
|
||||
}
|
||||
}
|
||||
//Allow loading of saved survey
|
||||
if (Yii::app()->getConfig('move')=="loadall")
|
||||
{
|
||||
$redata = compact(array_keys(get_defined_vars()));
|
||||
Yii::import("application.libraries.Load_answers");
|
||||
$tmp = new Load_answers();
|
||||
$tmp->run($redata);
|
||||
}
|
||||
|
||||
|
||||
//Check if TOKEN is used for EVERY PAGE
|
||||
//This function fixes a bug where users able to submit two surveys/votes
|
||||
//by checking that the token has not been used at each page displayed.
|
||||
// bypass only this check at first page (Step=0) because
|
||||
// this check is done in buildsurveysession and error message
|
||||
// could be more interresting there (takes into accound captcha if used)
|
||||
if ($tokensexist == 1 && isset($token) && $token!="" &&
|
||||
isset($_SESSION['survey_'.$surveyid]['step']) && $_SESSION['survey_'.$surveyid]['step']>0 && tableExists("tokens_{$surveyid}}}"))
|
||||
{
|
||||
// check also if it is allowed to change survey after completion
|
||||
if ($thissurvey['alloweditaftercompletion'] == 'Y' ) {
|
||||
$tokenInstance = Token::model($surveyid)->findByAttributes(array('token' => $token));
|
||||
} else {
|
||||
$tokenInstance = Token::model($surveyid)->usable()->incomplete()->findByAttributes(array('token' => $token));
|
||||
}
|
||||
|
||||
if (!isset($tokenInstance) && !$previewmode)
|
||||
{
|
||||
//TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT
|
||||
$asMessage = array(
|
||||
null,
|
||||
$clang->gT("This is a controlled survey. You need a valid token to participate."),
|
||||
sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']." (<a href='mailto:{$thissurvey['adminemail']}'>"."{$thissurvey['adminemail']}</a>)")
|
||||
);
|
||||
|
||||
$this->_niceExit($redata, __LINE__, $thistpl, $asMessage, true);
|
||||
}
|
||||
}
|
||||
if ($tokensexist == 1 && isset($token) && $token!="" && tableExists("{{tokens_".$surveyid."}}") && !$previewmode) //check if token is in a valid time frame
|
||||
{
|
||||
// check also if it is allowed to change survey after completion
|
||||
if ($thissurvey['alloweditaftercompletion'] == 'Y' ) {
|
||||
$tokenInstance = Token::model($surveyid)->editable()->findByAttributes(array('token' => $token));
|
||||
} else {
|
||||
$tokenInstance = Token::model($surveyid)->usable()->incomplete()->findByAttributes(array('token' => $token));
|
||||
}
|
||||
if (!isset($tokenInstance))
|
||||
{
|
||||
$tk = Token::model($surveyid)->findByAttributes(array('token' => $token));
|
||||
if($tk->completed == 'N')
|
||||
{
|
||||
$now = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig("timeadjust"));
|
||||
if(strtotime($now) < strtotime($tk->validfrom))
|
||||
{
|
||||
$err = $clang->gT("This invitation is not valid yet.");
|
||||
}
|
||||
else
|
||||
{
|
||||
$err = $clang->gT("This invitation is not valid anymore.");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
$err = $clang->gT("This invitation has already been used.");
|
||||
}
|
||||
$asMessage = array(
|
||||
null,
|
||||
$clang->gT("We are sorry but you are not allowed to enter this survey."),
|
||||
$err,
|
||||
sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']." (<a href='mailto:{$thissurvey['adminemail']}'>"."{$thissurvey['adminemail']}</a>)")
|
||||
);
|
||||
|
||||
$this->_niceExit($redata, __LINE__, $thistpl, $asMessage, true);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//Clear session and remove the incomplete response if requested.
|
||||
if (isset($move) && $move == "clearall")
|
||||
{
|
||||
// delete the response but only if not already completed
|
||||
$s_lang = $_SESSION['survey_'.$surveyid]['s_lang'];
|
||||
if (isset($_SESSION['survey_'.$surveyid]['srid']) && !SurveyDynamic::model($surveyid)->isCompleted($_SESSION['survey_'.$surveyid]['srid']))
|
||||
{
|
||||
// delete the response but only if not already completed
|
||||
$result= dbExecuteAssoc('DELETE FROM {{survey_'.$surveyid.'}} WHERE id='.$_SESSION['survey_'.$surveyid]['srid']." AND submitdate IS NULL");
|
||||
if($result->count()>0){ // Using count() here *should* be okay for MSSQL because it is a delete statement
|
||||
// find out if there are any fuqt questions - checked
|
||||
$fieldmap = createFieldMap($surveyid,'short',false,false,$s_lang);
|
||||
foreach ($fieldmap as $field)
|
||||
{
|
||||
if ($field['type'] == "|" && !strpos($field['fieldname'], "_filecount"))
|
||||
{
|
||||
if (!isset($qid)) { $qid = array(); }
|
||||
$qid[] = $field['fieldname'];
|
||||
}
|
||||
}
|
||||
|
||||
// if yes, extract the response json to those questions
|
||||
if (isset($qid))
|
||||
{
|
||||
$query = "SELECT * FROM {{survey_".$surveyid."}} WHERE id=".$_SESSION['survey_'.$surveyid]['srid'];
|
||||
$result = dbExecuteAssoc($query);
|
||||
foreach($result->readAll() as $row)
|
||||
{
|
||||
foreach ($qid as $question)
|
||||
{
|
||||
$json = $row[$question];
|
||||
if ($json == "" || $json == NULL)
|
||||
continue;
|
||||
|
||||
// decode them
|
||||
$phparray = json_decode($json);
|
||||
|
||||
foreach ($phparray as $metadata)
|
||||
{
|
||||
$target = Yii::app()->getConfig("uploaddir")."/surveys/".$surveyid."/files/";
|
||||
// delete those files
|
||||
unlink($target.$metadata->filename);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// done deleting uploaded files
|
||||
}
|
||||
|
||||
// also delete a record from saved_control when there is one
|
||||
dbExecuteAssoc('DELETE FROM {{saved_control}} WHERE srid='.$_SESSION['survey_'.$surveyid]['srid'].' AND sid='.$surveyid);
|
||||
}
|
||||
killSurveySession($surveyid);
|
||||
sendCacheHeaders();
|
||||
doHeader();
|
||||
|
||||
$redata = compact(array_keys(get_defined_vars()));
|
||||
$this->_printTemplateContent($thistpl.'/startpage.pstpl', $redata, __LINE__);
|
||||
echo "\n\n<!-- JAVASCRIPT FOR CONDITIONAL QUESTIONS -->\n"
|
||||
."\t<script type='text/javascript'>\n"
|
||||
."\t<!--\n"
|
||||
."function checkconditions(value, name, type, evt_type)\n"
|
||||
."\t{\n"
|
||||
."\t}\n"
|
||||
."\t//-->\n"
|
||||
."\t</script>\n\n";
|
||||
|
||||
//Present the clear all page using clearall.pstpl template
|
||||
$this->_printTemplateContent($thistpl.'/clearall.pstpl', $redata, __LINE__);
|
||||
|
||||
$this->_printTemplateContent($thistpl.'/endpage.pstpl', $redata, __LINE__);
|
||||
doFooter();
|
||||
exit;
|
||||
}
|
||||
|
||||
|
||||
//Check to see if a refering URL has been captured.
|
||||
if (!isset($_SESSION['survey_'.$surveyid]['refurl']))
|
||||
{
|
||||
$_SESSION['survey_'.$surveyid]['refurl']=GetReferringUrl(); // do not overwrite refurl
|
||||
}
|
||||
|
||||
// Let's do this only if
|
||||
// - a saved answer record hasn't been loaded through the saved feature
|
||||
// - the survey is not anonymous
|
||||
// - the survey is active
|
||||
// - a token information has been provided
|
||||
// - the survey is setup to allow token-response-persistence
|
||||
|
||||
if (!isset($_SESSION['survey_'.$surveyid]['srid']) && $thissurvey['anonymized'] == "N" && $thissurvey['active'] == "Y" && isset($token) && $token !='')
|
||||
{
|
||||
// load previous answers if any (dataentry with nosubmit)
|
||||
//$oSurveyTokenInstance=SurveyDynamic::model($surveyid)->find(array('select'=>'id,submitdate,lastpage', 'condition'=>'token=:token', 'order'=>'id DESC','params'=>array('token' => $token)));
|
||||
$oSurveyTokenInstance=SurveyDynamic::model($surveyid)->find(array('condition'=>'token=:token', 'order'=>'id DESC','params'=>array('token' => $token)));
|
||||
if ( $oSurveyTokenInstance )
|
||||
{
|
||||
if((empty($oSurveyTokenInstance->submitdate) || $thissurvey['alloweditaftercompletion'] == 'Y' ) && $thissurvey['tokenanswerspersistence'] == 'Y')
|
||||
{
|
||||
$_SESSION['survey_'.$surveyid]['srid'] = $oSurveyTokenInstance->id;
|
||||
if (!empty($oSurveyTokenInstance->lastpage))
|
||||
{
|
||||
$_SESSION['survey_'.$surveyid]['LEMtokenResume'] = true;
|
||||
$_SESSION['survey_'.$surveyid]['step'] = $oSurveyTokenInstance->lastpage;
|
||||
}
|
||||
}
|
||||
buildsurveysession($surveyid);
|
||||
if(!empty($oSurveyTokenInstance->submitdate)) // alloweditaftercompletion
|
||||
{
|
||||
$_SESSION['survey_'.$surveyid]['maxstep'] = $_SESSION['survey_'.$surveyid]['totalsteps'];
|
||||
}
|
||||
loadanswers();
|
||||
}
|
||||
}
|
||||
// Preview action : Preview right already tested before
|
||||
if ($previewmode)
|
||||
{
|
||||
// Unset all SESSION: be sure to have the last version
|
||||
unset($_SESSION['fieldmap-' . $surveyid . $clang->langcode]);// Needed by createFieldMap: else fieldmap can be outdated
|
||||
unset($_SESSION['survey_'.$surveyid]);
|
||||
if ($param['action'] == 'previewgroup')
|
||||
{
|
||||
$thissurvey['format'] = 'G';
|
||||
}
|
||||
elseif ($param['action'] == 'previewquestion')
|
||||
{
|
||||
$thissurvey['format'] = 'S';
|
||||
}
|
||||
buildsurveysession($surveyid,true);
|
||||
}
|
||||
|
||||
sendCacheHeaders();
|
||||
|
||||
//Send local variables to the appropriate survey type
|
||||
unset($redata);
|
||||
$redata = compact(array_keys(get_defined_vars()));
|
||||
Yii::import('application.helpers.SurveyRuntimeHelper');
|
||||
$tmp = new SurveyRuntimeHelper();
|
||||
$tmp->run($surveyid,$redata);
|
||||
|
||||
if (isset($_POST['saveall']) || isset($flashmessage))
|
||||
{
|
||||
echo "<script type='text/javascript'> $(document).ready( function() { alert('".$clang->gT("Your responses were successfully saved.","js")."');}) </script>";
|
||||
}
|
||||
}
|
||||
|
||||
function _getParameters($args = array(), $post = array())
|
||||
{
|
||||
$param = array();
|
||||
if(@$args[0]==__CLASS__) array_shift($args);
|
||||
if(count($args)%2 == 0) {
|
||||
for ($i = 0; $i < count($args); $i+=2) {
|
||||
//Sanitize input from URL with returnGlobal
|
||||
$param[$args[$i]] = returnGlobal($args[$i], true);
|
||||
}
|
||||
}
|
||||
|
||||
// Need some $param (else PHP notice)
|
||||
foreach(array('lang','action','newtest','qid','gid','sid','loadname','loadpass','scid','thisstep','move','token') as $sNeededParam)
|
||||
{
|
||||
$param[$sNeededParam]=returnGlobal($sNeededParam,true);
|
||||
}
|
||||
|
||||
return $param;
|
||||
}
|
||||
|
||||
function _loadRequiredHelpersAndLibraries()
|
||||
{
|
||||
//Load helpers, libraries and config vars
|
||||
Yii::app()->loadHelper("database");
|
||||
Yii::app()->loadHelper("frontend");
|
||||
Yii::app()->loadHelper("surveytranslator");
|
||||
}
|
||||
|
||||
function _loadLimesurveyLang($mvSurveyIdOrBaseLang)
|
||||
{
|
||||
if ( is_numeric($mvSurveyIdOrBaseLang) && Survey::model()->findByPk($mvSurveyIdOrBaseLang))
|
||||
{
|
||||
$baselang = Survey::model()->findByPk($mvSurveyIdOrBaseLang)->language;
|
||||
}
|
||||
elseif (!empty($mvSurveyIdOrBaseLang))
|
||||
{
|
||||
$baselang = $mvSurveyIdOrBaseLang;
|
||||
}
|
||||
else
|
||||
{
|
||||
$baselang = Yii::app()->getConfig('defaultlang');
|
||||
}
|
||||
Yii::import("application.libraries.Limesurvey_lang");
|
||||
return new Limesurvey_lang($baselang);
|
||||
}
|
||||
|
||||
function _isClientTokenDifferentFromSessionToken($clientToken, $surveyid)
|
||||
{
|
||||
return $clientToken != '' && isset($_SESSION['survey_'.$surveyid]['token']) && $clientToken != $_SESSION['survey_'.$surveyid]['token'];
|
||||
}
|
||||
|
||||
function _isSurveyFinished($surveyid)
|
||||
{
|
||||
return isset($_SESSION['survey_'.$surveyid]['finished']) && $_SESSION['survey_'.$surveyid]['finished'] === true;
|
||||
}
|
||||
|
||||
function _surveyCantBeViewedWithCurrentPreviewAccess($surveyid, $bIsSurveyActive, $bSurveyExists)
|
||||
{
|
||||
$bSurveyPreviewRequireAuth = Yii::app()->getConfig('surveyPreview_require_Auth');
|
||||
return $surveyid && $bIsSurveyActive === false && $bSurveyExists && isset($bSurveyPreviewRequireAuth) && $bSurveyPreviewRequireAuth == true && !$this->_canUserPreviewSurvey($surveyid);
|
||||
}
|
||||
|
||||
function _didSessionTimeout($surveyid)
|
||||
{
|
||||
return !isset($_SESSION['survey_'.$surveyid]['s_lang']) && isset($_POST['thisstep']);
|
||||
}
|
||||
|
||||
function _canUserPreviewSurvey($iSurveyID)
|
||||
{
|
||||
if ( !isset($_SESSION['loginID']) ) // This is not needed because Permission::model()->hasSurveyPermission control connexion
|
||||
return false;
|
||||
|
||||
return Permission::model()->hasSurveyPermission($iSurveyID,'surveycontent','read');
|
||||
}
|
||||
|
||||
function _userHasPreviewAccessSession($iSurveyID){
|
||||
return (isset($_SESSION['USER_RIGHT_PREVIEW']) && ($_SESSION['USER_RIGHT_PREVIEW'] == $iSurveyID));
|
||||
}
|
||||
|
||||
function _niceExit(&$redata, $iDebugLine, $sTemplateDir = null, $asMessage = array())
|
||||
{
|
||||
|
||||
if(isset($redata['surveyid']) && $redata['surveyid'] && !isset($thisurvey))
|
||||
{
|
||||
$thissurvey=getSurveyInfo($redata['surveyid']);
|
||||
$sTemplateDir= getTemplatePath($thissurvey['template']);
|
||||
}
|
||||
else
|
||||
{
|
||||
$sTemplateDir= getTemplatePath($sTemplateDir);
|
||||
}
|
||||
sendCacheHeaders();
|
||||
|
||||
doHeader();
|
||||
$this->_printTemplateContent($sTemplateDir.'/startpage.pstpl', $redata, $iDebugLine);
|
||||
$this->_printMessage($asMessage);
|
||||
$this->_printTemplateContent($sTemplateDir.'/endpage.pstpl', $redata, $iDebugLine);
|
||||
|
||||
doFooter();
|
||||
exit;
|
||||
}
|
||||
|
||||
function _createNewUserSessionAndRedirect($surveyid, &$redata, $iDebugLine, $asMessage = array())
|
||||
{
|
||||
$clang = Yii::app()->lang;
|
||||
killSurveySession($surveyid);
|
||||
$thissurvey=getSurveyInfo($surveyid);
|
||||
if($thissurvey)
|
||||
{
|
||||
$templatename=$thissurvey['template'];
|
||||
}
|
||||
else
|
||||
{
|
||||
$templatename=Yii::app()->getConfig('defaulttemplate');;
|
||||
}
|
||||
// Let's redirect the client to the same URL after having reset the session
|
||||
$this->_niceExit($redata, $iDebugLine, $templatename, $asMessage);
|
||||
}
|
||||
|
||||
|
||||
|
||||
function _printMessage($asLines)
|
||||
{
|
||||
if ( func_num_args() > 1 )
|
||||
$asLines = func_get_args();
|
||||
|
||||
if ( count($asLines) == 0 )
|
||||
return;
|
||||
|
||||
$sError = array_shift($asLines);
|
||||
|
||||
echo "\t<div id='wrapper'>\n";
|
||||
echo "\t<p id='tokenmessage'>\n";
|
||||
if ( $sError != null )
|
||||
{
|
||||
echo "\t<span class='error'>".$sError."</span><br /><br />\n";
|
||||
}
|
||||
echo "\t".implode ("<br /><br />\n\t", $asLines)."<br /><br />\n";
|
||||
echo "\t</p>\n";
|
||||
echo "\t</div>\n";
|
||||
}
|
||||
|
||||
function _printTemplateContent($sTemplateFile, &$redata, $iDebugLine = -1)
|
||||
{
|
||||
echo templatereplace(file_get_contents($sTemplateFile),array(),$redata,'survey['.$iDebugLine.']');
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
/* End of file survey.php */
|
||||
/* Location: ./application/controllers/survey.php */
|
140
sources/application/core/ConsoleApplication.php
Normal file
140
sources/application/core/ConsoleApplication.php
Normal file
|
@ -0,0 +1,140 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* Load the globals helper as early as possible. Only earlier solution is to use
|
||||
* index.php
|
||||
*/
|
||||
require_once(dirname(dirname(__FILE__)) . '/helpers/globals.php');
|
||||
|
||||
class ConsoleApplication extends CConsoleApplication
|
||||
{
|
||||
|
||||
protected $config = array();
|
||||
|
||||
public $lang = null;
|
||||
|
||||
/**
|
||||
*
|
||||
* @var PluginManager
|
||||
*/
|
||||
protected $pluginManager;
|
||||
|
||||
/**
|
||||
* @var LimesurveyApi
|
||||
*/
|
||||
protected $api;
|
||||
|
||||
public function __construct($config = null) {
|
||||
parent::__construct($config);
|
||||
|
||||
// Set webroot alias.
|
||||
Yii::setPathOfAlias('webroot', realpath(Yii::getPathOfAlias('application') . '/../'));
|
||||
// Load email settings.
|
||||
$email = require(Yii::app()->basePath. DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'email.php');
|
||||
$this->config = array_merge($this->config, $email);
|
||||
|
||||
// Now initialize the plugin manager
|
||||
$this->initPluginManager();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the Api object.
|
||||
*/
|
||||
public function getApi()
|
||||
{
|
||||
if (!isset($this->api))
|
||||
{
|
||||
$this->api = new LimesurveyApi();
|
||||
}
|
||||
return $this->api;
|
||||
}
|
||||
|
||||
/**
|
||||
* This function is implemented since em_core_manager incorrectly requires
|
||||
* it to create urls.
|
||||
*/
|
||||
public function getController()
|
||||
{
|
||||
return $this;
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns a config variable from the config
|
||||
*
|
||||
* @access public
|
||||
* @param string $name
|
||||
* @return mixed
|
||||
*/
|
||||
public function getConfig($name = null)
|
||||
{
|
||||
if (isset($this->$name))
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
elseif (isset($this->config[$name]))
|
||||
{
|
||||
return $this->config[$name];
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the pluginManager
|
||||
*
|
||||
* @return PluginManager
|
||||
*/
|
||||
public function getPluginManager()
|
||||
{
|
||||
return $this->pluginManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method handles initialization of the plugin manager
|
||||
*
|
||||
* When you want to insert your own plugin manager, or experiment with different settings
|
||||
* then this is where you should do that.
|
||||
*/
|
||||
public function initPluginManager()
|
||||
{
|
||||
Yii::import('application.libraries.PluginManager.*');
|
||||
Yii::import('application.libraries.PluginManager.Storage.*');
|
||||
Yii::import('application.libraries.PluginManager.Question.*');
|
||||
$this->pluginManager = new PluginManager($this->getApi());
|
||||
|
||||
// And load the active plugins
|
||||
$this->pluginManager->loadPlugins();
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a helper
|
||||
*
|
||||
* @access public
|
||||
* @param string $helper
|
||||
* @return void
|
||||
*/
|
||||
public function loadHelper($helper)
|
||||
{
|
||||
Yii::import('application.helpers.' . $helper . '_helper', true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a configuration variable into the config
|
||||
*
|
||||
* @access public
|
||||
* @param string $name
|
||||
* @param mixed $value
|
||||
* @return void
|
||||
*/
|
||||
public function setConfig($name, $value)
|
||||
{
|
||||
$this->config[$name] = $value;
|
||||
}
|
||||
|
||||
}
|
||||
?>
|
46
sources/application/core/LSAuthResult.php
Normal file
46
sources/application/core/LSAuthResult.php
Normal file
|
@ -0,0 +1,46 @@
|
|||
<?php
|
||||
/*
|
||||
* LimeSurvey
|
||||
* Copyright (C) 2007-2013 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.
|
||||
*
|
||||
*/
|
||||
class LSAuthResult
|
||||
{
|
||||
protected $_code;
|
||||
protected $_message;
|
||||
|
||||
public function __construct($code = 0, $message = '') {
|
||||
$this->setError($code, $message);
|
||||
}
|
||||
|
||||
public function isValid()
|
||||
{
|
||||
if ($this->_code === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function getCode()
|
||||
{
|
||||
return $this->_code;
|
||||
}
|
||||
|
||||
public function getMessage()
|
||||
{
|
||||
return $this->_message;
|
||||
}
|
||||
|
||||
public function setError($code, $message = null) {
|
||||
$this->_code = $code;
|
||||
$this->_message = $message;
|
||||
}
|
||||
}
|
48
sources/application/core/LSBootstrap.php
Normal file
48
sources/application/core/LSBootstrap.php
Normal file
|
@ -0,0 +1,48 @@
|
|||
<?php
|
||||
Yii::import('application.extensions.bootstrap.components.Bootstrap', true);
|
||||
class LSBootstrap extends Bootstrap
|
||||
{
|
||||
/**
|
||||
* Returns the URL to the published assets folder.
|
||||
*
|
||||
* Modified version, to prevent republish (and slowness) when debug is on
|
||||
*
|
||||
* @return string the URL
|
||||
*/
|
||||
public function getAssetsUrl() {
|
||||
$republish = false; // Change to republish, not needed for now.
|
||||
if (isset($this->_assetsUrl))
|
||||
return $this->_assetsUrl;
|
||||
else
|
||||
{
|
||||
$assetsPath = Yii::getPathOfAlias('bootstrap.assets');
|
||||
$assetsUrl = Yii::app()->assetManager->publish($assetsPath, false, -1, $republish);
|
||||
return $this->_assetsUrl = $assetsUrl;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers the Bootstrap JavaScript.
|
||||
* @param int $position the position of the JavaScript code.
|
||||
* @see CClientScript::registerScriptFile
|
||||
*/
|
||||
public function registerJS($position = CClientScript::POS_HEAD)
|
||||
{
|
||||
/** @var CClientScript $cs */
|
||||
$cs = Yii::app()->getClientScript();
|
||||
$cs->packages['bootstrap'] = array(
|
||||
'baseUrl' => $this->getAssetsUrl(),
|
||||
'js' => array(
|
||||
'js/bootstrap.min.js'
|
||||
),
|
||||
'depends' => array('jquery')
|
||||
);
|
||||
$cs->registerPackage('bootstrap');
|
||||
/** enable bootboxJS? */
|
||||
if($this->enableBootboxJS)
|
||||
{
|
||||
$cs->registerScriptFile($this->getAssetsUrl() . '/js/bootstrap.bootbox.min.js', $position);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
55
sources/application/core/LSHttpRequest.php
Normal file
55
sources/application/core/LSHttpRequest.php
Normal file
|
@ -0,0 +1,55 @@
|
|||
<?php
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* Description of HttpRequest
|
||||
*
|
||||
*
|
||||
* Used in LSYii_Application.php
|
||||
* <pre>
|
||||
* 'request'=>array(
|
||||
* 'class'=>'HttpRequest',
|
||||
* 'noCsrfValidationRoutes'=>array(
|
||||
* '^services/wsdl.*$'
|
||||
* ),
|
||||
* 'enableCsrfValidation'=>true,
|
||||
* 'enableCookieValidation'=>true,
|
||||
* ),
|
||||
* </pre>
|
||||
*
|
||||
* Every route will be interpreted as a regex pattern.
|
||||
*
|
||||
*/
|
||||
class LSHttpRequest extends CHttpRequest {
|
||||
public $noCsrfValidationRoutes = array();
|
||||
|
||||
protected function normalizeRequest(){
|
||||
parent::normalizeRequest();
|
||||
|
||||
if(!isset($_SERVER['REQUEST_METHOD']) || $_SERVER['REQUEST_METHOD'] != 'POST') return;
|
||||
|
||||
$route = Yii::app()->getUrlManager()->parseUrl($this);
|
||||
if($this->enableCsrfValidation){
|
||||
foreach($this->noCsrfValidationRoutes as $cr){
|
||||
if(preg_match('#'.$cr.'#', $route)){
|
||||
Yii::app()->detachEventHandler('onBeginRequest',
|
||||
array($this,'validateCsrfToken'));
|
||||
Yii::trace('Route "'.$route.' passed without CSRF validation');
|
||||
break; // found first route and break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
171
sources/application/core/LSUserIdentity.php
Normal file
171
sources/application/core/LSUserIdentity.php
Normal file
|
@ -0,0 +1,171 @@
|
|||
<?php
|
||||
/*
|
||||
* LimeSurvey
|
||||
* Copyright (C) 2007-2013 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.
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* For 2.06 most of the functionality in this class will be moved to the LSWebUser class.
|
||||
* To not delay release of 2.05 this class was kept the way it is now.
|
||||
*
|
||||
* @@TODO Move to LSWebUser and change documentation / workflow for authentication plugins
|
||||
*/
|
||||
class LSUserIdentity extends CUserIdentity {
|
||||
|
||||
const ERROR_IP_LOCKED_OUT = 98;
|
||||
const ERROR_UNKNOWN_HANDLER = 99;
|
||||
|
||||
protected $config = array();
|
||||
|
||||
/**
|
||||
* The userid
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public $id = null;
|
||||
|
||||
/**
|
||||
* A User::model() object
|
||||
*
|
||||
* @var User
|
||||
*/
|
||||
public $user;
|
||||
|
||||
/**
|
||||
* This is the name of the plugin to handle authentication
|
||||
* default handler is used for remote control
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $plugin = 'Authdb';
|
||||
|
||||
public function authenticate() {
|
||||
// First initialize the result, we can later retieve it to get the exact error code/message
|
||||
$result = new LSAuthResult(self::ERROR_NONE);
|
||||
|
||||
// Check if the ip is locked out
|
||||
if (FailedLoginAttempt::model()->isLockedOut()) {
|
||||
$message = sprintf(gT('You have exceeded the number of maximum login attempts. Please wait %d minutes before trying again.'), App()->getConfig('timeOutTime') / 60);
|
||||
$result->setError(self::ERROR_IP_LOCKED_OUT, $message);
|
||||
}
|
||||
|
||||
// If still ok, continue
|
||||
if ($result->isValid())
|
||||
{
|
||||
if (is_null($this->plugin)) {
|
||||
$result->setError(self::ERROR_UNKNOWN_HANDLER);
|
||||
} else {
|
||||
// Delegate actual authentication to plugin
|
||||
$authEvent = new PluginEvent('newUserSession', $this);
|
||||
$authEvent->set('identity', $this);
|
||||
App()->getPluginManager()->dispatchEvent($authEvent, array($this->plugin));
|
||||
$pluginResult = $authEvent->get('result');
|
||||
if ($pluginResult instanceof LSAuthResult) {
|
||||
$result = $pluginResult;
|
||||
} else {
|
||||
$result->setError(self::ERROR_UNKNOWN_IDENTITY);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($result->isValid()) {
|
||||
// Perform postlogin
|
||||
$this->postLogin();
|
||||
} else {
|
||||
// Log a failed attempt
|
||||
$userHostAddress = getIPAddress();
|
||||
FailedLoginAttempt::model()->addAttempt($userHostAddress);
|
||||
App()->session->regenerateID(); // Handled on login by Yii
|
||||
}
|
||||
|
||||
$this->errorCode = $result->getCode();
|
||||
$this->errorMessage = $result->getMessage();
|
||||
|
||||
return $result->isValid();
|
||||
}
|
||||
|
||||
public function getConfig()
|
||||
{
|
||||
return $this->config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current user's ID
|
||||
*
|
||||
* @access public
|
||||
* @return int
|
||||
*/
|
||||
public function getId()
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the active user's record
|
||||
*
|
||||
* @access public
|
||||
* @return User
|
||||
*/
|
||||
public function getUser()
|
||||
{
|
||||
return $this->user;
|
||||
}
|
||||
|
||||
protected function postLogin()
|
||||
{
|
||||
$user = $this->getUser();
|
||||
App()->user->login($this);
|
||||
|
||||
// Check for default password
|
||||
if ($this->password === 'password') {
|
||||
App()->user->setFlash('pwdnotify', gT('Warning: You are still using the default password (\'password\'). Please change your password and re-login again.'));
|
||||
}
|
||||
|
||||
// Do session setup
|
||||
Yii::app()->session['loginID'] = (int) $user->uid;
|
||||
Yii::app()->session['user'] = $user->users_name;
|
||||
Yii::app()->session['full_name'] = $user->full_name;
|
||||
Yii::app()->session['htmleditormode'] = $user->htmleditormode;
|
||||
Yii::app()->session['templateeditormode'] = $user->templateeditormode;
|
||||
Yii::app()->session['questionselectormode'] = $user->questionselectormode;
|
||||
Yii::app()->session['dateformat'] = $user->dateformat;
|
||||
Yii::app()->session['session_hash'] = hash('sha256',getGlobalSetting('SessionName').$user->users_name.$user->uid);
|
||||
|
||||
// Perform language settings
|
||||
if (App()->request->getPost('loginlang','default') != 'default')
|
||||
{
|
||||
$user->lang = sanitize_languagecode(App()->request->getPost('loginlang'));
|
||||
$user->save();
|
||||
$sLanguage=$user->lang;
|
||||
}
|
||||
else if ($user->lang=='auto' || $user->lang=='')
|
||||
{
|
||||
$sLanguage=getBrowserLanguage();
|
||||
}
|
||||
else
|
||||
{
|
||||
$sLanguage=$user->lang;
|
||||
}
|
||||
|
||||
Yii::app()->session['adminlang'] = $sLanguage;
|
||||
$lang = new limesurvey_lang($sLanguage);
|
||||
App()->lang = $lang;
|
||||
App()->getController()->lang= $lang;
|
||||
}
|
||||
|
||||
public function setPlugin($name) {
|
||||
$this->plugin = $name;
|
||||
}
|
||||
|
||||
public function setConfig($config) {
|
||||
$this->config = $config;
|
||||
}
|
||||
}
|
99
sources/application/core/LSWebUser.php
Normal file
99
sources/application/core/LSWebUser.php
Normal file
|
@ -0,0 +1,99 @@
|
|||
<?php
|
||||
Yii::import('application.helpers.Hash', true);
|
||||
|
||||
class LSWebUser extends CWebUser
|
||||
{
|
||||
protected $sessionVariable = 'LSWebUser';
|
||||
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->loginUrl = Yii::app()->createUrl('admin/authentication', array('sa' => 'login'));
|
||||
|
||||
// Try to fix missing language in plugin controller
|
||||
Yii::import('application.libraries.Limesurvey_lang');
|
||||
if (empty(Yii::app()->session['adminlang']))
|
||||
{
|
||||
Yii::app()->session["adminlang"] = Yii::app()->getConfig("defaultlang");
|
||||
}
|
||||
|
||||
$lang = new Limesurvey_lang(Yii::app()->session['adminlang']);
|
||||
Yii::app()->setLang($lang);
|
||||
}
|
||||
|
||||
public function checkAccess($operation, $params = array(), $allowCaching = true)
|
||||
{
|
||||
if ($operation == 'administrator')
|
||||
{
|
||||
return Permission::model()->hasGlobalPermission('superadmin', 'read');
|
||||
}
|
||||
else
|
||||
{
|
||||
return parent::checkAccess($operation, $params, $allowCaching);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public function getStateKeyPrefix()
|
||||
{
|
||||
return $this->sessionVariable;
|
||||
}
|
||||
|
||||
|
||||
public function setFlash($key, $value, $defaultValue = null) {
|
||||
$this->setState("flash.$key", $value, $defaultValue);
|
||||
}
|
||||
public function hasFlash($key) {
|
||||
$this->hasState("flash.$key");
|
||||
}
|
||||
|
||||
public function getFlashes($delete = true)
|
||||
{
|
||||
$result = $this->getState('flash', array());
|
||||
$this->removeState('flash');
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function getState($key, $defaultValue = null)
|
||||
{
|
||||
if (!isset($_SESSION[$this->sessionVariable]) || !Hash::check($_SESSION[$this->sessionVariable], $key))
|
||||
{
|
||||
return $defaultValue;
|
||||
}
|
||||
else
|
||||
{
|
||||
return Hash::get($_SESSION[$this->sessionVariable], $key);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a state variable.
|
||||
* @param string $key
|
||||
*/
|
||||
public function removeState($key)
|
||||
{
|
||||
$this->setState($key, null);
|
||||
}
|
||||
|
||||
public function setState($key, $value, $defaultValue = null)
|
||||
{
|
||||
$current = isset($_SESSION[$this->sessionVariable]) ? $_SESSION[$this->sessionVariable] : array();
|
||||
if($value === $defaultValue)
|
||||
{
|
||||
$_SESSION[$this->sessionVariable] = Hash::remove($current, $key);
|
||||
}
|
||||
else
|
||||
{
|
||||
$_SESSION[$this->sessionVariable] = Hash::insert($current, $key, $value);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
public function hasState($key)
|
||||
{
|
||||
return isset($_SESSION[$this->sessionVariable]) && Hash::check($_SESSION[$this->sessionVariable], $key);
|
||||
}
|
||||
|
||||
}
|
||||
?>
|
298
sources/application/core/LSYii_Application.php
Normal file
298
sources/application/core/LSYii_Application.php
Normal file
|
@ -0,0 +1,298 @@
|
|||
<?php
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Load the globals helper as early as possible. Only earlier solution is to use
|
||||
* index.php
|
||||
*/
|
||||
require_once(dirname(dirname(__FILE__)) . '/helpers/globals.php');
|
||||
|
||||
/**
|
||||
* Implements global config
|
||||
* @property CLogRouter $log Log router component.
|
||||
*/
|
||||
class LSYii_Application extends CWebApplication
|
||||
{
|
||||
protected $config = array();
|
||||
/**
|
||||
* @var Limesurvey_lang
|
||||
*/
|
||||
public $lang = null;
|
||||
|
||||
/**
|
||||
*
|
||||
* @var PluginManager
|
||||
*/
|
||||
protected $pluginManager;
|
||||
/**
|
||||
* @var LimesurveyApi
|
||||
*/
|
||||
protected $api;
|
||||
/**
|
||||
*
|
||||
* Initiates the application
|
||||
*
|
||||
* @access public
|
||||
* @param array $config
|
||||
* @return void
|
||||
*/
|
||||
public function __construct($config = null)
|
||||
{
|
||||
if (is_string($config) && !file_exists($config))
|
||||
{
|
||||
$config = __DIR__ . '/../config/config-sample-mysql' . EXT;
|
||||
}
|
||||
if(is_string($config)) {
|
||||
$config = require($config);
|
||||
}
|
||||
|
||||
if (isset($config['config']['debug']) && $config['config']['debug'] == 2)
|
||||
{
|
||||
// If debug = 2 we add firebug / console logging for all trace messages
|
||||
// If you want to var_dump $config you could do:
|
||||
//
|
||||
// Yii::trace(CVarDumper::dumpAsString($config), 'vardump');
|
||||
//
|
||||
// or shorter:
|
||||
//
|
||||
//traceVar($config);
|
||||
//
|
||||
// This statement won't cause any harm or output when debug is 1 or 0
|
||||
$config['preload'][] = 'log';
|
||||
if (array_key_exists('components', $config) && array_key_exists('log', $config['components'])) {
|
||||
// We already have some custom logging, only add our own
|
||||
} else {
|
||||
// No logging yet, set it up
|
||||
$config['components']['log'] = array(
|
||||
'class' => 'CLogRouter');
|
||||
}
|
||||
// Add logging of trace
|
||||
$config['components']['log']['routes'][] = array(
|
||||
'class' => 'CWebLogRoute', // you can include more levels separated by commas... trace is shown on debug only
|
||||
'levels' => 'trace', // you can include more separated by commas
|
||||
'categories' => 'vardump', // show in firebug/console
|
||||
'showInFireBug' => true
|
||||
);
|
||||
|
||||
// if debugsql = 1 we add sql logging to the output
|
||||
if (array_key_exists('debugsql', $config['config']) && $config['config']['debugsql'] == 1) {
|
||||
// Add logging of trace
|
||||
$config['components']['log']['routes'][] = array(
|
||||
'class' => 'CWebLogRoute', // you can include more levels separated by commas... trace is shown on debug only
|
||||
'levels' => 'trace', // you can include more separated by commas
|
||||
'categories' => 'system.db.*', // show in firebug/console
|
||||
'showInFireBug' => true
|
||||
);
|
||||
$config['components']['db']['enableProfiling'] = true;
|
||||
$config['components']['db']['enableParamLogging'] = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!isset($config['components']['request']))
|
||||
{
|
||||
$config['components']['request']=array();
|
||||
}
|
||||
if (!isset($config['components']['session']))
|
||||
{
|
||||
$config['components']['session']=array();
|
||||
}
|
||||
$config['components']['session']=array_merge_recursive($config['components']['session'],array(
|
||||
'cookieParams' => array(
|
||||
'httponly' => true,
|
||||
),
|
||||
));
|
||||
|
||||
if (!isset($config['components']['assetManager']))
|
||||
{
|
||||
$config['components']['assetManager']=array();
|
||||
}
|
||||
$config['components']['assetManager']=array_merge_recursive($config['components']['assetManager'],array(
|
||||
'basePath'=> dirname(dirname(dirname(__FILE__))).DIRECTORY_SEPARATOR.'tmp'.DIRECTORY_SEPARATOR.'assets' // Enable to activate cookie protection
|
||||
));
|
||||
|
||||
parent::__construct($config);
|
||||
Yii::setPathOfAlias('bootstrap' , Yii::getPathOfAlias('ext.bootstrap'));
|
||||
// Load the default and environmental settings from different files into self.
|
||||
$ls_config = require(__DIR__ . '/../config/config-defaults.php');
|
||||
$email_config = require(__DIR__ . '/../config/email.php');
|
||||
$version_config = require(__DIR__ . '/../config/version.php');
|
||||
$settings = array_merge($ls_config, $version_config, $email_config);
|
||||
|
||||
if(file_exists(__DIR__ . '/../config/config.php'))
|
||||
{
|
||||
$ls_config = require(__DIR__ . '/../config/config.php');
|
||||
if(is_array($ls_config['config']))
|
||||
{
|
||||
$settings = array_merge($settings, $ls_config['config']);
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($settings as $key => $value)
|
||||
$this->setConfig($key, $value);
|
||||
|
||||
App()->getAssetManager()->setBaseUrl(Yii::app()->getBaseUrl(false) . '/tmp/assets');
|
||||
// Now initialize the plugin manager
|
||||
$this->initPluginManager();
|
||||
|
||||
}
|
||||
|
||||
|
||||
public function init() {
|
||||
parent::init();
|
||||
Yii::import('application.helpers.ClassFactory');
|
||||
ClassFactory::registerClass('Token_', 'Token');
|
||||
ClassFactory::registerClass('Response_', 'Response');
|
||||
}
|
||||
/**
|
||||
* This method handles initialization of the plugin manager
|
||||
*
|
||||
* When you want to insert your own plugin manager, or experiment with different settings
|
||||
* then this is where you should do that.
|
||||
*/
|
||||
public function initPluginManager()
|
||||
{
|
||||
Yii::import('application.libraries.PluginManager.*');
|
||||
Yii::import('application.libraries.PluginManager.Storage.*');
|
||||
Yii::import('application.libraries.PluginManager.Question.*');
|
||||
$this->pluginManager = new PluginManager($this->getApi());
|
||||
|
||||
// And load the active plugins
|
||||
$this->pluginManager->loadPlugins();
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a helper
|
||||
*
|
||||
* @access public
|
||||
* @param string $helper
|
||||
* @return void
|
||||
*/
|
||||
public function loadHelper($helper)
|
||||
{
|
||||
Yii::import('application.helpers.' . $helper . '_helper', true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a library
|
||||
*
|
||||
* @access public
|
||||
* @param string $helper
|
||||
* @return void
|
||||
*/
|
||||
public function loadLibrary($library)
|
||||
{
|
||||
Yii::import('application.libraries.'.$library, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a configuration variable into the config
|
||||
*
|
||||
* @access public
|
||||
* @param string $name
|
||||
* @param mixed $value
|
||||
* @return void
|
||||
*/
|
||||
public function setConfig($name, $value)
|
||||
{
|
||||
$this->config[$name] = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a 'flash message'.
|
||||
*
|
||||
* A flahs message will be shown on the next request and can contain a message
|
||||
* to tell that the action was successful or not. The message is displayed and
|
||||
* cleared when it is shown in the view using the widget:
|
||||
* <code>
|
||||
* $this->widget('application.extensions.FlashMessage.FlashMessage');
|
||||
* </code>
|
||||
*
|
||||
* @param string $message
|
||||
* @param string $type
|
||||
* @return LSYii_Application Provides a fluent interface
|
||||
*/
|
||||
public function setFlashMessage($message,$type='default')
|
||||
{
|
||||
$aFlashMessage=$this->session['aFlashMessage'];
|
||||
$aFlashMessage[]=array('message'=>$message,'type'=>$type);
|
||||
$this->session['aFlashMessage'] = $aFlashMessage;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a config from a file
|
||||
*
|
||||
* @access public
|
||||
* @param string $file
|
||||
* @return void
|
||||
*/
|
||||
public function loadConfig($file)
|
||||
{
|
||||
$config = require_once(APPPATH . '/config/' . $file . '.php');
|
||||
if(is_array($config))
|
||||
{
|
||||
foreach ($config as $k => $v)
|
||||
$this->setConfig($k, $v);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a config variable from the config
|
||||
*
|
||||
* @access public
|
||||
* @param string $name
|
||||
* @param type $default Value to return when not found, default is false
|
||||
* @return mixed
|
||||
*/
|
||||
public function getConfig($name, $default = false)
|
||||
{
|
||||
return isset($this->config[$name]) ? $this->config[$name] : $default;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* For future use, cache the language app wise as well.
|
||||
*
|
||||
* @access public
|
||||
* @param Limesurvey_lang
|
||||
* @return void
|
||||
*/
|
||||
public function setLang(Limesurvey_lang $lang)
|
||||
{
|
||||
$this->lang = $lang;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the Api object.
|
||||
*/
|
||||
public function getApi()
|
||||
{
|
||||
if (!isset($this->api))
|
||||
{
|
||||
$this->api = new LimesurveyApi();
|
||||
}
|
||||
return $this->api;
|
||||
}
|
||||
/**
|
||||
* Get the pluginManager
|
||||
*
|
||||
* @return PluginManager
|
||||
*/
|
||||
public function getPluginManager()
|
||||
{
|
||||
return $this->pluginManager;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
169
sources/application/core/LSYii_Controller.php
Normal file
169
sources/application/core/LSYii_Controller.php
Normal file
|
@ -0,0 +1,169 @@
|
|||
<?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.
|
||||
*
|
||||
*/
|
||||
|
||||
abstract class LSYii_Controller extends CController
|
||||
{
|
||||
/**
|
||||
* This array contains the survey / group / question id used by the menu widget.
|
||||
* @var array
|
||||
*/
|
||||
public $navData = array();
|
||||
/**
|
||||
* Basic initialiser to the base controller class
|
||||
*
|
||||
* @access public
|
||||
* @param string $id
|
||||
* @param CWebModule $module
|
||||
* @return void
|
||||
*/
|
||||
public function __construct($id, $module = null)
|
||||
{
|
||||
parent::__construct($id, $module);
|
||||
$this->_checkInstallation();
|
||||
|
||||
Yii::app()->session->init();
|
||||
$this->loadLibrary('LS.LS');
|
||||
$this->loadHelper('globalsettings');
|
||||
$this->loadHelper('common');
|
||||
$this->loadHelper('expressions.em_manager');
|
||||
$this->loadHelper('replacements');
|
||||
$this->_init();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that installation was already done by looking for config.php
|
||||
* Will redirect to the installer script if not exists.
|
||||
*
|
||||
* @access protected
|
||||
* @return void
|
||||
*/
|
||||
protected function _checkInstallation()
|
||||
{
|
||||
$file_name = Yii::app()->getConfig('rootdir').'/application/config/config.php';
|
||||
if (!file_exists($file_name))
|
||||
{
|
||||
$this->redirect(array('/installer'));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a helper
|
||||
*
|
||||
* @access public
|
||||
* @param string $helper
|
||||
* @return void
|
||||
*/
|
||||
public function loadHelper($helper)
|
||||
{
|
||||
Yii::app()->loadHelper($helper);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a library
|
||||
*
|
||||
* @access public
|
||||
* @param string $helper
|
||||
* @return void
|
||||
*/
|
||||
public function loadLibrary($library)
|
||||
{
|
||||
Yii::app()->loadLibrary($library);
|
||||
}
|
||||
|
||||
protected function _init()
|
||||
{
|
||||
// Check for most necessary requirements
|
||||
// Now check for PHP & db version
|
||||
// Do not localize/translate this!
|
||||
|
||||
$dieoutput='';
|
||||
if (version_compare(PHP_VERSION, '5.3.0', '<'))
|
||||
$dieoutput .= 'This script can only be run on PHP version 5.3.0 or later! Your version: '.PHP_VERSION.'<br />';
|
||||
|
||||
if (!function_exists('mb_convert_encoding'))
|
||||
$dieoutput .= "This script needs the PHP Multibyte String Functions library installed: See <a href='http://manual.limesurvey.org/wiki/Installation_FAQ'>FAQ</a> and <a href='http://de.php.net/manual/en/ref.mbstring.php'>PHP documentation</a><br />";
|
||||
|
||||
if ($dieoutput != '')
|
||||
throw new CException($dieoutput);
|
||||
|
||||
if (ini_get("max_execution_time") < 1200) @set_time_limit(1200); // Maximum execution time - works only if safe_mode is off
|
||||
if ((int)substr(ini_get("memory_limit"),0,-1) < (int) Yii::app()->getConfig('memory_limit')) @ini_set("memory_limit",Yii::app()->getConfig('memory_limit').'M'); // Set Memory Limit for big surveys
|
||||
|
||||
// The following function (when called) includes FireBug Lite if true
|
||||
defined('FIREBUG') or define('FIREBUG' , Yii::app()->getConfig('use_firebug_lite'));
|
||||
|
||||
//Every 50th time clean up the temp directory of old files (older than 1 day)
|
||||
//depending on the load the probability might be set higher or lower
|
||||
if (rand(1,50)==1)
|
||||
{
|
||||
cleanTempDirectory();
|
||||
}
|
||||
|
||||
//GlobalSettings Helper
|
||||
Yii::import("application.helpers.globalsettings");
|
||||
|
||||
enforceSSLMode();// This really should be at the top but for it to utilise getGlobalSetting() it has to be here
|
||||
|
||||
if (Yii::app()->getConfig('debug')==1) {//For debug purposes - switch on in config.php
|
||||
@ini_set("display_errors", 1);
|
||||
error_reporting(E_ALL);
|
||||
}
|
||||
elseif (Yii::app()->getConfig('debug')==2) {//For debug purposes - switch on in config.php
|
||||
@ini_set("display_errors", 1);
|
||||
error_reporting(E_ALL | E_STRICT);
|
||||
}
|
||||
else {
|
||||
@ini_set("display_errors", 0);
|
||||
error_reporting(0);
|
||||
}
|
||||
|
||||
//SET LOCAL TIME
|
||||
$timeadjust = Yii::app()->getConfig("timeadjust");
|
||||
if (substr($timeadjust,0,1)!='-' && substr($timeadjust,0,1)!='+') {$timeadjust='+'.$timeadjust;}
|
||||
if (strpos($timeadjust,'hours')===false && strpos($timeadjust,'minutes')===false && strpos($timeadjust,'days')===false)
|
||||
{
|
||||
Yii::app()->setConfig("timeadjust",$timeadjust.' hours');
|
||||
}
|
||||
|
||||
Yii::app()->setConfig('adminimageurl', Yii::app()->getConfig('styleurl').Yii::app()->getConfig('admintheme').'/images/');
|
||||
Yii::app()->setConfig('adminstyleurl', Yii::app()->getConfig('styleurl').Yii::app()->getConfig('admintheme').'/');
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an absolute URL based on the given controller and action information.
|
||||
* @param string $route the URL route. This should be in the format of 'ControllerID/ActionID'.
|
||||
* @param array $params additional GET parameters (name=>value). Both the name and value will be URL-encoded.
|
||||
* @param string $schema schema to use (e.g. http, https). If empty, the schema used for the current request will be used.
|
||||
* @param string $ampersand the token separating name-value pairs in the URL.
|
||||
* @return string the constructed URL
|
||||
*/
|
||||
public function createAbsoluteUrl($route,$params=array(),$schema='',$ampersand='&')
|
||||
{
|
||||
$sPublicUrl=Yii::app()->getConfig("publicurl");
|
||||
// Control if public url are really public : need scheme and host
|
||||
// If yes: use it
|
||||
$aPublicUrl=parse_url($sPublicUrl);
|
||||
if(isset($aPublicUrl['scheme']) && isset($aPublicUrl['host']))
|
||||
{
|
||||
$url=parent::createAbsoluteUrl($route,$params,$schema,$ampersand);
|
||||
$sActualBaseUrl=Yii::app()->getBaseUrl(true);
|
||||
if (substr($url, 0, strlen($sActualBaseUrl)) == $sActualBaseUrl) {
|
||||
$url = substr($url, strlen($sActualBaseUrl));
|
||||
}
|
||||
return trim($sPublicUrl,"/").$url;
|
||||
}
|
||||
else
|
||||
return parent::createAbsoluteUrl($route,$params,$schema,$ampersand);
|
||||
}
|
||||
}
|
49
sources/application/core/LSYii_EmailIDNAValidator.php
Normal file
49
sources/application/core/LSYii_EmailIDNAValidator.php
Normal file
|
@ -0,0 +1,49 @@
|
|||
<?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.
|
||||
*
|
||||
*/
|
||||
|
||||
class LSYii_EmailIDNAValidator extends CValidator {
|
||||
|
||||
public $allowEmpty=false;
|
||||
public $allowMultiple=false;
|
||||
|
||||
|
||||
public function validateAttribute($object,$attribute){
|
||||
|
||||
if ($object->$attribute=='' && $this->allowEmpty)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if ($this->allowMultiple)
|
||||
{
|
||||
$aEmailAdresses=explode(';',$object->$attribute);
|
||||
}
|
||||
else
|
||||
{
|
||||
$aEmailAdresses=array($object->$attribute);
|
||||
}
|
||||
|
||||
foreach ($aEmailAdresses as $sEmailAddress)
|
||||
{
|
||||
if (!validateEmailAddress($object->$attribute))
|
||||
{
|
||||
$this->addError($object, $attribute, gT('Invalid email address.'));
|
||||
return;
|
||||
}
|
||||
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
}
|
170
sources/application/core/LSYii_Validators.php
Normal file
170
sources/application/core/LSYii_Validators.php
Normal file
|
@ -0,0 +1,170 @@
|
|||
<?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.
|
||||
*
|
||||
*/
|
||||
|
||||
class LSYii_Validators extends CValidator {
|
||||
|
||||
/**
|
||||
* Filter attribute for fixCKeditor
|
||||
* @var boolean
|
||||
*/
|
||||
public $fixCKeditor=false;
|
||||
/**
|
||||
* Filter attribute for XSS
|
||||
* @var boolean
|
||||
*/
|
||||
public $xssfilter=true;
|
||||
/**
|
||||
* Filter attribute for url
|
||||
* @var boolean
|
||||
*/
|
||||
public $isUrl=false;
|
||||
/**
|
||||
* Filter attribute for isLanguage
|
||||
* @var boolean
|
||||
*/
|
||||
public $isLanguage=false;
|
||||
/**
|
||||
* Filter attribute for isLanguageMulti (multi language string)
|
||||
* @var boolean
|
||||
*/
|
||||
public $isLanguageMulti=false;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->xssfilter=($this->xssfilter && Yii::app()->getConfig('filterxsshtml') && !Permission::model()->hasGlobalPermission('superadmin','read'));
|
||||
}
|
||||
|
||||
protected function validateAttribute($object,$attribute)
|
||||
{
|
||||
if($this->xssfilter)
|
||||
{
|
||||
$object->$attribute=$this->xssFilter($object->$attribute);
|
||||
}
|
||||
if($this->isUrl)
|
||||
{
|
||||
if ($object->$attribute== 'http://' || $object->$attribute=='https://') {$object->$attribute="";}
|
||||
$object->$attribute=html_entity_decode($object->$attribute, ENT_QUOTES, "UTF-8"); // 140219 : Why not urlencode ?
|
||||
}
|
||||
if($this->isLanguage)
|
||||
{
|
||||
$object->$attribute=$this->languageFilter($object->$attribute);
|
||||
}
|
||||
if($this->isLanguageMulti)
|
||||
{
|
||||
$object->$attribute=$this->multiLanguageFilter($object->$attribute);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove some empty characters put by CK editor
|
||||
* Did we need to do if user don't use inline HTML editor ?
|
||||
*
|
||||
* @param string $value
|
||||
*/
|
||||
public function fixCKeditor($value)
|
||||
{
|
||||
// Actually don't use it in model : model apply too when import : needed or not ?
|
||||
$value = str_replace('<br type="_moz" />','',$value);
|
||||
if ($value == "<br />" || $value == " " || $value == " ")
|
||||
{
|
||||
$value = "";
|
||||
}
|
||||
if (preg_match("/^[\s]+$/",$value))
|
||||
{
|
||||
$value='';
|
||||
}
|
||||
if ($value == "\n")
|
||||
{
|
||||
$value = "";
|
||||
}
|
||||
if (trim($value) == " " || trim($value)=='')
|
||||
{ // chrome adds a single element to empty fckeditor fields
|
||||
$value = "";
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
/**
|
||||
* Remove any script or dangerous HTML
|
||||
*
|
||||
* @param string $value
|
||||
*/
|
||||
public function xssFilter($value)
|
||||
{
|
||||
$filter = new CHtmlPurifier();
|
||||
$filter->options = array(
|
||||
'AutoFormat.RemoveEmpty'=>false,
|
||||
'CSS.AllowTricky'=>true, // Allow display:none; (and other)
|
||||
'HTML.SafeObject'=>true, // To allow including youtube
|
||||
'Output.FlashCompat'=>true,
|
||||
'Attr.EnableID'=>true, // Allow to set id
|
||||
'Attr.AllowedFrameTargets'=>array('_blank','_self'),
|
||||
'URI.AllowedSchemes'=>array(
|
||||
'http' => true,
|
||||
'https' => true,
|
||||
'mailto' => true,
|
||||
'ftp' => true,
|
||||
'nntp' => true,
|
||||
'news' => true,
|
||||
)
|
||||
);
|
||||
// To allow script BUT purify : HTML.Trusted=true (plugin idea for admin or without XSS filtering ?)
|
||||
Yii::import('application.helpers.expressions.em_core_helper');// Already imported in em_manager_helper.php ?
|
||||
$oExpressionManager= new ExpressionManager;
|
||||
$aValues=$oExpressionManager->asSplitStringOnExpressions($value);// Return array of array : 0=>the string,1=>string length,2=>string type (STRING or EXPRESSION)
|
||||
$sNewValue="";
|
||||
foreach($aValues as $aValue){
|
||||
if($aValue[2]=="STRING")
|
||||
$sNewValue.=$filter->purify($aValue[0]);
|
||||
else
|
||||
{
|
||||
$sExpression=trim($aValue[0], '{}');
|
||||
$sNewValue.="{";
|
||||
$aParsedExpressions=$oExpressionManager->Tokenize($sExpression,true);// Return array of array : 0=>the string,1=>string length,2=>string type
|
||||
foreach($aParsedExpressions as $aParsedExpression)
|
||||
{
|
||||
if($aParsedExpression[2]=='DQ_STRING')
|
||||
$sNewValue.="\"".$filter->purify($aParsedExpression[0])."\"";
|
||||
elseif($aParsedExpression[2]=='SQ_STRING')
|
||||
$sNewValue.="'".$filter->purify($aParsedExpression[0])."'";
|
||||
else
|
||||
$sNewValue.=$aParsedExpression[0];
|
||||
}
|
||||
$sNewValue.="}";
|
||||
}
|
||||
}
|
||||
return $sNewValue;
|
||||
}
|
||||
/**
|
||||
* Defines the customs validation rule for language string
|
||||
*
|
||||
* @param mixed $value
|
||||
*/
|
||||
public function languageFilter($value)
|
||||
{
|
||||
// Maybe use the array of language ?
|
||||
return preg_replace('/[^a-z0-9-]/i', '', $value);
|
||||
}
|
||||
/**
|
||||
* Defines the customs validation rule for multi language string
|
||||
*
|
||||
* @param mixed $value
|
||||
*/
|
||||
public function multiLanguageFilter($value)
|
||||
{
|
||||
$aValue=explode(" ",trim($value));
|
||||
$aValue=array_map("sanitize_languagecode",$aValue);
|
||||
return implode(" ",$aValue);
|
||||
}
|
||||
|
||||
}
|
1027
sources/application/core/Survey_Common_Action.php
Normal file
1027
sources/application/core/Survey_Common_Action.php
Normal file
File diff suppressed because it is too large
Load diff
181
sources/application/core/UserIdentity.php
Normal file
181
sources/application/core/UserIdentity.php
Normal file
|
@ -0,0 +1,181 @@
|
|||
<?php
|
||||
/*
|
||||
* 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.
|
||||
*
|
||||
*/
|
||||
|
||||
class UserIdentity extends CUserIdentity
|
||||
{
|
||||
protected $id;
|
||||
protected $user;
|
||||
protected $sOneTimePassword;
|
||||
|
||||
/**
|
||||
* Checks whether this user has correctly entered password or not
|
||||
*
|
||||
* @access public
|
||||
* @return bool
|
||||
*/
|
||||
public function authenticate($sOneTimePassword='')
|
||||
{
|
||||
if (Yii::app()->getConfig("auth_webserver")==false || $this->username != "")
|
||||
{
|
||||
$user = User::model()->findByAttributes(array('users_name' => $this->username));
|
||||
|
||||
if ($user !== null)
|
||||
{
|
||||
if (gettype($user->password)=='resource')
|
||||
{
|
||||
$sStoredPassword=stream_get_contents($user->password,-1,0); // Postgres delivers bytea fields as streams :-o
|
||||
}
|
||||
else
|
||||
{
|
||||
$sStoredPassword=$user->password;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
$this->errorCode = self::ERROR_USERNAME_INVALID;
|
||||
return !$this->errorCode;
|
||||
}
|
||||
|
||||
if ($sOneTimePassword!='' && Yii::app()->getConfig("use_one_time_passwords") && md5($sOneTimePassword)==$user->one_time_pw)
|
||||
{
|
||||
$user->one_time_pw='';
|
||||
$user->save();
|
||||
$this->id = $user->uid;
|
||||
$this->user = $user;
|
||||
$this->errorCode = self::ERROR_NONE;
|
||||
}
|
||||
elseif ($sStoredPassword !== hash('sha256', $this->password))
|
||||
{
|
||||
$this->errorCode = self::ERROR_PASSWORD_INVALID;
|
||||
}
|
||||
else
|
||||
{
|
||||
$this->id = $user->uid;
|
||||
$this->user = $user;
|
||||
$this->errorCode = self::ERROR_NONE;
|
||||
}
|
||||
}
|
||||
elseif(Yii::app()->getConfig("auth_webserver") === true && (isset($_SERVER['PHP_AUTH_USER'])||isset($_SERVER['LOGON_USER']) ||isset($_SERVER['REMOTE_USER']))) // normal login through webserver authentication
|
||||
{
|
||||
if (isset($_SERVER['PHP_AUTH_USER'])) {
|
||||
$sUser=$_SERVER['PHP_AUTH_USER'];
|
||||
}
|
||||
elseif (isset($_SERVER['REMOTE_USER'])) {
|
||||
$sUser=$_SERVER['REMOTE_USER'];
|
||||
} else {
|
||||
$sUser = $_SERVER['LOGON_USER'];
|
||||
}
|
||||
if (strpos($sUser,"\\")!==false) {
|
||||
$sUser = substr($sUser, strrpos($sUser, "\\")+1);
|
||||
}
|
||||
|
||||
$aUserMappings=Yii::app()->getConfig("auth_webserver_user_map");
|
||||
if (isset($aUserMappings[$sUser]))
|
||||
{
|
||||
$sUser = $aUserMappings[$sUser];
|
||||
}
|
||||
$this->username = $sUser;
|
||||
|
||||
$oUser=User::model()->findByAttributes(array('users_name'=>$sUser));
|
||||
if (is_null($oUser))
|
||||
{
|
||||
if (function_exists("hook_get_auth_webserver_profile"))
|
||||
{
|
||||
// If defined this function returns an array
|
||||
// describing the defaukt profile for this user
|
||||
$aUserProfile = hook_get_auth_webserver_profile($sUser);
|
||||
}
|
||||
elseif (Yii::app()->getConfig("auth_webserver_autocreate_user"))
|
||||
{
|
||||
$aUserProfile=Yii::app()->getConfig("auth_webserver_autocreate_profile");
|
||||
}
|
||||
} else {
|
||||
$this->id = $oUser->uid;
|
||||
$this->user = $oUser;
|
||||
$this->errorCode = self::ERROR_NONE;
|
||||
}
|
||||
|
||||
|
||||
|
||||
if (Yii::app()->getConfig("auth_webserver_autocreate_user") && isset($aUserProfile) && is_null($oUser))
|
||||
{ // user doesn't exist but auto-create user is set
|
||||
$oUser=new User;
|
||||
$oUser->users_name=$sUser;
|
||||
$oUser->password=hash('sha256', createPassword());
|
||||
$oUser->full_name=$aUserProfile['full_name'];
|
||||
$oUser->parent_id=1;
|
||||
$oUser->lang=$aUserProfile['lang'];
|
||||
$oUser->email=$aUserProfile['email'];
|
||||
$oUser->create_survey=$aUserProfile['create_survey'];
|
||||
$oUser->create_user=$aUserProfile['create_user'];
|
||||
$oUser->delete_user=$aUserProfile['delete_user'];
|
||||
$oUser->superadmin=$aUserProfile['superadmin'];
|
||||
$oUser->configurator=$aUserProfile['configurator'];
|
||||
$oUser->manage_template=$aUserProfile['manage_template'];
|
||||
$oUser->manage_label=$aUserProfile['manage_label'];
|
||||
|
||||
if ($oUser->save())
|
||||
{
|
||||
$aTemplates=explode(",",$aUserProfile['templatelist']);
|
||||
foreach ($aTemplates as $sTemplateName)
|
||||
{
|
||||
$oPermission=new Permission;
|
||||
$oPermission->uid = $oUser->uid;
|
||||
$oPermission->entity = 'template';
|
||||
$oPermission->permission = trim($sTemplateName);
|
||||
$oPermission->read_p = 1;
|
||||
$oPermission->save();
|
||||
}
|
||||
|
||||
// read again user from newly created entry
|
||||
$this->id = $oUser->uid;
|
||||
$this->user = $oUser;
|
||||
$this->errorCode = self::ERROR_NONE;
|
||||
}
|
||||
else
|
||||
{
|
||||
$this->errorCode = self::ERROR_USERNAME_INVALID;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
$this->errorCode = self::ERROR_USERNAME_INVALID;
|
||||
}
|
||||
return !$this->errorCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current user's ID
|
||||
*
|
||||
* @access public
|
||||
* @return int
|
||||
*/
|
||||
public function getId()
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the active user's record
|
||||
*
|
||||
* @access public
|
||||
* @return CActiveRecord
|
||||
*/
|
||||
public function getUser()
|
||||
{
|
||||
return $this->user;
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue