public function setUp()
 {
     parent::setUp();
     $this->loginWithPermission('ADMIN');
     // Save versioned state
     $this->oldReadingMode = Versioned::get_reading_mode();
     Versioned::set_stage(Versioned::DRAFT);
     // Set backend root to /UploadFieldTest
     AssetStoreTest_SpyStore::activate('UploadFieldTest');
     // Set the File Name Filter replacements so files have the expected names
     Config::inst()->update('FileNameFilter', 'default_replacements', array('/\\s/' => '-', '/_/' => '-', '/[^A-Za-z0-9+.\\-]+/' => '', '/[\\-]{2,}/' => '-', '/^[\\.\\-_]+/' => ''));
     // Create a test folders for each of the fixture references
     foreach (Folder::get() as $folder) {
         $path = AssetStoreTest_SpyStore::getLocalPath($folder);
         Filesystem::makeFolder($path);
     }
     // Create a test files for each of the fixture references
     $files = File::get()->exclude('ClassName', 'Folder');
     foreach ($files as $file) {
         $path = AssetStoreTest_SpyStore::getLocalPath($file);
         Filesystem::makeFolder(dirname($path));
         $fh = fopen($path, "w+");
         fwrite($fh, str_repeat('x', 1000000));
         fclose($fh);
     }
 }
 public function getFormField()
 {
     $field = FileAttachmentField::create($this->Name, $this->Title);
     //		$field = FileField::create($this->Name, $this->Title);
     if ($this->getSetting('Folder')) {
         $folder = Folder::get()->byId($this->getSetting('Folder'));
         if ($folder) {
             $field->setFolderName(preg_replace("/^assets\\//", "", $folder->Filename));
         }
     }
     if ($this->getSetting('Obfuscate')) {
         $folder = rtrim($field->getFolderName(), '/');
         $folder .= '/' . md5(time() + mt_rand());
         $field->setFolderName($folder);
     }
     if ($this->getSetting('MultipleUploads')) {
         $field->setMultiple(true);
     }
     if ($this->Required) {
         // Required validation can conflict so add the Required validation messages
         // as input attributes
         $errorMessage = $this->getErrorMessage()->HTML();
         $field->setAttribute('data-rule-required', 'true');
         $field->setAttribute('data-msg-required', $errorMessage);
     }
     return $field;
 }
 /**
  * Displays a random image with colorbox effect from a given assets subfolder
  * Uses template "csoft-shortcode/templates/Includes/RandomImage.ss" for output 
  * 
  * @param mixed $arguments (folder='subfolder_in_assets' align='left|right')
  * @param $content = null
  * @param $parser = null
  * @return processed template RandomImage.ss
  */
 public static function cwsShortCodeRandomImageHandler($arguments, $content = null, $parser = null)
 {
     // only proceed if subfolder was defined
     if (!isset($arguments['folder'])) {
         return;
     }
     // sanitize user inputs
     $folder = Convert::raw2sql($arguments['folder']);
     $align = isset($arguments['align']) ? strtolower(Convert::raw2xml($arguments['align'])) : '';
     // fetch all images in random order from the user defined folder
     $folder = Folder::get()->filter('Filename', "assets/{$folder}/")->First();
     $randomImage = $folder ? Image::get()->filter('ParentID', $folder->ID)->sort('RAND()') : false;
     // exit if user defined folder does not contain any image
     if (!$randomImage) {
         return;
     }
     // extract image caption from image filename
     $caption = $randomImage->Title;
     if (preg_match('#(\\d*-)?(.+)\\.(jpg|gif|png)#i', $caption, $matches)) {
         $caption = ucfirst(str_replace('-', ' ', $matches[2]));
     }
     // prepare data for output
     $data = array('RandomImage' => $randomImage->First(), 'Alignment' => $align, 'Caption' => $caption);
     // load template and process data
     $template = new SSViewer('RandomImage');
     return $template->process(new ArrayData($data));
 }
Ejemplo n.º 4
0
 function setup()
 {
     $oRootFolder =& Folder::get(1);
     $this->oUser = User::get(1);
     $sName = 'PermissionsTrest' . strftime('%Y%m%d%H%M%S');
     $this->oFolder =& KTFolderUtil::add($oRootFolder, $sName, $this->oUser);
 }
Ejemplo n.º 5
0
 public function getFormField()
 {
     $field = new FileField($this->Name, $this->Title);
     if ($this->getSetting('Folder')) {
         $folder = Folder::get()->byId($this->getSetting('Folder'));
         if ($folder) {
             $field->setFolderName(preg_replace("/^assets\\//", "", $folder->Filename));
         }
     }
     return $field;
 }
 function getCMSFields()
 {
     $fields = parent::getCMSFields();
     if ($this->FolderID) {
         $filescount = File::get()->filter(array("ParentID" => $this->FolderID))->count();
         $fields->addFieldToTab('Root.Main', new LiteralField("addnew", "<p><a href='/admin/assets/show/" . $this->FolderID . "' class='ss-ui-button ss-ui-action-constructive ui-button' style='font-size:130%' data-icon=add''>Manage Files (" . $filescount . ")</span></a></p>"), 'Title');
     }
     $fields->insertAfter(new TextField("FilesHeading", "Files Heading"), 'Content');
     $folders = class_exists('FileVersion') ? Folder::get()->exclude("Filename:PartialMatch", "_versions")->map("ID", "Title") : Folder::get()->map("ID", "Title");
     $dropdown = new DropdownField("FolderID", "Folder", $folders);
     $this->FolderID ? $dropdown->setEmptyString("Clear list") : $dropdown->setEmptyString(" ");
     $fields->insertAfter($dropdown, 'FilesHeading');
     return $fields;
 }
