/**
  * Process all incoming requests passed to this controller, checking
  * that the file exists and passing the file through if possible.
  */
 public function handleRequest(SS_HTTPRequest $request, DataModel $model)
 {
     // Copied from Controller::handleRequest()
     $this->pushCurrent();
     $this->urlParams = $request->allParams();
     $this->request = $request;
     $this->response = new SS_HTTPResponse();
     $this->setDataModel($model);
     $url = array_key_exists('url', $_GET) ? $_GET['url'] : $_SERVER['REQUEST_URI'];
     // remove any relative base URL and prefixed slash that get appended to the file path
     // e.g. /mysite/assets/test.txt should become assets/test.txt to match the Filename field on File record
     $url = Director::makeRelative(ltrim(str_replace(BASE_URL, '', $url), '/'));
     $file = File::find($url);
     if ($this->canDownloadFile($file)) {
         // If we're trying to access a resampled image.
         if (preg_match('/_resampled\\/[^-]+-/', $url)) {
             // File::find() will always return the original image, but we still want to serve the resampled version.
             $file = new Image();
             $file->Filename = $url;
         }
         $this->extend('onBeforeSendFile', $file);
         return $this->sendFile($file);
     } else {
         if ($file instanceof File) {
             // Permission failure
             Security::permissionFailure($this, 'You are not authorised to access this resource. Please log in.');
         } else {
             // File doesn't exist
             $this->response = new SS_HTTPResponse('File Not Found', 404);
         }
     }
     return $this->response;
 }
 public function authenticateFile()
 {
     $file_alias = $this->getParam('alias');
     $file = File::find('alias', $file_alias);
     if ($file == NULL) {
         System::displayError(System::getLanguage()->_('ErrorFileNotFound'), '404 Not Found');
     }
     $password = Utils::getPOST('password', '');
     $errorMsg = '';
     if (Utils::getPOST('submit', false) != false) {
         if ($file->verifyPassword($password)) {
             System::getSession()->setData('authenticatedFiles', array_merge(array($file->alias), System::getSession()->getData('authenticatedFiles', array())));
             System::forwardToRoute(Router::getInstance()->build('DownloadController', 'show', $file));
             exit;
         } else {
             $errorMsg = System::getLanguage()->_('InvalidPassword');
         }
     }
     $smarty = new Template();
     $smarty->assign('title', System::getLanguage()->_('Authenticate'));
     $smarty->assign('infoMsg', System::getLanguage()->_('ProtectedAccessAuthMsg'));
     $smarty->assign('errorMsg', $errorMsg);
     $smarty->requireResource('auth');
     $smarty->display('auth/file.tpl');
 }
 private function loadFile()
 {
     if ($this->file != NULL) {
         return;
     }
     $this->file = File::find('alias', $this->getParam('alias', ''));
     if ($this->file == NULL) {
         System::displayError(System::getLanguage()->_('ErrorFileNotFound'), '404 Not Found');
     }
     if (System::getUser() != NULL) {
         $user_id = System::getUser()->uid;
     } else {
         $user_id = -1;
     }
     if ($user_id != $this->file->uid) {
         if ($this->file->permission == FilePermissions::PRIVATE_ACCESS) {
             System::displayError(System::getLanguage()->_('PermissionDenied'), '403 Forbidden');
             exit;
         } elseif ($this->file->permission == FilePermissions::RESTRICTED_ACCESS) {
             if (is_array(System::getSession()->getData("authenticatedFiles"))) {
                 if (!in_array($this->file->alias, System::getSession()->getData("authenticatedFiles"))) {
                     System::forwardToRoute(Router::getInstance()->build('AuthController', 'authenticateFile', $this->file));
                     exit;
                 }
             } else {
                 System::forwardToRoute(Router::getInstance()->build('AuthController', 'authenticateFile', $this->file));
                 exit;
             }
         }
     }
 }
Example #4
0
 function get_dl($id = null)
 {
     $digitless = ltrim($id, '0..9');
     // file link can be either
     if ($digitless === '' or $digitless[0] === '.') {
         $file = File::find(strtok($id, '.'));
     } else {
         $file = File::where('name', '=', $id)->get();
     }
     if (!$file) {
         return;
     } elseif ($this->can('file.dl.deny.' . $file->id)) {
         return false;
     } else {
         $path = $file->file();
         $override = Event::until('file.dl.before', array(&$path, &$file, $this));
         if ($override !== null) {
             return $override;
         } elseif (!$file instanceof File) {
             return E_SERVER;
         } else {
             // In case the model was changed during event firing.
             $file->save();
             return Event::until('file.dl.response', array(&$path, $file, $this));
         }
     }
 }
Example #5
0
 public static function autoloader($class)
 {
     // return if class already exists
     if (class_exists($class, FALSE)) {
         return TRUE;
     }
     // first check for a controller
     if (strstr($class, 'controller')) {
         // format to controller filename convention "c_<controller>.php"
         $file = 'c_' . str_replace('_controller', '', $class);
         if ($path = File::find('controllers/' . $file)) {
             require $path;
             return TRUE;
         } else {
             return FALSE;
         }
         // try the libraries folders
     } elseif ($path = File::find('libraries/' . $class)) {
         require $path;
         return TRUE;
         // try the vendors folders
     } elseif ($path = File::find('vendors/' . $class . '/' . $class)) {
         require $path;
         return TRUE;
     }
     // couldn't find the file
     return FALSE;
 }
