Exemple #1
0
 /**
  * create all table's dto and dao
  *
  * @access public
  */
 function autoCreate()
 {
     $fileUtility = new FileUtility();
     $stringUtility = new StringUtility();
     $tableDefinitionDao = new TableDefinitionDao();
     $tableNameArray = $tableDefinitionDao->getTableNameList();
     $fileNameArray = array();
     $generationGapSuffix = GENERATIONGAP_SUFFIX;
     $baseDaoGenerator = new BaseDaoGenerator();
     $baseDao = $baseDaoGenerator->createBaseDaoClass();
     $fileUtility->writePhpFile(OUTPUT_DIR . "BaseDao", $baseDao);
     $fileNameArray[] = "BaseDao";
     $dtoGenerator = new DtoGenerator();
     $dto = $dtoGenerator->createDto();
     $fileUtility->writePhpFile(OUTPUT_DIR . $className . "TableDto", $dto);
     $fileNameArray[] = $className . "TableDto";
     foreach ($tableNameArray as $tableName) {
         $className = $stringUtility->getClassName($tableName);
         $columnList = $tableDefinitionDao->getColumnList($tableName);
         $primaryKeyList = $tableDefinitionDao->getPrimaryKeyList($tableName);
         $daoGenerator = new DaoGenerator();
         if (USE_BASE_CLASS) {
             $dao = $daoGenerator->createDao($tableName, $columnList, $primaryKeyList[0], "BaseDao");
         } else {
             $dao = $daoGenerator->createDao($tableName, $columnList, $primaryKeyList[0]);
         }
         $fileUtility->writePhpFile(OUTPUT_DIR . $className . "Dao", $dao);
         $fileNameArray[] = $className . "Dao";
     }
     return $fileNameArray;
 }
Exemple #2
0
 public static function getDirectoryFiles($dirName)
 {
     $files = array();
     $handle = opendir($dirName);
     if (!$handle) {
         return -1;
     }
     while (false !== ($file = readdir($handle))) {
         if ($file == '.' || $file == '..') {
             continue;
         }
         $fileName = $dirName . '/' . $file;
         if (is_dir($fileName)) {
             $mp = self::getDirectoryFiles($fileName);
             $tmp = array_merge($files, $mp);
             $files = $tmp;
         } else {
             if (!($info = stat($fileName))) {
                 continue;
             }
             $fileSize = filesize($fileName);
             if ($fileSize <= 50) {
                 continue;
             }
             if (!($fileExt = strchr($file, '.'))) {
                 continue;
             }
             $fileExt = strtolower(substr($fileExt, 1));
             // Make sure it's a document type we can get text from
             if (($docType = FileUtility::getDocumentType($file)) == DOCUMENT_TYPE_UNKNOWN) {
                 continue;
             }
             $fileMp = array('realName' => $file, 'name' => $fileName, 'size' => $fileSize, 'ext' => $fileExt, 'type' => $docType, 'cTime' => $info['ctime'], 'parsed' => false);
             $files[] = $fileMp;
         }
     }
     return $files;
 }
 /**
  * Takes input from a form (already validated) and assigns the values to
  * the fields contained within this table.
  * 
  * Certain operations are performed before inserting. The field is checked
  * to see whether it is key or not, and date, image and file input fields
  * are handled automatically
  * @param vars - An array of key=>value pairs to assign to the fields
  * @access public
  */
 function assignFieldValues($vars)
 {
     $ret = true;
     /*assign field field values*/
     $fields = $this->fields();
     foreach ($fields as $field) {
         $field->initialise();
         if (!$field->auto()) {
             if (isset($vars[$field->name()]) && !isset($vars['delete_' . $field->name()])) {
                 $val = $vars[$field->name()];
                 $this->initialiseFieldValue($field, $val);
             } else {
                 $uploads = FileUtility::uploadFiles();
                 if (isset($vars['delete_' . $field->name()])) {
                     $this->initialiseFieldValue($field, '');
                 } else {
                     $val = ArrayUtility::getArrayValue($uploads, $field->name());
                 }
                 if ($val) {
                     $this->initialiseFieldValue($field, $val);
                 }
             }
         }
         $val = '';
     }
     return true;
 }
Exemple #4
0
    exit;
}
//Get the XML file out and start importing them into our database.
//TODO: See question_import.php 287-289.
$qti_import = new QTIImport($import_path);
$qids = $qti_import->importQuestions($attributes);
//import test
$tid = $qti_import->importTest();
//associate question and tests
foreach ($qids as $order => $qid) {
    if (isset($qti_import->weights[$order])) {
        $weight = round($qti_import->weights[$order]);
    } else {
        $weight = 0;
    }
    $new_order = $order + 1;
    //	$sql = "INSERT INTO " . TABLE_PREFIX . "tests_questions_assoc" .
    //			"(test_id, question_id, weight, ordering, required) " .
    //			"VALUES ($tid, $qid, $weight, $new_order, 0)";
    //	$result = mysql_query($sql, $db);
    $testsQuestionsAssocDAO = new TestsQuestionsAssocDAO();
    $testsQuestionsAssocDAO->Create($tid, $qid, $weight, $new_order);
}
//debug('imported test');
if (!$msg->containsErrors()) {
    $msg->addFeedback('IMPORT_SUCCEEDED');
}
//clear directory
FileUtility::clr_dir(TR_CONTENT_DIR . 'import/' . $_course_id);
header('Location: index.php?_course_id=' . $_course_id);
exit;
Exemple #5
0
    /* check if this file extension is allowed: */
    /* $IllegalExtentions is defined in ./include/config.inc.php */
    if (in_array($ext_new, $IllegalExtentions)) {
        $errors = array('FILE_ILLEGAL', $ext_new);
        $msg->addError($errors);
    } else {
        if ($current_path . $pathext . $_POST['new_name'] == $current_path . $pathext . $_POST['oldname']) {
            //do nothing
            $msg->addFeedback('ACTION_COMPLETED_SUCCESSFULLY');
            header('Location: index.php?pathext=' . urlencode($_POST['pathext']) . SEP . 'framed=' . $_POST['framed'] . SEP . 'popup=' . $_POST['popup'] . SEP . 'cp=' . $_POST['cp'] . SEP . 'cid=' . $_POST['cid'] . SEP . 'pid=' . $_POST['pid'] . SEP . 'a_type=' . $_POST['a_type'] . SEP . '_course_id=' . $_course_id);
            exit;
        } else {
            if (FileUtility::course_realpath($current_path . $pathext . $_POST['new_name']) == FALSE) {
                $msg->addError('CANNOT_RENAME');
            } else {
                if (FileUtility::course_realpath($current_path . $pathext . $_POST['oldname']) == FALSE) {
                    $msg->addError('CANNOT_RENAME');
                } else {
                    if (file_exists($current_path . $pathext . $_POST['new_name'])) {
                        $msg->addError('CANNOT_RENAME');
                    } else {
                        @rename($current_path . $pathext . $_POST['oldname'], $current_path . $pathext . $_POST['new_name']);
                        $msg->addFeedback('ACTION_COMPLETED_SUCCESSFULLY');
                        header('Location: index.php?pathext=' . urlencode($_POST['pathext']) . SEP . 'framed=' . $_POST['framed'] . SEP . 'popup=' . $_POST['popup'] . SEP . 'cp=' . $_POST['cp'] . SEP . 'cid=' . $_POST['cid'] . SEP . 'pid=' . $_POST['pid'] . SEP . 'a_type=' . $_POST['a_type'] . SEP . '_course_id=' . $_course_id);
                        exit;
                    }
                }
            }
        }
    }
}
 /**
  * Clear the query cache for the object
  */
 public function clearQueryCache()
 {
     FileUtility::deleteFilesMatchingWildCard(Application::CACHE . 'query*-' . $this->getClass(true) . '-*');
 }