Ejemplo n.º 7
0
 public function getFormField()
 {
     $field = FileField::create($this->Name, $this->Title);
     if ($this->getSetting('Folder')) {
         $folder = Folder::get()->byId($this->getSetting('Folder'));
         if ($folder) {
             $field->setFolderName(preg_replace("/^assets\\//", "", $folder->Filename));
         }
     }
     if ($this->Required) {
         // Required validation can conflict so add the Required validation messages
         // as input attributes
         $errorMessage = $this->getErrorMessage()->HTML();
         $field->setAttribute('data-rule-required', 'true');
         $field->setAttribute('data-msg-required', $errorMessage);
     }
     return $field;
 }
 public function onBeforeWrite()
 {
     parent::onBeforeWrite();
     $imageAdded = false;
     if ($this->AutomaticallyIncludedFolderID) {
         debug::log("A");
         if ($folder = Folder::get()->byID($this->AutomaticallyIncludedFolderID)) {
             if ($files = Image::get()->filter("ParentID", $folder->ID)) {
                 foreach ($files as $file) {
                     if (ImageGalleryEntry::get()->filter(array("ImageID" => $file->ID, "ParentID" => $this->ID))->count()) {
                         //do nothing
                         //debug::log("already exists");
                     } else {
                         $ImageGalleryEntry = new ImageGalleryEntry();
                         $ImageGalleryEntry->Title = $file->Title;
                         $ImageGalleryEntry->ImageID = $file->ID;
                         $ImageGalleryEntry->ParentID = $this->ID;
                         $ImageGalleryEntry->write();
                         $imageAdded = true;
                         //debug::log("writing");
                     }
                 }
             } else {
                 //debug::log("D");
             }
         } else {
             //debug::log("C");
         }
     } else {
         //debug::log("B");
     }
     if ($ImageGalleryEntries = ImageGalleryEntry::get()->filter(array("ParentID" => $this->ID))) {
         foreach ($ImageGalleryEntries as $ImageGalleryEntry) {
             $image = Image::get()->filter(array("ID" => $ImageGalleryEntry->ImageID))->exclude(array("Title" => $ImageGalleryEntry->Title))->First();
             if ($image) {
                 $image->Title = $image->Name = $ImageGalleryEntry->Title;
                 $image->write();
             }
         }
     }
     if ($imageAdded) {
         //LeftAndMain::force_reload();
     }
 }
Ejemplo n.º 9
0
 function _show()
 {
     if (is_null($this->_sShowPermission)) {
         return true;
     }
     $oFolder = Folder::get($this->oDocument->getFolderId());
     if ($this->_bMutator && $this->oDocument->getImmutable()) {
         if ($this->_bMutationAllowedByAdmin === true) {
             if (!KTBrowseUtil::inAdminMode($this->oUser, $oFolder)) {
                 return false;
             }
         } else {
             return false;
         }
     }
     if ($this->_bAdminAlwaysAvailable) {
         if (Permission::userIsSystemAdministrator($this->oUser->getId())) {
             return true;
         }
         if (Permission::isUnitAdministratorForFolder($this->oUser, $this->oDocument->getFolderId())) {
             return true;
         }
     }
     $oPermission =& KTPermission::getByName($this->_sShowPermission);
     if (PEAR::isError($oPermission)) {
         return true;
     }
     if (!KTWorkflowUtil::actionEnabledForDocument($this->oDocument, $this->sName)) {
         return false;
     }
     // be nasty in archive/delete status.
     $status = $this->oDocument->getStatusID();
     if ($status == DELETED || $status == ARCHIVED) {
         return false;
     }
     if ($this->bAllowInAdminMode) {
         // check if this user is in admin mode
         if (KTBrowseUtil::inAdminMode($this->oUser, $oFolder)) {
             return true;
         }
     }
     return KTPermissionUtil::userHasPermissionOnItem($this->oUser, $oPermission, $this->oDocument);
 }