Example #6
0
 /**
  * Show the form for editing the specified file meta.
  *
  * @param  int $id
  * @return \Response
  * @throws \Exception
  */
 public function edit($id)
 {
     $file = File::find($id);
     if ($file) {
         return $this->theme->ofWithLayout('partials.file_config_form', compact('file'));
     }
     throw new \Exception('Unable to find file, it may no longer exist');
 }
Example #7
0
 function image($width = null)
 {
     if (!func_num_args()) {
         return $this->image ? File::find($this->image) : null;
     } elseif ($image = $this->image()) {
         $source = $image->file();
         return Block_Thumb::url(compact('width', 'source'));
     }
 }
 function search_files()
 {
     if (isset($_POST['search']) && $_POST['search'] != "") {
         $search = " name LIKE '%" . $_POST['search'] . "%' ";
     } else {
         $files = File::find('all');
     }
     echo FileWrapper::display($files);
     wp_die();
 }
 /**
  * @var bool $enabled If set to FALSE, keep it from showing in the list
  * and from being executable through URL or CLI.
  *
  * @access public
  * @param SS_Request
  */
 public function run($request)
 {
     $dbFilename = $request->getVar('db') ? $request->getVar('db') : 'database.sql.gz';
     $file = File::find($dbFilename);
     if (!$this->checkExtension($dbFilename) || !$file) {
         echo Debug::text("Sorry, either I could not find {$dbFilename} in assets or is not the right format");
         echo Debug::text("Only allowed file formats are .sql or .gz");
         exit;
     }
     // make sure existing DB tables are dropped
     if ($this->dropDBTables()) {
         $this->importSql($file);
     }
 }
Example #10
0
 /**
  * Finds all CakeAdmin files in app/libs/admin
  *
  * @return array
  * @todo test me
  */
 function find()
 {
     $this->handler();
     $this->handler->cd(APPLIBS);
     $content = $this->handler->read();
     if (empty($content[0])) {
         return false;
     }
     if (!in_array('admin', $content[0])) {
         return false;
     }
     $this->handler->cd(APPLIBS . 'admin');
     $content = $this->handler->find('([a-z_]+)(.php)');
     return empty($content) ? false : $content;
 }
Example #11
0
/**
 * The request router looks at the URI path, tries to load it from /assets,
 * then tries to route the request through the Router if it's a model.
 * If it's not a model, the PageEngine tries to render the template file.
 */
function routeRequest()
{
    $path = getPath();
    if (!$path) {
        return PageEngine::renderPage('index');
    }
    if (File::find("assets/{$path}")) {
        File::render("assets/{$path}");
    }
    try {
        $router = new Router();
        return $router->route($path);
    } catch (ModelExistenceException $e) {
        return PageEngine::renderPage($path);
    }
}
 public function saveInto(DataObjectInterface $record)
 {
     if ($record->hasField($this->name) && $record->escapeTypeForField($this->name) != 'xml') {
         throw new Exception('HtmlEditorField->saveInto(): This field should save into a HTMLText or HTMLVarchar field.');
     }
     $htmlValue = Injector::inst()->create('HTMLValue', $this->value);
     // Sanitise if requested
     if ($this->config()->sanitise_server_side) {
         $santiser = Injector::inst()->create('HtmlEditorSanitiser', HtmlEditorConfig::get_active());
         $santiser->sanitise($htmlValue);
     }
     // Resample images and add default attributes
     if ($images = $htmlValue->getElementsByTagName('img')) {
         foreach ($images as $img) {
             // strip any ?r=n data from the src attribute
             $img->setAttribute('src', preg_replace('/([^\\?]*)\\?r=[0-9]+$/i', '$1', $img->getAttribute('src')));
             // Resample the images if the width & height have changed.
             if ($image = File::find(urldecode(Director::makeRelative($img->getAttribute('src'))))) {
                 $width = (int) $img->getAttribute('width');
                 $height = (int) $img->getAttribute('height');
                 if ($width && $height && ($width != $image->getWidth() || $height != $image->getHeight())) {
                     //Make sure that the resized image actually returns an image:
                     $resized = $image->ResizedImage($width, $height);
                     if ($resized) {
                         $img->setAttribute('src', $resized->getRelativePath());
                     }
                 }
             }
             // Add default empty title & alt attributes.
             if (!$img->getAttribute('alt')) {
                 $img->setAttribute('alt', '');
             }
             if (!$img->getAttribute('title')) {
                 $img->setAttribute('title', '');
             }
             // Use this extension point to manipulate images inserted using TinyMCE, e.g. add a CSS class, change default title
             // $image is the image, $img is the DOM model
             $this->extend('processImage', $image, $img);
         }
     }
     // optionally manipulate the HTML after a TinyMCE edit and prior to a save
     $this->extend('processHTML', $htmlValue);
     // Store into record
     $record->{$this->name} = $htmlValue->getContent();
 }
 /**
  * Handle the requests, checking the request file exists and is downloadable.
  * 
  * @param SS_HTTPRequest $request
  * @param DataModel $model
  * @return mixed null
  */
 public function handleRequest(SS_HTTPRequest $request, DataModel $model)
 {
     if (!$request) {
         user_error("Controller::handleRequest() not passed a request!", E_USER_ERROR);
     }
     $this->pushCurrent();
     $this->urlParams = $request->allParams();
     $this->request = $request;
     $this->response = new SS_HTTPResponse();
     $this->setDataModel($model);
     $this->extend('onBeforeInit');
     // Init
     $this->baseInitCalled = false;
     $this->init();
     if (!$this->baseInitCalled) {
         user_error("init() method on class '{$this->class}' doesn't call Controller::init()." . "Make sure that you have parent::init() included.", E_USER_WARNING);
     }
     $this->extend('onAfterInit');
     $address = $this->getRequest()->getVars();
     if (empty($address['url'])) {
         return;
     }
     // make the $url normalised as "assets/somefolder/somefile.ext, so we could find the file record if it has.
     $url = Director::makeRelative(ltrim(str_replace(BASE_URL, '', $address['url']), '/'));
     $file = File::find($url);
     $exists = $file && file_exists($file->getFullPath());
     // F/S check added to File::exists() in SS v3.2.0
     if ($exists) {
         if ($this->canSendToBrowser($file)) {
             //when requesting a re-sampled image, $file is the original image, hence we need to reset the file path
             if (preg_match('/_resampled\\/[^-]+-/', $url)) {
                 $file = new Image();
                 $file->Filename = $url;
             }
             $this->sendFileToBrowser($file);
         } else {
             if ($file instanceof Image) {
                 $this->sendLockpadSamepleImageToBrowser($file);
             } else {
                 $this->treatFileAccordingToStatus($file);
             }
         }
     }
 }