Exemple #7
0
 private function importBulkResumes()
 {
     if (!isset($_SESSION['CATS']) || empty($_SESSION['CATS'])) {
         CommonErrors::fatal(COMMONERROR_NOTLOGGEDIN, $this);
     }
     if ($_SESSION['CATS']->getAccessLevel() < ACCESS_LEVEL_SA) {
         CommonErrors::fatal(COMMONERROR_PERMISSION, $this);
     }
     $uploadPath = FileUtility::getUploadPath($this->_siteID, 'massimport');
     $attachments = new Attachments($this->_siteID);
     $bulkResumes = $attachments->getBulkAttachments();
     if (!count($bulkResumes)) {
         CommonErrors::fatal(COMMONERROR_BADINDEX, $this);
     }
     /**
      * Write the parsed resume contents to the new file which will
      * be created as a text document for each bulk attachment.
      */
     foreach ($bulkResumes as $bulkResume) {
         $fullName = $bulkResume['originalFileName'];
         if (!strlen(trim($fullName))) {
             $fullName = 'Untitled';
         }
         $mp = explode('.', $fullName);
         $fileName = implode('.', array_slice($mp, 0, -1));
         if (!@file_exists($newFileName = $uploadPath . '/_BulkResume_' . $fileName . '.txt')) {
             // Some old files are fulltext encoded which makes them a pain for the parser, fixing here:
             $contents = DatabaseSearch::fulltextDecode($bulkResume['text']);
             @file_put_contents($newFileName, $contents);
             chmod($newFileName, 0777);
         }
     }
     CATSUtility::transferRelativeURI('m=import&a=massImport&step=2');
 }
 /**
  * Store the contents of a file upload in the site's upload directory with an
  * optional sub-directory and return the name of the file (not including path).
  *
  * @param integer ID of the site containing the file
  * @param string Optional sub-directory to place the file
  * @param string Index of the $_FILES array (name from the <input> tag)
  * @return string Complete name of the file (not including path)
  */
 public static function getUploadFileFromPost($siteID, $subDirectory, $id)
 {
     if (isset($_FILES[$id])) {
         if (!@file_exists($_FILES[$id]['tmp_name'])) {
             // File was removed, accessed from another window, or no longer exists
             return false;
         }
         if (!eval(Hooks::get('FILE_UTILITY_SPACE_CHECK'))) {
             return;
         }
         $uploadPath = FileUtility::getUploadPath($siteID, $subDirectory);
         $newFileName = $_FILES[$id]['name'];
         // Could just while(file_exists) it, but I'm paranoid of infinate loops
         // Shouldn't have 1000 files of the same name anyway
         for ($i = 0; @file_exists($uploadPath . '/' . $newFileName) && $i < 1000; $i++) {
             $mp = explode('.', $newFileName);
             $fileNameBase = implode('.', array_slice($mp, 0, count($mp) - 1));
             $fileNameExt = $mp[count($mp) - 1];
             if (preg_match('/(.*)_Copy([0-9]{1,3})$/', $fileNameBase, $matches)) {
                 // Copy already appending, increase the #
                 $fileNameBase = sprintf('%s_Copy%d', $matches[1], intval($matches[2]) + 1);
             } else {
                 $fileNameBase .= '_Copy1';
             }
             $newFileName = $fileNameBase . '.' . $fileNameExt;
         }
         if (@move_uploaded_file($_FILES[$id]['tmp_name'], $uploadPath . '/' . $newFileName) && @chmod($uploadPath . '/' . $newFileName, 0777)) {
             return $newFileName;
         }
     }
     return false;
 }
 /**
  * Destructor - removes temporary folder and its content.
  * Should self-destruct automatically for PHP 5.0+; otherwise developers should call this function
  * to clean up.
  * @access	public
  * @author	Harris Wong
  */
 function __destruct()
 {
     FileUtility::clr_dir($this->zipfile_dir);
 }
 /**
  * Clear the cache for a particular file path
  * @param path - the path for which to clear the cache for
  * @access protected
  */
 protected function clearCache($path)
 {
     $path = MarkupInterpreter::cachePath($path);
     FileUtility::deleteFilesMatchingWildCard(Application::CACHE . '*' . $path . '*');
 }
            $files[$file1] .= '<img src="images/edit.gif" border="0" alt="' . _AT('edit') . '" title="' . _AT('edit') . '" height="15" width="18" class="img-size-fm4" />';
            $files[$file1] .= '</a>';
        }
        $files[$file1] .= '&nbsp;</td>';
        $files[$file1] .= '<td  align="right" style="white-space:nowrap">';
        if ($popup == TRUE) {
            if ($a_type > 0) {
                $files[$file1] .= '<input class="button" type="button" name="alternative" value="' . _AT('use_as_alternative') . '" onclick="javascript: setAlternative(\'' . get_relative_path($_GET['cp'], $pathext) . $file . '\', \'' . TR_BASE_HREF . $get_file . $pathext . urlencode($file) . '\', \'' . $cid . '\', \'' . $pid . '\', \'' . $a_type . '\');" />&nbsp;';
            } else {
                $files[$file1] .= '<input class="button" type="button" name="insert" value="' . _AT('insert') . '" onclick="javascript:insertFile(\'' . $file . '\', \'' . get_relative_path($_GET['cp'], $pathext) . '\', \'' . $ext . '\', \'' . $_SESSION['prefs']['PREF_CONTENT_EDITOR'] . '\');" />&nbsp;';
            }
        }
        $files[$file1] .= AT_date(_AT('filemanager_date_format'), $filedata[10], TR_DATE_UNIX_TIMESTAMP);
        $files[$file1] .= '&nbsp;</td>';
        $files[$file1] .= '<td  align="right" style="white-space:nowrap">';
        $files[$file1] .= FileUtility::get_human_size($filedata[7]) . '</td></tr>';
    }
}
// end while
// sort listing and output directories
if (is_array($dirs)) {
    ksort($dirs, SORT_STRING);
    foreach ($dirs as $x => $y) {
        echo $y;
    }
}
//sort listing and output files
if (is_array($files)) {
    ksort($files, SORT_STRING);
    foreach ($files as $x => $y) {
        echo $y;
 /**
  * Delete course
  * @access  public
  * @param   course ID
  * @return  true, if successful
  *          false and add error into global var $msg, if unsuccessful
  * @author  Cindy Qi Li
  */
 public function Delete($courseID)
 {
     require_once TR_INCLUDE_PATH . 'classes/FileUtility.class.php';
     require_once TR_INCLUDE_PATH . 'classes/DAO/ContentDAO.class.php';
     require_once TR_INCLUDE_PATH . 'classes/DAO/ForumsCoursesDAO.class.php';
     $contentDAO = new ContentDAO();
     $forumsCoursesDAO = new ForumsCoursesDAO();
     unset($_SESSION['s_cid']);
     // delete course content dir
     $content_dir = TR_CONTENT_DIR . $courseID . '/';
     FileUtility::clr_dir($content_dir);
     // delete tests and tests related data
     $sql = "DELETE FROM " . TABLE_PREFIX . "content_tests_assoc\n\t\t         WHERE content_id in (SELECT content_id FROM " . TABLE_PREFIX . "content WHERE course_id = " . $courseID . ")";
     $this->execute($sql);
     $sql = "DELETE FROM " . TABLE_PREFIX . "tests_questions_categories WHERE course_id = " . $courseID;
     $this->execute($sql);
     $sql = "DELETE FROM " . TABLE_PREFIX . "tests_questions_assoc \n\t\t         WHERE test_id in (SELECT test_id FROM " . TABLE_PREFIX . "tests WHERE course_id = " . $courseID . ")";
     $this->execute($sql);
     $sql = "DELETE FROM " . TABLE_PREFIX . "tests_questions WHERE course_id = " . $courseID;
     $this->execute($sql);
     $sql = "DELETE FROM " . TABLE_PREFIX . "tests WHERE course_id = " . $courseID;
     $this->execute($sql);
     // delete forums that are associated with this course
     $forumsCoursesDAO->DeleteByCourseID($courseID);
     // loop thru content to delete using ContentDAO->Delete(), which deletes a4a objects as well
     $content_rows = $contentDAO->getContentByCourseID($courseID);
     if (is_array($content_rows)) {
         foreach ($content_rows as $content) {
             $contentDAO->Delete($content['content_id']);
         }
     }
     $sql = "DELETE FROM " . TABLE_PREFIX . "content WHERE course_id = " . $courseID;
     $this->execute($sql);
     // delete user <-> course association
     $sql = "DELETE FROM " . TABLE_PREFIX . "user_courses WHERE course_id = " . $courseID;
     $this->execute($sql);
     // delete the course
     $sql = "DELETE FROM " . TABLE_PREFIX . "courses WHERE course_id = " . $courseID;
     return $this->execute($sql);
 }
Exemple #13
0
            } else {
                $msg->addError(array('MAX_STORAGE_EXCEEDED', get_human_size($my_MaxCourseSize)));
                FileUtility::handleAjaxUpload(500);
                if ($alter) {
                    header('Location: ' . $_base_href . 'editor/edit_content.php?cid=' . $_REQUEST['cid'] . SEP . 'pathext=' . $_POST['pathext'] . SEP . 'popup=' . $_GET['popup'] . SEP . 'tab=' . $_REQUEST['tab'] . SEP . '_course_id=' . $_course_id);
                } else {
                    header('Location: index.php?pathext=' . $_POST['pathext'] . SEP . 'popup=' . $_GET['popup'] . SEP . 'framed=' . $framed . SEP . 'cp=' . $_GET['cp'] . SEP . 'pid=' . $_GET['pid'] . SEP . 'cid=' . $_GET['cid'] . SEP . 'a_type=' . $_GET['a_type'] . SEP . '_course_id=' . $_course_id);
                }
                exit;
            }
        } else {
            $msg->addError(array('FILE_TOO_BIG', get_human_size($my_MaxFileSize)));
            FileUtility::handleAjaxUpload(500);
            if ($alter) {
                header('Location: ' . $_base_href . 'editor/edit_content.php?cid=' . $_REQUEST['cid'] . SEP . 'pathext=' . $_POST['pathext'] . SEP . 'popup=' . $_GET['popup'] . SEP . 'tab=' . $_REQUEST['tab'] . SEP . '_course_id=' . $_course_id);
            } else {
                header('Location: index.php?pathext=' . $_POST['pathext'] . SEP . 'popup=' . $_GET['popup'] . SEP . 'framed=' . $framed . SEP . 'cp=' . $_GET['cp'] . SEP . 'pid=' . $_GET['pid'] . SEP . 'cid=' . $_GET['cid'] . SEP . 'a_type=' . $_GET['a_type'] . SEP . '_course_id=' . $_course_id);
            }
            exit;
        }
    } else {
        $msg->addError('FILE_NOT_SELECTED');
        FileUtility::handleAjaxUpload(500);
        if ($alter) {
            header('Location: ' . $_base_href . 'editor/edit_content.php?cid=' . $_REQUEST['cid'] . SEP . 'pathext=' . $_POST['pathext'] . SEP . 'popup=' . $_GET['popup'] . SEP . 'tab=' . $_REQUEST['tab'] . SEP . '_course_id=' . $_course_id);
        } else {
            header('Location: index.php?pathext=' . $_POST['pathext'] . SEP . 'popup=' . $_GET['popup'] . SEP . 'framed=' . $framed . SEP . 'cp=' . $_GET['cp'] . SEP . 'pid=' . $_GET['pid'] . SEP . 'cid=' . $_GET['cid'] . SEP . 'a_type=' . $_GET['a_type'] . SEP . '_course_id=' . $_course_id);
        }
        exit;
    }
}
 public function init()
 {
     FileUtility::loadClassWithoutYii('phpexcel/PHPExcel.php');
     return true;
 }