Ejemplo n.º 10
0
 public function setUp()
 {
     parent::setUp();
     // Set backend root to /FolderTest
     AssetStoreTest_SpyStore::activate('FolderTest');
     // Create a test folders for each of the fixture references
     foreach (Folder::get() as $folder) {
         $path = AssetStoreTest_SpyStore::getLocalPath($folder);
         SS_Filesystem::makeFolder($path);
     }
     // Create a test files for each of the fixture references
     $files = File::get()->exclude('ClassName', 'Folder');
     foreach ($files as $file) {
         $path = AssetStoreTest_SpyStore::getLocalPath($file);
         SS_Filesystem::makeFolder(dirname($path));
         $fh = fopen($path, "w+");
         fwrite($fh, str_repeat('x', 1000000));
         fclose($fh);
     }
 }
 public function getFormField()
 {
     $field = FileField::create($this->Name, $this->Title);
     // filter out '' since this would be a regex problem on JS end
     $field->getValidator()->setAllowedExtensions(array_filter(Config::inst()->get('File', 'allowed_extensions')));
     if ($this->getSetting('Folder')) {
         $folder = Folder::get()->byId($this->getSetting('Folder'));
         if ($folder) {
             $field->setFolderName(preg_replace("/^assets\\//", "", $folder->Filename));
         }
     }
     if ($this->Required) {
         // Required validation can conflict so add the Required validation messages
         // as input attributes
         $errorMessage = $this->getErrorMessage()->HTML();
         $field->setAttribute('data-rule-required', 'true');
         $field->setAttribute('data-msg-required', $errorMessage);
     }
     return $field;
 }
 /**
  * Save Snapshots of extension in assets folder
  *
  * @param string $thumbnailUrl, $extensionName
  * @return int
  */
 public static function save_snapshot($thumbnailUrl, $extensionName)
 {
     $folderToSave = 'assets/Uploads/Snapshots/';
     $folderObject = Folder::get()->filter("Filename", $folderToSave)->first();
     if (!$folderObject) {
         $folderObject = Folder::find_or_make('Uploads/Snapshots/');
         $folderObject->write();
     }
     $fileExtension = preg_replace('/^.*\\.([^.]+)$/D', '$1', $thumbnailUrl);
     $thumbnailBaseName = str_replace('/', '-', $extensionName);
     $thumbnailName = $thumbnailBaseName . '-thumbnail.' . $fileExtension;
     $ch = curl_init();
     $timeout = 30;
     curl_setopt($ch, CURLOPT_URL, $thumbnailUrl);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
     $data = curl_exec($ch);
     $response = curl_getinfo($ch);
     curl_close($ch);
     if ($response['http_code'] == '404') {
         throw new InvalidArgumentException("Image not found on given Url Please check 'Snapshot' field in composer.json file");
     }
     $imageContent = $data;
     if ($folderObject) {
         $thumbnailFile = fopen(BASE_PATH . DIRECTORY_SEPARATOR . $folderToSave . $thumbnailName, 'w');
         fwrite($thumbnailFile, $imageContent);
         fclose($thumbnailFile);
     } else {
         throw new InvalidArgumentException("Could not create {$folderToSave} , Please create it mannually ");
     }
     if ($thumbnailObject = Image::get()->filter("Name", $thumbnailName)->first()) {
         return $thumbnailObject->ID;
     } else {
         $thumbnailObject = new Image();
         $thumbnailObject->ParentID = $folderObject->ID;
         $thumbnailObject->Name = $thumbnailName;
         $thumbnailObject->OwnerID = Member::currentUser() ? Member::currentUser()->ID : 0;
         $thumbnailObject->write();
         return $thumbnailObject->ID;
     }
 }
 function _fieldValues()
 {
     if (empty($this->dDateTime)) {
         $this->dDateTime = getCurrentDateTime();
     }
     if (empty($this->iSessionId)) {
         $this->iSessionId = $_SESSION['sessionID'];
     }
     $oFolder = Folder::get($this->iFolderId);
     // head off the certain breakage down the line.
     if (PEAR::isError($oFolder) || $oFolder === false) {
         $this->bAdminMode = 0;
     } else {
         if (KTBrowseUtil::inAdminMode($oUser, $oFolder)) {
             $this->bAdminMode = 1;
         } else {
             $this->bAdminMode = 0;
         }
     }
     return parent::_fieldValues();
 }