Example #14
0
 /**
  * Descends depth-first into directories, calling $closure
  * for each file or directory, depending on $excludeDirs
  *
  * @param mixed $closure a user function, as defined by call_user_func
  * @param string $path the starting directory
  * @param bool $excludeDirs set to true to exclude directories (the default)
  * @return void
  */
 public static function find($closure, $path, $excludeDirs = true)
 {
     if (is_dir($path)) {
         if (!$excludeDirs) {
             call_user_func($closure, $path);
         }
     } else {
         call_user_func($closure, $path);
         return;
     }
     $fh = opendir($path);
     if (!$fh) {
         throw new Exception("{$path} does not exist or is inaccessible");
     }
     while (false !== ($file = readdir($fh))) {
         if ($file[0] == '.') {
             continue;
         }
         File::find($closure, "{$path}/{$file}", $excludeDirs);
     }
     closedir($fh);
 }
 /**
  * Fetch and update the media thumbnail
  */
 public function updateOEmbedThumbnail()
 {
     $oembed = $this->Media();
     if ($oembed && $oembed->thumbnail_url) {
         $fileName = preg_replace('/[^A-z0-9\\._-]/', '', $oembed->thumbnail_url);
         if ($existing = File::find($fileName)) {
             $this->MediaThumbID = $existing->ID;
         } else {
             $contents = @file_get_contents($oembed->thumbnail_url);
             if ($contents) {
                 $folder = Folder::find_or_make('downloaded');
                 file_put_contents($folder->getFullPath() . $fileName, $contents);
                 $file = Image::create();
                 $file->setFilename($folder->getFilename() . $fileName);
                 $file->ParentID = $folder->ID;
                 $this->MediaThumbID = $file->write();
             }
         }
     } else {
         $this->MediaThumbID = 0;
     }
 }
 /**
  * Check if file exists, both checking filtered filename and exact filename
  *
  * @param string $originalFile Filename
  * @return bool
  */
 protected function checkFileExists($originalFile)
 {
     // Check both original and safely filtered filename
     $nameFilter = FileNameFilter::create();
     $filteredFile = $nameFilter->filter($originalFile);
     // Resolve expected folder name
     $folderName = $this->getFolderName();
     $folder = Folder::find_or_make($folderName);
     $parentPath = $folder ? $folder->getFilename() : '';
     // check if either file exists
     return File::find($parentPath . $originalFile) || File::find($parentPath . $filteredFile);
 }
 public function test_for_multiple_inclussion()
 {
     $AkelosLogFile = new File(array('name' => 'akelos.log'));
     $this->assertTrue($AkelosLogFile->save());
     $LogTag =& $AkelosLogFile->tag->create(array('name' => 'logs'));
     $KasteLogFile = new File(array('name' => 'kaste.log'));
     $this->assertTrue($KasteLogFile->save());
     $KasteLogFile->tag->add($LogTag);
     $BermiLogFile = new File(array('name' => 'bermi.log'));
     $this->assertTrue($BermiLogFile->save());
     $BermiLogFile->tag->add($LogTag);
     $ids = array($AkelosLogFile->getId(), $KasteLogFile->getId(), $BermiLogFile->getId());
     $File = new File();
     $Files =& $File->find($ids, array('include' => array('tags', 'taggings')));
     foreach ($Files as $File) {
         foreach ($File->tags as $Tag) {
             $this->assertEqual($Tag->name, $LogTag->name);
         }
         foreach ($File->taggings as $Tagging) {
             $this->assertEqual($Tagging->tag_id, $LogTag->id);
         }
     }
     $File = new File();
     $this->assertTrue($Files =& $File->find($ids, array('conditions' => "name = 'kaste.log'")));
     $this->assertEqual($Files[0]->name, 'kaste.log');
     /**
      * @todo Implement eager loading for second-level associations
      */
     $File = new File();
     $Files =& $File->find('all', array('include' => array('taggings')));
     foreach (array_keys($Files) as $k) {
         $File =& $Files[$k];
         foreach (array_keys($File->taggings) as $l) {
             $Tagging =& $File->taggings[$l];
             $Tagging->tag->load();
             $this->assertEqual($Tagging->tag->name, $LogTag->name);
             $this->assertEqual($Tagging->tag_id, $LogTag->id);
         }
     }
     /**
      * @todo Implement eager loading for second-level associations
      */
     $Files =& $File->find('all', array('include' => array('tags')));
     foreach ($Files as $File) {
         foreach ($File->tags as $Tag) {
             $this->assertEqual($Tag->name, $LogTag->name);
             $Tag->tagging->load();
             foreach ($Tag->taggings as $Tagging) {
                 $this->assertEqual($Tagging->tag_id, $LogTag->id);
             }
         }
     }
     $File = new File();
     $Files =& $File->find('all', array('include' => array('tags')));
     $tag_ids = array();
     foreach ($Files as $File) {
         foreach ($File->tags as $Tag) {
             $tag_ids[] = $Tag->getId();
         }
     }
     $Tag = new Tag();
     $Tags =& $Tag->find($tag_ids, array('include' => 'taggings'));
     foreach (array_keys($Files) as $k) {
         foreach (array_keys($Files[$k]->tags) as $m) {
             foreach (array_keys($Tags) as $n) {
                 if ($Tags[$n]->id == $Files[$k]->tags[$m]->id) {
                     $Files[$k]->tags[$m]->taggings =& $Tags[$n]->taggings;
                 }
             }
         }
     }
 }
 public function saveInto($record)
 {
     if ($record->escapeTypeForField($this->name) != 'xml') {
         throw new Exception('HtmlEditorField->saveInto(): This field should save into a HTMLText or HTMLVarchar field.');
     }
     $linkedPages = array();
     $linkedFiles = array();
     $htmlValue = new SS_HTMLValue($this->value);
     // Populate link tracking for internal links & links to asset files.
     if ($links = $htmlValue->getElementsByTagName('a')) {
         foreach ($links as $link) {
             $href = Director::makeRelative($link->getAttribute('href'));
             if ($href) {
                 if (preg_match('/\\[sitetree_link id=([0-9]+)\\]/i', $href, $matches)) {
                     $ID = $matches[1];
                     // clear out any broken link classes
                     if ($class = $link->getAttribute('class')) {
                         $link->setAttribute('class', preg_replace('/(^ss-broken|ss-broken$| ss-broken )/', null, $class));
                     }
                     $linkedPages[] = $ID;
                     if (!DataObject::get_by_id('SiteTree', $ID)) {
                         $record->HasBrokenLink = true;
                     }
                 } else {
                     if (substr($href, 0, strlen(ASSETS_DIR) + 1) == ASSETS_DIR . '/') {
                         $candidateFile = File::find(Convert::raw2sql(urldecode($href)));
                         if ($candidateFile) {
                             $linkedFiles[] = $candidateFile->ID;
                         } else {
                             $record->HasBrokenFile = true;
                         }
                     } else {
                         if ($href == '' || $href[0] == '/') {
                             $record->HasBrokenLink = true;
                         }
                     }
                 }
             }
         }
     }
     // Resample images, add default attributes and add to assets tracking.
     if ($images = $htmlValue->getElementsByTagName('img')) {
         foreach ($images as $img) {
             // strip any ?r=n data from the src attribute
             $img->setAttribute('src', preg_replace('/([^\\?]*)\\?r=[0-9]+$/i', '$1', $img->getAttribute('src')));
             if (!($image = File::find($path = urldecode(Director::makeRelative($img->getAttribute('src')))))) {
                 if (substr($path, 0, strlen(ASSETS_DIR) + 1) == ASSETS_DIR . '/') {
                     $record->HasBrokenFile = true;
                 }
                 continue;
             }
             // Resample the images if the width & height have changed.
             $width = $img->getAttribute('width');
             $height = $img->getAttribute('height');
             if ($image) {
                 if ($width && $height && ($width != $image->getWidth() || $height != $image->getHeight())) {
                     //Make sure that the resized image actually returns an image:
                     $resized = $image->ResizedImage($width, $height);
                     if ($resized) {
                         $img->setAttribute('src', $resized->getRelativePath());
                     }
                 }
             }
             // Add default empty title & alt attributes.
             if (!$img->getAttribute('alt')) {
                 $img->setAttribute('alt', '');
             }
             if (!$img->getAttribute('title')) {
                 $img->setAttribute('title', '');
             }
             //If the src attribute is not set, then we won't add this to the list:
             if ($img->getAttribute('src')) {
                 // Add to the tracked files.
                 $linkedFiles[] = $image->ID;
             }
         }
     }
     // Save file & link tracking data.
     if ($record->ID && $record->many_many('LinkTracking') && ($tracker = $record->LinkTracking())) {
         $filter = sprintf('"FieldName" = \'%s\' AND "SiteTreeID" = %d', $this->name, $record->ID);
         DB::query("DELETE FROM \"{$tracker->tableName}\" WHERE {$filter}");
         if ($linkedPages) {
             foreach ($linkedPages as $item) {
                 $SQL_fieldName = Convert::raw2sql($this->name);
                 DB::query("INSERT INTO \"SiteTree_LinkTracking\" (\"SiteTreeID\",\"ChildID\", \"FieldName\")\n\t\t\t\t\tVALUES ({$record->ID}, {$item}, '{$SQL_fieldName}')");
             }
         }
     }
     if ($record->ID && $record->many_many('ImageTracking') && ($tracker = $record->ImageTracking())) {
         $filter = sprintf('"FieldName" = \'%s\' AND "SiteTreeID" = %d', $this->name, $record->ID);
         DB::query("DELETE FROM \"{$tracker->tableName}\" WHERE {$filter}");
         $fieldName = $this->name;
         if ($linkedFiles) {
             foreach ($linkedFiles as $item) {
                 $tracker->add($item, array('FieldName' => $this->name));
             }
         }
     }
     $record->{$this->name} = $htmlValue->getContent();
 }
 public function trackLinksInField($fieldName)
 {
     $record = $this->owner;
     $linkedPages = array();
     $linkedFiles = array();
     $htmlValue = Injector::inst()->create('HTMLValue', $record->{$fieldName});
     $links = $this->parser->process($htmlValue);
     // Highlight broken links in the content.
     foreach ($links as $link) {
         $classStr = trim($link['DOMReference']->getAttribute('class'));
         if (!$classStr) {
             $classes = array();
         } else {
             $classes = explode(' ', $classStr);
         }
         // Add or remove the broken class from the link, depending on the link status.
         if ($link['Broken']) {
             $classes = array_unique(array_merge($classes, array('ss-broken')));
         } else {
             $classes = array_diff($classes, array('ss-broken'));
         }
         if (!empty($classes)) {
             $link['DOMReference']->setAttribute('class', implode(' ', $classes));
         } else {
             $link['DOMReference']->removeAttribute('class');
         }
     }
     $record->{$fieldName} = $htmlValue->getContent();
     // Populate link tracking for internal links & links to asset files.
     foreach ($links as $link) {
         switch ($link['Type']) {
             case 'sitetree':
                 if ($link['Broken']) {
                     $record->HasBrokenLink = true;
                 } else {
                     $linkedPages[] = $link['Target'];
                 }
                 break;
             case 'file':
                 if ($link['Broken']) {
                     $record->HasBrokenFile = true;
                 } else {
                     $linkedFiles[] = $link['Target'];
                 }
                 break;
             default:
                 if ($link['Broken']) {
                     $record->HasBrokenLink = true;
                 }
                 break;
         }
     }
     // Add file tracking for image references
     if ($images = $htmlValue->getElementsByTagName('img')) {
         foreach ($images as $img) {
             if ($image = File::find($path = urldecode(Director::makeRelative($img->getAttribute('src'))))) {
                 $linkedFiles[] = $image->ID;
             } else {
                 if (substr($path, 0, strlen(ASSETS_DIR) + 1) == ASSETS_DIR . '/') {
                     $record->HasBrokenFile = true;
                 }
             }
         }
     }
     // Update the "LinkTracking" many_many
     if ($record->ID && $record->many_many('LinkTracking') && ($tracker = $record->LinkTracking())) {
         $tracker->removeByFilter(sprintf('"FieldName" = \'%s\' AND "%s" = %d', $fieldName, $tracker->getForeignKey(), $record->ID));
         if ($linkedPages) {
             foreach ($linkedPages as $item) {
                 $tracker->add($item, array('FieldName' => $fieldName));
             }
         }
     }
     // Update the "ImageTracking" many_many
     if ($record->ID && $record->many_many('ImageTracking') && ($tracker = $record->ImageTracking())) {
         $tracker->removeByFilter(sprintf('"FieldName" = \'%s\' AND "%s" = %d', $fieldName, $tracker->getForeignKey(), $record->ID));
         if ($linkedFiles) {
             foreach ($linkedFiles as $item) {
                 $tracker->add($item, array('FieldName' => $fieldName));
             }
         }
     }
 }
 /**
  * Add a new group and return its details suitable for ajax.
  *
  * @todo Move logic into Folder class, and use LeftAndMain->doAdd() default implementation.
  */
 public function doAdd($data, $form)
 {
     $class = $this->stat('tree_class');
     // check create permissions
     if (!singleton($class)->canCreate()) {
         return Security::permissionFailure($this);
     }
     // check addchildren permissions
     if (singleton($class)->hasExtension('Hierarchy') && isset($data['ParentID']) && is_numeric($data['ParentID']) && $data['ParentID']) {
         $parentRecord = DataObject::get_by_id($class, $data['ParentID']);
         if ($parentRecord->hasMethod('canAddChildren') && !$parentRecord->canAddChildren()) {
             return Security::permissionFailure($this);
         }
     } else {
         $parentRecord = null;
     }
     // Check parent
     $parentID = $parentRecord && $parentRecord->ID ? (int) $parentRecord->ID : 0;
     // Build filename
     $filename = isset($data['Name']) ? basename($data['Name']) : _t('AssetAdmin.NEWFOLDER', "NewFolder");
     if ($parentRecord && $parentRecord->ID) {
         $filename = $parentRecord->getFilename() . '/' . $filename;
     }
     // Get the folder to be created
     // Ensure name is unique
     foreach ($this->getNameGenerator($filename) as $filename) {
         if (!File::find($filename)) {
             break;
         }
     }
     // Create record
     $record = Folder::create();
     $record->ParentID = $parentID;
     $record->Name = $record->Title = basename($filename);
     $record->write();
     if ($parentRecord) {
         return $this->redirect(Controller::join_links($this->Link('show'), $parentRecord->ID));
     } else {
         return $this->redirect($this->Link());
     }
 }
 /**
  * Gets the ID of a folder given a path relative to /assets/.
  *
  * @param string $path
  * @return int Folder ID
  */
 protected function folderIDFromPath($path)
 {
     $folder = File::find($path);
     if ($folder) {
         return $folder->ID;
     }
 }
 public function get_images()
 {
     $files = File::find(array("conditions" => "type like '%image%'"));
     return $files->toArray();
 }
 /**
  * Given a file and filename, ensure that file renaming / replacing rules are satisfied
  *
  * If replacing, this method may replace $this->file with an existing record to overwrite.
  * If renaming, a new value for $filename may be returned
  *
  * @param string $filename
  * @return string $filename A filename safe to write to
  * @throws Exception
  */
 protected function resolveExistingFile($filename)
 {
     // Create a new file record (or try to retrieve an existing one)
     if (!$this->file) {
         $fileClass = File::get_class_for_file_extension(File::get_file_extension($filename));
         $this->file = Object::create($fileClass);
     }
     // Skip this step if not writing File dataobjects
     if (!$this->file instanceof File) {
         return $filename;
     }
     // Check there is if existing file
     $existing = File::find($filename);
     // If replacing (or no file exists) confirm this filename is safe
     if ($this->replaceFile || !$existing) {
         // If replacing files, make sure to update the OwnerID
         if (!$this->file->ID && $this->replaceFile && $existing) {
             $this->file = $existing;
             $this->file->OwnerID = Member::currentUserID();
         }
         // Filename won't change if replacing
         return $filename;
     }
     // if filename already exists, version the filename (e.g. test.gif to test-v2.gif, test-v2.gif to test-v3.gif)
     $renamer = $this->getNameGenerator($filename);
     foreach ($renamer as $newName) {
         if (!File::find($newName)) {
             return $newName;
         }
     }
     // Fail
     $tries = $renamer->getMaxTries();
     throw new Exception("Could not rename {$filename} with {$tries} tries");
 }
 /**
  * Scrape the content of a field to detect anly links to local SiteTree pages or files
  *
  * @param string $field The name of the field on {@link @owner} to scrape
  */
 function trackLinksInField($field)
 {
     $record = $this->owner;
     $linkedPages = array();
     $linkedFiles = array();
     $htmlValue = Injector::inst()->create('HTMLValue', $record->{$field});
     // Populate link tracking for internal links & links to asset files.
     if ($links = $htmlValue->getElementsByTagName('a')) {
         foreach ($links as $link) {
             $href = Director::makeRelative($link->getAttribute('href'));
             if ($href) {
                 if (preg_match('/\\[(sitetree|file)_link[,\\s]id=([0-9]+)\\]/i', $href, $matches)) {
                     $type = $matches[1];
                     $id = $matches[2];
                     if ($type === 'sitetree') {
                         if (SiteTree::get()->byID($id)) {
                             $linkedPages[] = $id;
                         } else {
                             $record->HasBrokenLink = true;
                         }
                     } else {
                         if ($type === 'file') {
                             if (File::get()->byID($id)) {
                                 $linkedFiles[] = $id;
                             } else {
                                 $record->HasBrokenFile = true;
                             }
                         }
                     }
                 } else {
                     if ($href == '' || $href[0] == '/') {
                         $record->HasBrokenLink = true;
                     }
                 }
             }
         }
     }
     // Add file tracking for image references
     if ($images = $htmlValue->getElementsByTagName('img')) {
         foreach ($images as $img) {
             if ($image = File::find($path = urldecode(Director::makeRelative($img->getAttribute('src'))))) {
                 $linkedFiles[] = $image->ID;
             } else {
                 if (substr($path, 0, strlen(ASSETS_DIR) + 1) == ASSETS_DIR . '/') {
                     $record->HasBrokenFile = true;
                 }
             }
         }
     }
     // Update the "LinkTracking" many_many
     if ($record->ID && $record->many_many('LinkTracking') && ($tracker = $record->LinkTracking())) {
         $tracker->removeByFilter(sprintf('"FieldName" = \'%s\' AND "%s" = %d', $field, $tracker->getForeignKey(), $record->ID));
         if ($linkedPages) {
             foreach ($linkedPages as $item) {
                 $tracker->add($item, array('FieldName' => $field));
             }
         }
     }
     // Update the "ImageTracking" many_many
     if ($record->ID && $record->many_many('ImageTracking') && ($tracker = $record->ImageTracking())) {
         $tracker->removeByFilter(sprintf('"FieldName" = \'%s\' AND "%s" = %d', $field, $tracker->getForeignKey(), $record->ID));
         if ($linkedFiles) {
             foreach ($linkedFiles as $item) {
                 $tracker->add($item, array('FieldName' => $field));
             }
         }
     }
 }