Exemple #15
0
 private function _createDirectory($attachmentID, $storedFilename)
 {
     /* Make sure attachments exists. */
     if (!is_dir('./attachments')) {
         /* No? Create it. */
         @mkdir('./attachments', 0777);
         @touch('./attachments/index.php');
     }
     /* Attachments are first grouped under a directory for each site ID. */
     $siteDirectory = './attachments/site_' . $this->_siteID;
     /* Make sure the site directory exists. */
     if (!is_dir($siteDirectory)) {
         /* No? Create it. */
         @mkdir($siteDirectory, 0777);
     }
     /* Attachments are then grouped in groups of 1000 attachment IDs. */
     $IDGroupDirectory = sprintf('%s/%sxxx', $siteDirectory, (int) ($attachmentID / 1000));
     /* Make sure the attachment ID group directory exists. */
     if (!is_dir($IDGroupDirectory)) {
         /* No? Create it. */
         @mkdir($IDGroupDirectory, 0777);
     }
     /* If we had to create directories above, make sure that the creation
      * was successful.
      */
     if (!is_dir($IDGroupDirectory)) {
         $this->_isError = true;
         $this->_error = sprintf('Cannot create directory %s, and it does not already exist.', $IDGroupDirectory);
         return false;
     }
     /* Prevent webserver listing of new directories. */
     if (!file_exists($siteDirectory . '/index.php')) {
         @file_put_contents($siteDirectory . '/index.php', "\n");
     }
     if (!file_exists($IDGroupDirectory . '/index.php')) {
         @file_put_contents($IDGroupDirectory . '/index.php', "\n");
     }
     /* Get a unique directroy name in which to store the attachment. */
     $uniqueDirectory = sprintf('%s/%s/', $IDGroupDirectory, FileUtility::getUniqueDirectory($IDGroupDirectory, $storedFilename));
     /* Attempt to create a directory for this attachment ID. */
     if (!is_dir($uniqueDirectory)) {
         @mkdir($uniqueDirectory, 0777);
     }
     /* Was creation successful? */
     if (!is_dir($uniqueDirectory)) {
         $this->_isError = true;
         $this->_error = sprintf('Cannot create directory %s, and it does not already exist.', $uniqueDirectory);
         return false;
     }
     /* We probably don't have permission to chmod, but try anyway. */
     @chmod($uniqueDirectory, 0777);
     return $uniqueDirectory;
 }