Ejemplo n.º 14
0
 function do_main()
 {
     $this->aBreadcrumbs[] = array('url' => $_SERVER['PHP_SELF'], 'name' => _kt('Archived Documents'));
     $this->oPage->setBreadcrumbDetails(_kt('browse'));
     $oFolder = Folder::get(KTUtil::arrayGet($_REQUEST, 'fFolderId', 1));
     if (PEAR::isError($oFolder)) {
         $this->errorRedirectToMain(_kt('Invalid folder selected.'));
         exit(0);
     }
     // Setup the collection for restore display.
     $aBaseParams = array();
     $collection = new AdvancedCollection();
     $oCR =& KTColumnRegistry::getSingleton();
     $col = $oCR->getColumn('ktcore.columns.selection');
     $aColOptions = array();
     //$aColOptions['qs_params'] = kt_array_merge($aBaseParams, array('fFolderId'=>$oFolder->getId()));
     $aColOptions['show_folders'] = false;
     $aColOptions['show_documents'] = true;
     $aColOptions['rangename'] = '_d[]';
     $col->setOptions($aColOptions);
     $collection->addColumn($col);
     $col = $oCR->getColumn('ktcore.columns.title');
     //$col->setOptions(array('qs_params'=>kt_array_merge($aBaseParams, array('action' => 'new', 'fFolderId'=>$oFolder->getId()))));
     $col->setOptions(array('link_documents' => false));
     $collection->addColumn($col);
     //$qObj = new BrowseQuery($iFolderId);
     $qObj = new ArchivedBrowseQuery($oFolder->getId());
     $collection->setQueryObject($qObj);
     $aOptions = $collection->getEnvironOptions();
     $aOptions['result_url'] = KTUtil::addQueryString($_SERVER['PHP_SELF'], array(kt_array_merge($aBaseParams, array('fFolderId' => $oFolder->getId()))));
     $collection->setOptions($aOptions);
     $aURLParams = $aBaseParams;
     $aURLParams['action'] = 'restore';
     $aBreadcrumbs = KTUtil::generate_breadcrumbs($oFolder, $iFolderId, $aURLParams);
     $aTemplateData = array('context' => $this, 'folder' => $oFolder, 'breadcrumbs' => $aBreadcrumbs, 'collection' => $collection);
     $oTemplate =& $this->oValidator->validateTemplate('ktcore/document/admin/archivebrowse');
     return $oTemplate->render($aTemplateData);
 }
 public function setUp()
 {
     parent::setUp();
     // Set backend root to /ImageTest
     AssetStoreTest_SpyStore::activate('ProtectedFileControllerTest');
     // Create a test folders for each of the fixture references
     foreach (Folder::get() as $folder) {
         /** @var Folder $folder */
         $filePath = AssetStoreTest_SpyStore::getLocalPath($folder);
         \Filesystem::makeFolder($filePath);
     }
     // Create a test files for each of the fixture references
     foreach (File::get()->exclude('ClassName', 'Folder') as $file) {
         /** @var File $file */
         $path = AssetStoreTest_SpyStore::getLocalPath($file);
         \Filesystem::makeFolder(dirname($path));
         $fh = fopen($path, "w+");
         fwrite($fh, str_repeat('x', 1000000));
         fclose($fh);
         // Create variant for each file
         $this->getAssetStore()->setFromString(str_repeat('y', 100), $file->Filename, $file->Hash, 'variant');
     }
 }
 public function setUp()
 {
     parent::setUp();
     $this->loginWithPermission('ADMIN');
     // Save versioned state
     $this->oldReadingMode = Versioned::get_reading_mode();
     Versioned::reading_stage('Stage');
     // Set backend root to /UploadFieldTest
     AssetStoreTest_SpyStore::activate('UploadFieldTest');
     // Create a test folders for each of the fixture references
     foreach (Folder::get() as $folder) {
         $path = AssetStoreTest_SpyStore::getLocalPath($folder);
         Filesystem::makeFolder($path);
     }
     // Create a test files for each of the fixture references
     $files = File::get()->exclude('ClassName', 'Folder');
     foreach ($files as $file) {
         $path = AssetStoreTest_SpyStore::getLocalPath($file);
         Filesystem::makeFolder(dirname($path));
         $fh = fopen($path, "w+");
         fwrite($fh, str_repeat('x', 1000000));
         fclose($fh);
     }
 }