Example #25
0
 /**
  * Loads files
  */
 public function loadFiles()
 {
     $files = File::find('folder_ID', $this->id);
     if (!is_array($files) && $files != NULL) {
         $this->files = array($files);
     } else {
         $this->files = $files;
         if ($this->files != NULL) {
             usort($this->files, array('File', 'compare'));
         }
     }
 }
 function trackLinksInField($field)
 {
     $record = $this->owner;
     $linkedPages = array();
     $linkedFiles = array();
     $htmlValue = Injector::inst()->create('HTMLValue', $record->{$field});
     // Populate link tracking for internal links & links to asset files.
     if ($links = $htmlValue->getElementsByTagName('a')) {
         foreach ($links as $link) {
             $href = Director::makeRelative($link->getAttribute('href'));
             if ($href) {
                 if (preg_match('/\\[sitetree_link,id=([0-9]+)\\]/i', $href, $matches)) {
                     $ID = $matches[1];
                     // clear out any broken link classes
                     if ($class = $link->getAttribute('class')) {
                         $link->setAttribute('class', preg_replace('/(^ss-broken|ss-broken$| ss-broken )/', null, $class));
                     }
                     $linkedPages[] = $ID;
                     if (!DataObject::get_by_id('SiteTree', $ID)) {
                         $record->HasBrokenLink = true;
                     }
                 } else {
                     if (substr($href, 0, strlen(ASSETS_DIR) + 1) == ASSETS_DIR . '/') {
                         $candidateFile = File::find(Convert::raw2sql(urldecode($href)));
                         if ($candidateFile) {
                             $linkedFiles[] = $candidateFile->ID;
                         } else {
                             $record->HasBrokenFile = true;
                         }
                     } else {
                         if ($href == '' || $href[0] == '/') {
                             $record->HasBrokenLink = true;
                         }
                     }
                 }
             }
         }
     }
     // Add file tracking for image references
     if ($images = $htmlValue->getElementsByTagName('img')) {
         foreach ($images as $img) {
             if ($image = File::find($path = urldecode(Director::makeRelative($img->getAttribute('src'))))) {
                 $linkedFiles[] = $image->ID;
             } else {
                 if (substr($path, 0, strlen(ASSETS_DIR) + 1) == ASSETS_DIR . '/') {
                     $record->HasBrokenFile = true;
                 }
             }
         }
     }
     // Update the "LinkTracking" many_many
     if ($record->ID && $record->many_many('LinkTracking') && ($tracker = $record->LinkTracking())) {
         $tracker->removeByFilter(sprintf('"FieldName" = \'%s\' AND "%s" = %d', $field, $tracker->getForeignKey(), $record->ID));
         if ($linkedPages) {
             foreach ($linkedPages as $item) {
                 $tracker->add($item, array('FieldName' => $field));
             }
         }
     }
     // Update the "ImageTracking" many_many
     if ($record->ID && $record->many_many('ImageTracking') && ($tracker = $record->ImageTracking())) {
         $tracker->removeByFilter(sprintf('"FieldName" = \'%s\' AND "%s" = %d', $field, $tracker->getForeignKey(), $record->ID));
         if ($linkedFiles) {
             foreach ($linkedFiles as $item) {
                 $tracker->add($item, array('FieldName' => $field));
             }
         }
     }
 }
 public function permissions()
 {
     try {
         $file = File::find('alias', $this->getParam('alias', ''));
     } catch (FileNotFoundException $e) {
         System::displayError(System::getLanguage()->_('ErrorFileNotFound'), '404 Not Found');
     }
     $form = new Form('form-permissions', '');
     $fieldset = new Fieldset(System::getLanguage()->_('PermissionSetting'));
     $permission = new Select('permission', System::getLanguage()->_('Permission'), FilePermissions::getAll());
     $permission->selected_value = $file->permission;
     $password = new Password('password', System::getLanguage()->_('Password'));
     $fieldset->addElements($permission, $password);
     $form->addElements($fieldset);
     if (Utils::getPOST('submit', false) !== false) {
         if ($form->validate()) {
             if ($permission->selected_value == 2 && empty($password->value)) {
                 $password->error = System::getLanguage()->_('InvalidPassword');
             } else {
                 $file->permission->setPermission($permission->selected_value, $password->value);
                 System::forwardToRoute(Router::getInstance()->build('DownloadController', 'download', $file));
                 exit;
             }
         }
     }
     $form->addButton(new Button(System::getLanguage()->_('Cancel'), 'icon icon-cancel', Router::getInstance()->build('DownloadController', 'download', $file)));
     $smarty = new Template();
     $smarty->assign('title', System::getLanguage()->_('PermissionSetting'));
     $smarty->assign('form', $form->__toString());
     $smarty->display('form.tpl');
 }
