/** * Try to Upload the given file returning the filename on success * * @param array $file $_FILES array element * @param string $dir destination directory * @param boolean $overwrite existing files of the same name? * @param integer $size maximum size allowed (can also be set in php.ini or server config) */ public function file($file, $dir, $overwrite = FALSE, $size = FALSE) { // Invalid upload? if (!isset($file['tmp_name'], $file['name'], $file['error'], $file['size']) or $file['error'] != UPLOAD_ERR_OK) { return FALSE; } // File to large? if ($size and $size > $file['size']) { return FALSE; } // Create $basename, $filename, $dirname, & $extension variables extract(pathinfo($file['name']) + array('extension' => '')); // Make the name file system safe $filename = sanitize_filename($filename); // We must have a valid name and file type if (empty($filename) or empty($extension)) { return FALSE; } $extension = strtolower($extension); // Don't allow just any file! if (!$this->allowed_file($extension)) { return FALSE; } // Make sure we can use the destination directory Directory::usable($dir); // Create a unique name if we don't want files overwritten $name = $overwrite ? "{$filename}.{$ext}" : $this->unique_filename($dir, $filename, $extension); // Move the file to the correct location if (move_uploaded_file($file['tmp_name'], $dir . $name)) { return $name; } }
/** * {@inheritdoc} */ protected function fire() { $process = new Process('mysqldump --version'); $process->run(); if (!$process->isSuccessful()) { throw new \RuntimeException('mysqldump could not be found in your $PATH.'); } ee()->load->helper('security'); // where to create the file, default to current dir $path = $this->argument('path') ?: '.'; $path = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; $gzip = $this->option('gzip'); if ($gzip) { $process = new Process('gzip --version'); $process->run(); if (!$process->isSuccessful()) { throw new \RuntimeException('gzip could not be found in your $PATH.'); } } $extension = $gzip ? '.sql.gz' : '.sql'; $name = $this->option('name'); // set a default name <db>[-<env>]-<yyyymmddhhmmss> if (!$name) { $name = sanitize_filename(ee()->db->database); $env = $this->getApplication()->getEnvironment(); if ($env) { $name .= '-' . $env; } $name .= '-' . date('YmdHis'); } $file = $path . $name . $extension; // compile the mysqldump command using EE's db credentials $command = sprintf('MYSQL_PWD=%s mysqldump -u %s -h %s %s %s > %s', escapeshellarg(ee()->db->password), escapeshellarg(ee()->db->username), escapeshellarg(ee()->db->hostname), escapeshellarg(ee()->db->database), $gzip ? ' | gzip' : '', escapeshellarg($file)); $process = new Process($command); $process->setTimeout(3600); $process->run(); if (!$process->isSuccessful()) { $this->error('Could not execute mysqldump.'); return; } $backups = $this->option('backups'); // check if we need to delete any old backups if (is_numeric($backups)) { $finder = new Finder(); // look for other files in the path that use the // sql / sql.gz extension $finder->files()->in($path)->name('*' . $extension)->sortByModifiedTime(); // omit the X most recent files $files = array_slice(array_reverse(iterator_to_array($finder)), $backups); // if there are backups beyond our limit, delete them foreach ($files as $file) { unlink($file->getRealPath()); } } $this->info($file . ' created.'); }
public function gimmeZip($id) { set_time_limit(300); $contest = Contest::findOrFail($id); $entries = UserContestEntry::where('contest_id', $id)->with('user')->get(); $tmpBase = sys_get_temp_dir() . "/c{$id}-" . time(); $workingFolder = "{$tmpBase}/working"; $outputFolder = "{$tmpBase}/out"; try { if (!is_dir($workingFolder)) { mkdir($workingFolder, 0755, true); } if (!is_dir($outputFolder)) { mkdir($outputFolder, 0755, true); } // fetch entries foreach ($entries as $entry) { $targetDir = "{$workingFolder}/" . ($entry->user ?? new \App\Models\DeletedUser())->username . " ({$entry->user_id})/"; if (!is_dir($targetDir)) { mkdir($targetDir, 0755, true); } copy($entry->fileUrl(), "{$targetDir}/" . sanitize_filename($entry->original_filename)); } // zip 'em $zipOutput = "{$outputFolder}/contest-{$id}.zip"; $zip = new \ZipArchive(); $zip->open($zipOutput, \ZipArchive::CREATE); foreach (glob("{$workingFolder}/**/*.*") as $file) { // we just want the path relative to the working folder root $new_filename = str_replace("{$workingFolder}/", '', $file); $zip->addFile($file, $new_filename); } $zip->close(); // send 'em on their way header('Content-Disposition: attachment; filename=' . basename($zipOutput)); header('Content-Type: application/zip'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($zipOutput)); readfile($zipOutput); } finally { deltree($tmpBase); } }
/** * {@inheritdoc} */ protected function fire() { ee()->load->helper('security'); // where to create the file, default to current dir $path = $this->argument('path') ?: '.'; $path = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; $gzip = $this->option('gzip'); $extension = $gzip ? '.sql.gz' : '.sql'; $name = $this->option('name'); // set a default name <db>[-<env>]-<yyyymmddhhmmss> if (!$name) { $name = sanitize_filename(ee()->db->database); $env = $this->getApplication()->getEnvironment(); if ($env) { $name .= '-' . $env; } $name .= '-' . date('YmdHis'); } $file = $path . $name . $extension; // compile the mysqldump command using EE's db credentials $command = sprintf('MYSQL_PWD="%s" /usr/bin/env mysqldump -u "%s" -h "%s" "%s"%s > %s', ee()->db->password, ee()->db->username, ee()->db->hostname, ee()->db->database, $gzip ? ' | gzip' : '', $file); $executed = system($command); $backups = $this->option('backups'); // check if we need to delete any old backups if (is_numeric($backups)) { $finder = new Finder(); // look for other files in the path that use the // sql / sql.gz extension $finder->files()->in($path)->name('*' . $extension)->sortByModifiedTime(); // omit the X most recent files $files = array_slice(array_reverse(iterator_to_array($finder)), $backups); // if there are backups beyond our limit, delete them foreach ($files as $file) { unlink($file->getRealPath()); } } if ($executed !== false) { $this->info($file . ' created.'); } else { $this->error('Could not execute mysqldump.'); } }
echo "<p>Reorganizing your images folder..."; # strip images prefix from pictures table $sql = "UPDATE " . TABLE_PREFIX . "pictures SET path = SUBSTRING(path,8) WHERE SUBSTRING(path,1,7) = 'images/'"; $result = mysql_query($sql); $sql = "SELECT id,name FROM " . TABLE_PREFIX . "collections"; $result = mysql_query($sql) or die(mysql_error() . "<br /><br />" . $sql); while ($row = mysql_fetch_assoc($result)) { $sql = "UPDATE " . TABLE_PREFIX . "collections SET path = '" . strtolower(sanitize_filename($row['name'])) . "' WHERE id = " . $row['id']; #print $sql; #print "<br>"; mysql_query($sql); } $sql = "SELECT id,name FROM " . TABLE_PREFIX . "albums"; $result = mysql_query($sql) or die(mysql_error() . "<br /><br />" . $sql); while ($row = mysql_fetch_assoc($result)) { $sql = "UPDATE " . TABLE_PREFIX . "albums SET path = '" . strtolower(sanitize_filename($row['name'])) . "' WHERE id = " . $row['id']; #print $sql; #print "<br>"; mysql_query($sql); } // loop through each image from the pictures table, get its parent album name and parent collection // name, create subdirectories, move the file, and update the PATH field in pictures. // We need to do a join on the tables to get album names and collection names $sql = "SELECT p.path AS path, p.id AS pid,c.path AS collection_path, a.path AS album_path\r\n\t\tFROM " . TABLE_PREFIX . "albums a, " . TABLE_PREFIX . "pictures p, " . TABLE_PREFIX . "collections c \r\n\t\tWHERE p.parent_album = a.id AND p.parent_collection = c.id"; $result = mysql_query($sql) or die(mysql_error() . "<br /><br />" . $sql); echo "<ul>"; while ($row = mysql_fetch_assoc($result)) { $errors = 0; $filename = basename($row['path']); $directory = $row['collection_path'] . "/" . $row['album_path'] . "/"; $new_path = "images/" . $directory . $filename;
function plogger_get_thumbnail_info() { global $thumbnail_config; global $config; $thumb_config = $thumbnail_config[THUMB_SMALL]; $base_filename = sanitize_filename(basename($GLOBALS["current_picture"]["path"])); $prefix = $thumb_config['filename_prefix'] . $GLOBALS["current_picture"]["id"] . "-"; $thumbpath = $config['basedir'] . 'thumbs/' . $prefix . $base_filename; $image_info = getimagesize($thumbpath); return $image_info; }
<?php require_once dirname(__FILE__) . '/classes/core/startup.php'; require_once dirname(__FILE__) . '/config-defaults.php'; require_once dirname(__FILE__) . '/common.php'; require_once $homedir . '/classes/core/class.progressbar.php'; require_once dirname(__FILE__) . '/classes/core/language.php'; if (!isset($surveyid)) { $surveyid = returnglobal('sid'); } else { //This next line ensures that the $surveyid value is never anything but a number. $surveyid = sanitize_int($surveyid); } if (isset($_GET['filegetcontents'])) { $sFileName = sanitize_filename($_GET['filegetcontents']); if (substr($sFileName, 0, 6) == 'futmp_') { $sFileDir = $tempdir . '/upload/'; } elseif (substr($sFileName, 0, 3) == 'fu_') { $sFileDir = "{$uploaddir}/surveys/{$surveyid}/files/"; } readfile($sFileDir . $sFileName); exit; } // Compute the Session name // Session name is based: // * on this specific limesurvey installation (Value SessionName in DB) // * on the surveyid (from Get or Post param). If no surveyid is given we are on the public surveys portal $usquery = "SELECT stg_value FROM " . db_table_name("settings_global") . " where stg_name='SessionName'"; $usresult = db_execute_assoc($usquery, '', true); //Checked if ($usresult) {
function PrinterStoring__generateFilename($raw_name) { $return_name = NULL; $CI =& get_instance(); $CI->load->helper('security'); // remove unsecurity chars and non ascii chars $return_name = filter_var(sanitize_filename($raw_name), FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH); // replace space and some chars $return_name = str_replace(array(' ', '`', '|', ':', '*', '%', ',', '^'), '_', $return_name); //TODO check if we need to filter '(' and ')' for interface or not return $return_name; }
<p><img src="../../img/symbole/rotation.gif" alt="" width="15" height="15"><strong class="title"> selected files uploaded via ftp will be taken over!</strong></p><?php echo "<p class=\"v10\">"; flush(); foreach ($ftp["mark"] as $key => $value) { if (!ini_get('safe_mode') && function_exists('set_time_limit')) { set_time_limit(60); } $file = $ftp["file"][$key]; $file_path = PHPWCMS_ROOT . $phpwcms["ftp_path"] . $file; if (is_file($file_path)) { $file_type = ''; $file_error["upload"] = 0; $file_size = filesize($file_path); $file_ext = check_image_extension($file_path); $file_ext = false === $file_ext ? which_ext($file) : $file_ext; $file_name = sanitize_filename($ftp["filename"][$key]); $file_hash = md5($file_name . microtime()); if (trim($file_type) === '') { //check file_type if (is_mimetype_by_extension($file_ext)) { $file_type = get_mimetype_by_extension($file_ext); } else { $file_check = getimagesize($file_path); if (version_compare("4.3.0", phpversion(), ">=") && $file_check) { $file_type = image_type_to_mime_type($file_check[2]); } if (!is_mimetype_format($file_type)) { $file_type = get_mimetype_by_extension($file_ext); } } }
/** * Function: sanitize_dirname * sanitizes a string that will be used as a directory name * * Parameters: * $string - The string to sanitize. * $force_lowercase - Force the string to lowercase? * $alphanumeric - If set to *true*, will remove all non-alphanumeric characters. */ function sanitize_dirname($string, $force_lowercase = false, $alphanumeric = false) { $string = str_replace(".", "", $string); return sanitize_filename($string, $force_lowercase, $alphanumeric); }
<?php require 'test-more.php'; require '../../cacti/scripts/ss_get_by_ssh.php'; $debug = true; is(sanitize_filename(array('foo' => 'bar'), array('foo', 'biz'), 'tail'), 'bar_tail', 'sanitize_filename'); is_deeply(proc_stat_parse(null, file_get_contents('samples/proc_stat-001.txt')), array('STAT_interrupts' => '339490', 'STAT_context_switches' => '697948', 'STAT_forks' => '11558', 'STAT_CPU_user' => '24198', 'STAT_CPU_nice' => '0', 'STAT_CPU_system' => '69614', 'STAT_CPU_idle' => '2630536', 'STAT_CPU_iowait' => '558', 'STAT_CPU_irq' => '5872', 'STAT_CPU_softirq' => '1572', 'STAT_CPU_steal' => '0', 'STAT_CPU_guest' => '0'), 'samples/proc_stat-001.txt'); is_deeply(proc_stat_parse(null, file_get_contents('samples/proc_stat-002.txt')), array('STAT_interrupts' => '87480486', 'STAT_context_switches' => '125521467', 'STAT_forks' => '239810', 'STAT_CPU_user' => '2261920', 'STAT_CPU_nice' => '38824', 'STAT_CPU_system' => '986335', 'STAT_CPU_idle' => '39683698', 'STAT_CPU_iowait' => '62368', 'STAT_CPU_irq' => '19193', 'STAT_CPU_softirq' => '8499', 'STAT_CPU_steal' => '0', 'STAT_CPU_guest' => '0'), 'samples/proc_stat-002.txt'); is(ss_get_by_ssh(array('file' => 'samples/proc_stat-001.txt', 'type' => 'proc_stat', 'host' => 'localhost', 'items' => 'gw,gx,gy,gz,hg,hh,hi,hj,hk,hl,hm,hn')), 'gw:24198 gx:0 gy:69614 gz:2630536 hg:558 hh:5872 hi:1572 hj:0 hk:0' . ' hl:339490 hm:697948 hn:11558', 'main(samples/proc_stat-001.txt)'); is_deeply(memory_parse(null, file_get_contents('samples/free-001.txt')), array('STAT_memcached' => '22106112', 'STAT_membuffer' => '1531904', 'STAT_memshared' => '0', 'STAT_memfree' => '17928192', 'STAT_memused' => '21389312', 'STAT_memtotal' => '62955520'), 'samples/free-001.txt'); is_deeply(memory_parse(null, file_get_contents('samples/free-002.txt')), array('STAT_memcached' => '1088184320', 'STAT_membuffer' => '131469312', 'STAT_memshared' => '0', 'STAT_memfree' => '189325312', 'STAT_memused' => '7568291328', 'STAT_memtotal' => '8977270272'), 'samples/free-002.txt (issue 102)'); is(ss_get_by_ssh(array('file' => 'samples/free-001.txt', 'type' => 'memory', 'host' => 'localhost', 'items' => 'hq,hr,hs,ht,hu,hv')), 'hq:22106112 hr:1531904 hs:0 ht:17928192 hu:21389312 hv:62955520', 'main(samples/free-001.txt)'); is_deeply(w_parse(null, file_get_contents('samples/w-001.txt')), array('STAT_loadavg' => '0.00', 'STAT_numusers' => '2'), 'samples/w-001.txt'); is_deeply(w_parse(null, file_get_contents('samples/w-002.txt')), array('STAT_loadavg' => '0.29', 'STAT_numusers' => '6'), 'samples/w-002.txt'); is_deeply(w_parse(null, file_get_contents('samples/w-003.txt')), array('STAT_loadavg' => '0.02', 'STAT_numusers' => '1'), 'samples/w-003.txt'); is_deeply(w_parse(null, file_get_contents('samples/w-004.txt')), array('STAT_loadavg' => '11.02', 'STAT_numusers' => '1'), 'samples/w-004.txt'); is_deeply(w_parse(null, file_get_contents('samples/uptime-001.txt')), array('STAT_loadavg' => '0.00', 'STAT_numusers' => '0'), 'samples/uptime-001.txt'); is(ss_get_by_ssh(array('file' => 'samples/w-001.txt', 'type' => 'w', 'host' => 'localhost', 'items' => 'ho,hp')), 'ho:0.00 hp:2', 'main(samples/w-001.txt)'); is_deeply(memcached_parse(null, file_get_contents('samples/memcached-001.txt')), array('MEMC_pid' => '2120', 'MEMC_uptime' => '32314', 'MEMC_time' => '1261775864', 'MEMC_version' => '1.2.2', 'MEMC_pointer_size' => '32', 'MEMC_rusage_user' => '396024', 'MEMC_rusage_system' => '1956122', 'MEMC_curr_items' => '0', 'MEMC_total_items' => '0', 'MEMC_bytes' => '0', 'MEMC_curr_connections' => '1', 'MEMC_total_connections' => '5', 'MEMC_connection_structures' => '2', 'MEMC_cmd_get' => '0', 'MEMC_cmd_set' => '0', 'MEMC_get_hits' => '0', 'MEMC_get_misses' => '0', 'MEMC_evictions' => '0', 'MEMC_bytes_read' => '45', 'MEMC_bytes_written' => '942', 'MEMC_limit_maxbytes' => '67108864', 'MEMC_threads' => '1'), 'samples/memcached-001.txt'); is(ss_get_by_ssh(array('file' => 'samples/memcached-001.txt', 'type' => 'memcached', 'host' => 'localhost', 'items' => 'ij,ik,il,im,in,io,ip,iq,ir,is,it,iu,iv')), 'ij:396024 ik:1956122 il:0 im:0 in:0 io:1 ip:5 iq:0 ir:0 is:0 it:0 iu:45' . ' iv:942', 'main(samples/memcached-001.txt)'); is_deeply(nginx_parse(null, file_get_contents('samples/nginx-001.txt')), array('NGINX_active_connections' => '251', 'NGINX_server_accepts' => '255601634', 'NGINX_server_handled' => '255601634', 'NGINX_server_requests' => '671013148', 'NGINX_reading' => '5', 'NGINX_writing' => '27', 'NGINX_waiting' => '219'), 'samples/nginx-001.txt'); is(ss_get_by_ssh(array('file' => 'samples/nginx-001.txt', 'type' => 'nginx', 'host' => 'localhost', 'items' => 'hw,hx,hy,hz,ig,ih,ii')), 'hw:251 hx:255601634 hy:255601634 hz:671013148 ig:5 ih:27 ii:219', 'main(samples/nginx-001.txt)'); is_deeply(apache_parse(null, file_get_contents('samples/apache-001.txt')), array('APACHE_Requests' => '3452389', 'APACHE_Bytes_sent' => '23852769280', 'APACHE_Idle_workers' => '8', 'APACHE_Busy_workers' => '1', 'APACHE_CPU_Load' => '.023871', 'APACHE_Waiting_for_connection' => '8', 'APACHE_Starting_up' => 0, 'APACHE_Reading_request' => 0, 'APACHE_Sending_reply' => '1', 'APACHE_Keepalive' => 0, 'APACHE_DNS_lookup' => 0, 'APACHE_Closing_connection' => 0, 'APACHE_Logging' => 0, 'APACHE_Gracefully_finishing' => 0, 'APACHE_Idle_cleanup' => 0, 'APACHE_Open_slot' => '247'), 'samples/apache-001.txt'); is_deeply(apache_parse(null, file_get_contents('samples/apache-002.txt')), array('APACHE_Requests' => '368', 'APACHE_Bytes_sent' => 1151 * 1024, 'APACHE_Idle_workers' => '19', 'APACHE_Busy_workers' => '1', 'APACHE_CPU_Load' => '.0284617', 'APACHE_Waiting_for_connection' => '19', 'APACHE_Starting_up' => 0, 'APACHE_Reading_request' => 0, 'APACHE_Sending_reply' => '1', 'APACHE_Keepalive' => 0, 'APACHE_DNS_lookup' => 0, 'APACHE_Closing_connection' => 0, 'APACHE_Logging' => 0, 'APACHE_Gracefully_finishing' => 0, 'APACHE_Idle_cleanup' => 0, 'APACHE_Open_slot' => '236'), 'samples/apache-002.txt'); is(ss_get_by_ssh(array('file' => 'samples/apache-001.txt', 'type' => 'apache', 'host' => 'localhost', 'items' => 'gg,gh,gi,gj,gk,gl,gm,gn,go,gp,gq,gr,gs,gt,gu,gv')), 'gg:3452389 gh:23852769280 gi:8 gj:1 gk:.023871 gl:8 gm:0 gn:0 go:1 gp:0' . ' gq:0 gr:0 gs:0 gt:0 gu:0 gv:247', 'main(samples/apache-001.txt)'); is_deeply(diskstats_parse(array('device' => 'hda1'), file_get_contents('samples/diskstats-001.txt')), array('DISK_reads' => '12043', 'DISK_reads_merged' => '387', 'DISK_sectors_read' => '300113', 'DISK_time_spent_reading' => '6472', 'DISK_writes' => '12737', 'DISK_writes_merged' => '21340', 'DISK_sectors_written' => '272616', 'DISK_time_spent_writing' => '22360', 'DISK_io_time' => '12368', 'DISK_io_time_weighted' => '28832', 'DISK_io_ops' => '24780'), 'samples/diskstats-001.txt'); is_deeply(diskstats_parse(array('device' => 'sda4'), file_get_contents('samples/diskstats-002.txt')), array('DISK_reads' => '30566', 'DISK_reads_merged' => '3341', 'DISK_sectors_read' => '586664', 'DISK_time_spent_reading' => '370308', 'DISK_writes' => '150943', 'DISK_writes_merged' => '163833', 'DISK_sectors_written' => '2518672', 'DISK_time_spent_writing' => '12081496', 'DISK_io_time' => '347416', 'DISK_io_time_weighted' => '12451664', 'DISK_io_ops' => '181509'), 'samples/diskstats-002.txt'); is_deeply(diskstats_parse(array('device' => 'sda2'), file_get_contents('samples/diskstats-003.txt')), array('DISK_reads' => '15425346', 'DISK_reads_merged' => '0', 'DISK_sectors_read' => '385290786', 'DISK_time_spent_reading' => '0', 'DISK_writes' => '472909074', 'DISK_writes_merged' => '0', 'DISK_sectors_written' => '3783272616', 'DISK_time_spent_writing' => '0', 'DISK_io_time' => '0', 'DISK_io_time_weighted' => '0', 'DISK_io_ops' => '488334420'), 'samples/diskstats-003.txt'); is(ss_get_by_ssh(array('file' => 'samples/diskstats-001.txt', 'type' => 'diskstats', 'host' => 'localhost', 'items' => 'iw,ix,iy,iz,jg,jh,ji,jj,jk,jl,jm', 'device' => 'hda1')), 'iw:12043 ix:387 iy:300113 iz:6472 jg:12737 jh:21340 ji:272616 jj:22360' . ' jk:24780 jl:12368 jm:28832', 'main(samples/diskstats-001.txt)'); is_deeply(openvz_parse(array(), file_get_contents('samples/openvz-001.txt')), array('OPVZ_kmemsize_held' => '8906701', 'OPVZ_kmemsize_failcnt' => '0', 'OPVZ_lockedpages_held' => '0', 'OPVZ_lockedpages_failcnt' => '0', 'OPVZ_privvmpages_held' => '39695', 'OPVZ_privvmpages_failcnt' => '0', 'OPVZ_shmpages_held' => '688', 'OPVZ_shmpages_failcnt' => '0', 'OPVZ_numproc_held' => '32', 'OPVZ_numproc_failcnt' => '0', 'OPVZ_physpages_held' => '11101', 'OPVZ_physpages_failcnt' => '0', 'OPVZ_vmguarpages_held' => '0', 'OPVZ_vmguarpages_failcnt' => '0', 'OPVZ_oomguarpages_held' => '11101', 'OPVZ_oomguarpages_failcnt' => '0', 'OPVZ_numtcpsock_held' => '6', 'OPVZ_numtcpsock_failcnt' => '0', 'OPVZ_numflock_held' => '6', 'OPVZ_numflock_failcnt' => '0', 'OPVZ_numpty_held' => '1', 'OPVZ_numpty_failcnt' => '0', 'OPVZ_numsiginfo_held' => '0', 'OPVZ_numsiginfo_failcnt' => '0', 'OPVZ_tcpsndbuf_held' => '338656', 'OPVZ_tcpsndbuf_failcnt' => '0', 'OPVZ_tcprcvbuf_held' => '98304', 'OPVZ_tcprcvbuf_failcnt' => '0', 'OPVZ_othersockbuf_held' => '9280', 'OPVZ_othersockbuf_failcnt' => '0', 'OPVZ_dgramrcvbuf_held' => '0', 'OPVZ_dgramrcvbuf_failcnt' => '0', 'OPVZ_numothersock_held' => '9', 'OPVZ_numothersock_failcnt' => '0', 'OPVZ_dcachesize_held' => '0', 'OPVZ_dcachesize_failcnt' => '0', 'OPVZ_numfile_held' => '788', 'OPVZ_numfile_failcnt' => '0', 'OPVZ_numiptent_held' => '10', 'OPVZ_numiptent_failcnt' => '0'), 'samples/openvz-001.txt'); is(ss_get_by_ssh(array('file' => 'samples/openvz-001.txt', 'type' => 'openvz', 'host' => 'localhost', 'items' => 'jn,jo,jp,jq,jr,js,jt,ju,jv,jw,jx,jy,jz,kg,kh,ki,kj,kk,kl,km,kn,ko,kp,kq,kr,ks,kt,ku,kv,kw,kx,ky,kz,lg,lh,li,lj,lk,ll,lm')), 'jn:8906701 jo:0 jp:0 jq:0 jr:39695 js:0 jt:688 ju:0 jv:32 jw:0 jx:11101' . ' jy:0 jz:0 kg:0 kh:11101 ki:0 kj:6 kk:0 kl:6 km:0 kn:1 ko:0 kp:0 kq:0' . ' kr:338656 ks:0 kt:98304 ku:0 kv:9280 kw:0 kx:0 ky:0 kz:9 lg:0 lh:0 li:0' . ' lj:788 lk:0 ll:10 lm:0', 'main(samples/openvz-001.txt)');
function test_sanitize_filename() { $this->assertEquals('hello.doc', sanitize_filename('hello.doc')); $filename = './<!--foo-->'; $this->assertEquals('foo', sanitize_filename($filename)); }
$podcast_simplexml = simplexml_load_string(file_get_contents(trim($podcast_url))); if (!$podcast_simplexml) { echo "{$podcast_title} ({$podcast_url}) is not providing valid XML. Skipping.\n"; break; } if (!file_exists(PODDIE_PODCAST_STORAGE . "/{$podcast_title}")) { echo "New podcast subscription detected: {$podcast_title}.\n"; exec("mkdir -p '" . PODDIE_PODCAST_STORAGE . "/{$podcast_title}'"); } foreach ($podcast_simplexml->channel->item as $item) { if (++$episodes_kept >= $episodes_to_keep) { break; } $url = (string) $item->enclosure['url']; $episode_title_filename_extension = strtolower(pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION)); $episode_title_filename = date('Y-m-d', strtotime((string) $item->pubDate)) . " - " . sanitize_filename(remove_timestamp((string) $item->title)) . ".{$episode_title_filename_extension}"; if ($url != '' && !file_exists(PODDIE_PODCAST_STORAGE . "/{$podcast_title}/{$episode_title_filename}") && strpos($poddie_already_fetched, $url) === false) { echo "Fetching '{$url}' into '" . PODDIE_PODCAST_STORAGE . "/{$podcast_title}/{$episode_title_filename}'\n"; download($url, PODDIE_PODCAST_STORAGE . "/{$podcast_title}/{$episode_title_filename}"); $id3tag = substr($episode_title_filename, 0, strrpos($episode_title_filename, '.')); exec(PODDIE_ID3TAG_BIN . " --song='{$id3tag}' '" . PODDIE_PODCAST_STORAGE . "/{$podcast_title}/{$episode_title_filename}'"); log_fetched($url); $downloaded_files_count++; } } $downloaded_files = scan_dir(PODDIE_PODCAST_STORAGE . "/{$podcast_title}"); for ($index = intval($episodes_to_keep); $index <= count($downloaded_files) - 1; $index++) { $file_to_remove = PODDIE_PODCAST_STORAGE . "/{$podcast_title}/{$downloaded_files[$index]}"; echo "Removing {$index} from {$podcast_title} ({$file_to_remove})\n"; unlink($file_to_remove); }
if (isset($_POST['printableexport'])) { $pdf->intopdf(FlattenText($fname[0] . $fname[1], true) . ": " . $fname[2]); $pdf->ln(2); } else { $printoutput .= "\t<tr class='printanswersquestionhead'><td colspan='2'>{$fname[0]}</td></tr>\n"; } } else { if (isset($_POST['printableexport'])) { $pdf->intopdf(FlattenText($fname[0] . $fname[1], true) . ": " . $fname[2]); $pdf->ln(2); } else { $printoutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]}</td><td class='printanswersanswertext'>{$fname[2]}</td></tr>"; } } } $printoutput .= "</table>\n"; if (isset($_POST['printableexport'])) { header("Pragma: public"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); $sExportFileName = sanitize_filename($surveyname); $pdf->Output($sExportFileName . "-" . $surveyid . ".pdf", "D"); } //Display the page with user answers if (!isset($_POST['printableexport'])) { sendcacheheaders(); doHeader(); echo templatereplace(file_get_contents(sGetTemplatePath($thistpl) . '/startpage.pstpl')); echo templatereplace(file_get_contents(sGetTemplatePath($thistpl) . '/printanswers.pstpl'), array('ANSWERTABLE' => $printoutput)); echo templatereplace(file_get_contents(sGetTemplatePath($thistpl) . '/endpage.pstpl')); echo "</body></html>"; }
$newdirname = $usertemplaterootdir . "/" . $newname; $olddirname = $usertemplaterootdir . "/" . $copydir; if (isStandardTemplate($newname)) { echo "<script type=\"text/javascript\">\n<!--\nalert(\"" . sprintf($clang->gT("Template could not be renamed to `%s`.", "js"), $newname) . " " . $clang->gT("This name is reserved for a standard template.", "js") . "\");\n//-->\n</script>"; } elseif (rename($olddirname, $newdirname) == false) { echo "<script type=\"text/javascript\">\n<!--\nalert(\"" . sprintf($clang->gT("Directory could not be renamed to `%s`.", "js"), $newname) . " " . $clang->gT("Maybe you don't have permission.", "js") . "\");\n//-->\n</script>"; } else { $templates[$newname] = $newdirname; $templatename = $newname; } } if ($action == "templateuploadfile") { if ($demoModeOnly == true) { $action = ''; } else { $the_full_file_path = $usertemplaterootdir . "/" . $templatename . "/" . sanitize_filename($_FILES['the_file']['name']); if ($extfile = strrchr($_FILES['the_file']['name'], '.')) { if (!(stripos(',' . $allowedtemplateuploads . ',', ',' . substr($extfile, 1) . ',') === false)) { //Uploads the file into the appropriate directory if (!@move_uploaded_file($_FILES['the_file']['tmp_name'], $the_full_file_path)) { echo "<strong><font color='red'>" . $clang->gT("Error") . "</font></strong><br />\n"; echo sprintf($clang->gT("An error occurred uploading your file. This may be caused by incorrect permissions in your %s folder."), $tempdir) . "<br /><br />\n"; echo "<input type='submit' value='" . $clang->gT("Main Admin Screen") . "' onclick=\"window.open('{$scriptname}', '_top')\" />\n"; echo "</td></tr></table>\n"; echo "</body>\n</html>\n"; exit; } } else { // if we came here is because the file extention is not allowed @unlink($_FILES['the_file']['tmp_name']); echo "<strong><font color='red'>" . $clang->gT("Error") . "</font></strong><br />\n";
function upgrade_image_list() { $list = array(); $total = 0; // Strip 'images/' prefix from pictures table $sql = "UPDATE " . PLOGGER_TABLE_PREFIX . "pictures SET path = SUBSTRING(path,8) WHERE SUBSTRING(path,1,7) = 'images/'"; mysql_query($sql); // Update 'path' for collections table $sql = "SELECT id,name FROM " . PLOGGER_TABLE_PREFIX . "collections"; $result = mysql_query($sql); while ($row = mysql_fetch_assoc($result)) { $sql = "UPDATE " . PLOGGER_TABLE_PREFIX . "collections SET path = '" . strtolower(sanitize_filename($row['name'])) . "' WHERE id = " . $row['id']; mysql_query($sql); if (!file_exists(PLOGGER_DIR . 'plog-content/images/' . strtolower(sanitize_filename($row['name'])))) { $list[$total] = array('container' => 1, 'new_path' => 'plog-content/images/' . strtolower(sanitize_filename($row['name']))); $total++; } } // Update 'path' for albums table $sql = "SELECT a.id AS id, a.name AS name, c.path AS collection_path\n\t\t\t\t\tFROM " . PLOGGER_TABLE_PREFIX . "albums a, " . PLOGGER_TABLE_PREFIX . "collections c\n\t\t\t\t\tWHERE a.parent_id = c.id"; $result = mysql_query($sql); while ($row = mysql_fetch_assoc($result)) { $sql = "UPDATE " . PLOGGER_TABLE_PREFIX . "albums SET path = '" . strtolower(sanitize_filename($row['name'])) . "' WHERE id = " . $row['id']; mysql_query($sql); if (!file_exists(PLOGGER_DIR . 'plog-content/images/' . $row['collection_path'] . '/' . strtolower(sanitize_filename($row['name'])))) { $list[$total] = array('container' => 1, 'new_path' => 'plog-content/images/' . $row['collection_path'] . '/' . strtolower(sanitize_filename($row['name']))); $total++; } } // Loop through each image from the pictures table, get its parent album name and parent collection $sql = "SELECT p.path AS path, p.id AS pid,c.path AS collection_path, a.path AS album_path\n\t\t\tFROM " . PLOGGER_TABLE_PREFIX . "albums a, " . PLOGGER_TABLE_PREFIX . "pictures p, " . PLOGGER_TABLE_PREFIX . "collections c \n\t\t\tWHERE p.parent_album = a.id AND p.parent_collection = c.id"; $result = mysql_query($sql); while ($row = mysql_fetch_assoc($result)) { $filename = sanitize_filename(basename($row['path'])); $c_directory = $row['collection_path'] . '/'; $a_directory = $row['collection_path'] . '/' . $row['album_path'] . '/'; $new_path = $row['collection_path'] . '/' . $row['album_path'] . '/' . $filename; // If the file exists, grab the information and add to the total if (!file_exists(PLOGGER_DIR . 'plog-content/images/' . $new_path)) { // First see if it's in the old directory structure if (file_exists(PLOGGER_DIR . 'images/' . $row['path'])) { $path = 'images/'; // Next check the temporary folder location for closing folder permissions } else { if (file_exists(PLOGGER_DIR . 'plog-content/images-old/' . $row['path'])) { $path = 'plog-content/images-old/'; // Otherwise check if it's in the new structure, but set up without new sanitized paths } else { if (file_exists(PLOGGER_DIR . 'plog-content/images/' . $row['path'])) { $path = 'plog-content/images/'; } else { // Have no idea where the old image is $path = ''; } } } $list[$total] = array('id' => $row['pid'], 'old_path' => $path . $row['path'], 'new_path' => $new_path); $total++; } } // Add any photos from the uploads directory if (file_exists(PLOGGER_DIR . 'uploads/')) { $old_uploads = get_files(PLOGGER_DIR . 'uploads/', false, false, dirname(dirname(dirname(__FILE__))) . '/uploads/'); $new_uploads = get_files(PLOGGER_DIR . 'plog-content/uploads/', false, false, dirname(dirname(dirname(__FILE__))) . '/plog-content/uploads/'); // Compare the two paths for differences $compare_uploads = array_diff($old_uploads, $new_uploads); foreach ($compare_uploads as $uploads) { $list[$total] = array('uploads' => 1, 'old_path' => 'uploads/' . $uploads, 'new_path' => 'plog-content/uploads/' . $uploads); $total++; } } $list['total'] = $total; return $list; }
/** * 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) { global $siteadminname, $siteadminemail; Yii::app()->loadHelper("frontend"); Yii::import('application.libraries.admin.pdf'); $surveyid = (int) $surveyid; Yii::app()->loadHelper('database'); if (isset($_SESSION['survey_' . $surveyid]['sid'])) { $surveyid = $_SESSION['survey_' . $surveyid]['sid']; } else { die('Invalid survey/session'); } //Debut session time out if (!isset($_SESSION['survey_' . $surveyid]['finished']) || !isset($_SESSION['survey_' . $surveyid]['srid'])) { //require_once($rootdir.'/classes/core/language.php'); $baselang = Survey::model()->findByPk($surveyid)->language; Yii::import('application.libraries.Limesurvey_lang', true); $clang = new Limesurvey_lang($baselang); //A nice exit sendCacheHeaders(); doHeader(); echo templatereplace(file_get_contents(getTemplatePath(validateTemplateDir("default")) . "/startpage.pstpl"), array(), 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."), $siteadminname, $siteadminemail) . "\n" . "</center><br />\n"; echo templatereplace(file_get_contents(getTemplatePath(validateTemplateDir("default")) . "/endpage.pstpl"), array(), array()); doFooter(); exit; } //Fin session time out $id = $_SESSION['survey_' . $surveyid]['srid']; //I want to see the answers with this id $clang = $_SESSION['survey_' . $surveyid]['s_lang']; //Ensure script is not run directly, avoid path disclosure //if (!isset($rootdir) || isset($_REQUEST['$rootdir'])) {die( "browse - Cannot run this script directly");} // Set the language for dispay //require_once($rootdir.'/classes/core/language.php'); // has been secured if (isset($_SESSION['survey_' . $surveyid]['s_lang'])) { $clang = SetSurveyLanguage($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']); $language = $_SESSION['survey_' . $surveyid]['s_lang']; } else { $language = Survey::model()->findByPk($surveyid)->language; $clang = SetSurveyLanguage($surveyid, $language); } // Get the survey inforamtion $thissurvey = getSurveyInfo($surveyid, $language); //SET THE TEMPLATE DIRECTORY if (!isset($thissurvey['templatedir']) || !$thissurvey['templatedir']) { $thistpl = validateTemplateDir("default"); } else { $thistpl = validateTemplateDir($thissurvey['templatedir']); } if ($thissurvey['printanswers'] == 'N') { die; //Die quietly if print answers is not permitted } //CHECK IF SURVEY IS ACTIVATED AND EXISTS $surveytable = "{{survey_{$surveyid}}}"; $surveyname = $thissurvey['surveyls_title']; $anonymized = $thissurvey['anonymized']; //OK. IF WE GOT THIS FAR, THEN THE SURVEY EXISTS AND IT IS ACTIVE, SO LETS GET TO WORK. //SHOW HEADER $printoutput = ''; $printoutput .= "<form action='" . Yii::app()->getController()->createUrl('printanswers/view/surveyid/' . $surveyid . '/printableexport/pdf') . "' method='post'>\n<center><input type='submit' value='" . $clang->gT("PDF export") . "'id=\"exportbutton\"/><input type='hidden' name='printableexport' /></center></form>"; if ($printableexport == 'pdf') { require Yii::app()->getConfig('rootdir') . '/application/config/tcpdf.php'; Yii::import('application.libraries.admin.pdf', true); $pdf = new pdf(); $pdf->setConfig($tcpdf); //$pdf->SetFont($pdfdefaultfont,'',$pdffontsize); $pdf->AddPage(); //$pdf->titleintopdf($clang->gT("Survey name (ID)",'unescaped').": {$surveyname} ({$surveyid})"); $pdf->SetTitle($clang->gT("Survey name (ID)", 'unescaped') . ": {$surveyname} ({$surveyid})"); } $printoutput .= "\t<div class='printouttitle'><strong>" . $clang->gT("Survey name (ID):") . "</strong> {$surveyname} ({$surveyid})</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, $thissurvey['anonymized'] != "N", $surveyid); $aFullResponseTable = getFullResponseTable($surveyid, $id, $language, true); //Get the fieldmap @TODO: do we need to filter out some fields? unset($aFullResponseTable['id']); unset($aFullResponseTable['token']); unset($aFullResponseTable['lastpage']); unset($aFullResponseTable['startlanguage']); unset($aFullResponseTable['datestamp']); unset($aFullResponseTable['startdate']); $printoutput .= "<table class='printouttable' >\n"; if ($printableexport == 'pdf') { $pdf->intopdf($clang->gT("Question", 'unescaped') . ": " . $clang->gT("Your answer", 'unescaped')); } $oldgid = 0; $oldqid = 0; foreach ($aFullResponseTable as $sFieldname => $fname) { if (substr($sFieldname, 0, 4) == 'gid_') { if ($printableexport) { $pdf->intopdf(flattenText($fname[0], false, true)); $pdf->ln(2); } else { $printoutput .= "\t<tr class='printanswersgroup'><td colspan='2'>{$fname[0]}</td></tr>\n"; } } elseif (substr($sFieldname, 0, 4) == 'qid_') { if ($printableexport == 'pdf') { $pdf->intopdf(flattenText($fname[0] . $fname[1], false, true) . ": " . $fname[2]); $pdf->ln(2); } else { $printoutput .= "\t<tr class='printanswersquestionhead'><td colspan='2'>{$fname[0]}</td></tr>\n"; } } elseif ($sFieldname == 'submitdate') { if ($anonymized != 'Y') { if ($printableexport == 'pdf') { $pdf->intopdf(flattenText($fname[0] . $fname[1], false, true) . ": " . $fname[2]); $pdf->ln(2); } else { $printoutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]} {$sFieldname}</td><td class='printanswersanswertext'>{$fname[2]}</td></tr>"; } } } else { if ($printableexport == 'pdf') { $pdf->intopdf(flattenText($fname[0] . $fname[1], false, true) . ": " . $fname[2]); $pdf->ln(2); } else { $printoutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]}</td><td class='printanswersanswertext'>{$fname[2]}</td></tr>"; } } } $printoutput .= "</table>\n"; if ($printableexport == 'pdf') { header("Pragma: public"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); $sExportFileName = sanitize_filename($surveyname); $pdf->Output($sExportFileName . "-" . $surveyid . ".pdf", "D"); } //Display the page with user answers if (!$printableexport) { sendCacheHeaders(); doHeader(); echo templatereplace(file_get_contents(getTemplatePath($thistpl) . '/startpage.pstpl')); echo templatereplace(file_get_contents(getTemplatePath($thistpl) . '/printanswers.pstpl'), array('ANSWERTABLE' => $printoutput)); echo templatereplace(file_get_contents(getTemplatePath($thistpl) . '/endpage.pstpl')); echo "</body></html>"; } LimeExpressionManager::FinishProcessingGroup(); LimeExpressionManager::FinishProcessingPage(); }
/** * Function that initialises all data and call other functions to load default view. * * @access protected * @param string $templatename * @param string $screenname * @param string $editfile * @param bool $showsummary * @return */ protected function _initialise($templatename, $screenname, $editfile, $showsummary = true, $useindex = false) { // LimeSurvey style global $oEditedTemplate; $oEditedTemplate = Template::model()->getTemplateConfiguration($templatename); // In survey mode, bootstrap is loaded via the app init. // From template editor, we just add the bootstrap files to the js/css to load for template_helper::templatereplace() if ($oEditedTemplate->cssFramework == 'bootstrap') { // Core templates (are published only if exists) $oEditedTemplate->config->files->css->filename[] = "../../styles-public/bootstrap-for-template-editor.css"; $oEditedTemplate->config->files->js->filename[] = "../../scripts/bootstrap-for-template-editor.js"; // User templates (are published only if exists) $oEditedTemplate->config->files->css->filename[] = "../../../styles-public/bootstrap-for-template-editor.css"; $oEditedTemplate->config->files->js->filename[] = "../../../scripts/bootstrap-for-template-editor.js"; } //App()->getClientScript()->reset(); Yii::app()->loadHelper('surveytranslator'); Yii::app()->loadHelper('admin/template'); $files = $this->_initfiles($templatename); $cssfiles = $this->_initcssfiles($oEditedTemplate); // Standard Support Files // These files may be edited or saved $supportfiles[] = array('name' => 'print_img_radio.png'); $supportfiles[] = array('name' => 'print_img_checkbox.png'); // Standard screens // Only these may be viewed $screens[] = array('name' => gT('Survey List Page'), 'id' => 'surveylist'); $screens[] = array('name' => gT('Welcome Page'), 'id' => 'welcome'); $screens[] = array('name' => gT('Question Page'), 'id' => 'question'); $screens[] = array('name' => gT('Completed Page'), 'id' => 'completed'); $screens[] = array('name' => gT('Clear All Page'), 'id' => 'clearall'); $screens[] = array('name' => gT('Register Page'), 'id' => 'register'); $screens[] = array('name' => gT('Load Page'), 'id' => 'load'); $screens[] = array('name' => gT('Save Page'), 'id' => 'save'); $screens[] = array('name' => gT('Print answers page'), 'id' => 'printanswers'); $screens[] = array('name' => gT('Printable survey page'), 'id' => 'printablesurvey'); // Page display blocks $SurveyList = array('startpage.pstpl', 'surveylist.pstpl', 'endpage.pstpl'); $Welcome = array('startpage.pstpl', 'welcome.pstpl', 'privacy.pstpl', 'navigator.pstpl', 'endpage.pstpl'); $Question = array('startpage.pstpl', 'survey.pstpl', 'startgroup.pstpl', 'groupdescription.pstpl', 'question.pstpl', 'endgroup.pstpl', 'navigator.pstpl', 'endpage.pstpl'); $CompletedTemplate = array('startpage.pstpl', 'assessment.pstpl', 'completed.pstpl', 'endpage.pstpl'); $Clearall = array('startpage.pstpl', 'clearall.pstpl', 'endpage.pstpl'); $Register = array('startpage.pstpl', 'survey.pstpl', 'register.pstpl', 'endpage.pstpl'); $Save = array('startpage.pstpl', 'save.pstpl', 'endpage.pstpl'); $Load = array('startpage.pstpl', 'load.pstpl', 'endpage.pstpl'); $printtemplate = array('startpage.pstpl', 'printanswers.pstpl', 'endpage.pstpl'); $printablesurveytemplate = array('print_survey.pstpl', 'print_group.pstpl', 'print_question.pstpl'); $file_version = "LimeSurvey template editor " . Yii::app()->getConfig('versionnumber'); Yii::app()->session['s_lang'] = Yii::app()->session['adminlang']; $templatename = sanitize_dirname($templatename); $screenname = autoUnescape($screenname); // Checks if screen name is in the list of allowed screen names if (multiarray_search($screens, 'id', $screenname) === false) { Yii::app()->user->setFlash('error', gT('Invalid screen name')); $this->getController()->redirect(array("admin/templates/sa/upload")); } if (!isset($action)) { $action = sanitize_paranoid_string(returnGlobal('action')); } if (!isset($subaction)) { $subaction = sanitize_paranoid_string(returnGlobal('subaction')); } if (!isset($newname)) { $newname = sanitize_dirname(returnGlobal('newname')); } if (!isset($copydir)) { $copydir = sanitize_dirname(returnGlobal('copydir')); } if (is_file(Yii::app()->getConfig('usertemplaterootdir') . '/' . $templatename . '/question_start.pstpl')) { $files[] = array('name' => 'question_start.pstpl'); $Question[] = 'question_start.pstpl'; } $editfile = sanitize_filename($editfile); // Fixed with editable file after, but put in aData before fix $availableeditorlanguages = array('bg', 'cs', 'de', 'dk', 'en', 'eo', 'es', 'fi', 'fr', 'hr', 'it', 'ja', 'mk', 'nl', 'pl', 'pt', 'ru', 'sk', 'zh'); // 2.06 way of doing. if (!$useindex) { $extension = substr(strrchr($editfile, "."), 1); } else { // The extension is now set as a prefix separated by a _ $file_datas = explode("_", $editfile); $extension = $file_datas[0]; // The file name is now based on the index of the oTemplate files $file_index = $file_datas[1]; switch ($extension) { case 'css': $aTemplateFiles = (array) $oEditedTemplate->config->files_editable->css->filename; break; case 'js': $aTemplateFiles = (array) $oEditedTemplate->config->files_editable->js->filename; break; default: $aTemplateFiles = (array) $oEditedTemplate->config->files_editable->css->filename; break; } $editfile = $aTemplateFiles[$file_index]; } if ($extension == 'css' || $extension == 'js') { $highlighter = $extension; } else { $highlighter = 'html'; } if (in_array(Yii::app()->session['adminlang'], $availableeditorlanguages)) { $codelanguage = Yii::app()->session['adminlang']; } else { $codelanguage = 'en'; } $templates = getTemplateList(); if (!isset($templates[$templatename])) { $templatename = Yii::app()->getConfig('defaulttemplate'); } $normalfiles = array("DUMMYENTRY", ".", "..", "preview.png"); foreach ($files as $fl) { $normalfiles[] = $fl["name"]; } foreach ($cssfiles as $fl) { $normalfiles[] = $fl["name"]; } // Some global data $aData['sitename'] = Yii::app()->getConfig('sitename'); $siteadminname = Yii::app()->getConfig('siteadminname'); $siteadminemail = Yii::app()->getConfig('siteadminemail'); // Set this so common.php doesn't throw notices about undefined variables $thissurvey['active'] = 'N'; // FAKE DATA FOR TEMPLATES $thissurvey['name'] = gT("Template Sample"); $thissurvey['description'] = "<p>" . gT('This is a sample survey description. It could be quite long.') . "</p>" . "<p>" . gT("But this one isn't.") . "<p>"; $thissurvey['welcome'] = "<p>" . gT('Welcome to this sample survey') . "<p>" . "<p>" . gT('You should have a great time doing this') . "<p>"; $thissurvey['allowsave'] = "Y"; $thissurvey['active'] = "Y"; $thissurvey['tokenanswerspersistence'] = "Y"; $thissurvey['templatedir'] = $templatename; $thissurvey['format'] = "G"; $thissurvey['surveyls_url'] = "http://www.limesurvey.org/"; $thissurvey['surveyls_urldescription'] = gT("Some URL description"); $thissurvey['usecaptcha'] = "A"; $percentcomplete = makegraph(6, 10); $groupname = gT("Group 1: The first lot of questions"); $groupdescription = gT("This group description is fairly vacuous, but quite important."); $navigator = $this->getController()->render('/admin/templates/templateeditor_navigator_view', array('screenname' => $screenname), true); $completed = $this->getController()->render('/admin/templates/templateeditor_completed_view', array(), true); $assessments = $this->getController()->render('/admin/templates/templateeditor_assessments_view', array(), true); $printoutput = $this->getController()->render('/admin/templates/templateeditor_printoutput_view', array(), true); $totalquestions = '10'; $surveyformat = 'Format'; $notanswered = '5'; $privacy = ''; $surveyid = '1295'; $token = 1234567; $templatedir = $oEditedTemplate->viewPath; $templateurl = getTemplateURL($templatename); // Save these variables in an array $aData['thissurvey'] = $thissurvey; $aData['percentcomplete'] = $percentcomplete; $aData['groupname'] = $groupname; $aData['groupdescription'] = $groupdescription; $aData['navigator'] = $navigator; $aData['help'] = gT("This is some help text."); $aData['surveyformat'] = $surveyformat; $aData['totalquestions'] = $totalquestions; $aData['completed'] = $completed; $aData['notanswered'] = $notanswered; $aData['privacy'] = $privacy; $aData['surveyid'] = $surveyid; $aData['sid'] = $surveyid; $aData['token'] = $token; $aData['assessments'] = $assessments; $aData['printoutput'] = $printoutput; $aData['templatedir'] = $templatedir; $aData['templateurl'] = $templateurl; $aData['templatename'] = $templatename; $aData['screenname'] = $screenname; $aData['editfile'] = $editfile; $myoutput[] = ""; switch ($screenname) { case 'surveylist': unset($files); $surveylist = array("nosid" => gT("You have not provided a survey identification number"), "contact" => sprintf(gT("Please contact %s ( %s ) for further assistance."), Yii::app()->getConfig("siteadminname"), Yii::app()->getConfig("siteadminemail")), "listheading" => gT("The following surveys are available:"), "list" => $this->getController()->render('/admin/templates/templateeditor_surveylist_view', array(), true)); $aData['surveylist'] = $surveylist; $myoutput[] = ""; //$myoutput[] = templatereplace(file_get_contents("$templatedir/startpage.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate); foreach ($SurveyList as $qs) { $files[] = array("name" => $qs); $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/{$qs}", $aData, $oEditedTemplate)); } break; case 'question': unset($files); foreach ($Question as $qs) { $files[] = array("name" => $qs); } $myoutput[] = $this->getController()->render('/admin/templates/templateeditor_question_meta_view', array(), true); $aData['aReplacements'] = array('SAVE_LINKS' => '<li><a href="#" id="saveallbtnlink">Resume later</a></li>', 'CLEARALL_LINKS' => '<li><a href="#" id="clearallbtnlink">' . gT("Exit and clear survey") . '</a></li>'); $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/startpage.pstpl", $aData, $oEditedTemplate)); $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/survey.pstpl", $aData, $oEditedTemplate)); $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/startgroup.pstpl", $aData, $oEditedTemplate)); $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/groupdescription.pstpl", $aData, $oEditedTemplate)); $aReplacements = array('QUESTION_TEXT' => gT("How many roads must a man walk down?"), 'QUESTION_CODE' => '1a', 'QUESTIONHELP' => 'helpful text', 'QUESTION_MANDATORY' => gT("*"), 'QUESTION_MAN_CLASS' => ' mandatory', 'QUESTION_ESSENTIALS' => 'id="question1"', 'QUESTION_CLASS' => 'list-radio', 'QUESTION_NUMBER' => '1'); $aReplacements['ANSWER'] = $this->getController()->render('/admin/templates/templateeditor_question_answer_view', array(), true); $aData['aReplacements'] = $aReplacements; $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/question.pstpl", $aData, $oEditedTemplate)); $aReplacements = array('QUESTION_TEXT' => gT('Please explain something in detail:'), 'QUESTION_CODE' => '2a', 'QUESTION_ESSENTIALS' => 'id="question2"', 'QUESTION_CLASS' => 'text-long', 'QUESTION_NUMBER' => '2'); $aReplacements['ANSWER'] = $this->getController()->render('/admin/templates/templateeditor_question_answer_view', array('alt' => true), true); $aData['aReplacements'] = $aReplacements; $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/question.pstpl", $aData, $oEditedTemplate)); $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/endgroup.pstpl", $aData, $oEditedTemplate)); $aData['aReplacements'] = array('MOVEPREVBUTTON' => '<button type="submit" id="moveprevbtn" value="moveprev" name="moveprev" accesskey="p" class="submit button btn btn-default btn-lg ">Previous</button>', 'MOVENEXTBUTTON' => '<button type="submit" id="movenextbtn" value="movenext" name="movenext" accesskey="n" class="submit button btn btn-default btn-lg ">Next</button>'); $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/navigator.pstpl", $aData, $oEditedTemplate)); $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/endpage.pstpl", $aData, $oEditedTemplate)); break; case 'welcome': unset($files); foreach ($Welcome as $qs) { $files[] = array("name" => $qs); $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/{$qs}", $aData, $oEditedTemplate)); } /* $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/startpage.pstpl", $aData, $oEditedTemplate)); $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/welcome.pstpl", $aData, $oEditedTemplate)); $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/privacy.pstpl", $aData, $oEditedTemplate)); */ $aData['aReplacements'] = array('MOVENEXTBUTTON' => '<button type="submit" id="movenextbtn" value="movenext" name="movenext" accesskey="n" class="submit button btn btn-default btn-lg">Next</button>'); $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/navigator.pstpl", $aData, $oEditedTemplate)); $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/endpage.pstpl", $aData, $oEditedTemplate)); break; case 'register': unset($files); foreach ($Register as $qs) { $files[] = array("name" => $qs); } $myoutput[] = templatereplace(file_get_contents("{$templatedir}/startpage.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate); $aData = array('aReplacements' => array('SURVEYNAME' => 'Survey name')); $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/survey.pstpl", $aData, $oEditedTemplate)); $aData['aReplacements'] = array('REGISTERERROR' => 'Example error message', 'REGISTERMESSAGE1' => 'Register message 1', 'REGISTERMESSAGE2' => 'Register message 2', 'REGISTERFORM' => $this->getController()->render('/admin/templates/templateeditor_register_view', array('alt' => true), true)); $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/register.pstpl", $aData, $oEditedTemplate)); $myoutput[] = templatereplace(file_get_contents("{$templatedir}/endpage.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate); $myoutput[] = "\n"; break; case 'save': unset($files); foreach ($Save as $qs) { $files[] = array("name" => $qs); } $myoutput[] = templatereplace(file_get_contents("{$templatedir}/startpage.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate); $myoutput[] = templatereplace(file_get_contents("{$templatedir}/save.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate); $myoutput[] = templatereplace(file_get_contents("{$templatedir}/endpage.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate); $myoutput[] = "\n"; break; case 'load': unset($files); foreach ($Load as $qs) { $files[] = array("name" => $qs); } $myoutput[] = templatereplace(file_get_contents("{$templatedir}/startpage.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate); $myoutput[] = templatereplace(file_get_contents("{$templatedir}/load.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate); $myoutput[] = templatereplace(file_get_contents("{$templatedir}/endpage.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate); $myoutput[] = "\n"; break; case 'clearall': unset($files); foreach ($Clearall as $qs) { $files[] = array("name" => $qs); } $myoutput[] = templatereplace(file_get_contents("{$templatedir}/startpage.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate); $myoutput[] = templatereplace(file_get_contents("{$templatedir}/clearall.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate); $myoutput[] = templatereplace(file_get_contents("{$templatedir}/endpage.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate); $myoutput[] = "\n"; break; case 'completed': unset($files); $myoutput[] = ""; foreach ($CompletedTemplate as $qs) { $files[] = array("name" => $qs); $myoutput = array_merge($myoutput, doreplacement($oEditedTemplate->viewPath . "/{$qs}", $aData, $oEditedTemplate)); } break; case 'printablesurvey': unset($files); foreach ($printablesurveytemplate as $qs) { $files[] = array("name" => $qs); } $questionoutput = array(); foreach (file("{$templatedir}/print_question.pstpl") as $op) { $questionoutput[] = templatereplace($op, array('QUESTION_NUMBER' => '1', 'QUESTION_CODE' => 'Q1', 'QUESTION_MANDATORY' => gT('*'), 'QUESTION_SCENARIO' => 'Only answer this if certain conditions are met.', 'QUESTION_CLASS' => ' mandatory list-radio', 'QUESTION_TYPE_HELP' => gT('Please choose *only one* of the following:'), 'QUESTION_MAN_MESSAGE' => '', 'QUESTION_VALID_MESSAGE' => '', 'QUESTION_FILE_VALID_MESSAGE' => '', 'QUESTION_TEXT' => gT('This is a sample question text. The user was asked to pick an entry.'), 'QUESTIONHELP' => gT('This is some help text for this question.'), 'ANSWER' => $this->getController()->render('/admin/templates/templateeditor_printablesurvey_quesanswer_view', array('templateurl' => $templateurl), true)), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate); } $groupoutput = array(); $groupoutput[] = templatereplace(file_get_contents("{$templatedir}/print_group.pstpl"), array('QUESTIONS' => implode(' ', $questionoutput)), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate); $myoutput[] = templatereplace(file_get_contents("{$templatedir}/print_survey.pstpl"), array('GROUPS' => implode(' ', $groupoutput), 'FAX_TO' => gT("Please fax your completed survey to:") . " 000-000-000", 'SUBMIT_TEXT' => gT("Submit your survey."), 'HEADELEMENTS' => getPrintableHeader(), 'SUBMIT_BY' => sprintf(gT("Please submit by %s"), date('d.m.y')), 'THANKS' => gT('Thank you for completing this survey.'), 'END' => gT('This is the survey end message.')), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate); break; case 'printanswers': unset($files); foreach ($printtemplate as $qs) { $files[] = array("name" => $qs); } $myoutput[] = templatereplace(file_get_contents("{$templatedir}/startpage.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate); $myoutput[] = templatereplace(file_get_contents("{$templatedir}/printanswers.pstpl"), array('ANSWERTABLE' => $printoutput), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate); $myoutput[] = templatereplace(file_get_contents("{$templatedir}/endpage.pstpl"), array(), $aData, 'Unspecified', false, NULL, array(), false, $oEditedTemplate); $myoutput[] = "\n"; break; } $myoutput[] = "</html>"; $jsfiles = $this->_getEditableJsFiles($oEditedTemplate); if (is_array($files)) { $match = 0; foreach ($files as $f) { if ($editfile == $f["name"]) { $match = 1; } } $aCssAndJsfiles = array_merge($cssfiles, $jsfiles); foreach ($aCssAndJsfiles as $f) { if ($editfile == $f["name"]) { $match = 1; } } if ($match == 0) { if (count($files) > 0) { $editfile = $files[0]["name"]; } else { $editfile = ""; } } } // Get list of 'otherfiles' // We can't use $oTemplate->otherFiles, because of retrocompatibility with 2.06 template and the big mess of it mixing files $filesdir = $oEditedTemplate->filesPath != '' ? $oEditedTemplate->filesPath : $templatedir . '../files'; $otherfiles = array(); if (file_exists($filesdir) && ($handle = opendir($filesdir))) { while (false !== ($file = readdir($handle))) { if (!array_search($file, $normalfiles)) { if (!is_dir($templatedir . DIRECTORY_SEPARATOR . $file)) { $otherfiles[] = array("name" => $file); } } } closedir($handle); } $aData['codelanguage'] = $codelanguage; $aData['highlighter'] = $highlighter; $aData['screens'] = $screens; $aData['templatename'] = $templatename; $aData['templates'] = $templates; $aData['editfile'] = $editfile; $aData['screenname'] = $screenname; $aData['tempdir'] = Yii::app()->getConfig('tempdir'); $aData['usertemplaterootdir'] = Yii::app()->getConfig('usertemplaterootdir'); $aViewUrls['templateeditorbar_view'][] = $aData; if ($showsummary) { //$aCssfileseditable = (array) $oEditedTemplate->config->files_editable->css->filename; $aViewUrls = array_merge($aViewUrls, $this->_templatesummary($templatename, $screenname, $editfile, $templates, $files, $cssfiles, $jsfiles, $otherfiles, $myoutput)); } App()->getClientScript()->registerScriptFile(App()->getAssetManager()->publish(ADMIN_SCRIPT_PATH . 'admin_core.js')); return $aViewUrls; }
// Check if update has been clicked, handle erroneous conditions, or upload if (isset($_REQUEST['upload'])) { foreach ($_REQUEST as $key => $val) { $_REQUEST[$key] = stripslashes($val); } $pi = pathinfo($_FILES['userfile']['name']); if ($_FILES['userfile']['name'] == '') { $output .= "\n\t" . '<p class="errors">' . plog_tr('No filename specified') . '!</p>' . "\n"; } else { if (strtolower($pi['extension']) == 'zip') { // Let's decompress the zip file into the 'plog-content/uploads/' folder and then redirect the user to plog-import.php include PLOGGER_DIR . 'plog-includes/lib/pclzip-2-4/pclzip.lib.php'; // Zip file to extract $archive = new PclZip($_FILES['userfile']['tmp_name']); // Create a temporary folder in 'plog-content/uploads/' based on the .zip file name $zipname = strtolower(sanitize_filename(substr($_FILES['userfile']['name'], 0, -4))); $zipdir = $config['basedir'] . 'plog-content/uploads/' . $zipname; $zipdirkey = md5($zipdir); $zipresult = makeDirs($zipdir); if (is_safe_mode()) { chmod_ftp($zipdir, 0777); } // Extract to 'plog-content/uploads/' folder $results = $archive->extract(PCLZIP_OPT_REMOVE_ALL_PATH, PCLZIP_OPT_PATH, $zipdir); if (is_safe_mode()) { chmod_ftp($zipdir); } if ($results == 0) { // Failed $output .= "\n\t" . '<p class="errors">' . plog_tr('Error') . ': ' . $archive->errorInfo(true) . '</p>' . "\n"; } else {
$key = intval($key); if ($value != "0_1") { $file_keys .= ($file_keys ? ":" : "") . $key . "_" . intval($value); $file_keywords[$key] = intval($value); } else { $file_error["keywords"][$key] = 1; } } } //starts upload of file if (!is_uploaded_file($_FILES["file"]["tmp_name"])) { $file_error["file"] = $BL['be_fprivup_err1']; } elseif ($_FILES["file"]["size"] > $phpwcms["file_maxsize"]) { $file_error["file"] = $BL['be_fprivup_err2'] . " " . number_format($phpwcms["file_maxsize"] / 1024, 2, ',', '.') . " kB"; } else { $fileName = sanitize_filename($_FILES["file"]["name"]); $fileExt = check_image_extension($_FILES["file"]["tmp_name"], $fileName); $fileExt = $fileExt === false ? which_ext($fileName) : $fileExt; $fileHash = md5($fileName . microtime()); $fileType = is_mimetype_format($_FILES["file"]["type"]) ? $_FILES["file"]["type"] : get_mimetype_by_extension($fileExt); $fileSize = intval($_FILES["file"]["size"]); // Check against forbidden file names $forbiddenUploadName = array('.htaccess', 'web.config', 'lighttpd.conf', 'nginx.conf'); if (in_array(strtolower($fileName), $forbiddenUploadName)) { $file_error["file"] = sprintf($BL['be_fprivup_err7'], $fileName); } // Only allowed file extensions if (empty($file_error["file"])) { if (is_string($phpwcms['allowed_upload_ext'])) { $phpwcms['allowed_upload_ext'] = convertStringToArray(strtolower($phpwcms['allowed_upload_ext'])); }
$POST_val[$POST_name]['name'] = ''; $cnt_form['upload_value']['exclude'] = str_replace(' ', '', $cnt_form['upload_value']['exclude']); $cnt_form['upload_value']['exclude'] = str_replace('.', '', $cnt_form['upload_value']['exclude']); $cnt_form['upload_value']['exclude'] = explode(',', $cnt_form['upload_value']['exclude']); $cnt_form['upload_value']['exclude'] = array_diff($cnt_form['upload_value']['exclude'], array('')); $cnt_form['upload_value']['exclude'] = implode('|', $cnt_form['upload_value']['exclude']); $cnt_form['upload_value']['exclude'] = strtolower($cnt_form['upload_value']['exclude']); $cnt_form['upload_value']['regexp'] = '/(.' . $cnt_form['upload_value']['exclude'] . ')$/'; if ($cnt_form["fields"][$key]['required'] && empty($_FILES[$POST_name]['name'])) { $POST_ERR[$key] = $cnt_form["fields"][$key]['error']; $POST_ERR[$key] = str_replace('{MAXLENGTH}', '', $POST_ERR[$key]); $POST_ERR[$key] = str_replace('{FILESIZE}', fsize(0, ' '), $POST_ERR[$key]); $POST_ERR[$key] = str_replace('{FILENAME}', '"n.a."', $POST_ERR[$key]); $POST_ERR[$key] = str_replace('{FILEEXT}', '"n.a."', $POST_ERR[$key]); } elseif (!empty($_FILES[$POST_name]['name'])) { $cnt_form['upload_value']['filename'] = time() . '_' . sanitize_filename($_FILES[$POST_name]['name']); if (!empty($cnt_form['upload_value']['maxlength']) && $_FILES[$POST_name]['size'] > intval($cnt_form['upload_value']['maxlength']) || preg_match($cnt_form['upload_value']['regexp'], strtolower($_FILES[$POST_name]['name'])) || !@move_uploaded_file($_FILES[$POST_name]['tmp_name'], PHPWCMS_ROOT . '/' . $cnt_form['upload_value']['folder'] . '/' . $cnt_form['upload_value']['filename'])) { $POST_ERR[$key] = $cnt_form["fields"][$key]['error']; $POST_ERR[$key] = str_replace('{MAXLENGTH}', empty($cnt_form['upload_value']['maxlength']) ? '' : fsize($cnt_form['upload_value']['maxlength'], ' '), $POST_ERR[$key]); $POST_ERR[$key] = str_replace('{FILESIZE}', fsize(empty($_FILES[$POST_name]['size']) ? 0 : $_FILES[$POST_name]['size'], ' '), $POST_ERR[$key]); $POST_ERR[$key] = str_replace('{FILENAME}', empty($_FILES[$POST_name]['name']) || trim($_FILES[$POST_name]['name']) == '' ? '"n.a."' : $_FILES[$POST_name]['name'], $POST_ERR[$key]); $POST_ERR[$key] = str_replace('{FILEEXT}', '.' . str_replace('|', ', .', str_replace(',', ', .', $cnt_form['upload_value']['exclude'])), $POST_ERR[$key]); } else { $POST_val[$POST_name]['name'] = $cnt_form['upload_value']['filename']; @chmod(PHPWCMS_ROOT . '/' . $cnt_form['upload_value']['folder'] . '/' . $cnt_form['upload_value']['filename'], 0644); } } if (isset($POST_ERR[$key])) { @unlink($_FILES[$POST_name]['tmp_name']); @unlink(PHPWCMS_ROOT . '/' . $cnt_form['upload_value']['folder'] . '/' . $cnt_form['upload_value']['filename']); $cnt_form["fields"][$key]['class'] = getFieldErrorClass($value['class'], $cnt_form["error_class"]);
/** * Responsible to import a template file. * * @access public * @return void */ public function uploadfile() { if (!Permission::model()->hasGlobalPermission('templates', 'import')) { die('No permission'); } $clang = $this->getController()->lang; $action = returnGlobal('action'); $editfile = returnGlobal('editfile'); $templatename = returnGlobal('templatename'); $screenname = returnGlobal('screenname'); $files = $this->_initfiles($templatename); $cssfiles = $this->_initcssfiles(); $basedestdir = Yii::app()->getConfig('usertemplaterootdir'); $tempdir = Yii::app()->getConfig('tempdir'); $allowedtemplateuploads = Yii::app()->getConfig('allowedtemplateuploads'); $filename = sanitize_filename($_FILES['upload_file']['name'], false, false); // Don't force lowercase or alphanumeric $fullfilepath = $basedestdir . "/" . $templatename . "/" . $filename; if ($action == "templateuploadfile") { if (Yii::app()->getConfig('demoMode')) { $uploadresult = $clang->gT("Demo mode: Uploading template files is disabled."); } elseif ($filename != $_FILES['upload_file']['name']) { $uploadresult = $clang->gT("This filename is not allowed to be uploaded."); } elseif (!in_array(strtolower(substr(strrchr($filename, '.'), 1)), explode(",", $allowedtemplateuploads))) { $uploadresult = $clang->gT("This file type is not allowed to be uploaded."); } else { //Uploads the file into the appropriate directory if (!@move_uploaded_file($_FILES['upload_file']['tmp_name'], $fullfilepath)) { $uploadresult = sprintf($clang->gT("An error occurred uploading your file. This may be caused by incorrect permissions in your %s folder."), $tempdir); } else { $uploadresult = sprintf($clang->gT("File %s uploaded"), $filename); } } Yii::app()->session['flashmessage'] = $uploadresult; } $this->getController()->redirect(array("admin/templates/sa/view/editfile/" . $editfile . "/screenname/" . $screenname . "/templatename/" . $templatename)); }
function saveUploadedFile($file, $target, $exttype = '', $imgtype = '', $rename = 0, $maxsize = 0) { // imgtype can be all exif_imagetype supported by your PHP install // see http://www.php.net/exif_imagetype $file_status = array('status' => false, 'error' => '', 'name' => '', 'tmp_name' => '', 'size' => 0, 'path' => '', 'ext' => '', 'rename' => '', 'maxsize' => intval($maxsize), 'error_num' => 0, 'type' => ''); if (!isset($_FILES[$file]) || !is_uploaded_file($_FILES[$file]['tmp_name'])) { $file_status['error'] = 'Upload not defined'; return $file_status; } $file_status['name'] = sanitize_filename($_FILES[$file]['name']); $file_status['ext'] = which_ext($file_status['name']); $file_status['tmp_name'] = $_FILES[$file]['tmp_name']; $file_status['size'] = $_FILES[$file]['size']; $file_status['type'] = empty($_FILES[$file]['type']) || !is_mimetype_format($_FILES[$file]['type']) ? get_mimetype_by_extension($file_status['ext']) : $_FILES[$file]['type']; $file_status['path'] = $target; $file_status['rename'] = $file_status['name']; $file_status['maxsize'] = empty($file_status['maxsize']) ? $GLOBALS['phpwcms']['file_maxsize'] : $file_status['maxsize']; if (intval($file_status['size']) > $file_status['maxsize']) { $file_status['error'] = 'File is too large'; $file_status['error_num'] = 400; return $file_status; } if (empty($target)) { $file_status['error'] = 'Target directory not defined'; $file_status['error_num'] = 412; return $file_status; } if (!@_mkdir($target)) { $file_status['error'] = 'The target directory "' . $target . '" can not be found or generated'; $file_status['error_num'] = 412; return $file_status; } if ($_FILES[$file]['error']) { $file_status['error'] = $_FILES[$file]['error']; $file_status['error_num'] = 409; return $file_status; } if ($imgtype) { $imgtype = convertStringToArray(strtolower($imgtype)); if (count($imgtype)) { $data = @getimagesize($_FILES[$file]['tmp_name']); $exif_imagetype = array(1 => 'gif', 2 => 'jpeg', 2 => 'jpg', 3 => 'png', 4 => 'swf', 5 => 'psd', 6 => 'bmp', 7 => 'tif', 8 => 'tiff', 9 => 'jpc', 10 => 'jp2', 11 => 'jpx', 12 => 'jb2', 13 => 'swc', 14 => 'iff', 15 => 'wbmp', 16 => 'xbm'); if (!$data && !$exttype) { $file_status['error'] = 'Format' . ($file_status['ext'] ? ' *.' . $file_status['ext'] : '') . ' not supported ('; $allowed = array(); foreach ($imgtype as $value) { $allowed[] = '*.' . $exif_imagetype[$value]; } $file_status['error'] .= implode(', ', $allowed) . ')'; $file_status['error_num'] = 415; @unlink($_FILES[$file]['tmp_name']); return $file_status; } elseif ($data) { if (empty($exif_imagetype[$data[2]]) || !in_array($data[2], $imgtype)) { $file_status['error'] = 'File type '; $file_status['error'] .= empty($exif_imagetype[$data[2]]) ? $data[2] : $exif_imagetype[$data[2]]; $file_status['error'] .= ' is not supported for this upload ('; foreach ($imgtype as $imgt) { $file_status['error'] .= empty($exif_imagetype[$imgt]) ? $imgt : $exif_imagetype[$imgt]; $file_status['error'] .= ', '; } $file_status['error'] = trim(trim($file_status['error']), ','); $file_status['error'] .= ' only)'; $file_status['error_num'] = 415; @unlink($_FILES[$file]['tmp_name']); return $file_status; } $file_status['image'] = $data; $exttype = ''; } } } if ($exttype) { $exttype = convertStringToArray(strtolower($exttype)); if (!in_array($file_status['ext'], $exttype)) { $file_status['error'] = 'File type *.' . $file_status['ext'] . ' is not supported for this upload (*.' . implode(', *.', $exttype) . ' only)'; $file_status['error_num'] = 415; @unlink($_FILES[$file]['tmp_name']); return $file_status; } } if (!is_writable($target)) { $file_status['error'] = 'Target directory <b>' . str_replace(PHPWCMS_ROOT, '', $target) . '</b> is not writable'; $file_status['error_num'] = 412; @unlink($_FILES[$file]['tmp_name']); return $file_status; } $rename = convertStringToArray($rename); if (count($rename)) { $_temp_name = cut_ext($file_status['rename']); foreach ($rename as $value) { switch ($value) { case 1: $_temp_name = str_replace(array(':', '/', "\\", ' '), array('-', '-', '-', '_'), phpwcms_remove_accents($_temp_name)); $_temp_name = preg_replace('/[^0-9a-z_\\-\\.]/i', '', $_temp_name); break; case 2: $_temp_name = time() . '_' . $_temp_name; break; case 3: $_temp_name = date('Ymd-His') . '_' . $_temp_name; break; case 4: $_temp_name = date('Ymd') . '_' . $_temp_name; break; case 5: $_temp_name = generic_string(6) . '_' . $_temp_name; break; case 6: $_temp_name = md5($_temp_name . ($file_status['ext'] ? '.' . $file_status['ext'] : '')); break; case 7: $_temp_name = shortHash($_temp_name . ($file_status['ext'] ? '.' . $file_status['ext'] : '')); break; } } $file_status['rename'] = $_temp_name . ($file_status['ext'] ? '.' . $file_status['ext'] : ''); } @umask(0); if (!@move_uploaded_file($_FILES[$file]['tmp_name'], $target . $file_status['rename'])) { if (!copy($_FILES[$file]['tmp_name'], $target . $file_status['rename'])) { $file_status['error'] = 'Saving uploaded file <b>' . html($file_status['name']) . '</b> to <b>' . html(str_replace(PHPWCMS_ROOT, '', $target . $file_status['rename'])) . '</b> failed'; $file_status['error_num'] = 412; @unlink($_FILES[$file]['tmp_name']); return $file_status; } } @chmod($target . $file_status['rename'], 0644); $file_status['status'] = true; return $file_status; }
} else { @session_name($stg_SessionName . '-runtime-publicportal'); } } else { session_name("LimeSurveyRuntime-{$surveyid}"); } session_set_cookie_params(0, $relativeurl . '/admin/'); @session_start(); $baselang = GetBaseLanguageFromSurveyID($surveyid); $clang = new limesurvey_lang($baselang); if (empty($_SESSION) || !isset($_SESSION['fieldname'])) { die("You don't have a valid session !"); } $sFieldname = $_GET['fieldname']; $sFilename = sanitize_filename($_GET['filename']); $sOriginalFileName = sanitize_filename($_GET['name']); if (substr($sFilename, 0, 6) == 'futmp_') { $sFileDir = $tempdir . '/upload/'; } elseif (substr($sFilename, 0, 3) == 'fu_') { $sFileDir = "{$uploaddir}/surveys/{$surveyid}/files/"; } else { die('Invalid filename'); } $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;
function update_album($album_id, $name, $description, $thumbnail_id = 0) { global $config; $errors = $output = ""; $target_name = strtolower(sanitize_filename($name)); $album_id = intval($album_id); $thumbnail_id = intval($thumbnail_id); $name = mysql_real_escape_string(SmartStripSlashes($name)); $description = mysql_real_escape_string(SmartStripSlashes($description)); // first, get the album name and collection name of our source album $sql = "SELECT c.path AS collection_path, a.path AS album_path\r\n\t\t\tFROM " . TABLE_PREFIX . "albums a, " . TABLE_PREFIX . "collections c\r\n\t\t\tWHERE c.id = a.parent_id AND a.id = '{$album_id}'"; $result = run_query($sql); $row = mysql_fetch_assoc($result); $source_album_name = SmartStripSlashes($row["album_path"]); $source_collection_name = SmartStripSlashes($row["collection_path"]); $source_path = $config['basedir'] . "images/" . $source_collection_name . "/" . $source_album_name; $target_path = $config['basedir'] . "images/" . $source_collection_name . "/" . $target_name; // perform the rename on the directory if (!rename($source_path, $target_path)) { return array("errors" => sprintf(plog_tr("Error renaming directory! (%s to %s)"), $source_path, $target_path)); } $target_name = mysql_real_escape_string($target_name); // proceed only if rename succeeded $query = "UPDATE " . TABLE_PREFIX . "albums SET\r\n\t\t\tname = '{$name}',\r\n\t\t\tdescription = '{$description}',\r\n\t\t\tthumbnail_id = '{$thumbnail_id}',\r\n\t\t\tpath = '{$target_name}'\r\n\t\t WHERE id='{$album_id}'"; $result = mysql_query($query); if (!$result) { return array("errors" => mysql_error()); } $output .= plog_tr('You have successfully modified the selected album.'); // update the path field for all pictures within that album $sql = "SELECT p.path AS path, p.id AS id,c.name AS collection_name, a.name AS album_name\r\n\t\t\tFROM " . TABLE_PREFIX . "albums a, " . TABLE_PREFIX . "pictures p, " . TABLE_PREFIX . "collections c\r\n\t\t\tWHERE p.parent_album = a.id AND p.parent_collection = c.id AND p.parent_album = '{$album_id}'"; $result = run_query($sql); while ($row = mysql_fetch_assoc($result)) { $filename = basename($row['path']); $new_path = $source_collection_name . "/" . $target_name . "/" . $filename; // update database $sql = "UPDATE " . TABLE_PREFIX . "pictures SET path = '{$new_path}' WHERE id = '{$row['id']}'"; mysql_query($sql) or $errors .= mysql_error(); } return array("errors" => $errors, "output" => $output); }
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); // Settings //$cleanupTargetDir = false; // Remove old files //$maxFileAge = 60 * 60; // Temp file age in seconds // 5 minutes execution time @set_time_limit(5 * 60); // Uncomment this one to fake upload time // usleep(5000); // Get parameters $chunk = isset($_REQUEST["chunk"]) ? $_REQUEST["chunk"] : 0; $chunks = isset($_REQUEST["chunks"]) ? $_REQUEST["chunks"] : 0; $fileName = sanitize_filename(isset($_REQUEST["name"]) ? $_REQUEST["name"] : ''); // Clean the fileName for security reasons $fileName = preg_replace('/[^\\w\\._]+/', '', $fileName); // Make sure the fileName is unique but only if chunking is disabled if ($chunks < 2 && file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName)) { $ext = strrpos($fileName, '.'); $fileName_a = substr($fileName, 0, $ext); $fileName_b = substr($fileName, $ext); $count = 1; while (file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName_a . '_' . $count . $fileName_b)) { $count++; } $fileName = $fileName_a . '_' . $count . $fileName_b; } // Create target dir if (!file_exists($targetDir)) {
require_once "_fonctions.php"; $uploadDir = $_POST["path"]; $extensions = explode(",", $_POST["exts"]); $badExtensions = array("php", "php3", "php4", "php5", "php7", "js", "asp"); $imagesExtentions = array("jpg", "jpeg", "gif", "png"); if (!(int) $_POST["wMax"]) { $_POST["wMax"] = 0; } if (!(int) $_POST["hMax"]) { $_POST["hMax"] = 0; } if (!empty($_FILES)) { $tempFile = $_FILES['Filedata']['tmp_name']; $fileParts = pathinfo($_FILES['Filedata']['name']); $extensionFile = strtolower($fileParts['extension']); $fileName = sanitize_filename($fileParts["filename"]); $targetFileName = $fileName . "." . $extensionFile; $targetFile = $uploadDir . $targetFileName; $targetFileFromRacine = str_replace("../", "", $targetFile); $idResultat = 0; if (!in_array($extensionFile, $extensions)) { $idResultat = 1; } if (in_array($extensionFile, $badExtensions)) { $idResultat = 2; } // si pas d'erreurs détectées, on uploader le fichier if ($idResultat == 0) { if (move_uploaded_file($tempFile, $targetFile)) { // Redimnesionnement Image principal ////////////////////////////// list($width_targetFile, $height_targetFile) = getimagesize($targetFile);
function vmstat_cachefile($options) { return sanitize_filename($options, array('host'), 'vmstat'); }
/** * 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)) { $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'])) { 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"; $sData['thissurvey'] = $aSurveyInfo; $sOutput = templatereplace($sOutput, array(), $sData, '', $aSurveyInfo['anonymized'] == "Y", NULL, array(), true); // Do a static replacement 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 { ob_start(function ($buffer, $phase) { App()->getClientScript()->render($buffer); App()->getClientScript()->reset(); return $buffer; }); ob_implicit_flush(false); sendCacheHeaders(); doHeader(); 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(); }
/** * 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)) { $sLanguage = Survey::model()->findByPk($iSurveyID)->language; } else { $iSurveyID = 0; $sLanguage = Yii::app()->getConfig("defaultlang"); } SetSurveyLanguage($iSurveyID, $sLanguage); $aSurveyInfo = getSurveyInfo($iSurveyID, $sLanguage); $oTemplate = Template::model()->getInstance(null, $iSurveyID); //Survey is not finished or don't exist if (!isset($_SESSION['survey_' . $iSurveyID]['finished']) || !isset($_SESSION['survey_' . $iSurveyID]['srid'])) { sendCacheHeaders(); doHeader(); /// $oTemplate is a global variable defined in controller/survey/index echo templatereplace(file_get_contents($oTemplate->viewPath . '/startpage.pstpl'), array()); echo "<center><br />\n" . "\t<font color='RED'><strong>" . gT("Error") . "</strong></font><br />\n" . "\t" . gT("We are sorry but your session has expired.") . "<br />" . 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(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($oTemplate->viewPath . '/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");} //Ensure Participants printAnswer setting is set to true or that the logged user have read permissions over the responses. if ($aSurveyInfo['printanswers'] == 'N' && !Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'read')) { throw new CHttpException(401, 'You are not allowed to print answers.'); } //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 if ($sExportType != 'pdf') { $sOutput = CHtml::form(array("printanswers/view/surveyid/{$iSurveyID}/printableexport/pdf"), 'post') . "<center><input class='btn btn-default' type='submit' value='" . gT("PDF export") . "'id=\"exportbutton\"/><input type='hidden' name='printableexport' /></center></form>"; $sOutput .= "\t<div class='printouttitle'><strong>" . 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"; $sOutput .= "\t<tr class='printanswersgroupdesc'><td colspan='2'>{$fname[1]}</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>"; } } elseif (substr($sFieldname, 0, 4) != 'qid_') { $sOutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]}</td><td class='printanswersanswertext'>" . flattenText($fname[2]) . "</td></tr>"; } } $sOutput .= "</table>\n"; $sData['thissurvey'] = $aSurveyInfo; $sOutput = templatereplace($sOutput, array(), $sData, '', $aSurveyInfo['anonymized'] == "Y", NULL, array(), true); // Do a static replacement ob_start(function ($buffer, $phase) { App()->getClientScript()->render($buffer); App()->getClientScript()->reset(); return $buffer; }); ob_implicit_flush(false); sendCacheHeaders(); doHeader(); echo templatereplace(file_get_contents($oTemplate->viewPath . '/startpage.pstpl'), array(), $sData); echo templatereplace(file_get_contents($oTemplate->viewPath . '/printanswers.pstpl'), array('ANSWERTABLE' => $sOutput), $sData); echo templatereplace(file_get_contents($oTemplate->viewPath . '/endpage.pstpl'), array(), $sData); echo "</body></html>"; ob_flush(); } if ($sExportType == 'pdf') { // Get images for TCPDF from template directory define('K_PATH_IMAGES', getTemplatePath($aSurveyInfo['template']) . DIRECTORY_SEPARATOR); Yii::import('application.libraries.admin.pdf', true); Yii::import('application.helpers.pdfHelper'); $aPdfLanguageSettings = pdfHelper::getPdfLanguageSettings(App()->language); $oPDF = new pdf(); $sDefaultHeaderString = $sSurveyName . " (" . gT("ID", 'unescaped') . ":" . $iSurveyID . ")"; $oPDF->initAnswerPDF($aSurveyInfo, $aPdfLanguageSettings, Yii::app()->getConfig('sitename'), $sSurveyName, $sDefaultHeaderString); 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']); foreach ($aFullResponseTable as $sFieldname => $fname) { if (substr($sFieldname, 0, 4) == 'gid_') { $oPDF->addGidAnswer($fname[0], $fname[1]); } elseif ($sFieldname == 'submitdate') { if ($sAnonymized != 'Y') { $oPDF->addAnswer($fname[0] . " " . $fname[1], $fname[2]); } } elseif (substr($sFieldname, 0, 4) != 'qid_') { $oPDF->addAnswer($fname[0] . " " . $fname[1], $fname[2]); } } header("Pragma: public"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); $sExportFileName = sanitize_filename($sSurveyName); $oPDF->Output($sExportFileName . "-" . $iSurveyID . ".pdf", "D"); } LimeExpressionManager::FinishProcessingGroup(); LimeExpressionManager::FinishProcessingPage(); }