Ejemplo n.º 17
0
 function check()
 {
     $this->browse_mode = KTUtil::arrayGet($_REQUEST, 'fBrowseMode', 'folder');
     $action = KTUtil::arrayGet($_REQUEST, $this->event_var, 'main');
     $this->editable = false;
     // catch the alternative actions.
     if ($action != 'main') {
         return true;
     }
     // if we're going to main ...
     // folder browse mode
     if ($this->browse_mode == 'folder') {
         $in_folder_id = KTUtil::arrayGet($_REQUEST, 'fFolderId');
         if (empty($in_folder_id)) {
             $oConfig = KTConfig::getSingleton();
             if ($oConfig->get('tweaks/browseToUnitFolder')) {
                 $iHomeFolderId = $this->oUser->getHomeFolderId();
                 if ($iHomeFolderId) {
                     $in_folder_id = $iHomeFolderId;
                 }
             }
         }
         $folder_id = (int) $in_folder_id;
         // conveniently, will be 0 if not possible.
         if ($folder_id == 0) {
             $folder_id = 1;
         }
         $_REQUEST['fBrowseMode'] = 'folder';
         // here we need the folder object to do the breadcrumbs.
         $oFolder =& Folder::get($folder_id);
         if (PEAR::isError($oFolder)) {
             return false;
             // just fail.
         }
         // check whether the user can edit this folder
         $oPerm = KTPermission::getByName('ktcore.permissions.write');
         if (KTPermissionUtil::userHasPermissionOnItem($this->oUser, $oPerm, $oFolder)) {
             $this->editable = true;
         } else {
             $this->editable = false;
         }
         // set the title and breadcrumbs...
         $this->oPage->setTitle(_kt('Browse'));
         if (KTPermissionUtil::userHasPermissionOnItem($this->oUser, 'ktcore.permissions.folder_details', $oFolder)) {
             $this->oPage->setSecondaryTitle($oFolder->getName());
         } else {
             if (KTBrowseUtil::inAdminMode($this->oUser, $oFolder)) {
                 $this->oPage->setSecondaryTitle(sprintf('(%s)', $oFolder->getName()));
             } else {
                 $this->oPage->setSecondaryTitle('...');
             }
         }
         //Figure out if we came here by navigating trough a shortcut.
         //If we came here from a shortcut, the breadcrumbspath should be relative
         //to the shortcut folder.
         $iSymLinkFolderId = KTUtil::arrayGet($_REQUEST, 'fShortcutFolder', null);
         if (is_numeric($iSymLinkFolderId)) {
             $oBreadcrumbsFolder = Folder::get($iSymLinkFolderId);
             $this->aBreadcrumbs = kt_array_merge($this->aBreadcrumbs, KTBrowseUtil::breadcrumbsForFolder($oBreadcrumbsFolder, array('final' => false)));
             $this->aBreadcrumbs[] = array('name' => $oFolder->getName());
         } else {
             $this->aBreadcrumbs = kt_array_merge($this->aBreadcrumbs, KTBrowseUtil::breadcrumbsForFolder($oFolder));
         }
         $this->oFolder =& $oFolder;
         // we now have a folder, and need to create the query.
         $aOptions = array('ignorepermissions' => KTBrowseUtil::inAdminMode($this->oUser, $oFolder));
         $this->oQuery = new BrowseQuery($oFolder->getId(), $this->oUser, $aOptions);
         $this->resultURL = KTUtil::addQueryString($_SERVER['PHP_SELF'], sprintf('fFolderId=%d', $oFolder->getId()));
         // and the portlets
         $portlet = new KTActionPortlet(sprintf(_kt('About this folder')));
         $aActions = KTFolderActionUtil::getFolderInfoActionsForFolder($this->oFolder, $this->oUser);
         $portlet->setActions($aActions, $this->sName);
         $this->oPage->addPortlet($portlet);
         $portlet = new KTActionPortlet(sprintf(_kt('Actions on this folder')));
         $aActions = KTFolderActionUtil::getFolderActionsForFolder($oFolder, $this->oUser);
         $portlet->setActions($aActions, null);
         $this->oPage->addPortlet($portlet);
     } else {
         if ($this->browse_mode == 'lookup_value') {
             // browsing by a lookup value
             $this->editable = false;
             // check the inputs
             $field = KTUtil::arrayGet($_REQUEST, 'fField', null);
             $oField = DocumentField::get($field);
             if (PEAR::isError($oField) || $oField == false) {
                 $this->errorRedirectToMain('No Field selected.');
                 exit(0);
             }
             $value = KTUtil::arrayGet($_REQUEST, 'fValue', null);
             $oValue = MetaData::get($value);
             if (PEAR::isError($oValue) || $oValue == false) {
                 $this->errorRedirectToMain('No Value selected.');
                 exit(0);
             }
             $this->oQuery = new ValueBrowseQuery($oField, $oValue);
             $this->resultURL = KTUtil::addQueryString($_SERVER['PHP_SELF'], sprintf('fBrowseMode=lookup_value&fField=%d&fValue=%d', $field, $value));
             // setup breadcrumbs
             $this->aBreadcrumbs = array(array('name' => _kt('Lookup Values'), 'url' => KTUtil::addQueryString($_SERVER['PHP_SELF'], 'action=selectField')), array('name' => $oField->getName(), 'url' => KTUtil::addQueryString($_SERVER['PHP_SELF'], 'action=selectLookup&fField=' . $oField->getId())), array('name' => $oValue->getName(), 'url' => KTUtil::addQueryString($_SERVER['PHP_SELF'], sprintf('fBrowseMode=lookup_value&fField=%d&fValue=%d', $field, $value))));
         } else {
             if ($this->browse_mode == 'document_type') {
                 // browsing by document type
                 $this->editable = false;
                 $doctype = KTUtil::arrayGet($_REQUEST, 'fType', null);
                 $oDocType = DocumentType::get($doctype);
                 if (PEAR::isError($oDocType) || $oDocType == false) {
                     $this->errorRedirectToMain('No Document Type selected.');
                     exit(0);
                 }
                 $this->oQuery = new TypeBrowseQuery($oDocType);
                 // FIXME probably want to redirect to self + action=selectType
                 $this->aBreadcrumbs[] = array('name' => _kt('Document Types'), 'url' => KTUtil::addQueryString($_SERVER['PHP_SELF'], 'action=selectType'));
                 $this->aBreadcrumbs[] = array('name' => $oDocType->getName(), 'url' => KTUtil::addQueryString($_SERVER['PHP_SELF'], 'fBrowseMode=document_type&fType=' . $oDocType->getId()));
                 $this->resultURL = KTUtil::addQueryString($_SERVER['PHP_SELF'], sprintf('fType=%s&fBrowseMode=document_type', $doctype));
             } else {
                 // FIXME what should we do if we can't initiate the browse?  we "pretend" to have no perms.
                 return false;
             }
         }
     }
     return true;
 }
Ejemplo n.º 18
0
 function rebuildAllPermissions()
 {
     $oRootFolder = Folder::get(1);
     KTPermissionUtil::updatePermissionLookupRecursive($oRootFolder);
 }
Ejemplo n.º 19
0
 function create()
 {
     if (empty($this->dCreated)) {
         $this->dCreated = getCurrentDateTime();
     }
     if (empty($this->dModified)) {
         $this->dModified = getCurrentDateTime();
     }
     if (empty($this->iModifiedUserId)) {
         $this->iModifiedUserId = $this->iCreatorId;
     }
     if (empty($this->iOwnerId)) {
         $this->iOwnerId = $this->iCreatorId;
     }
     if (empty($this->iMetadataVersion)) {
         $this->iMetadataVersion = 0;
     }
     if (empty($this->bIsCheckedOut)) {
         $this->bIsCheckedOut = false;
     }
     if (empty($this->bImmutable)) {
         $this->bImmutable = false;
     }
     $oFolder = Folder::get($this->getFolderId());
     if (PEAR::isError($oFolder) || $oFolder === false || empty($oFolder)) {
         return false;
     }
     $this->iPermissionObjectId = $oFolder->getPermissionObjectId();
     $res = parent::create();
     return $res;
 }