Will print '.' for each file, except for deleted ones which are marked as 'x'.

END_OF_HELP;
require_once INSTALLDIR . '/scripts/commandline.inc';
if (!have_option('y', 'yes')) {
    print "About to delete local file entries where the file cannot be found. Are you sure? [y/N] ";
    $response = fgets(STDIN);
    if (strtolower(trim($response)) != 'y') {
        print "Aborting.\n";
        exit(0);
    }
}
print "Deleting";
$file = new File();
$file->whereAdd('filename IS NOT NULL');
// local files
$file->whereAdd('filehash IS NULL', 'AND');
// without filehash value
if ($file->find()) {
    while ($file->fetch()) {
        try {
            $file->getPath();
            print '.';
        } catch (FileNotFoundException $e) {
            $file->delete();
            print 'x';
        }
    }
}
print "\nDONE.\n";
 public function saveInto(DataObjectInterface $record)
 {
     if ($record->hasField($this->name) && $record->escapeTypeForField($this->name) != 'xml') {
         throw new Exception('HtmlEditorField->saveInto(): This field should save into a HTMLText or HTMLVarchar field.');
     }
     $htmlValue = Injector::inst()->create('HTMLValue', $this->value);
     // Sanitise if requested
     if ($this->config()->sanitise_server_side) {
         $santiser = Injector::inst()->create('HtmlEditorSanitiser', HtmlEditorConfig::get_active());
         $santiser->sanitise($htmlValue);
     }
     // Resample images and add default attributes
     if ($images = $htmlValue->getElementsByTagName('img')) {
         foreach ($images as $img) {
             // strip any ?r=n data from the src attribute
             $img->setAttribute('src', preg_replace('/([^\\?]*)\\?r=[0-9]+$/i', '$1', $img->getAttribute('src')));
             // Resample the images if the width & height have changed.
             // TODO: look for -10x here?
             $filename = RetinaImage::removeFilenameAppender(urldecode(Director::makeRelative($img->getAttribute('src'))), '-10x');
             $image = File::find($filename);
             // try to find it using the legacy way
             if (!$image) {
                 $image = File::find(urldecode(Director::makeRelative($img->getAttribute('src'))));
             }
             if ($image) {
                 $imagemap = $image->toMap();
                 $retinaimage = RetinaImage::create();
                 foreach ($imagemap as $key => $value) {
                     $retinaimage->{$key} = $value;
                 }
                 $width = $img->getAttribute('width');
                 $height = $img->getAttribute('height');
                 if ($width && $height && ($width != $retinaimage->getWidth() || $height != $retinaimage->getHeight()) || !$img->hasAttribute('srcset') && RetinaImage::$forceretina) {
                     //Make sure that the resized image actually returns an image:
                     if (!is_numeric($width) || !is_numeric($height)) {
                         $width = (int) ($retinaimage->getWidth() / 2);
                         $height = (int) ($retinaimage->getHeight() / 2);
                     }
                     $resized = $retinaimage->ResizedImage($width, $height);
                     $url = $resized->getRelativePath();
                     $onex10 = $retinaimage->insertFilenameAppender($url, '-10x');
                     $onex15 = $retinaimage->insertFilenameAppender($url, '-15x');
                     $onex20 = $retinaimage->insertFilenameAppender($url, '-20x');
                     if ($resized) {
                         $img->setAttribute('src', $onex10);
                     }
                     // srcset=\"$onex10 1x, $onex15 1.5x, $onex20 2x\"
                     $img->setAttribute('srcset', "{$onex10} 1x, {$onex15} 1.5x, {$onex20} 2x");
                 }
             }
             // Add default empty title & alt attributes.
             if (!$img->getAttribute('alt')) {
                 $img->setAttribute('alt', '');
             }
             if (!$img->getAttribute('title')) {
                 $img->setAttribute('title', '');
             }
         }
     }
     // Store into record
     $record->{$this->name} = $htmlValue->getContent();
 }
