function cleanup_phone($phone) { $phone = str_replace(' ', '', $phone); $phone = str_replace('(', '', $phone); $phone = str_replace(')', '', $phone); $phone = str_replace('-', '', $phone); $phone = str_replace('.', '', $phone); return $phone; } require_once 'HTML/QuickForm.php'; $uploadForm = new HTML_QuickForm('upload_form', 'post'); $uploadForm->setRequiredNote('<span style="color:#ff0000;">*</span> = campos requeridos.'); $uploadForm->addElement('header', 'MyHeader', 'Importar alumnos desde una planilla'); $uploadForm->addElement('hidden', 'action', 'alumno_import'); $file =& $uploadForm->addElement('file', 'filename', 'Archivo:'); $uploadForm->setMaxFileSize(5120000); $uploadForm->addRule('filename', 'Debe seleccionar un archivo', 'uploadedfile'); $uploadForm->addElement('submit', 'btnUpload', 'Cargar Base'); $field_names_ok = array('legajo', 'nombre', 'doc_nro', 'email', 'telefono', 'orientacion', 'notas'); if ($uploadForm->validate()) { unset($params); $params['time0'] = time(); $uploaded_file = $_FILES['filename']['tmp_name']; $handle = fopen($uploaded_file, 'r'); if (!$handle) { die('Error al abrir el archivo ' . $uploaded_file); } // get field names in the first line $field_names = fgetcsv($handle, 4096, chr(9)); // check field names $field_diff = array_diff($field_names_ok, $field_names);
$form->addElement('static', 'note', _FORCEDOWNLOADFILEINFO); $form->setDefaults(array('folders_to_hierarchy' => true)); //$form -> addElement('select', 'import_method', _IMPORTMETHOD, array(_UPLOADFILE, _FROMURL, _FROMPATH), 'onchange = "selectBox(this);"'); $form->addElement('file', 'import_file[0]', _IMPORTFILE); for ($i = 1; $i < 10; $i++) { $form->addElement('file', "import_file[{$i}]", null); } $form->addElement('text', "import_url[0]", _IMPORTFROMURL, 'class = "inputText"'); for ($i = 1; $i < 10; $i++) { $form->addElement('text', "import_url[{$i}]", null, 'class = "inputText"'); } $form->addElement('text', "import_path[0]", _IMPORTFROMPATH, 'class = "inputText"'); for ($i = 1; $i < 10; $i++) { $form->addElement('text', "import_path[{$i}]", null, 'class = "inputText"'); } $form->setMaxFileSize(FileSystemTree::getUploadMaxSize() * 1024); //getUploadMaxSize returns size in KB $form->addElement('submit', 'import_submit', _IMPORT, 'class = "flatButton"'); if ($form->isSubmitted() && $form->validate()) { try { $values = $form->exportValues(); $errors = $uploadedFiles = array(); //Create, if it does not exist, the folder where the files will be uploaded //is_dir($uploadDir = $currentUser -> getDirectory().'temp/') OR mkdir($uploadDir, 0755); $uploadDir = $currentLesson->getDirectory(); $filesystem = new FileSystemTree($uploadDir, true); //Perform any direct file uploads foreach ($_FILES['import_file']['name'] as $key => $name) { if (!in_array($name, $uploadedFiles)) { //This way we bypass duplicates try {
function admin_display($task) { global $db, $cfg; if ($task == NULL) { $task = 'contests'; } switch ($task) { case 'users': $table = new HTML_Table(); $res =& db_query('users_list'); $res->fetchInto($row); // add users table headers $headers = array_keys($row); array_push($headers, 'groups'); array_push($headers, 'actions'); $table->addRow($headers, null, 'TH'); // add user records while ($row) { $res2 =& db_query('groups_by_user_id', $row['user_id']); // get list of gourps for this user $groups = ''; $res2->fetchInto($row2); while ($row2) { $groups .= $row2['name']; if ($res2->fetchInto($row2)) { $groups .= ', '; } } $res2->free(); array_push($row, $groups); // actions array_push($row, "<a href=\"index.php?view=admin&task=edit_user&id={$row['user_id']}\">edit</a>" . ", <a href=\"index.php?view=admin&task=del_user&id={$row['user_id']}\">delete</a>"); $table->addRow(array_values($row)); $res->fetchInto($row); } $res->free(); $table->altRowAttributes(1, null, array("class" => "altrow")); echo '<div class="overflow">' . $table->toHtml() . '</div>'; break; case 'del_user': db_query('del_user_by_id', $_GET['id']); db_query('del_user_perms_by_id', $_GET['id']); redirect('index.php?view=admin&task=users'); break; case 'edit_user': // user id to edit given as arg $res =& db_query('groups_by_user_id', $_GET['id']); // get list of all groups for this user $user_groups = array(); while ($res->fetchInto($row)) { array_push($user_groups, $row['group_id']); } $res->free(); // get hanndle of user $res =& db_query('user_by_id', $_GET['id']); $res->fetchInto($row); $handle = $row['handle']; $res->free(); $form = new HTML_QuickForm('userForm', 'post', 'index.php?view=admin&task=edit_user&id=' . $_GET['id']); $form->addElement('header', null, 'Groups for user ' . $handle . ' (id: ' . $_GET['id'] . ')'); // get list of all available groups $res =& db_query('groups_list'); // add checkbox for each group $groups = array(); while ($res->fetchInto($row)) { $elem =& $form->addElement('checkbox', $row['group_id'], $row['name']); if (in_array($row['group_id'], $user_groups)) { $elem->setChecked(true); } $groups[$row['group_id']] = $row['name']; } $res->free(); $form->addElement('submit', 'submit', 'Apply Changes'); if ($form->validate()) { $data = $form->getSubmitValues(); foreach ($groups as $gid => $name) { $elem =& $form->getElement($gid); if ($data[$gid] == 1) { auth_set_perm($_GET['id'], $gid); $elem->setChecked(true); } else { auth_clear_perm($_GET['id'], $gid); $elem->setChecked(false); } } } $form->display(); break; case 'groups': $table = new HTML_Table(); $res =& db_query('groups_list'); $res->fetchInto($row); // add groups table header $headers = array_keys($row); array_push($headers, 'views'); array_push($headers, 'actions'); $table->addRow($headers, null, 'TH'); // add group records while ($row) { $res2 =& db_query('views_by_group_id', $row['group_id']); // get list of views allowed for this group $views = ''; $res2->fetchInto($row2); while ($row2) { $views .= $row2['view']; if ($res2->fetchInto($row2)) { $views .= ', '; } } $res2->free(); array_push($row, $views); array_push($row, "<a href=\"index.php?view=admin&task=edit_group&id={$row['group_id']}\">edit</a>" . ", <a href=\"index.php?view=admin&task=del_group&id={$row['group_id']}\">delete</a>"); $table->addRow(array_values($row)); $res->fetchInto($row); } $res->free(); // decor $table->altRowAttributes(1, null, array("class" => "altrow")); echo '<div class="overflow">' . $table->toHtml() . '</div>'; echo "<hr />"; // form for adding a group $form = new HTML_QuickForm('addGroupForm', 'post', 'index.php?view=admin&task=groups'); $form->addElement('header', null, 'Add a group'); $form->addElement('text', 'name', 'Name: '); $form->addElement('submit', null, 'Submit'); $form->applyFilter('name', 'trim'); $form->addRule('name', 'Group name is required.', 'required', null, 'client'); if ($form->validate()) { $res =& $db->autoExecute('groups', $form->getSubmitValues(), DB_AUTOQUERY_INSERT); if (PEAR::isError($res)) { error($db->toString()); } redirect('index.php?view=admin&task=groups'); } $form->display(); break; case 'del_group': db_query('del_group_by_id', $_GET['id']); redirect('index.php?view=admin&task=groups'); break; case 'edit_group': // get list of views allowed for this group $group_views = array(); $res =& db_query('views_by_group_id', $_GET['id']); while ($res->fetchInto($row)) { array_push($group_views, $row['view']); } $res->free(); // get name of group $res =& db_query('group_by_id', $_GET['id']); $res->fetchInto($row); $name = $row['name']; $res->free(); $form = new HTML_QuickForm('groupForm', 'post', 'index.php?view=admin&task=edit_group&id=' . $_GET['id']); $form->addElement('header', null, 'Views for group ' . $name . ' (id: ' . $_GET['id'] . ')'); // get list of all available views $view_paths = glob($cfg['dir']['views'] . '/*.php'); $views = array(); // create the checkboxes, add each view to $views for later checking foreach ($view_paths as $path) { $tmp = explode('.', basename($path)); $elem =& $form->addElement('checkbox', $tmp[0], $tmp[0]); if (in_array($tmp[0], $group_views)) { $elem->setChecked(true); } array_push($views, $tmp[0]); } $form->addElement('submit', 'submit', 'Apply Changes'); if ($form->validate()) { $data = $form->getSubmitValues(); foreach ($views as $view) { $elem =& $form->getElement($view); if ($data[$view] == 1) { auth_set_view($_GET['id'], $view); $elem->setChecked(true); } else { auth_clear_view($_GET['id'], $view); $elem->setChecked(false); } } } $form->display(); break; case 'views': $table = new HTML_Table(); $table->addRow(array('name', 'path'), null, 'TH'); // display list of views $view_paths = glob($cfg['dir']['views'] . '/*.php'); foreach ($view_paths as $path) { $tmp = explode('.', basename($path)); $table->addRow(array($tmp[0], $path)); } $table->altRowAttributes(1, null, array("class" => "altrow")); echo '<div class="overflow">' . $table->toHtml() . '</div>'; ?> <p>To add a view, just drop a .php view-module file inside the views directory. You can remove a view by deleting or renaming the corresponding file inside the views directory. </p> <?php break; case 'contests': $table = new HTML_Table(); $res =& db_query('contests_list'); $res->fetchInto($row); if ($row) { // add contests table headers $headers = array_keys($row); array_push($headers, 'actions'); $table->addRow($headers, null, 'TH'); // add contests table records while ($row) { // Get the handle of the manager for displaying $manager_name = '[none]'; $res2 =& $db->query($cfg['sql']['user_by_id'], $row['manager']); if (!PEAR::isError($res2)) { $res2->fetchInto($row2); $manager_name = $row2['handle']; $res2->free(); } $row['manager'] = $manager_name; // add edit,delete actions $row['actions'] = "<a href=\"index.php?view=admin&task=edit_contest&id={$row['contest_id']}\">edit</a>, " . "<a href=\"index.php?view=admin&task=del_contest&id={$row['contest_id']}\">delete</a>"; $table->addRow(array_values($row)); $res->fetchInto($row); } $res->free(); // decoration $table->altRowAttributes(1, null, array("class" => "altrow")); echo '<div class="overflow">' . $table->toHtml() . '</div>'; } else { ?> <p>No contests added yet.</p> <?php } echo "<hr />"; // get list of all available managers $res =& db_query('users_by_group_name', 'Managers'); while ($res->fetchInto($row)) { $managers[$row['user_id']] = $row['handle']; } // form for adding a contest $form = new HTML_QuickForm('contestAddForm', 'post', selflink()); $form->addElement('header', null, 'Add a contest'); $form->addElement('text', 'name', 'Name:'); $form->addElement('text', 'description', 'Description:'); $elem =& $form->addElement('text', 'team_size', 'Size of team:'); $form->addElement('select', 'division', 'Division:', $cfg['tcl']['divisions']); $elem->setValue('1'); $date = getdate(); $form->addElement('date', 'show_time', 'Activation time:', array('format' => 'dMY H:i', 'minYear' => $date['year'], 'maxYear' => $date['year'] + 5)); $form->addElement('date', 'begin_time', 'Begin time:', array('format' => 'dMY H:i', 'minYear' => $date['year'], 'maxYear' => $date['year'] + 5)); $form->addElement('date', 'end_time', 'End time:', array('format' => 'dMY H:i', 'minYear' => $date['year'], 'maxYear' => $date['year'] + 5)); $form->addElement('select', 'manager', 'Contest manager:', $managers); $form->addElement('submit', null, 'Submit'); $form->applyFilter('name', 'trim'); $form->applyFilter('description', 'trim'); $form->applyFilter('team_size', 'trim'); $form->addRule('name', 'Contest name is required.', 'required', null, 'client'); $form->addRule('manager', 'Contest manager is required.', 'required', null, 'client'); $form->addRule('team_size', 'Team size is required.', 'required', null, 'client'); // validate or display form if ($form->validate()) { $data = $form->getSubmitValues(); $data['show_time'] = form2sql_datetime($data['show_time']); $data['begin_time'] = form2sql_datetime($data['begin_time']); $data['end_time'] = form2sql_datetime($data['end_time']); $db->autoExecute('contests', $data, DB_AUTOQUERY_INSERT); if (PEAR::isError($res)) { error($db->toString()); } redirect('index.php?view=admin&task=contests'); } else { $form->display(); } break; case 'del_contest': $res =& db_query('del_contest_by_id', $_GET['id']); redirect('index.php?view=admin&task=contests'); break; case 'edit_contest': // contest to edit given as arg $res =& db_query('contest_by_id', $_GET['id']); $res->fetchInto($row); $res->free(); // get list of all available managers $res =& db_query('users_by_group_name', 'Managers'); while ($res->fetchInto($row2)) { $managers[$row2['user_id']] = $row2['handle']; } // form for editing the contest $form = new HTML_QuickForm('contestEditForm', 'post', selflink()); $form->addElement('header', null, "Edit contest {$row['name']} (id: {$row['contest_id']})"); $form->addElement('text', 'name', 'Name:'); $form->addElement('text', 'description', 'Description:'); $elem =& $form->addElement('text', 'team_size', 'Size of team:'); $elem->setValue('1'); $form->addElement('select', 'division', 'Division:', $cfg['tcl']['divisions']); $date = getdate(); $form->addElement('date', 'show_time', 'Activation time:', array('format' => 'dMY H:i', 'minYear' => $date['year'], 'maxYear' => $date['year'] + 5)); $form->addElement('date', 'begin_time', 'Begin time:', array('format' => 'dMY H:i', 'minYear' => $date['year'], 'maxYear' => $date['year'] + 5)); $form->addElement('date', 'end_time', 'End time:', array('format' => 'dMY H:i', 'minYear' => $date['year'], 'maxYear' => $date['year'] + 5)); $form->addElement('select', 'manager', 'Contest manager:', $managers); $form->addElement('text', 'rules', 'Rules URL:'); $form->addElement('submit', null, 'Submit'); // convert date format and dtore default values $row['show_time'] = sql2form_datetime($row['show_time']); $row['begin_time'] = sql2form_datetime($row['begin_time']); $row['end_time'] = sql2form_datetime($row['end_time']); $form->setDefaults($row); $form->applyFilter('name', 'trim'); $form->applyFilter('description', 'trim'); $form->applyFilter('team_size', 'trim'); $form->addRule('name', 'Contest name is required.', 'required', null, 'client'); $form->addRule('manager', 'Contest manager is required.', 'required', null, 'client'); $form->addRule('team_size', 'Team size is required.', 'required', null, 'client'); // validate or display form if ($form->validate()) { $data = $form->getSubmitValues(); $data['show_time'] = form2sql_datetime($data['show_time']); $data['begin_time'] = form2sql_datetime($data['begin_time']); $data['end_time'] = form2sql_datetime($data['end_time']); $db->autoExecute('contests', $data, DB_AUTOQUERY_UPDATE, 'contest_id=' . $_GET['id']); if (PEAR::isError($res)) { error($db->toString()); } redirect('index.php?view=admin&task=contests'); } else { $form->display(); } break; case 'shell': $form = new HTML_QuickForm('shellForm', 'post', selflink()); $field =& $form->addElement('text', 'command', 'Command:'); $field->setSize(100); $ifield =& $form->addElement('textarea', 'input', 'Standard Input:'); $ifield->setRows(10); $ifield->SetCols(80); $form->addElement('submit', null, 'Submit'); $form->display(); if ($form->validate()) { // Write std input file $iname = tempnam("/tmp", "in"); $ifile = fopen($iname, 'w'); fwrite($ifile, $form->getSubmitValue('input')); fclose($ifile); $cmd = $form->getSubmitValue('command'); echo "<pre class=\"shell_output\">"; echo "<b>\$ " . html_escape($cmd) . "</b>\n"; exec("{$cmd} 2>&1 < {$iname}", $out, $ret); foreach ($out as $line) { echo html_escape($line) . "\n"; } echo "</pre>\n"; echo "<p>Command returned: {$ret}</p>\n"; } break; case 'uploader': // Get list of directories to which files can be uploaded $dirs = subdir_list('.'); array_unshift($dirs, './'); $form = new HTML_QuickForm('uploaderForm', 'post', selflink()); $form->addElement('header', null, 'Upload a File:'); $file =& $form->addElement('file', 'file', 'File:'); $form->addElement('select', 'dir', 'Destination:', $dirs); $form->addElement('submit', 'upload', 'Upload'); $form->addRule('file', 'Please select file to upload.', 'required', null, 'client'); $form->setMaxFileSize(10485760); // try 10 MB max file size if ($form->validate()) { if ($file->isUploadedFile()) { $dir = $dirs[$form->getSubmitValue('dir')]; if ($file->moveUploadedFile($dir)) { echo "<p>File uploaded successfully to {$dir}.</p>"; } else { echo "<p>Failed to save uploaded file to {$dir} (insufficient permissions?).</p>"; } } else { echo "<p>File upload did not finish successfully</p>"; } } $form->display(); echo "<p><b>Note:</b> Any previous file with the same name will be replaced.</p>"; echo "<hr />"; $form = new HTML_QuickForm('mkdirForm', 'post', selflink()); $form->addElement('header', null, 'Create a Directory:'); $form->addElement('text', 'name', 'Name:'); $form->addElement('select', 'dir', 'Destination:', $dirs); $form->addElement('submit', 'mkdir', 'Mkdir'); $form->addRule('name', 'Please enter directory name.', 'required', null, 'client'); if ($form->validate()) { $path = $dirs[$form->getSubmitValue('dir')] . '/' . $form->getSubmitValue('name'); if (file_exists($path)) { echo "<p><b>Warning:</b> File or directory {$path} already exists.</p>"; } else { if (mkdir($path)) { echo "<p>Directory {$path} created.</p>"; } else { echo "<p>Failed to create directory {$path}. Make sure parent directory permissions allow it.</p>"; } } } $form->display(); break; case 'phpinfo': phpinfo(); break; } }
/** * The main functionality * * (non-PHPdoc) * @see libraries/EfrontModule#getModule() */ public function getModule() { $smarty = $this->getSmartyVar(); $smarty->assign("T_MODULE_BASEDIR", $this->moduleBaseDir); $smarty->assign("T_MODULE_BASELINK", $this->moduleBaseLink); $smarty->assign("T_MODULE_BASEURL", $this->moduleBaseUrl); $dir = $this->moduleBaseDir . 'assets/'; if (!is_dir($dir)) { mkdir($dir, 0755); } if ($_SESSION['s_type'] == 'administrator') { try { $form = new HTML_QuickForm("upload_files_form", "post", $this->moduleBaseUrl . '&tab=upload', "", null, true); $form->registerRule('checkParameter', 'callback', 'eF_checkParameter'); //Register this rule for checking user input with our function, eF_checkParameter $form->addElement('file', 'file', _UPLOADFILE); if (G_VERSIONTYPE == 'enterprise') { $tree = new EfrontBranchesTree(); $pathString = $tree->toPathString(); //$result = eF_getTableData("module_hcd_branch", "*", "url is not null and url !=''"); $handle = '<img id = "busy" src = "images/16x16/clock.png" style = "display:none;" alt = "{$smarty.const._LOADING}" title = "{$smarty.const._LOADING}"/><div id = "autocomplete_leaflet_branches" class = "autocomplete"></div> '; $form->addElement('static', 'sidenote', $handle); $form->addElement('text', 'leaflet_branch_autoselect', _BRANCH, 'class = "autoCompleteTextBox" id = "autocomplete"'); $form->addElement('hidden', 'leaflet_branch', '', 'id = "leaflet_branch_value"'); } $form->setMaxFileSize(FileSystemTree::getUploadMaxSize() * 1024); $form->addElement('submit', 'submit_upload', _UPLOAD, 'class = "flatButton"'); if ($form->isSubmitted() && $form->validate()) { $values = $form->exportValues(); try { if ($values['leaflet_branch'] && eF_checkParameter($values['leaflet_branch'], 'id')) { $branch = new EfrontBranch($values['leaflet_branch']); if (!$branch->branch['url']) { throw new Exception("You must assign a url to the selected branch to upload files for it"); } $dir = $this->moduleBaseDir . 'assets/' . $branch->branch['url']; mkdir($dir, 0755); } $filesystem = new FileSystemTree($dir); $file = $filesystem->uploadFile("file", $dir); } catch (Exception $e) { $smarty->assign("T_EXCEPTION_TRACE", $e->getTraceAsString()); $message = $e->getMessage() . ' (' . $e->getCode() . ') <a href = "javascript:void(0)" onclick = "eF_js_showDivPopup(event, \'' . _ERRORDETAILS . '\', 2, \'error_details\')">' . _MOREINFO . '</a>'; $message_type = failure; $this->setMessageVar($message, $message_type); } } $smarty->assign('T_UPLOAD_FORM', $form->toArray()); $url = $this->moduleBaseUrl; $basedir = $dir; $options = array('zip' => false, 'upload' => false, 'create_folder' => false, 'folders' => true); /**The file manager*/ include "file_manager.php"; } catch (Exception $e) { $smarty->assign("T_EXCEPTION_TRACE", $e->getTraceAsString()); $message = $e->getMessage() . ' (' . $e->getCode() . ') <a href = "javascript:void(0)" onclick = "eF_js_showDivPopup(event, \'' . _ERRORDETAILS . '\', 2, \'error_details\')">' . _MOREINFO . '</a>'; $message_type = 'failure'; $this->setMessageVar($message, $message_type); } } else { if (defined('G_BRANCH_URL') && G_BRANCH_URL) { try { $assets_path = $root_path = $this->moduleBaseDir . 'assets/' . G_BRANCH_URL; } catch (Exception $e) { //do nothing here if the directory doesn't exist } } else { $assets_path = $root_path = $this->moduleBaseDir . 'assets/'; } $files = array(); if (!empty($_GET['folder'])) { $folder = urldecode($_GET['folder']); if (is_dir($assets_path . $folder)) { $folder = new EfrontDirectory($assets_path . $folder); if (strpos(realpath($folder['path']), $root_path) === false) { throw new Exception("Invalid folder"); } $parent_folder = dirname($folder['path']); $url = urlencode(str_replace($root_path, '', $folder['path'])); $assets_path = $folder['path']; $parent_url = $this->moduleBaseUrl . "&folder=" . urlencode(str_replace($root_path, '', dirname($folder['path']) . '/')); $parent_url or $parent_url = $this->moduleBaseUrl . 'assets/'; $files[] = array('text' => '.. (Up one level)', 'image' => $this->moduleBaseLink . 'ico/folders.png', 'href' => $parent_url); } } //pr($url);pr($parent_url); // $filesystem = new FileSystemTree($assets_path, true); foreach ($filesystem->tree as $key => $value) { if ($value instanceof EfrontDirectory) { $files[] = array('text' => basename($key), 'image' => $this->moduleBaseLink . 'ico/folders.png', 'href' => $this->moduleBaseUrl . "&folder=" . urlencode(str_replace($root_path, '', $value['path'] . '/'))); } } foreach ($filesystem->tree as $key => $value) { if ($value instanceof EfrontFile) { if (is_file($this->moduleBaseDir . 'ico/' . pathinfo($key, PATHINFO_EXTENSION) . '.png')) { $icon = $this->moduleBaseLink . 'ico/' . pathinfo($key, PATHINFO_EXTENSION) . '.png'; } else { $icon = $this->moduleBaseLink . 'ico/unknown.png'; } $files[] = array('text' => basename($key), 'image' => $icon, 'href' => $this->moduleBaseLink . str_replace($this->moduleBaseDir, '', $key)); } } $smarty->assign("T_FILES", $files); } return true; }
if ($projectUser['professor_upload_filename']) { try { $projectFile = new EfrontFile($projectUser['professor_upload_filename']); $smarty->assign("T_PROFESSOR_FILE", $projectFile); } catch (EfrontFileException $e) { $smarty->assign("T_EXCEPTION_TRACE", $e->getTraceAsString()); $message = _SOMEPROBLEMOCCURED . ': ' . $e->getMessage() . ' <a href = "javascript:void(0)" onclick = "eF_js_showDivPopup(event, \'' . _ERRORDETAILS . '\', 2, \'error_details\')">' . _MOREINFO . '</a>'; $message_type = 'failure'; } } $form = new HTML_QuickForm("upload_project_form", "post", basename($_SERVER['PHP_SELF']) . '?ctg=projects&view_project=' . $_GET['view_project'], "", null, true); if (!$projectFile) { $file = $form->addElement('file', 'filename', _FILE); $maxFileSize = FileSystemTree::getUploadMaxSize(); $form->addRule('filename', _THEFIELD . ' "' . _FILE . '" ' . _ISMANDATORY, 'required', null, 'client'); $form->setMaxFileSize($maxFileSize * 1024); $form->addElement('submit', 'submit_upload_project', _SENDPROJECT, 'class = "flatButton"'); } $smarty->assign("T_MAX_FILE_SIZE", $maxFileSize); if ($form->isSubmitted() && $form->validate() && !$currentProject->expired) { try { $projectDirectory = G_UPLOADPATH . $currentUser->user['login'] . '/projects'; if (!is_dir($projectDirectory)) { EfrontDirectory::createDirectory($projectDirectory); } $projectDirectory = G_UPLOADPATH . $currentUser->user['login'] . '/projects/' . $currentProject->project['id']; if (!is_dir($projectDirectory)) { EfrontDirectory::createDirectory($projectDirectory); } $filesystem = new FileSystemTree($projectDirectory); $uploadedFile = $filesystem->uploadFile('filename', $projectDirectory);
/** * Get an upload form * * This function is responsible for creating an "upload file" * form, as well as the equivalent HTML code. * <br/>Example: * <code> * $basedir = G_LESSONSPATH.'test/'; * $filesystem = new FileSystemTree($basedir); //Set the base directory that the file manager displayes * $url = 'administrator.php?ctg=file_manager'; //Set the url where file manager resides * $uploadForm = new HTML_QuickForm("upload_file_form", "post", $url, "", "", true); * $uploadFormString = $filesystem -> getUploadForm($uploadForm); * echo $uploadFormString; * </code> * * @param HTML_QuickForm $form The form to populate * @return string The HTML code of the form * @since 3.5.0 * @access public */ public function getUploadForm(&$form) { $form->registerRule('checkParameter', 'callback', 'eF_checkParameter'); //Register this rule for checking user input with our function, eF_checkParameter $form->addElement('file', 'file_upload[0]', null, 'class = "inputText"'); $form->addElement('file', 'file_upload[1]', null, 'class = "inputText"'); $form->addElement('file', 'file_upload[2]', null, 'class = "inputText"'); $form->addElement('file', 'file_upload[3]', null, 'class = "inputText"'); $form->addElement('file', 'file_upload[4]', null, 'class = "inputText"'); $form->addElement('file', 'file_upload[5]', null, 'class = "inputText"'); $form->addElement('file', 'file_upload[6]', null, 'class = "inputText"'); $form->addElement('text', 'url_upload', null, 'id = "url_upload" class = "inputText"'); $form->addElement('hidden', 'upload_current_directory', null, 'id = "upload_current_directory" class = "inputText"'); $form->addElement('submit', 'submit_upload_file', _UPLOAD, 'class = "flatButton" onclick = "$(\'uploading_image\').show()"'); $form->setMaxFileSize($this->getUploadMaxSize() * 1024); //getUploadMaxSize returns size in KB $renderer = new HTML_QuickForm_Renderer_ArraySmarty($smarty); $form->accept($renderer); $formArray = $renderer->toArray(); $formString = ' ' . $formArray['javascript'] . ' <form ' . $formArray['attributes'] . '> ' . $formArray['hidden'] . ' <table width = "100%"> <tr><td class = "labelCell">' . _UPLOADFILE . ': </td> <td class = "elementCell">' . $formArray['file_upload'][0]['html'] . '</td></tr> <tr style = "display:none"><td class = "labelCell">' . _UPLOADFILE . ': </td> <td class = "elementCell">' . $formArray['file_upload'][1]['html'] . '</td></tr> <tr style = "display:none"><td class = "labelCell">' . _UPLOADFILE . ': </td> <td class = "elementCell">' . $formArray['file_upload'][2]['html'] . '</td></tr> <tr style = "display:none"><td class = "labelCell">' . _UPLOADFILE . ': </td> <td class = "elementCell">' . $formArray['file_upload'][3]['html'] . '</td></tr> <tr style = "display:none"><td class = "labelCell">' . _UPLOADFILE . ': </td> <td class = "elementCell">' . $formArray['file_upload'][4]['html'] . '</td></tr> <tr style = "display:none"><td class = "labelCell">' . _UPLOADFILE . ': </td> <td class = "elementCell">' . $formArray['file_upload'][5]['html'] . '</td></tr> <tr style = "display:none"><td class = "labelCell">' . _UPLOADFILE . ': </td> <td class = "elementCell">' . $formArray['file_upload'][6]['html'] . '</td></tr> <tr><td></td> <td class = "elementCell"> <img src = "images/16x16/add.png" alt = "' . _ADDFILE . '" title = "' . _ADDFILE . '" onclick = "addUploadBox(this)"/></td></tr> <tr><td></td> <td class = "infoCell"><span id="messageError" class = "severeWarning"></span></td></tr> <tr><td></td> <td class = "infoCell">' . _MAXIMUMUPLOADSIZE . ': ' . $this->getUploadMaxSize() . ' ' . _KB . '</td></tr> <tr><td class = "labelCell">' . _UPLOADFILEFROMURL . ': </td> <td class = "elementCell">' . $formArray['url_upload']['html'] . '</td></tr> <tr><td></td> <td class = "submitCell"> ' . $formArray['submit_upload_file']['html'] . ' </td></tr> </table> </form> <img src = "images/others/progress_big.gif" id = "uploading_image" title = "' . _UPLOADING . '" alt = "' . _UPLOADING . '" style = "display:none;margin-left:auto;margin-right:auto;margin-top:30px;vertical-align:middle;"/>'; return $formString; }
/** * Populate the test form * * This function is used to populate the test form and create the * test html code. * <br/>Example: * <code> * $test = new EfrontTest(1); //Instantiate test form * $form = new HTML_QuickForm("questionForm", "post", "", "", null, true); //Create the test form * echo $test -> toHTMLQuickForm($form); //Populates the form and returns the equivalent HTML code * echo $test -> toHTMLQuickForm($form, 2); //Populates the form and returns the equivalent HTML code, but displays only question with id 2 * $test -> setDone('jdoe'); //Get the done test information for user 'jdoe'; * echo $test -> toHTMLQuickForm($form, false, true); //Populates the form and returns the equivalent HTML code, but the mode is set to display the done test * </code> * * @param HTML_QuickForm $form The form to populate * @param int $questionId If set, it displays only the designated question * @param boolean $done If set to true and the test has done information (previously acquired with setDone()), then it displays the done test * @param boolean $editHandles Whether to display correction handles, to update questions scores and feedback * @param boolean $nocache Whether to skip caching this time * @since 3.5.0 * @access public */ public function toHTMLQuickForm(&$form = false, $questionId = false, $done = false, $editHandles = false, $nocache = false, $isFeedback = false) { $storeCache = false; if (!$questionId && !$done && !$this->options['random_pool'] && !$this->options['shuffle_questions'] && !$this->options['shuffle_answers'] && !$nocache) { if ($testString = EfrontCache::getInstance()->getCache('test:' . $this->test['id'])) { return $testString; } else { $storeCache = true; } } $originalTestQuestions = $this->getQuestions(); //Initialize questions information, it case it isn't if (!$form) { $form = new HTML_QuickForm("questionForm", "post", "", "", null, true); //Create a sample form } $form->setMaxFileSize(FileSystemTree::getUploadMaxSize() * 1024); $allTestQuestions = $this->getQuestions(true); //$allTestQuestionsFilter = $allTestQuestions; // lines added for redo only wrong questions $allTestQuestionsFilter = array(); $resultCompleted = EfrontCompletedTest::retrieveCompletedTest("completed_tests ct join completed_tests_blob ctb on ct.id=ctb.completed_tests_ID", "ctb.test", "archive=1 AND users_LOGIN='******'s_login'] . "' AND tests_ID=" . $this->test['id'], "timestamp desc"); if (!empty($resultCompleted)) { $recentlyCompleted = unserialize($resultCompleted[0]['test']); if ($recentlyCompleted->redoOnlyWrong == true && !$done) { foreach ($recentlyCompleted->questions as $key => $value) { if ($value->score != 100 && isset($originalTestQuestions[$key])) { // && added for the case professor deleted question from test after student clicked to redo only wrong $value->userAnswer = false; $allTestQuestionsFilter[$key] = $value; } } $allTestQuestions = $allTestQuestionsFilter; } } // If we have a random pool of question then get a random sub-array of the questions if ($this->options['random_pool'] > 0 && $this->options['random_pool'] < sizeof($allTestQuestions)) { $rand_questions = array_rand($allTestQuestions, $this->options['random_pool']); $testQuestions = array(); foreach ($rand_questions as $question) { $testQuestions[$question] = $allTestQuestions[$question]; } } else { $testQuestions = $allTestQuestions; } $questionId && in_array($questionId, array_keys($testQuestions)) ? $testQuestions = $testQuestions[$questionId] : null; //If $questionId is specified, keep only this question $this->options['display_list'] ? $testString = '<style type = "text/css">span.orderedList{float:left;}</style>' : ($testString = '<style type = "text/css">span.orderedList{display:none;}</style>'); $count = 1; if ($this->test['content_ID']) { //Get unit names and ids $content = new EfrontContentTree(key($this->getLesson())); foreach (new EfrontNodeFilterIterator(new RecursiveIteratorIterator(new RecursiveArrayIterator($content->tree), RecursiveIteratorIterator::SELF_FIRST)) as $key => $value) { $units[$key] = $value['name']; } } $currentLesson = $this->getLesson(true); foreach ($testQuestions as $id => $question) { if ($done) { switch ($question->score) { case '': case 0: $image = 'error_delete.png'; $alt = _INCORRECTQUESTION; $title = _INCORRECTQUESTION; break; case '100': $image = 'success.png'; $alt = _QUESTIONISCORRECT; $title = _QUESTIONISCORRECT; break; default: $image = 'semi_success.png'; $alt = _PARTIALLYCORRECTQUESTION; $title = _PARTIALLYCORRECTQUESTION; break; } if ($question->pending) { $image = 'exclamation.png'; $alt = _CORRECTIONPENDING; $title = _CORRECTIONPENDING; } } $weight = round(10000 * $this->getQuestionWeight($question->question['id'])) / 100; $timeSpentString = ''; if (!empty($question->time)) { $timeSpent = eF_convertIntervalToTime($question->question['estimate'] - $question->time); $timeSpent['hours'] ? $timeSpentString .= $timeSpent['hours'] . _HOURSSHORTHAND . ' ' : null; $timeSpent['minutes'] ? $timeSpentString .= $timeSpent['minutes'] . _MINUTESSHORTHAND . ' ' : null; $timeSpent['seconds'] ? $timeSpentString .= $timeSpent['seconds'] . _SECONDSSHORTHAND . ' ' : null; $timeSpentString ? $timeSpentString = _TIMESPENT . ': ' . $timeSpentString : null; } //The hidden span below the div is used in a js down() so as to know which question we are looking at $testString .= ' <div id = "question_' . $count . '" ' . (!$done && $this->options['onebyone'] ? 'style = "display:none"' : '') . '> <span id = "question_content_' . $question->question['id'] . '" style = "display:none">' . $question->question['id'] . '</span> <table width = "100%"> <tr><td class = "questionWeight" style = "vertical-align:middle;"> <span style = "float:right">' . $timeSpentString . '</span>'; if (!$isFeedback) { $testString .= '<img src = "images/32x32/' . ($done && ($this->options['show_score'] || $_SESSION['s_type'] != 'student') ? $image : 'unit.png') . '" style = "vertical-align:middle" alt = "' . ($done ? $alt : _QUESTION) . '" title = "' . ($done ? $title : _QUESTION) . '"/> '; } $testString .= '<span style = "vertical-align:middle;font-weight:bold">' . _QUESTION . ' ' . $count++ . '</span> ' . ($this->options['display_weights'] || $done && !$isFeedback ? '<span style = "vertical-align:middle;margin-left:10px">(' . _WEIGHT . ' ' . $weight . '%)</span>' : '') . ' ' . ($units[$question->question['content_ID']] && $done ? '<span style = "vertical-align:middle;margin-left:10px">' . _UNIT . ' "' . $units[$question->question['content_ID']] . '"</span>' : '') . ' ' . ($_SESSION['s_lesson_user_type'] == "student" && $currentLesson->options['content_report'] == 1 ? '<a href = "content_report.php?ctg=tests&edit_question=' . $question->question['id'] . '&question_type=' . $question->question['type'] . '&lessons_Id=' . $_SESSION['s_lessons_ID'] . '" onclick = "eF_js_showDivPopup(event, \'' . _CONTENTREPORT . '\', 1)" target = "POPUP_FRAME"><img src = "images/16x16/warning.png" border=0 style = "vertical-align:middle" alt = "' . _CONTENTREPORT . '" title = "' . _CONTENTREPORT . '"/></a>' : '') . ' ' . ($_SESSION['s_lesson_user_type'] == "professor" ? '<a href = "' . basename($_SERVER['PHP_SELF']) . '?ctg=tests&edit_question=' . $question->question['id'] . '&question_type=' . $question->question['type'] . '&lessonId=' . $currentLesson->lesson['id'] . '&return=' . urlencode($_SERVER['QUERY_STRING']) . '" style = "float:right;line-height:32px;"><img src = "images/16x16/edit.png" alt = "' . _EDIT . '" title = "' . _EDIT . '" style = "loat:right;vertical-align:middle"/></a>' : '') . ' </td></tr> </table>'; if ($done) { if ($isFeedback) { $showCorrectAnswers = false; } else { if ($this->options['answers']) { $showCorrectAnswers = true; } else { if ($this->options['show_answers_if_pass'] && ($this->completedTest['status'] == 'passed' || $this->completedTest['status'] == 'completed')) { $showCorrectAnswers = true; } else { $showCorrectAnswers = false; } } } $questionString = $question->toHTMLSolved(new HTML_QuickForm(), $showCorrectAnswers, $this->options['given_answers']); $testString .= $questionString; } else { if (!empty($this->preview_correct)) { $question->preview_correct = true; } $questionString = $question->toHTML($form); $testString .= $questionString; } $testString .= '<br/></div>'; if ($done && !$isFeedback) { $testString .= ' <table style = "width:100%" > <tr><td> <span style = "font-weight:bold;" id = "question_' . $id . '_score_span"> ' . ($this->options['show_score'] || $_SESSION['s_type'] != 'student' ? _SCORE . ': <span style = "vertical-align:middle" id = "question_' . $id . '_score">' . formatScore($question->score) . '%</span>' : '') . ' ' . ($editHandles ? '<a href = "javascript:void(0)" onclick = "$(\'question_' . $id . '_score_span\').hide();$(\'edit_question_' . $id . '_score_span\').show();"><img src = "images/16x16/edit.png" title = "' . _CHANGESCORE . '" alt = "' . _CHANGESCORE . '" style = "vertical-align:middle" border = "0"/></a>' : '') . ' <span id = "question_' . $id . '_pending">' . ($question->pending ? ' (' . _THISQUESTIONCORRECTEDPROFESSOR . ')' : '') . '</span> </span> <span id = "edit_question_' . $id . '_score_span" style = "display:none;"> <input type = "text" name = "edit_question_' . $id . '_score" id = "edit_question_' . $id . '_score" value = "' . formatScore($question->score) . '" style = "vertical-align:middle"/> <a href = "javascript:void(0)" onclick = "editQuestionScore(this, ' . $id . ')"> <img src = "images/16x16/success.png" alt = "' . _SUBMIT . '" title = "' . _SUBMIT . '" border = "0" style = "vertical-align:middle"/> </a> <a href = "javascript:void(0)" onclick = "$(\'question_' . $id . '_score_span\').show();$(\'edit_question_' . $id . '_score_span\').hide();"> <img src = "images/16x16/error_delete.png" alt = "' . _CANCEL . '" title = "' . _CANCEL . '" border = "0" style = "vertical-align:middle"/> </a> </span>'; if ($this->options['show_score'] || $_SESSION['s_type'] != 'student') { $testString .= '<span style = "border-left:1px solid black;margin-left:5px;padding-left:5px">' . _SCOREINTEST . ': <span id = "question_' . $id . '_score_coefficient">' . formatScore($question->score) . '</span>% × ' . $weight . ' = <span id = "question_' . $id . '_scoreInTest">' . formatScore($question->scoreInTest) . '</span>%</span>'; } if ($editHandles) { $testString .= ' <span style = "border-left:1px solid black;margin-left:5px;padding-left:5px">'; if ($question->feedback) { $testString .= ' <img src = "images/16x16/edit.png" alt = "' . _EDITFEEDBACK . '" title = "' . _EDITFEEDBACK . '" border = "0" style = "vertical-align:middle"> <a href = "javascript:void(0)" onclick = "$(\'question_' . $id . '_feedback_div\').toggle();$(\'edit_question_' . $id . '_feedback_div\').toggle()">' . _EDITFEEDBACK . '</a>'; } else { $testString .= ' <img src = "images/16x16/add.png" alt = "' . _ADDFEEDBACK . '" title = "' . _ADDFEEDBACK . '" border = "0" style = "vertical-align:middle"> <a href = "javascript:void(0)" onclick = "$(\'question_' . $id . '_feedback_div\').toggle();$(\'edit_question_' . $id . '_feedback_div\').toggle()">' . _ADDFEEDBACK . '</a>'; } $testString .= ' </span> </td></tr> <tr><td> <div id = "question_' . $id . '_feedback_div" ' . ($question->feedback ? 'class = "feedback_test"' : '') . ' > <span id = "question_' . $id . '_feedback">' . $question->feedback . '</span> </div> <div id = "edit_question_' . $id . '_feedback_div" style = "display:none;"> <textarea id = "edit_question_' . $id . '_feedback" style = "vertical-align:middle;width:90%;height:50px">' . $question->feedback . '</textarea> <a href = "javascript:void(0)" onclick = "editQuestionFeedback(this, ' . $id . ')" style = "vertical-align:middle"> <img src = "images/16x16/success.png" alt = "' . _SUBMIT . '" title = "' . _SUBMIT . '" border = "0" style = "vertical-align:middle" /> </a> <a href = "javascript:void(0)" onclick = "$(\'question_' . $id . '_feedback_div\').toggle();$(\'edit_question_' . $id . '_feedback_div\').toggle()"> <img src = "images/16x16/error_delete.png" alt = "' . _CANCEL . '" title = "' . _CANCEL . '" border = "0" style = "vertical-align:middle" /> </a> </div> </td></tr>'; } else { $testString .= ' <div id = "question_' . $id . '_feedback_div" ' . ($question->feedback ? 'class = "feedback_test"' : '') . ' > <span id = "question_' . $id . '_feedback">' . $question->feedback . '</span> </div>'; } $testString .= ' </table><br/>'; } } if (!$done && $this->options['onebyone']) { if (!empty($GLOBALS['rtl'])) { $next_question_handle = 'arrow_left.png'; $previous_question_handle = 'arrow_right.png'; } else { $next_question_handle = 'arrow_right.png'; $previous_question_handle = 'arrow_left.png'; } $testString .= ' <table width = "100%"> <tr><td style = "text-align:center;vertical-align:middle;padding-top:50px"> <img src = "images/32x32/' . $previous_question_handle . '" alt = "' . _PREVIOUSQUESTION . '" title = "' . _PREVIOUSQUESTION . '" border = "0" id = "previous_question_button" onclick = "showTestQuestion(\'previous\')" style = "vertical-align:middle;margin-right:10px;' . ($this->options['only_forward'] ? 'visibility:hidden' : '') . '" /> <select id = "goto_question" name = "goto_question" style = "vertical-align:middle;' . ($this->options['only_forward'] ? 'display:none' : '') . '" onchange = "showTestQuestion(this.options[this.selectedIndex].value)">'; for ($i = 1; $i <= sizeof($testQuestions); $i++) { $testString .= ' <option value = "' . $i . '">' . $i . '</option>'; } $testString .= ' </select> <img src = "images/32x32/' . $next_question_handle . '" alt = "' . _NEXTQUESTION . '" title = "' . _NEXTQUESTION . '" border = "0" id = "next_question_button" onclick = "showTestQuestion(\'next\')" style = "vertical-align:middle"/> </td></tr> </table>'; $testString .= "\r\n <script>\r\n var total_questions = " . sizeof($testQuestions) . ";\r\n var current_question = " . ($this->currentQuestion ? $this->currentQuestion : 1) . ";\r\n //showTestQuestion(current_question);\r\n </script>"; } if (sizeof($this->questions) > 0) { if ($this->options['answer_all']) { $testString .= "\r\n\t\t\t\t<script>\r\n\t\t\t\tvar force_answer_all = 1;\r\n \ttranslations['youhavenotcompletedquestions'] = '" . _YOUHAVENOTCOMPLETEDTHEFOLLOWINGQUESTIONS . "';\r\n \ttranslations['youhavetoanswerallquestions'] = '" . _YOUHAVETOANSWERALLQUESTIONS . "';</script>"; } else { $testString .= "\r\n\t\t\t\t<script>\r\n\t\t\t\tvar force_answer_all = 0;\r\n \ttranslations['youhavenotcompletedquestions'] = '" . _YOUHAVENOTCOMPLETEDTHEFOLLOWINGQUESTIONS . "';\r\n \ttranslations['areyousureyouwanttosubmittest'] = '" . _AREYOUSUREYOUWANTTOSUBMITTEST . "';</script>"; } } /* if ($this -> options['shuffle_questions'] && !$form -> isSubmitted()) { $form -> addElement("hidden", "answers_order", serialize($shuffleOrder)); //The questions' answers order is hold at a hidden element, so that it can be stored when the test is complete } */ if ($storeCache) { EfrontCache::getInstance()->setCache('test:' . $this->test['id'], $testString); } return $testString; }