Exemple #16
0
        if (($f = @fopen($current_path . $pathext . $file, 'w')) && @fwrite($f, $content) !== false && @fclose($f)) {
            $msg->addFeedback(array('FILE_SAVED', $file));
            header('Location: index.php?pathext=' . $_POST['pathext'] . SEP . 'framed=' . $_POST['framed'] . SEP . 'popup=' . $_POST['popup'] . SEP . '_course_id=' . $_course_id);
            exit;
        } else {
            $msg->addError('FILE_NOT_SAVED');
        }
    }
    header('Location: index.php?pathext=' . $_POST['pathext'] . SEP . 'framed=' . $_POST['framed'] . SEP . 'popup=' . $_POST['popup'] . SEP . '_course_id=' . $_course_id);
    exit;
}
$path_parts = pathinfo($current_path . $pathext . $file);
$ext = strtolower($path_parts['extension']);
// open file to edit
$real = realpath($current_path . $pathext . $file);
if (FileUtility::course_realpath($current_path . $pathext . $file) == FALSE) {
    // error: File does not exist
    $msg->addError('FILE_NOT_EXIST');
    header('Location: index.php?pathext=' . $pathext . SEP . 'framed=' . $framed . SEP . 'popup=' . $popup . SEP . '_course_id=' . $_course_id);
    exit;
} else {
    if (is_dir($current_path . $pathext . $file)) {
        // error: cannot edit folder
        $msg->addError('BAD_FILE_TYPE');
        header('Location: index.php?pathext=' . $pathext . SEP . 'framed=' . $framed . SEP . 'popup=' . $popup . SEP . '_course_id=' . $_course_id);
        exit;
    } else {
        if (!is_readable($current_path . $pathext . $file)) {
            // error: File cannot open file
            $msg->addError(array('CANNOT_OPEN_FILE', $file));
            header('Location: index.php?pathext=' . $pathext . SEP . 'framed=' . $framed . SEP . 'popup=' . $popup . SEP . '_course_id=' . $_course_id);
 public static function display_tree($current_path, $cur_dir, $pathext, $ignore_children = false)
 {
     // open the cur_dir
     static $list_array;
     if (!isset($list_array)) {
         $list_array = explode(',', $_GET['list']);
     }
     if ($dir = opendir($current_path . $cur_dir)) {
         // recursively call output_dirs() for all directories in this directory
         while (false !== ($file = readdir($dir))) {
             //if the name is not a directory
             if ($file == '.' || $file == '..') {
                 continue;
             }
             // if it is a directory call function
             if (is_dir($current_path . $cur_dir . $file)) {
                 //$ldir = explode('/',$cur_dir.$file);
                 //$count = count($ldir);
                 //$label = $ldir[$count-1];
                 $check = '';
                 $here = '';
                 if ($cur_dir . $file == substr($pathext, 0, -1)) {
                     $check = 'checked="checked"';
                     $here = ' ' . _AT('current_location');
                 } else {
                     if ($cur_dir == $pathext && in_array($file, $list_array)) {
                         $ignore_children = true;
                     }
                 }
                 if ($ignore_children) {
                     $check = 'disabled="disabled"';
                     $class = ' disabled';
                 }
                 $dir_option .= '<ul><li class="folders' . $class . '">';
                 $dir_option .= '<label><input type="radio" name="dir_name" value="' . $cur_dir . $file . '" ' . $check . '/>' . $file . $here . '</label>';
                 $dir_option .= '' . FileUtility::display_tree($current_path, $cur_dir . $file . '/', $pathext, $ignore_children) . '';
                 $dir_option .= '</li></ul>';
                 if ($cur_dir == $pathext && in_array($file, $list_array)) {
                     $ignore_children = false;
                     $class = '';
                 }
             }
         }
         // end while
         closedir($dir);
     }
     return $dir_option;
 }
 private function show()
 {
     /* Is this a popup? */
     if (isset($_GET['display']) && $_GET['display'] == 'popup') {
         $isPopup = true;
     } else {
         $isPopup = false;
     }
     /* Bail out if we don't have a valid candidate ID. */
     if (!$this->isRequiredIDValid('jobOrderID', $_GET)) {
         /* FIXME: fatalPopup()? */
         CommonErrors::fatal(COMMONERROR_BADINDEX, $this, 'Invalid job order ID.');
     }
     $jobOrderID = $_GET['jobOrderID'];
     $jobOrders = new JobOrders($this->_siteID);
     $data = $jobOrders->get($jobOrderID);
     /* Bail out if we got an empty result set. */
     if (empty($data)) {
         CommonErrors::fatal(COMMONERROR_BADINDEX, $this, 'The specified job order ID could not be found.');
     }
     if ($data['isAdminHidden'] == 1 && $this->_accessLevel < ACCESS_LEVEL_MULTI_SA) {
         $this->listByView('This Job Order is hidden - only a CATS Administrator can unlock the Job Order.');
         return;
     }
     /* We want to handle formatting the city and state here instead of in
      * the template.
      */
     $data['cityAndState'] = StringUtility::makeCityStateString($data['city'], $data['state']);
     $data['description'] = trim($data['description']);
     $data['notes'] = trim($data['notes']);
     /* Determine the Job Type Description */
     $data['typeDescription'] = $jobOrders->typeCodeToString($data['type']);
     /* Convert '00-00-00' dates to empty strings. */
     $data['startDate'] = DateUtility::fixZeroDate($data['startDate']);
     /* Hot jobs [can] have different title styles than normal jobs. */
     if ($data['isHot'] == 1) {
         $data['titleClass'] = 'jobTitleHot';
     } else {
         $data['titleClass'] = 'jobTitleCold';
     }
     if ($data['public'] == 1) {
         $data['public'] = '<img src="images/public.gif" height="16" ' . 'width="16" title="This Job Order is marked as Public." />';
     } else {
         $data['public'] = '';
     }
     $attachments = new Attachments($this->_siteID);
     $attachmentsRS = $attachments->getAll(DATA_ITEM_JOBORDER, $jobOrderID);
     foreach ($attachmentsRS as $rowNumber => $attachmentsData) {
         /* Show an attachment icon based on the document's file type. */
         $attachmentIcon = strtolower(FileUtility::getAttachmentIcon($attachmentsRS[$rowNumber]['originalFilename']));
         $attachmentsRS[$rowNumber]['attachmentIcon'] = $attachmentIcon;
     }
     $careerPortalSettings = new CareerPortalSettings($this->_siteID);
     $careerPortalSettingsRS = $careerPortalSettings->getAll();
     if ($careerPortalSettingsRS['enabled'] == 1) {
         $careerPortalEnabled = true;
     } else {
         $careerPortalEnabled = false;
     }
     /* Add an MRU entry. */
     $_SESSION['CATS']->getMRU()->addEntry(DATA_ITEM_JOBORDER, $jobOrderID, $data['title']);
     if ($this->_accessLevel < ACCESS_LEVEL_DEMO) {
         $privledgedUser = false;
     } else {
         $privledgedUser = true;
     }
     /* Get extra fields. */
     $extraFieldRS = $jobOrders->extraFields->getValuesForShow($jobOrderID);
     $pipelineEntriesPerPage = $_SESSION['CATS']->getPipelineEntriesPerPage();
     $sessionCookie = $_SESSION['CATS']->getCookie();
     /* Get pipeline graph. */
     $graphs = new graphs();
     $pipelineGraph = $graphs->miniJobOrderPipeline(450, 250, array($jobOrderID));
     /* Get questionnaire information (if exists) */
     $questionnaireID = false;
     $questionnaireData = false;
     $careerPortalURL = false;
     $isPublic = false;
     if ($careerPortalEnabled && $data['public']) {
         $isPublic = true;
         if ($data['questionnaireID']) {
             $questionnaire = new Questionnaire($this->_siteID);
             $q = $questionnaire->get($data['questionnaireID']);
             if (is_array($q) && !empty($q)) {
                 $questionnaireID = $q['questionnaireID'];
                 $questionnaireData = $q;
             }
         }
     }
     $careerPortalSettings = new CareerPortalSettings($this->_siteID);
     $cpSettings = $careerPortalSettings->getAll();
     if (intval($cpSettings['enabled'])) {
         $careerPortalURL = CATSUtility::getAbsoluteURI() . 'careers/';
     }
     $this->_template->assign('active', $this);
     $this->_template->assign('isPublic', $isPublic);
     $this->_template->assign('questionnaireID', $questionnaireID);
     $this->_template->assign('questionnaireData', $questionnaireData);
     $this->_template->assign('careerPortalURL', $careerPortalURL);
     $this->_template->assign('data', $data);
     $this->_template->assign('extraFieldRS', $extraFieldRS);
     $this->_template->assign('attachmentsRS', $attachmentsRS);
     $this->_template->assign('pipelineEntriesPerPage', $pipelineEntriesPerPage);
     $this->_template->assign('pipelineGraph', $pipelineGraph);
     $this->_template->assign('jobOrderID', $jobOrderID);
     $this->_template->assign('isPopup', $isPopup);
     $this->_template->assign('careerPortalEnabled', $careerPortalEnabled);
     $this->_template->assign('privledgedUser', $privledgedUser);
     $this->_template->assign('sessionCookie', $_SESSION['CATS']->getCookie());
     if (!eval(Hooks::get('JO_SHOW'))) {
         return;
     }
     $this->_template->display('./modules/joborders/Show.tpl');
 }
Exemple #19
0
    public function capturePostData($siteID, $ignore = array())
    {
        $hiddenTags = '';

        foreach ($_POST as $name => $value)
        {
            if (in_array($name, $ignore)) continue;
            $hiddenTags .= sprintf('<input type="hidden" name="%s" value="%s" />%s',
                $name,
                htmlspecialchars($value),
                "\n"
            );
        }

        if (($uploadFile = FileUtility::getUploadFileFromPost($siteID, 'careerportaladd', 'file')) !== false)
        {
            $hiddenTags .= sprintf('<input type="hidden" name="file" value="%s" />%s',
                $uploadFile, "\n"
            );
        }

        return $hiddenTags;
    }
Exemple #20
0
 private function storeMonsterResumeText()
 {
     $this->_authenticate();
     if (!isset($_POST['resumeText'])) {
         $this->fatal('No resume.');
     }
     $resumeText = $_POST['resumeText'];
     /* The toolbar inputs the BODY of the monster page.  First, we convert
      * the HTML of the BODY into text with html2text...
      */
     $temporaryFile = FileUtility::makeRandomTemporaryFilePath() . '.html';
     if (file_put_contents($temporaryFile, $resumeText) === false) {
         $this->fatal('Failed to save data for parsing.');
     }
     $documentToText = new DocumentToText();
     $documentType = $documentToText->getDocumentType($temporaryFile, 'text/html');
     $documentToText->convert($temporaryFile, $documentType);
     if ($documentToText->isError()) {
         $this->_isTextExtractionError = true;
         $this->_textExtractionError = $documentToText->getError();
         $parsedText = '';
     } else {
         $parsedText = $documentToText->getString();
     }
     @unlink($temporaryFile);
     /* Now, we have to determine where the resume begins and ends and cut out the
      * top and bottom of the resume...
      */
     $parsedTextArray = explode("\n", $parsedText);
     $firstLine = 0;
     $lastLine = count($parsedTextArray) - 1;
     foreach ($parsedTextArray as $line => $data) {
         /* Find first line */
         if ((strpos($data, 'RESUME') !== false || strpos($data, 'CV') !== false) && strpos($data, '^BACK_TO_TOP') !== false && $firstLine == 0) {
             $firstLine = $line + 1;
         }
         /* Find last line */
         if (strpos($data, '^BACK_TO_TOP') !== false || strpos($data, 'Back_to_top') !== false || strpos($data, 'Back to top') !== false) {
             $lastLine = $line - 1;
         }
         /* TODO:  Look for more keywords present at the bottom of this page
          * in case Back_top_top goes away
          */
         /* Remove the back to top links from the resume to prevent indexing */
         if (strpos($data, '^BACK_TO_TOP') !== false) {
             $data = str_replace('^BACK TO TOP', '', $data);
         }
         /* Convert bullet points into - symbols. */
         $data = str_replace('%u2022', '-', $data);
         $parsedTextArray[$line] = $data;
     }
     $parsedTextArray = array_slice($parsedTextArray, $firstLine, $lastLine - $firstLine + 1);
     $parsedText = implode("\n", $parsedTextArray);
     /* Remember the output in the session and return to the toolbar
      * the ID number of the data.
      */
     $storedID = $_SESSION['CATS']->storeData($parsedText);
     echo $storedID;
     flush();
 }
Exemple #21
0
        $result = true;
        for ($i = 0; $i < $count; $i++) {
            $filename = $checkbox[$i];
            if (strpos($filename, '..') !== false) {
                $msg->addError('UNKNOWN');
                $result = false;
                header('Location: index.php?pathext=' . $_POST['pathext'] . SEP . 'framed=' . $_POST['framed'] . SEP . 'popup=' . $_POST['popup'] . SEP . 'cp=' . $_POST['cp'] . SEP . 'cid=' . $_POST['cid'] . SEP . 'pid=' . $_POST['pid'] . SEP . 'a_type=' . $_POST['a_type'] . SEP . '_course_id=' . $_course_id);
                exit;
            } else {
                if (!is_dir($current_path . $pathext . $filename)) {
                    $msg->addError(array('DIR_NOT_DELETED', $filename));
                    $result = false;
                    header('Location: index.php?pathext=' . $_POST['pathext'] . SEP . 'framed=' . $_POST['framed'] . SEP . 'popup=' . $_POST['popup'] . SEP . 'cp=' . $_POST['cp'] . SEP . 'cid=' . $_POST['cid'] . SEP . 'pid=' . $_POST['pid'] . SEP . 'a_type=' . $_POST['a_type'] . SEP . '_course_id=' . $_course_id);
                    exit;
                } else {
                    if (!($result = FileUtility::clr_dir($current_path . $pathext . $filename))) {
                        $msg->addError('DIR_NO_PERMISSION');
                        $result = false;
                        header('Location: index.php?pathext=' . $_POST['pathext'] . SEP . 'framed=' . $_POST['framed'] . SEP . 'popup=' . $_POST['popup'] . SEP . 'cp=' . $_POST['cp'] . SEP . 'cid=' . $_POST['cid'] . SEP . 'pid=' . $_POST['pid'] . SEP . 'a_type=' . $_POST['a_type'] . SEP . '_course_id=' . $_course_id);
                        exit;
                    }
                }
            }
        }
        if ($result) {
            $msg->addFeedback('DIR_DELETED');
        }
    }
    header('Location: index.php?pathext=' . $_POST['pathext'] . SEP . 'framed=' . $_POST['framed'] . SEP . 'popup=' . $_POST['popup'] . SEP . 'cp=' . $_POST['cp'] . SEP . 'cid=' . $_POST['cid'] . SEP . 'pid=' . $_POST['pid'] . SEP . 'a_type=' . $_POST['a_type'] . SEP . '_course_id=' . $_course_id);
    exit;
}
 private static function _checkReadWrite($directory)
 {
     $directory .= '/';
     if (!is_dir($directory)) {
         echo sprintf('<tr class="fail"><td><strong>Directory %s does not exist or is not a directory.</strong></td></tr>', $directory);
         return false;
     }
     $octalPermissions = FileUtility::getOctalPermissions($directory);
     $proceed = true;
     /* Check for read. */
     if (is_readable($directory)) {
         echo sprintf('<tr class="pass"><td>Directory %s is readable (permissions: %s).</td></tr>', $directory, $octalPermissions);
     } else {
         echo sprintf('<tr class="fail"><td><strong>Directory %s is not readable (permissions: %s).</strong></td></tr>', $directory, $octalPermissions);
         $proceed = false;
     }
     /* Check for write. */
     if (is_writeable($directory)) {
         echo sprintf('<tr class="pass"><td>Directory %s is writeable (permissions: %s).</td></tr>', $directory, $octalPermissions);
     } else {
         echo sprintf('<tr class="fail"><td><strong>Directory %s is not writeable (permissions: %s).</strong></td></tr>', $directory, $octalPermissions);
         $proceed = false;
     }
     /* Test ACTUAL writeability by creating a file, not relying on is_writable()
      * as it sometimes returns a false positive.
      */
     if (FileUtility::isDirectoryWritable($directory)) {
         echo sprintf('<tr class="pass"><td>Creating a file within %s succeeded.</td></tr>', $directory);
     } else {
         echo sprintf('<tr class="fail"><td><strong>Creating a file within %s failed. Check your permissions.</strong></td></tr>', $directory);
         $proceed = false;
     }
     /* Check for create directory ability. */
     $testPath = $directory . 'testdir';
     if (is_dir($testPath)) {
         FileUtility::recursivelyRemoveDirectory($testPath);
     }
     if (@mkdir($testPath, 0777)) {
         echo sprintf('<tr class="pass"><td>Directories can be created inside %s/.</td></tr>', $directory);
     } else {
         echo sprintf('<tr class="fail"><td><strong>Directories cannot be created inside %s/.</strong></td></tr>', $directory);
         $proceed = false;
     }
     if (is_dir($testPath)) {
         FileUtility::recursivelyRemoveDirectory($testPath);
     }
     return $proceed;
 }
Exemple #23
0
 public function wizard_import()
 {
     if (!isset($_SESSION['CATS']) || empty($_SESSION['CATS'])) {
         echo 'CATS has lost your session!';
         return;
     }
     $siteID = $_SESSION['CATS']->getSiteID();
     // Echos Ok to redirect to the import stage, or Fail to go to home module
     $files = ImportUtility::getDirectoryFiles(FileUtility::getUploadPath($siteID, 'massimport'));
     if (count($files)) {
         echo 'Ok';
     } else {
         echo 'Fail';
     }
 }
Exemple #24
0
        $patch_list_array = $patchListParser->getMyParsedArrayForVersion(VERSION);
    }
}
// end of get patch list
$module_content_folder = TR_CONTENT_DIR . "updater/temp";
if (!is_dir($module_content_folder)) {
    mkdir($module_content_folder);
}
if ($_POST['install_upload'] && $_POST['uploading']) {
    include_once TR_INCLUDE_PATH . 'lib/pclzip.lib.php';
    // clean up module content folder
    FileUtility::clr_dir($module_content_folder);
    // 1. unzip uploaded file to module's content directory
    $archive = new PclZip($_FILES['patchfile']['tmp_name']);
    if ($archive->extract(PCLZIP_OPT_PATH, $module_content_folder) == 0) {
        FileUtility::clr_dir($module_content_folder);
        $msg->addError('CANNOT_UNZIP');
    }
}
// Installation process
if ($_POST['install'] || $_POST['install_upload'] && !isset($_POST["not_ignore_version"])) {
    if (isset($_POST['id'])) {
        $id = $_POST['id'];
    } else {
        $id = $_REQUEST['id'];
    }
    if ($_POST['install'] && $id == "") {
        $msg->addError('CHOOSE_UNINSTALLED_PATCH');
    } else {
        if ($_POST['install']) {
            $patchURL = $patch_folder . $patch_list_array[$id][patch_folder] . "/";
Exemple #25
0
 private function show()
 {
     /* Bail out if we don't have a valid company ID. */
     if (!$this->isRequiredIDValid('companyID', $_GET)) {
         $this->listByView('Invalid company ID.');
         return;
     }
     $companyID = $_GET['companyID'];
     $companies = new Companies($this->_siteID);
     $data = $companies->get($companyID);
     /* Bail out if we got an empty result set. */
     if (empty($data)) {
         $this->listByView('The specified company ID could not be found.');
         return;
     }
     /* We want to handle formatting the city and state here instead
      * of in the template.
      */
     $data['cityAndState'] = StringUtility::makeCityStateString($data['city'], $data['state']);
     /*
      * Replace newlines with <br />, fix HTML "special" characters, and
      * strip leading empty lines and spaces.
      */
     $data['notes'] = trim(nl2br(htmlspecialchars($data['notes'], ENT_QUOTES)));
     /* Chop $data['notes'] to make $data['shortNotes']. */
     if (strlen($data['notes']) > self::NOTES_MAXLEN) {
         $data['shortNotes'] = substr($data['notes'], 0, self::NOTES_MAXLEN);
         $isShortNotes = true;
     } else {
         $data['shortNotes'] = $data['notes'];
         $isShortNotes = false;
     }
     /* Hot companies [can] have different title styles than normal companies. */
     if ($data['isHot'] == 1) {
         $data['titleClass'] = 'jobTitleHot';
     } else {
         $data['titleClass'] = 'jobTitleCold';
     }
     /* Link to Google Maps for this address */
     if (!empty($data['address']) && !empty($data['city']) && !empty($data['state'])) {
         $data['googleMaps'] = '<a href="http://maps.google.com/maps?q=' . urlencode($data['address']) . '+' . urlencode($data['city']) . '+' . urlencode($data['state']);
         /* Google Maps will find an address without Zip. */
         if (!empty($data['zip'])) {
             $data['googleMaps'] .= '+' . $data['zip'];
         }
         $data['googleMaps'] .= '" target=_blank><img src="images/google_maps.gif" style="border: none;" class="absmiddle" /></a>';
     } else {
         $data['googleMaps'] = '';
     }
     /* Attachments */
     $attachments = new Attachments($this->_siteID);
     $attachmentsRS = $attachments->getAll(DATA_ITEM_COMPANY, $companyID);
     foreach ($attachmentsRS as $rowNumber => $attachmentsData) {
         /* Show an attachment icon based on the document's file type. */
         $attachmentIcon = strtolower(FileUtility::getAttachmentIcon($attachmentsRS[$rowNumber]['originalFilename']));
         $attachmentsRS[$rowNumber]['attachmentIcon'] = $attachmentIcon;
     }
     /* Job Orders for this company */
     $jobOrders = new JobOrders($this->_siteID);
     $jobOrdersRS = $jobOrders->getAll(JOBORDERS_STATUS_ALL, -1, $companyID, -1);
     if (!empty($jobOrdersRS)) {
         foreach ($jobOrdersRS as $rowIndex => $row) {
             /* Convert '00-00-00' dates to empty strings. */
             $jobOrdersRS[$rowIndex]['startDate'] = DateUtility::fixZeroDate($jobOrdersRS[$rowIndex]['startDate']);
             /* Hot jobs [can] have different title styles than normal
              * jobs.
              */
             if ($jobOrdersRS[$rowIndex]['isHot'] == 1) {
                 $jobOrdersRS[$rowIndex]['linkClass'] = 'jobLinkHot';
             } else {
                 $jobOrdersRS[$rowIndex]['linkClass'] = 'jobLinkCold';
             }
             $jobOrdersRS[$rowIndex]['recruiterAbbrName'] = StringUtility::makeInitialName($jobOrdersRS[$rowIndex]['recruiterFirstName'], $jobOrdersRS[$rowIndex]['recruiterLastName'], false, LAST_NAME_MAXLEN);
             $jobOrdersRS[$rowIndex]['ownerAbbrName'] = StringUtility::makeInitialName($jobOrdersRS[$rowIndex]['ownerFirstName'], $jobOrdersRS[$rowIndex]['ownerLastName'], false, LAST_NAME_MAXLEN);
         }
     }
     /* Contacts for this company */
     $contacts = new Contacts($this->_siteID);
     $contactsRS = $contacts->getAll(-1, $companyID);
     $contactsRSWC = null;
     if (!empty($contactsRS)) {
         foreach ($contactsRS as $rowIndex => $row) {
             /* Hot contacts [can] have different title styles than normal contacts. */
             if ($contactsRS[$rowIndex]['isHot'] == 1) {
                 $contactsRS[$rowIndex]['linkClass'] = 'jobLinkHot';
             } else {
                 $contactsRS[$rowIndex]['linkClass'] = 'jobLinkCold';
             }
             if (!empty($contactsRS[$rowIndex]['ownerFirstName'])) {
                 $contactsRS[$rowIndex]['ownerAbbrName'] = StringUtility::makeInitialName($contactsRS[$rowIndex]['ownerFirstName'], $contactsRS[$rowIndex]['ownerLastName'], false, LAST_NAME_MAXLEN);
             } else {
                 $contactsRS[$rowIndex]['ownerAbbrName'] = 'None';
             }
             if ($contactsRS[$rowIndex]['leftCompany'] == 0) {
                 $contactsRSWC[] = $contactsRS[$rowIndex];
             } else {
                 $contactsRS[$rowIndex]['linkClass'] = 'jobLinkDead';
             }
         }
     }
     /* Add an MRU entry. */
     $_SESSION['CATS']->getMRU()->addEntry(DATA_ITEM_COMPANY, $companyID, $data['name']);
     /* Get extra fields. */
     $extraFieldRS = $companies->extraFields->getValuesForShow($companyID);
     /* Get departments. */
     $departmentsRS = $companies->getDepartments($companyID);
     /* Is the user an admin - can user see history? */
     if ($this->_accessLevel < ACCESS_LEVEL_DEMO) {
         $privledgedUser = false;
     } else {
         $privledgedUser = true;
     }
     $this->_template->assign('active', $this);
     $this->_template->assign('data', $data);
     $this->_template->assign('attachmentsRS', $attachmentsRS);
     $this->_template->assign('departmentsRS', $departmentsRS);
     $this->_template->assign('extraFieldRS', $extraFieldRS);
     $this->_template->assign('isShortNotes', $isShortNotes);
     $this->_template->assign('jobOrdersRS', $jobOrdersRS);
     $this->_template->assign('contactsRS', $contactsRS);
     $this->_template->assign('contactsRSWC', $contactsRSWC);
     $this->_template->assign('privledgedUser', $privledgedUser);
     $this->_template->assign('companyID', $companyID);
     if (!eval(Hooks::get('CLIENTS_SHOW'))) {
         return;
     }
     $this->_template->display('./modules/companies/Show.tpl');
 }
 /**
  * Adds a file to the archive.
  *
  * @param string Name of file as to be stored inside the archive,
  *               optionally including the path.
  * @param string File data.
  * @param integer Last modified timestamp, or false for current time.
  * @return void
  */
 function addFileFromDisk($name, $filename, $timestamp = false)
 {
     /* Normally, we would split this into several methods, but this must be
      * optimized for minimal RAM usage, which presents a design challenge.
      */
     $data = @file_get_contents($filename);
     /* Do we still have a valid file handle? */
     if (!$this->_fileHandle) {
         $this->_errorMessage = 'Unexpected end of file.';
         return false;
     }
     /* Convert DOS / Windows paths to UNIX paths. */
     $name = str_replace('\\', '/', $name);
     /* If a timestamp wasn't specified, use the current time. */
     if ($timestamp === false) {
         $timestamp = time();
     }
     /* Convert our UNIX timestamp to DOS format. */
     $DOSTime = FileCompressorUtility::UNIXToDOSTime($timestamp);
     /* Calculate the length of the file data before compression. */
     $uncompressedLength = filesize($filename);
     /* Calculate the CRC32 checksum of the file data to be compressed. */
     $CRC32 = HashUtility::crc32File($filename);
     /* Version needed to extract.
      *
      * Store Only: 10
      * DEFLATE:    20
      * BZIP2:      46
      *
      * From the ZIP format specification:
      *
      * Current minimum feature versions are as defined below:
      *
      * 1.0 - Default value
      * 1.1 - File is a volume label
      * 2.0 - File is a folder (directory)
      * 2.0 - File is compressed using Deflate compression
      * 2.0 - File is encrypted using traditional PKWARE encryption
      * 2.1 - File is compressed using Deflate64(tm)
      * 2.5 - File is compressed using PKWARE DCL Implode 
      * 2.7 - File is a patch data set 
      * 4.5 - File uses ZIP64 format extensions
      * 4.6 - File is compressed using BZIP2 compression*
      * 5.0 - File is encrypted using DES
      * 5.0 - File is encrypted using 3DES
      * 5.0 - File is encrypted using original RC2 encryption
      * 5.0 - File is encrypted using RC4 encryption
      * 5.1 - File is encrypted using AES encryption
      * 5.1 - File is encrypted using corrected RC2 encryption**
      * 5.2 - File is encrypted using corrected RC2-64 encryption**
      * 6.1 - File is encrypted using non-OAEP key wrapping***
      * 6.2 - Central directory encryption
      * 6.3 - File is compressed using LZMA
      * 6.3 - File is compressed using PPMd+
      * 6.3 - File is encrypted using Blowfish
      * 6.3 - File is encrypted using Twofish
      */
     $versionNeededToExtract = 20;
     /* General purpose bit-flag.
      *
      * From the ZIP format specification:
      *
      * Bit 0: If set, indicates that the file is encrypted.
      *
      * <cut, irrelevant>
      *
      * (For Methods 8 and 9 - Deflating)
      * Bit 2  Bit 1
      *   0      0    Normal (-en) compression option was used.
      *   0      1    Maximum (-exx/-ex) compression option was used.
      *   1      0    Fast (-ef) compression option was used.
      *   1      1    Super Fast (-es) compression option was used.
      *
      * <cut, irrelevant>
      *
      * Bit 3: If this bit is set, the fields crc-32, compressed 
      *        size and uncompressed size are set to zero in the 
      *        local header.  The correct values are put in the 
      *        data descriptor immediately following the compressed
      *        data.  (Note: PKZIP version 2.04g for DOS only 
      *        recognizes this bit for method 8 compression, newer 
      *        versions of PKZIP recognize this bit for any 
      *        compression method.)
      *
      * Bit 4: Reserved for use with method 8, for enhanced
      *        deflating. 
      *
      * Bit 5: If this bit is set, this indicates that the file is 
      *        compressed patched data.  (Note: Requires PKZIP 
      *        version 2.70 or greater)
      *
      * Bit 6: Strong encryption.  If this bit is set, you should
      *        set the version needed to extract value to at least
      *        50 and you must also set bit 0.  If AES encryption
      *        is used, the version needed to extract value must 
      *        be at least 51.
      *
      * Bit [7-10]: Currently unused.
      *
      * Bit 11: Language encoding flag (EFS).  If this bit is set,
      *         the filename and comment fields for this file
      *         must be encoded using UTF-8. (see APPENDIX D)
      *
      * Bit 12: Reserved by PKWARE for enhanced compression.
      *
      * Bit 13: Used when encrypting the Central Directory to indicate 
      *         selected data values in the Local Header are masked to
      *         hide their actual values.  See the section describing 
      *         the Strong Encryption Specification for details.
      *
      * Bit [14-15]: Reserved by PKWARE.
      */
     $generalPurposeBitFlag = 0;
     /* Compression method.
      *
      * 0:  STORE
      * 8:  DEFLATE
      * 12: BZIP2
      */
     $compressionMethod = 8;
     /* Extra field length. */
     $extraFieldLength = 0;
     /* Format:
      *
      * [4B] [Start of File Record Marker]
      * [2B] [Version Needed to Extract]
      * [2B] [General Purpose Bit Flag (See Above)]
      * [2B] [Compression Method (See Above)]
      *
      * [4B] [Last-Modified Timestamp in DOS Format]
      * [4B] [CRC32 Checksum of Compressed Data]
      * [4B] [Compressed Data Length]
      * [4B] [Uncompressed Data Length]
      *
      * [2B] [Filename Length]
      * [2B] [Extra Field Length]
      */
     $fileRecord = pack('VvvvVVVVvv', START_FILE_RECORD, $versionNeededToExtract, $generalPurposeBitFlag, $compressionMethod, $DOSTime, $CRC32, 0, $uncompressedLength, strlen($name), $extraFieldLength);
     /* Filename. */
     $fileRecord .= $name;
     /* This is the "data descriptor" section, however, apparently this
      * causes problems and is optional anyway.
      *
      * From the ZIP format specification:
      * C.  Data descriptor:
      *
      * crc-32                          4 bytes
      * compressed size                 4 bytes
      * uncompressed size               4 bytes
      *
      * This descriptor exists only if bit 3 of the general
      * purpose bit flag is set (see below).  It is byte aligned
      * and immediately follows the last byte of compressed data.
      * This descriptor is used only when it was not possible to
      * seek in the output .ZIP file, e.g., when the output .ZIP file
      * was standard output or a non-seekable device.  For ZIP64(tm) format
      * archives, the compressed and uncompressed sizes are 8 bytes each.
      *
      * When compressing files, compressed and uncompressed sizes 
      * should be stored in ZIP64 format (as 8 byte values) when a 
      * files size exceeds 0xFFFFFFFF.   However ZIP64 format may be 
      * used regardless of the size of a file.  When extracting, if 
      * the zip64 extended information extra field is present for 
      * the file the compressed and uncompressed sizes will be 8
      * byte values.  
      *
      * Although not originally assigned a signature, the value 
      * 0x08074b50 has commonly been adopted as a signature value 
      * for the data descriptor record.  Implementers should be 
      * aware that ZIP files may be encountered with or without this 
      * signature marking data descriptors and should account for
      * either case when reading ZIP files to ensure compatibility.
      * When writing ZIP files, it is recommended to include the
      * signature value marking the data descriptor record.  When
      * the signature is used, the fields currently defined for
      * the data descriptor record will immediately follow the
      * signature.
      *
      * <cut, irrlevent>
      *
      * When the Central Directory Encryption method is used, the data
      * descriptor record is not required, but may be used.  If present,
      * and bit 3 of the general purpose bit field is set to indicate
      * its presence, the values in fields of the data descriptor
      * record should be set to binary zeros.
      *
      * $fileRecord .= pack('V', START_DATA_DESCRIPTOR);
      * $fileRecord .= pack('V', $CRC32);
      * $fileRecord .= pack('V', $compressedLength);
      * $fileRecord .= pack('V', $uncompressedLength);
      */
     /* Get the length of this file record for use later on. */
     $fileRecordLength = strlen($fileRecord);
     /* Add this file record to the zip file. */
     if (fwrite($this->_fileHandle, $fileRecord) === false) {
         return false;
     }
     unset($fileRecord);
     $tempFilename = FileUtility::makeRandomTemporaryFilePath();
     $compressedLength = 0;
     $fhSource = fopen(realpath($filename), 'rb');
     $fhCompressor = gzopen($tempFilename, 'wb');
     if (!$fhSource or !$fhCompressor) {
         $this->_errorMessage = 'Unexpected end of file.';
         return false;
     }
     while (!feof($fhSource)) {
         $temp = fread($fhSource, 32767);
         gzwrite($fhCompressor, $temp);
     }
     gzclose($fhCompressor);
     fclose($fhSource);
     $fhCompressed = fopen($tempFilename, 'rb');
     if (!$fhCompressed) {
         $this->_errorMessage = 'Unexpected end of file.';
         return false;
     }
     /* Strip off the headers and footers. */
     $gzipHeaderLength = 10;
     $gzipFooterLength = 8;
     if (fseek($fhCompressed, $gzipHeaderLength, SEEK_SET) === -1) {
         $this->_errorMessage = 'Unexpected end of file.';
         return false;
     }
     while (!feof($fhCompressed)) {
         $temp = fread($fhCompressed, 8192);
         $compressedLength += strlen($temp);
         fwrite($this->_fileHandle, $temp);
     }
     fclose($fhCompressed);
     @unlink($tempFilename);
     /* Ignore last 8 bytes of compressed data. */
     $compressedLength -= $gzipFooterLength;
     /* We need to seek back into the file and correct the 4B representation
        of how large the compressed data is. It is stored at 
        pointer - $compressedSize - 12 bytes. */
     if (fseek($this->_fileHandle, 0 - $compressedLength - strlen($name) - $gzipFooterLength - 12, SEEK_CUR) === -1) {
         $this->_errorMessage = 'Unexpected end of file.';
         return false;
     }
     $compressedLengthPacked = pack('V', $compressedLength);
     fwrite($this->_fileHandle, $compressedLengthPacked);
     /* Seek to the end of the file, but seek back 4 bytes to recover CRC bug for gzcompress. */
     if (fseek($this->_fileHandle, 0 - $gzipFooterLength, SEEK_END) === -1) {
         $this->_errorMessage = 'Unexpected end of file.';
         return false;
     }
     /* Increment total compressed data length and file record count. */
     $fileRecordLength += $compressedLength;
     $this->_fileRecordsLength += $fileRecordLength;
     ++$this->_fileRecordCount;
     /* Create the Central Directory entry for this file and append it
      * to the Central Directory (stored in memory for now until all file
      * records have been written).
      */
     $this->createCentralDirectoryEntry($name, $DOSTime, $CRC32, $compressedLength, $uncompressedLength, $fileRecordLength);
     return true;
 }
 function copyDirectory($src, $dest)
 {
     $ret = '';
     if (@opendir($dest)) {
         if (@opendir($src)) {
             $list = FileUtlity::directoryList($src, FileUtility::RECURSE);
             foreach ($list as $dir => $files) {
                 $path_array = StringUtility::split($dir, '/');
                 /*test for trailing slash*/
                 if (!preg_match('\\//$', $dest)) {
                     $dest = $dest . '/';
                 }
                 $cur_path = $dest;
                 foreach ($path_array as $pcmp) {
                     $cur_path = $cur_path . $pcmp;
                     if (!@opendir($cur_path)) {
                         mkdir($cur_path);
                     }
                 }
                 foreach ($files as $file) {
                     FileUtility::copyFile($dir . $file, $cur_path . $file);
                 }
             }
         } else {
             throw new Exception('Source directory: ' . $src . ' does not exist or isn\'t a directory in fileutility.class.inc');
         }
     } else {
         throw new Exception('Destination directory: ' . $dest . ' does not exist or isn\'t a directory in fileutility.class.inc');
     }
 }
 /**
  * Executes a shell command in a platform-independent way and returns the
  * results in an array containing the exact system command executed, the
  * raw output of that command, and the command's return code.
  *
  * @param string command to execute
  * @return array command results
  */
 private function _executeCommand($command)
 {
     /* Running on Windows? */
     if (SystemUtility::isWindows()) {
         /* Generate a random temp file name. */
         $tempFile = sprintf('%s/%s.txt', realpath(CATS_TEMP_DIR), FileUtility::makeRandomFilename());
         /* Create a new COM Windows Scripting Host Shell object. */
         $WSHShell = new COM('WScript.Shell');
         /* Build the command to execute. */
         $command = sprintf('cmd.exe /C "%s > "%s""', $command, $tempFile);
         /* Execute the command via the Windows Scripting Host Shell. */
         $returnCode = $WSHShell->Run($command, 0, true);
         /* Grab the contents of the temporary file and remove it. */
         $output = file($tempFile);
         @unlink($tempFile);
     } else {
         @exec($command, $output, $returnCode);
     }
     return array('command' => $command, 'output' => $output, 'returnCode' => $returnCode);
 }
Exemple #29
0
 function testGetUniqueDirectory()
 {
     /* Get two random directory names; one with extra data and one
      * without.
      */
     $directoryA = FileUtility::getUniqueDirectory('attachments');
     $directoryB = FileUtility::getUniqueDirectory('attachments/', 'Extra Data!');
     /* Directories are also unique in time, with randomness added. */
     sleep(1);
     $directoryC = FileUtility::getUniqueDirectory('attachments');
     $directoryD = FileUtility::getUniqueDirectory('attachments');
     /* Make sure all directory names look like md5 strings. */
     $this->assertEqual(strlen($directoryA), 32, sprintf("'%s' should be 32 characters long", $directoryA));
     $this->assertEqual(strlen($directoryB), 32, sprintf("'%s' should be 32 characters long", $directoryB));
     $this->assertEqual(strlen($directoryC), 32, sprintf("'%s' should be 32 characters long", $directoryB));
     $this->assertEqual(strlen($directoryD), 32, sprintf("'%s' should be 32 characters long", $directoryB));
     /* Make sure extra data is actually being added (directory names
      * should not be identical).
      */
     $this->assertNotEqual($directoryA, $directoryB, sprintf("'%s' should not equal '%s'", $directoryA, $directoryB));
     $this->assertNotEqual($directoryA, $directoryC, sprintf("'%s' should not equal '%s'", $directoryA, $directoryC));
     $this->assertNotEqual($directoryA, $directoryD, sprintf("'%s' should not equal '%s'", $directoryA, $directoryD));
     $this->assertNotEqual($directoryB, $directoryC, sprintf("'%s' should not equal '%s'", $directoryB, $directoryC));
     $this->assertNotEqual($directoryB, $directoryD, sprintf("'%s' should not equal '%s'", $directoryB, $directoryD));
     $this->assertNotEqual($directoryC, $directoryD, sprintf("'%s' should not equal '%s'", $directoryC, $directoryD));
     /* No directory names should exist. */
     $this->assertFalse(file_exists('attachments/' . $directoryA), sprintf("'attachments/%s' should not exist", $directoryA));
     $this->assertFalse(file_exists('attachments/' . $directoryB), sprintf("'attachments/%s' should not exist", $directoryB));
     $this->assertFalse(file_exists('attachments/' . $directoryC), sprintf("'attachments/%s' should not exist", $directoryB));
     $this->assertFalse(file_exists('attachments/' . $directoryD), sprintf("'attachments/%s' should not exist", $directoryB));
 }
Exemple #30
0
print_progress($step);
/* try copying the content over from the old dir to the new one */
require '../include/classes/FileUtility.class.php';
// for copys()
$content_dir = urldecode(trim($_POST['step4']['content_dir']));
$_POST['step4']['copy_from'] = urldecode(trim($_POST['step4']['copy_from'])) . DIRECTORY_SEPARATOR;
//copy if copy_from is not empty
if ($_POST['step4']['copy_from'] && $_POST['step4']['copy_from'] != DIRECTORY_SEPARATOR) {
    if (is_dir($_POST['step4']['copy_from'])) {
        $files = scandir($_POST['step4']['copy_from']);
        foreach ($files as $file) {
            if ($file == '.' || $file == '..') {
                continue;
            }
            if (is_dir($_POST['step4']['copy_from'] . $file)) {
                FileUtility::copys($_POST['step4']['copy_from'] . $file, $content_dir . $file);
                if (is_dir($content_dir . $course)) {
                    $progress[] = 'Course content directory <b>' . $file . '</b> copied successfully.';
                } else {
                    $errors[] = 'Course content directory <b>' . $file . '</b> <strong>NOT</strong> copied.';
                }
            } else {
                // a regular file
                copy($_POST['step4']['copy_from'] . $file, $content_dir . $file);
            }
        }
    }
} else {
    $progress[] = 'Using existing content directory <strong>' . $content_dir . '</strong>.';
}
if (isset($progress)) {