if (!have_option('y', 'yes')) {
    print "About to remove duplicate URL entries in file and file_redirection tables. Are you sure? [y/N] ";
    $response = fgets(STDIN);
    if (strtolower(trim($response)) != 'y') {
        print "Aborting.\n";
        exit(0);
    }
}
$file = new File();
$file->query('SELECT id, url, COUNT(*) AS c FROM file GROUP BY url HAVING c > 1');
print "\nFound {$file->N} URLs with duplicate entries in file table";
while ($file->fetch()) {
    // We've got a URL that is duplicated in the file table
    $dupfile = new File();
    $dupfile->url = $file->url;
    if ($dupfile->find(true)) {
        print "\nDeleting duplicate entries in file table for URL: {$file->url} [";
        // Leave one of the URLs in the database by using ->find(true)
        // and only deleting starting with this fetch.
        while ($dupfile->fetch()) {
            print ".";
            $dupfile->delete();
        }
        print "]\n";
    } else {
        print "\nWarning! URL suddenly disappeared from database: {$file->url}\n";
    }
}
$file = new File_redirection();
$file->query('SELECT file_id, url, COUNT(*) AS c FROM file_redirection GROUP BY url HAVING c > 1');
print "\nFound {$file->N} URLs with duplicate entries in file_redirection table";