Ejemplo n.º 20
0
<?php

require_once "../../config/dmsDefaults.php";
require_once KT_LIB_DIR . '/documentmanagement/documentutil.inc.php';
require_once KT_LIB_DIR . '/filelike/fsfilelike.inc.php';
error_reporting(E_ALL);
$oFolder =& Folder::get(1);
$oUser =& User::get(1);
$sLocalname = KT_DIR . "/tests/document/dataset1/critique-of-pure-reason.txt";
$sFilename = tempnam("/tmp", "kt_tests_document_add");
copy($sLocalname, $sFilename);
DBUtil::startTransaction();
$oDocument =& KTDocumentUtil::add($oFolder, "testfullupload2.txt", $oUser, array('contents' => new KTFSFileLike($sFilename), 'metadata' => array()));
if (PEAR::isError($oDocument)) {
    print "FAILURE\n";
    var_dump($oDocument);
    exit(0);
}
DBUtil::commit();
print "SUCCESS\n";
Ejemplo n.º 21
0
 /**
  * COPY method helper for Folders
  *
  * @param  array   parameter passing array
  * @param  int     Parent Folder ID
  * @return string  HTTP status code or false
  */
 function _COPYFolder($options, $iFolderID)
 {
     /* ** Ensure that the destination path exists ** */
     if ($options['dest'] == '') {
         $options["dest"] = substr($options["dest_url"], strlen($_SERVER["SCRIPT_NAME"]));
     }
     $this->ktwebdavLog("Entering _COPYFolder. options are " . print_r($options, true), 'info', true);
     /* ** RFC 2518 Section 8.8.3. DAV compliant servers must support depth headers of '0' and 'infinity'.
        Check the requested depth. If depth is set to '0', set copyall to false. A depth of 0 indicates
        that the folder is copied without any children. If depth is set to '1', return a 400 error. ** */
     $copyAll = true;
     if ($options["depth"] != "infinity") {
         if ($options['depth'] == '0') {
             $copyAll = false;
             $this->ktwebdavLog("Depth is 0. Copy only the base folder.", 'info', true);
         } else {
             $this->ktwebdavLog("400 Bad request. Depth must be infinity or 0.", 'info', true);
             return "400 Bad request - Depth must be 'infinity' or '0'.";
         }
     }
     global $default;
     $new = true;
     /* ** Get the relevant paths. Get the basename of the destination path as the destination path name.
        Check whether the destination path refers to a folder / document. ** */
     $source_path = $options["path"];
     $dest_path = urldecode($options["dest"]);
     $sDestPathName = basename($dest_path);
     list($iDestFolder, $iDestDoc) = $this->_folderOrDocument($dest_path);
     /* ** Get the source and destination folder objects.
        If the destination document is null, then the destination is an existing folder. Check overwrite.
        If overwrite is true, then check permissions and delete the folder, continue.
        If the destination document returns an id, then the destination is a document, return 409 error.
        If the destination document is false, then continue. ** */
     $oSrcFolder = Folder::get($iFolderID);
     $oDestFolder = Folder::get($iDestFolder);
     include_once KT_LIB_DIR . '/foldermanagement/folderutil.inc.php';
     if (is_null($iDestDoc)) {
         // Destination is a folder and exists
         //$sDestPathName = '';
         $this->ktwebdavLog("Destination Folder exists.", 'info', true);
         $oReplaceFolder = $oDestFolder;
         if ($options['overwrite'] != 'T') {
             $this->ktwebdavLog("Overwrite needs to be TRUE.", 'info', true);
             return "412 Precondition Failed - Destination Folder exists. Overwrite needs to be TRUE.";
         }
         $this->ktwebdavLog("Overwrite is TRUE, deleting Destination Folder.", 'info', true);
         // Check if the user has permissions to delete this folder
         $oPerm =& KTPermission::getByName('ktcore.permissions.delete');
         $oUser =& User::get($this->userID);
         if (!KTPermissionUtil::userHasPermissionOnItem($oUser, $oPerm, $oReplaceFolder)) {
             return "403 Forbidden - User does not have sufficient permissions";
         }
         KTFolderUtil::delete($oReplaceFolder, $oUser, 'KTWebDAV move overwrites target.');
         // Destination folder has been deleted - get new object of destination parent folder
         list($iDestFolder, $iDestDoc) = $this->_folderOrDocument($dest_path);
         $oDestFolder = Folder::get($iDestFolder);
         $new = false;
     } else {
         if ($iDestDoc !== false) {
             // Destination is a document
             return "409 Conflict - Can't write a collection to a document";
         }
     }
     /* ** Get the destination folder object and the source document object.
        Check if user has permission to write to the folder.
        Copy the document. Pass parameters for the destination folder name and the depth of copy. ** */
     $oUser =& User::get($this->userID);
     $this->ktwebdavLog("Got an oSrcFolder of " . print_r($oSrcFolder, true), 'info', true);
     $this->ktwebdavLog("Got an oDestFolder of " . print_r($oDestFolder, true), 'info', true);
     $this->ktwebdavLog("Got an oUser of " . print_r($oUser, true), 'info', true);
     // Check if the user has permissions to write in this folder
     $oPerm =& KTPermission::getByName('ktcore.permissions.write');
     $oUser =& User::get($this->userID);
     if (!KTPermissionUtil::userHasPermissionOnItem($oUser, $oPerm, $oDestFolder)) {
         return "403 Forbidden - User does not have sufficient permissions";
     }
     $reason = isset($_SERVER['HTTP_REASON']) && !empty($_SERVER['HTTP_REASON']) ? $_SERVER['HTTP_REASON'] : "KTWebDAV Copy.";
     $res = KTFolderUtil::copy($oSrcFolder, $oDestFolder, $oUser, $reason, $sDestPathName, $copyAll);
     if (PEAR::isError($res)) {
         $this->ktwebdavLog("Copy on folder failed: " . $res->getMessage(), 'info', true);
         return "500 Internal Server Error - Copy on folder failed.";
     }
     if ($new) {
         $this->ktwebdavLog("201 Created", 'info', true);
         return "201 Created";
     } else {
         $this->ktwebdavLog("204 No Content", 'info', true);
         return "204 No Content";
     }
 }
 /**
  * Get path of a folder relative to /assets/ by id.
  * This will be a format appropriate for setting setFolderName to
  *
  * @param int $folderID
  * @return string|bool Relative path to the assets directory, or false if not found
  */
 protected function folderPathFromID($folderID)
 {
     if (empty($folderID)) {
         return false;
     }
     $folder = Folder::get()->byID($folderID);
     if (!$folder) {
         return false;
     }
     // Translate path
     $path = $folder->getFilename();
     if (stripos($path, ASSETS_DIR) === 0) {
         $path = substr($path, strlen(ASSETS_DIR) + 1);
     }
     return $path;
 }
 /**
  * Get the children sorted by name of this folder that are also folders.
  * 
  * @return ArrayList
  */
 public function getSortedChildFolders($sortField = 'Title', $sortDir = 'ASC')
 {
     return Folder::get()->filter(array('ParentID' => (int) $this->owner->ID))->sort($sortField, $sortDir);
 }
Ejemplo n.º 24
0
 public function getFolder()
 {
     return Folder::get($this->getFolderID());
 }
Ejemplo n.º 25
0
 function check()
 {
     $res = parent::check();
     if ($res !== true) {
         return $res;
     }
     if (!$this->oDocument->getIsCheckedOut()) {
         $_SESSION['KTErrorMessage'][] = _kt('This document is not checked out');
         controllerRedirect('viewDocument', 'fDocumentId=' . $this->oDocument->getId());
         exit(0);
     }
     // hard override if we're in admin mode for this doc.
     if (is_null($this->bInAdminMode)) {
         $oFolder = Folder::get($this->oDocument->getFolderId());
         if (KTBrowseUtil::inAdminMode($this->oUser, $oFolder)) {
             $this->bAdminMode = true;
             return true;
         }
     } else {
         if ($this->bInAdminMode == true) {
             return true;
         }
     }
     if ($this->oDocument->getCheckedOutUserID() != $this->oUser->getId()) {
         $_SESSION['KTErrorMessage'][] = _kt('This document is checked out, but not by you');
         controllerRedirect('viewDocument', 'fDocumentId=' . $this->oDocument->getId());
         exit(0);
     }
     return true;
 }
Ejemplo n.º 26
0
 function postValidate()
 {
     $oDocument =& $this->aInfo["document"];
     $oSubscriptionEvent = new SubscriptionEvent();
     $oFolder = Folder::get($oDocument->getFolderID());
     $oSubscriptionEvent->DiscussDocument($oDocument, $oFolder);
     $indexer = Indexer::get();
     $indexer->index($oDocument, 'D');
 }
Ejemplo n.º 27
0
 function do_rename()
 {
     $aErrorOptions = array('redirect_to' => array('', sprintf('fFolderId=%d', $this->oFolder->getId())));
     $sFolderName = KTUtil::arrayGet($_REQUEST, 'foldername');
     $aErrorOptions['defaultmessage'] = _kt("No folder name given");
     $sFolderName = $this->oValidator->validateString($sFolderName, $aErrorOptions);
     $sFolderName = $this->oValidator->validateIllegalCharacters($sFolderName, $aErrorOptions);
     $sOldFolderName = $this->oFolder->getName();
     if ($this->oFolder->getId() != 1) {
         $oParentFolder =& Folder::get($this->oFolder->getParentID());
         if (PEAR::isError($oParentFolder)) {
             $this->errorRedirectToMain(_kt('Unable to retrieve parent folder.'), $aErrorOptions['redirect_to'][1]);
             exit(0);
         }
         if (KTFolderUtil::exists($oParentFolder, $sFolderName)) {
             $this->errorRedirectToMain(_kt('A folder with that name already exists.'), $aErrorOptions['redirect_to'][1]);
             exit(0);
         }
     }
     $res = KTFolderUtil::rename($this->oFolder, $sFolderName, $this->oUser);
     if (PEAR::isError($res)) {
         $_SESSION['KTErrorMessage'][] = $res->getMessage();
         redirect(KTBrowseUtil::getUrlForFolder($this->oFolder));
         exit(0);
     } else {
         $_SESSION['KTInfoMessage'][] = sprintf(_kt('Folder "%s" renamed to "%s".'), $sOldFolderName, $sFolderName);
     }
     $this->commitTransaction();
     redirect(KTBrowseUtil::getUrlForFolder($this->oFolder));
     exit(0);
 }
Ejemplo n.º 28
0
 function do_new()
 {
     $this->oPage->setBreadcrumbDetails(_kt("New Link"));
     $this->oPage->setTitle(_kt("New Link"));
     $oPermission =& KTPermission::getByName('ktcore.permissions.write');
     if (PEAR::isError($oPermission) || !KTPermissionUtil::userHasPermissionOnItem($this->oUser, $oPermission, $this->oDocument)) {
         $this->errorRedirectToMain(_kt('You do not have sufficient permissions to add a document link'), sprintf("fDocumentId=%d", $this->oDocument->getId()));
         exit(0);
     }
     $oParentDocument =& $this->oDocument;
     if (PEAR::isError($oParentDocument)) {
         $this->errorRedirectToMain(_kt('Invalid parent document selected.'));
         exit(0);
     }
     $oFolder = Folder::get(KTUtil::arrayGet($_REQUEST, 'fFolderId', $oParentDocument->getFolderID()));
     if (PEAR::isError($oFolder) || $oFolder == false) {
         $this->errorRedirectToMain(_kt('Invalid folder selected.'));
         exit(0);
     }
     $iFolderId = $oFolder->getId();
     // Setup the collection for move display.
     $collection = new AdvancedCollection();
     $aBaseParams = array('fDocumentId' => $oParentDocument->getId());
     $oCR =& KTColumnRegistry::getSingleton();
     $col = $oCR->getColumn('ktcore.columns.selection');
     $aColOptions = array();
     $aColOptions['qs_params'] = kt_array_merge($aBaseParams, array('fFolderId' => $oFolder->getId()));
     $aColOptions['show_folders'] = false;
     $aColOptions['show_documents'] = true;
     $aColOptions['rangename'] = 'linkselection[]';
     $col->setOptions($aColOptions);
     $collection->addColumn($col);
     $col = $oCR->getColumn('ktdocumentlinks.columns.title');
     $col->setOptions(array('qs_params' => kt_array_merge($aBaseParams, array('action' => 'new', 'fFolderId' => $oFolder->getId()))));
     $collection->addColumn($col);
     $qObj = new BrowseQuery($iFolderId);
     $collection->setQueryObject($qObj);
     $aOptions = $collection->getEnvironOptions();
     //$aOptions['is_browse'] = true;
     $aResultUrl = $aBaseParams;
     $aResultUrl['fFolderId'] = $oFolder->getId();
     $aResultUrl['action'] = 'new';
     $aOptions['result_url'] = KTUtil::addQueryString($_SERVER['PHP_SELF'], $aResultUrl);
     $collection->setOptions($aOptions);
     $aURLParams = $aBaseParams;
     $aURLParams['action'] = 'new';
     $aBreadcrumbs = KTUtil::generate_breadcrumbs($oFolder, $iFolderId, $aURLParams);
     // Add an electronic signature
     global $default;
     if ($default->enableESignatures) {
         $sUrl = KTPluginUtil::getPluginPath('electronic.signatures.plugin', true);
         $heading = _kt('You are attempting to add a document link');
         $submit['type'] = 'button';
         $submit['onclick'] = "javascript: showSignatureForm('{$sUrl}', '{$heading}', 'ktcore.transactions.add_link', 'document', 'document_add_link_form', 'submit', {$oParentDocument->iId});";
     } else {
         $submit['type'] = 'submit';
         $submit['onclick'] = '';
     }
     $aTemplateData = array('context' => $this, 'folder' => $oFolder, 'parent' => $oParentDocument, 'breadcrumbs' => $aBreadcrumbs, 'collection' => $collection, 'link_types' => LinkType::getList("id > 0"), 'submit' => $submit);
     $oTemplate =& $this->oValidator->validateTemplate('ktstandard/action/link');
     return $oTemplate->render($aTemplateData);
 }
 function _retrieveFolderInfo($iFolderId)
 {
     $row_info = array('folderid' => $iFolderId);
     $row_info['type'] = 'folder';
     $row_info['folder'] =& Folder::get($iFolderId);
     return $row_info;
 }
Ejemplo n.º 30
0
 function form_changetype()
 {
     $oForm = new KTForm();
     $oForm->setOptions(array('label' => _kt("Change Document Type"), 'description' => _kt("Changing the document type will allow different metadata to be associated with it."), 'identifier' => 'ktcore.doc.edit.typechange', 'submit_label' => _kt("Update Document"), 'context' => $this, 'cancel_action' => 'main', 'action' => 'trytype'));
     $type = DocumentType::get($this->oDocument->getDocumentTypeId());
     $current_type_name = $type->getName();
     $oFolder = Folder::get($this->oDocument->getFolderID());
     $oForm->setWidgets(array(array('ktcore.widgets.entityselection', array('label' => _kt("New Document Type"), 'description' => _kt("Please select the new type for this document."), 'important_description' => sprintf(_kt("The document is currently of type \"%s\"."), $current_type_name), 'value' => $type->getId(), 'label_method' => 'getName', 'vocab' => DocumentType::getListForUserAndFolder($this->oUser, $oFolder), 'simple_select' => false, 'required' => true, 'name' => 'type'))));
     $oForm->setValidators(array(array('ktcore.validators.entity', array('test' => 'type', 'output' => 'type', 'class' => 'DocumentType'))));
     return $oForm;
 }