/** * Run the instance of a given hook * * @param string $namespace The namespace (addon/aspect) calling the hook * @param string $hook Name of hook * @param string $type Cumulative/replace/call * @param mixed $return Pass-through values * @param mixed $data Data to pass to hooked method * @return mixed */ public static function run($namespace, $hook, $type = NULL, $return = NULL, $data = NULL) { // @Todo: Clean this up globally $addons_path = BASE_PATH . Config::getAddOnsPath(); if (Folder::exists($addons_path) && Folder::exists(APP_PATH . '/core/tags')) { $finder = new Finder(); $files = $finder->files()->in($addons_path)->in(APP_PATH . '/core/tags')->name("hooks.*.php"); foreach ($files as $file) { require_once $file->getRealPath(); $class_name = 'Hooks_' . $file->getRelativePath(); $hook_class = new $class_name(); $method = $namespace . '__' . $hook; if (!method_exists($hook_class, $method)) { continue; } if ($type == 'cumulative') { $response = $hook_class->{$method}($data); if (is_array($response)) { $return = is_array($return) ? $return + $response : $response; } else { $return .= $response; } } elseif ($type == 'replace') { $return = $hook_class->{$method}($data); } else { $hook_class->{$method}($data); } } } else { Log::error('Add-ons path not found', 'hooks'); } return $return; }
public function unlink() { $f = new Folder($this->temp); $f->create(); $f->unlink(); $this->assertFalse($f->exists()); }
public function newFile($name, $contents) { $file = new File($this->t, $name); $path = new Folder($file->getPath()); $path->exists() || $path->create(); $file->out()->write($contents); }
/** * Constructor * * @param io.Folder folder * @throws lang.IllegalArgumentException if the given folder does not exist */ public function __construct(Folder $folder) { if (!$folder->exists()) { throw new IllegalArgumentException('Folder "' . $folder->getURI() . '" does not exist!'); } $this->folder = $folder; }
public function getFiles($formset, $path, $extension = "yaml") { if (!Folder::exists($path)) { return array(); } $finder = new Finder(); $matches = $finder->name("*." . $extension)->depth(0)->files()->followLinks()->in($path); $files = array(); foreach ($matches as $file) { $file_data = Parse::yaml($file->getContents()); $file_data['datestamp'] = date($this->config['datestamp_format'], $file->getMTime()); $meta = array('path' => $file->getRealpath(), 'filename' => $file->getFilename(), 'formset' => $formset, 'extension' => $file->getExtension(), 'datestamp' => $file->getMTime()); $data = array('meta' => $meta, 'fields' => $file_data); $files[] = $data; } return array_reverse($files); }
public function getFiles($formset, $path, $extension = "yaml") { if (!Folder::exists($path)) { return array(); } $finder = new Finder(); $matches = $finder->name("*." . $extension)->depth(0)->files()->followLinks()->in($path); $files = array(); foreach ($matches as $file) { // Ignore page.md if ($file->getFilename() == 'page.md') { continue; } $file_data = Parse::yaml($file->getContents()); $file_data['datestamp'] = date(array_get($this->config, 'datestamp_format', "m/d/Y"), $file->getMTime()); $meta = array('path' => $file->getRealpath(), 'filename' => $file->getFilename(), 'formset' => $formset, 'extension' => $file->getExtension(), 'datestamp' => $file->getMTime()); $meta['edit_path'] = Path::trimSlashes(Path::trimFileSystemFromContent(substr($meta['path'], 0, -1 - strlen($meta['extension'])))); $data = array('meta' => $meta, 'fields' => $file_data); $files[] = $data; } return array_reverse($files); }
/** * Execute action * * @return int */ public function perform() { $this->archive->open(ARCHIVE_READ); $args = $this->getArguments(); while ($entry = $this->archive->getEntry()) { if (!$this->_filter($entry, $args)) { continue; } $f = new File($entry); $data = $this->archive->extract($entry); if (!($this->options & Options::SIMULATE)) { // Create folder on demand. Note that inside a XAR, the directory // separator is *ALWAYS* a forward slash, so we need to change // it to whatever the OS we're currently running on uses. $dir = new Folder(str_replace('/', DIRECTORY_SEPARATOR, dirname($entry))); if (!$dir->exists()) { $dir->create(); } FileUtil::setContents($f, $data); } $this->options & Options::VERBOSE && $this->out->writeLinef('%10s %s', number_format(strlen($data), 0, FALSE, '.'), $entry); } $this->archive->close(); }
public function folderExists() { return Folder::exists(Path::assemble(BASE_PATH, $this->config['destination'])); }
private function list_files($theme_selected) { $files = array(); $files[] = new FormFieldSelectChoiceOption('--', ''); $folder = new Folder(PATH_TO_ROOT . $this->templates_path . $theme_selected . $this->tpl_files_path); foreach ($folder->get_files('`\\.tpl$`') as $file) { $files[] = new FormFieldSelectChoiceOption($file->get_name(), $file->get_name_without_extension()); } foreach (ModulesManager::get_activated_modules_map_sorted_by_localized_name() as $id => $module) { $folder = new Folder(PATH_TO_ROOT . '/' . $module->get_id() . '/templates'); if ($folder->exists()) { foreach ($folder->get_files('`\\.tpl$`') as $file) { $files[] = new FormFieldSelectChoiceOption(LangLoader::get_message('module', 'admin-modules-common') . ' ' . ModulesManager::get_module($module->get_id())->get_configuration()->get_name() . ' : ' . $file->get_name(), $module->get_id() . '/' . $file->get_name_without_extension()); } } } $folder = new Folder(PATH_TO_ROOT . '/user/templates'); if ($folder->exists()) { foreach ($folder->get_files('`\\.tpl$`') as $file) { $files[] = new FormFieldSelectChoiceOption(LangLoader::get_message('users', 'user-common') . ' : ' . $file->get_name(), 'user/' . $file->get_name_without_extension()); } } return $files; }
/** * @desc Redirect to update script when it is present and not installed. */ private static function redirect_to_update_script_if_needed() { $folder = new Folder(PATH_TO_ROOT . '/update'); if ($folder->exists() && !AppContext::get_request()->get_is_localhost() && version_compare(GeneralConfig::load()->get_phpboost_major_version(), UpdateServices::NEW_KERNEL_VERSION, '<')) { self::load_dynamic_constants(); AppContext::get_response()->redirect(new Url(HOST . DIR . '/update')); } }
private function delete_folder($folder_name) { $folder = new Folder(PATH_TO_ROOT . '/' . $folder_name); if ($folder->exists()) { $folder->delete(); } }
/** * Entry point * * @param text.doclet.RootDoc root * @return var */ public function start(RootDoc $root) { $this->processor = new MarkupBuilder(); // Option: API (will be used in title, default: none) $this->api = $this->option('api'); // Option: Gen (will be used in footer) $this->gen = $this->option('gen'); // Option: CSS to embed (filename, default: none) if ($css = $this->option('css')) { $this->css = FileUtil::getContents(new File($css)); } // Option: Output folder (default: Current directory, created if non-existant) $target = new Folder($this->option('output', '.')); $target->exists() || $target->create(); // Compute hierarchy Console::write('['); $this->hierarchy = array(); $seen = array(); while ($this->classes->hasNext()) { $class = $this->classes->next(); if (isset($seen[$class->qualifiedName()])) { continue; } $seen[$class->qualifiedName()] = TRUE; $key = $class->containingPackage()->name(); if (!isset($this->hierarchy[$key])) { $sub = new Folder($target, strtr($key, '.', DIRECTORY_SEPARATOR)); $sub->exists() || $sub->create(); $this->hierarchy[$key] = array('target' => $sub, 'doc' => $class->containingPackage(), 'contents' => array(INTERFACE_CLASS => array(), ORDINARY_CLASS => array(), ENUM_CLASS => array(), EXCEPTION_CLASS => array(), ERROR_CLASS => array())); } Console::write('.'); $this->hierarchy[$key]['contents'][$class->classType()][] = $class; } // Generate HTML files Console::write('>'); $this->writeOverview($this->hierarchy, $target)->close(); Console::writeLine($target, ']'); }
/** * Perform this action * * @param string[] args */ public function perform(array $args) { $installation = new Installation(); $installation->setBase(new Folder(isset($args[0]) ? $args[0] : dirname(Runtime::getInstance()->bootstrapScript()) . '/..')); $force = in_array('-f', $args); with($version = $installation->getVersion()); Console::writeLine('===> Local version ', $version, ' @ ', $installation->getBase()); if (strstr($version, '-dev')) { Console::writeLine('*** Cannot update development checkouts'); return 2; } // Query releases website for newer versions $c = new HttpConnection(self::UPGRADE_URL); $r = $c->get(new RequestData($version)); switch ($r->getStatusCode()) { case HttpConstants::STATUS_OK: case HttpConstants::STATUS_NOT_EXTENDED: Console::writeLine('*** ', $this->readLine($r->getInputStream())); return 2; case HttpConstants::STATUS_SEE_OTHER: $upgrade = $r->getHeader('X-Upgrade-To'); $base = $r->getHeader('Location'); Console::writeLine('---> Upgrading to ', $upgrade, ' (', $base, ')'); $target = new Folder($installation->getBase(), $upgrade); $target->exists() || $target->create(); // Verify dependencies $this->extract($base, 'depend', $target); with($p = new Properties($target->getURI() . 'depend.ini')); $verify = 1; $rtversion = phpversion(); $extensions = array_flip(array_map('strtolower', get_loaded_extensions())); foreach ($p->readSection('php') as $op => $compare) { if (!version_compare(phpversion(), $compare, $op)) { $verify &= $this->error('PHP version ' . $op . ' ' . $compare . ' required, have ' . $rtversion); } } foreach ($p->readSection('ext.required') as $ext => $usage) { if (!isset($extensions[$ext])) { $verify &= $this->error('PHP Extension ' . $ext . ' required for ' . $usage); } } foreach ($p->readSection('ext.conflict') as $ext => $usage) { if (isset($extensions[$ext])) { $verify &= $this->error('PHP Extension ' . $ext . ' conflicts (' . $usage . ')'); } } foreach ($p->readSection('ext.optional') as $ext => $usage) { if (!isset($extensions[$ext])) { $verify &= $this->error('PHP Extension ' . $ext . ' not found, needed for ' . $usage . ' (ignoring)'); } } foreach ($p->readSection('ini') as $setting => $match) { $value = ini_get($setting); if (!preg_match($match, $value)) { $verify &= $this->error('PHP .ini setting ' . $setting . ' needs to match ' . $match . ' (but is ' . $value . ')'); } } // Remove depend.ini, finally check if we should continue create(new File($p->getFilename()))->unlink(); if (!$verify) { if (!$force) { return 3; } Console::writeLine('!!! Ignoring errors because -f was passed'); } // Download base, tools, libraries and meta information $this->extract($base, 'base', $target); $this->extract($base, 'tools', $target); $this->extract($base, 'lib', $target); $this->extract($base, 'meta-inf', $target); // Verify it works by running the XP Framework core unittests $tests = array('net.xp_framework.unittest.core.**'); Console::writeLine('---> Running tests with [USE_XP=', $upgrade, ']:'); $rt = Runtime::getInstance(); set_include_path(implode(PATH_SEPARATOR, array(rtrim($target->getURI(), DIRECTORY_SEPARATOR), '', $target->getURI() . 'lib' . DIRECTORY_SEPARATOR . 'xp-net.xp_framework-' . $upgrade . '.xar'))); with($p = $rt->newInstance($rt->startupOptions(), 'class', 'xp.unittest.Runner', $tests)); $p->in->close(); while (!$p->out->eof()) { Console::writeLine($p->out->readLine()); } while (!$p->err->eof()) { Console::writeLine($p->err->readLine()); } $exit = $p->close(); // Nonzero exit means failure if (0 !== $exit) { Console::writeLine('*** Test run failed, please consult above error messsages'); Console::writeLine($p->getCommandLine()); return 2; } Console::writeLine('===> Done, installed @ ', $target); return 0; default: throw new IllegalStateException('Unexpected response ' . xp::stringOf($r)); } }
/** * Attempts to load an add-on file * * @param integer $type Type of add-on file to load * @param string $addon Add-on to load * @return Addon * @throws Exception */ public static function loadAddonResource($type, $addon) { $folders = Config::getAddOnLocations(); $file = null; $type_map = array(self::PLUGIN => array('abbreviation' => 'pi', 'name' => 'plugin'), self::FIELDTYPE => array('abbreviation' => 'ft', 'name' => 'fieldtype'), self::HOOKS => array('abbreviation' => 'hooks', 'name' => 'hooks'), self::TASKS => array('abbreviation' => 'tasks', 'name' => 'tasks'), self::MODIFIER => array('abbreviation' => 'mod', 'name' => 'modifier'), self::API => array('abbreviation' => 'api', 'name' => 'API')); if (!isset($type_map[$type])) { Log::error("Unknown add-on type.", "API", "Resource"); throw new Exception("Unknown add-on type."); } // grab the abbreviation and name $addon_details = $type_map[$type]; $abbr = $addon_details['abbreviation']; $name = $addon_details['name']; // loop through folders looking for addon foreach ($folders as $folder) { if (Folder::exists(BASE_PATH . '/' . $folder . $addon) && File::exists(BASE_PATH . '/' . $folder . $addon . '/' . $abbr . '.' . $addon . '.php')) { $file = $folder . $addon . '/' . $abbr . '.' . $addon . '.php'; break; } } if (!$file) { Log::error("Could not find files to load the `{$addon}` {$name}.", "API", "Resource"); throw new Exception("Could not find files to load the `{$addon}` {$name}."); } $class = ucwords($name) . "_" . $addon; if (!class_exists($class)) { throw new ResourceNotFoundException("Improperly formatted {$name} object."); } return new $class(); }
/** * Creates an array of breadcrumbs for a given Folder, ready to be * transformed to JSON * * @param Folder $folder * @return array */ protected function createBreadcrumbJSON(Folder $folder) { $breadcrumbs = array(); while ($folder->exists()) { $breadcrumbs[] = array('title' => $folder->Title, 'id' => $folder->ID); $folder = $folder->Parent(); } $breadcrumbs[] = array('title' => ASSETS_DIR, 'id' => 0); return array_reverse($breadcrumbs); }
/** * Removes all storage files last modified before a given $date * * @param mixed $date Date to use as threshold for deletion * @param string $folder Folder to apply wipe to with namespaced storage * @return void */ public function purgeFromBefore($date, $folder="") { $this->verifyStorageFolder(); $this->isValidFilename($folder); $path = $this->contextualize($folder . "/"); if (!Folder::exists($path)) { return; } $finder = new Finder(); $files = $finder->files() ->in($path) ->date("< " . Date::format("F j, Y H:i:s", $date)) ->followLinks(); foreach ($files as $file) { File::delete($file); } }
private function delete_old_files_user() { $file = new File(Url::to_rel('/user/controllers/UserErrorCSRFController.class.php')); $file->delete(); $file = new File(Url::to_rel('/user/controllers/UserMaintainController.class.php')); $file->delete(); $file = new File(Url::to_rel('/user/phpboost/EventsCommentsTopic.class.php')); $file->delete(); $file = new File(Url::to_rel('/user/phpboost/EventsExtensionPointProvider.class.php')); $file->delete(); $file = new File(Url::to_rel('/user/services/UserLostPasswordService.class.php')); $file->delete(); $file = new File(Url::to_rel('/user/templates/ErrorViewBuilder.tpl')); $file->delete(); $file = new File(Url::to_rel('/user/templates/UserMaintainController.tpl')); $file->delete(); $file = new File(Url::to_rel('/user/util/UserDisplayResponse.class.php')); $file->delete(); $folder = new Folder(Url::to_rel('/user/controllers/error')); if ($folder->exists()) { $folder->delete(); } }
/** * Copy a file, or recursively copy a folder and its contents. * * After executing this method successfully, this object will not point to the new folder! * This method can only copy files and folders, all other things will be ignored. * If the source path does not exist this function returns false. If the function could only * do a partial copy the function returns false after trying to copy the remaining files. * New folders are created with the default permissions set by Folder::create(). * * This function implements the ftp fallback! * * @see Folder::create() * @param string Destination path * @return bool Returns true on success, false on failure */ public function copy($dest) { if ($this->exists() == false) { return false; } $folder = new Folder($dest); // Create destination directory if missing if ($folder->exists() == false && $folder->create() == false) { return false; } $ret = true; if ($this->exists() && !$this->isEmpty()) { foreach ($this->getContents() as $content) { if ($content->copy($dest.self::SEPARATOR.$content->name()) == false) { $ret = false; } } } return $ret; }
public static function fetch_content_by_url($path) { $data = NULL; $content_root = Config::getContentRoot(); $content_type = Config::getContentType(); if (File::exists("{$content_root}/{$path}.{$content_type}") || is_dir("{$content_root}/{$path}")) { // endpoint or folder exists! } else { $path = Path::resolve($path); } if (File::exists("{$content_root}/{$path}.{$content_type}")) { $page = basename($path); $folder = substr($path, 0, -1 * strlen($page) - 1); $data = Statamic::get_content_meta($page, $folder); } elseif (Folder::exists("{$content_root}/{$path}")) { $data = Statamic::get_content_meta("page", $path); } return $data; }
/** * Perform this action * * @param string[] args */ public function perform(array $args) { with($target = new Folder($args[1])); $target->exists() || $target->create(); $this->extract(self::BASE_URL, $args[0], $target); }
/** * Get a file * * @param string filename * @return org.webdav.WebdavObject * @throws lang.ElementNotFoundException * @throws org.webdav.OperationNotAllowedException */ public function get($filename, $token = NULL) { $this->c->debug('FILENAME', $filename); $this->c->debug('TOKEN', $token); $filename = $this->_normalizePath($filename); // check for lock $lockinfo = $this->getLockInfo($filename); if ($lockinfo and $lockinfo['type'] == 'exclusive' and 'opaquelocktoken:' . $lockinfo['token'] != $token) { throw new IllegalArgumentException($filename . ' is locked exclusive'); } if (is_dir($this->base . $filename)) { $this->c->debug(get_class($this), '::GET Dir', $filename); $f = new Folder($this->base . $filename); if (!$f->exists()) { throw new ElementNotFoundException($filename . ' not found'); } while ($maxdepth >= 0 && ($entry = $f->getEntry())) { $isdir = is_dir($this->base . $filename . '/' . $entry); $atime = date('H:i:s d.m.y', fileatime($this->base . $filename . '/' . $entry)); if ($isdir) { $flist[0][$entry] .= sprintf(' <tr> <td><a href="%s/">%s</a></td> <td><DIR></td> <td>%s</td> <td> </td> </tr> ', rawurlencode($entry), $entry, $atime); } else { $flist[1][$entry] .= sprintf(' <tr> <td><a href="%s">%s</a></td> <td> </td> <td>%s</td> <td>%s Bytes</td> </tr> ', rawurlencode($entry), $entry, $atime, filesize($this->base . $filename . '/' . $entry)); } } asort($flist[0]); $html = '<table cellpadding=3>' . (strlen($filename) > 2 ? '<tr><td><a href="../">..</a></td><td><DIR></tr>' : '') . implode('', $flist[0]); asort($flist[1]); $flist = $html . implode('', $flist[1]) . '</table>'; $o = new WebdavObject($f->uri, NULL, strlen($flist), 'text/html', new Date(filectime($f->uri)), new Date(filemtime($f->uri))); $o->setData($flist); $f->close(); return $o; } $this->c->debug(get_class($this), '::GET filename', $filename); $this->c->debug(get_class($this), '::GET base', $this->base); // Open file and read contents // contentype if (!file_exists($this->base . $filename)) { throw new ElementNotFoundException($filename . ' not found'); } $f = new File($this->base . $filename); $contentType = ''; $this->c->debug(get_class($this), '::get ', $this->base . filename); $eProps = $this->propStorage->getProperties($f->uri); if (!empty($eProps['getcontenttype'])) { $contentType = $eProps['getcontenttype'][0]; } if (empty($contentType)) { $contentType = MimeType::getByFilename($f->uri, 'text/plain'); } $o = new WebdavObject($f->uri, NULL, $f->size(), $contentType, new Date($f->createdAt()), new Date($f->lastModified())); try { $f->open(FILE_MODE_READ); $o->setData($f->read($f->size())); $f->close(); } catch (FileFoundException $e) { throw new ElementNotFoundException($filename . ' not found'); } $this->c->debug('OBJ', $o->properties); return $o; }
private function delete_old_files() { $file = new File(Url::to_rel('/' . $this->module_id . '/formatting/smileys.php')); $file->delete(); $file = new File(Url::to_rel('/' . $this->module_id . '/templates/smileys.tpl')); $file->delete(); $file = new File(Url::to_rel('/' . $this->module_id . '/templates/js/tinymce/langs/en.js')); $file->delete(); $file = new File(Url::to_rel('/' . $this->module_id . '/templates/js/tinymce/langs/fr.js')); $file->delete(); $file = new File(Url::to_rel('/' . $this->module_id . '/templates/js/tinymce/plugins/fullscreen/editor_plugin.js')); $file->delete(); $file = new File(Url::to_rel('/' . $this->module_id . '/templates/js/tinymce/plugins/fullscreen/editor_plugin_src.js')); $file->delete(); $file = new File(Url::to_rel('/' . $this->module_id . '/templates/js/tinymce/plugins/fullscreen/fullscreen.htm')); $file->delete(); $file = new File(Url::to_rel('/' . $this->module_id . '/templates/js/tinymce/plugins/searchreplace/editor_plugin.js')); $file->delete(); $file = new File(Url::to_rel('/' . $this->module_id . '/templates/js/tinymce/plugins/searchreplace/editor_plugin_src.js')); $file->delete(); $file = new File(Url::to_rel('/' . $this->module_id . '/templates/js/tinymce/plugins/searchreplace/searchreplace.htm')); $file->delete(); $file = new File(Url::to_rel('/' . $this->module_id . '/templates/js/tinymce/plugins/table/cell.htm')); $file->delete(); $file = new File(Url::to_rel('/' . $this->module_id . '/templates/js/tinymce/plugins/table/editor_plugin.js')); $file->delete(); $file = new File(Url::to_rel('/' . $this->module_id . '/templates/js/tinymce/plugins/table/editor_plugin_src.js')); $file->delete(); $file = new File(Url::to_rel('/' . $this->module_id . '/templates/js/tinymce/plugins/table/merge_cells.htm')); $file->delete(); $file = new File(Url::to_rel('/' . $this->module_id . '/templates/js/tinymce/plugins/table/row.htm')); $file->delete(); $file = new File(Url::to_rel('/' . $this->module_id . '/templates/js/tinymce/plugins/table/table.htm')); $file->delete(); $file = new File(Url::to_rel('/' . $this->module_id . '/templates/js/tinymce/tiny_mce.js')); $file->delete(); $file = new File(Url::to_rel('/' . $this->module_id . '/templates/js/tinymce/tiny_mce_popup.js')); $file->delete(); $file = new File(Url::to_rel('/' . $this->module_id . '/templates/js/tinymce/tiny_mce_src.js')); $file->delete(); $folder = new Folder(Url::to_rel('/' . $this->module_id . '/templates/js/tinymce/plugins/emotions')); if ($folder->exists()) { $folder->delete(); } $folder = new Folder(Url::to_rel('/' . $this->module_id . '/templates/js/tinymce/plugins/inlinepopups')); if ($folder->exists()) { $folder->delete(); } $folder = new Folder(Url::to_rel('/' . $this->module_id . '/templates/js/tinymce/plugins/searchreplace/js')); if ($folder->exists()) { $folder->delete(); } $folder = new Folder(Url::to_rel('/' . $this->module_id . '/templates/js/tinymce/plugins/searchreplace/langs')); if ($folder->exists()) { $folder->delete(); } $folder = new Folder(Url::to_rel('/' . $this->module_id . '/templates/js/tinymce/plugins/table/js')); if ($folder->exists()) { $folder->delete(); } $folder = new Folder(Url::to_rel('/' . $this->module_id . '/templates/js/tinymce/plugins/table/langs')); if ($folder->exists()) { $folder->delete(); } $folder = new Folder(Url::to_rel('/' . $this->module_id . '/templates/js/tinymce/themes/advanced')); if ($folder->exists()) { $folder->delete(); } $folder = new Folder(Url::to_rel('/' . $this->module_id . '/templates/js/tinymce/utils')); if ($folder->exists()) { $folder->delete(); } }
/** * Upload file(s) * * @param string $destination Where the file is going * @param string $id The field took look at in the files array * @return array */ public static function uploadBatch($destination = null, $id = null) { $destination = $destination ?: Request::get('destination'); $id = $id ?: Request::get('id'); $files = self::standardizeFileUploads($_FILES); $results = array(); // Resizing configuration if ($resize = Request::get('resize')) { $width = Request::get('width', null); $height = Request::get('height', null); $ratio = Request::get('ratio', true); $upsize = Request::get('upsize', false); $quality = Request::get('quality', '75'); } // If $files[$id][0] exists, it means there's an array of images. // If there's not, there's just one. We want to change this to an array. if ( ! isset($files[$id][0])) { $tmp = $files[$id]; unset($files[$id]); $files[$id][] = $tmp; } // Process each image foreach ($files[$id] as $file) { // Image data $path = File::upload($file, $destination); $name = basename($path); // Resize if ($resize) { $image = \Intervention\Image\Image::make(Path::assemble(BASE_PATH, $path)); $resize_folder = Path::assemble($image->dirname, 'resized'); if ( ! Folder::exists($resize_folder)) { Folder::make($resize_folder); } $resize_path = Path::assemble($resize_folder, $image->basename); $path = Path::toAsset($resize_path); $name = basename($path); $image->resize($width, $height, $ratio, $upsize)->save($resize_path, $quality); } $results[] = compact('path', 'name'); } return $results; }
private function delete_old_files() { $file = new File(Url::to_rel('/' . $this->module_id . '/GalleryUrlBuilder.class.php')); $file->delete(); $file = new File(Url::to_rel('/' . $this->module_id . '/admin_gallery_cat.php')); $file->delete(); $file = new File(Url::to_rel('/' . $this->module_id . '/admin_gallery_cat_add.php')); $file->delete(); $file = new File(Url::to_rel('/' . $this->module_id . '/admin_xmlhttprequest.php')); $file->delete(); $file = new File(Url::to_rel('/' . $this->module_id . '/pics/index.php')); $file->delete(); $file = new File(Url::to_rel('/' . $this->module_id . '/pics/thumbnails/index.php')); $file->delete(); $file = new File(Url::to_rel('/' . $this->module_id . '/templates/admin_gallery_cat.tpl')); $file->delete(); $file = new File(Url::to_rel('/' . $this->module_id . '/templates/admin_gallery_cat_add.tpl')); $file->delete(); $file = new File(Url::to_rel('/' . $this->module_id . '/templates/admin_gallery_cat_del.tpl')); $file->delete(); $file = new File(Url::to_rel('/' . $this->module_id . '/templates/admin_gallery_cat_edit.tpl')); $file->delete(); $file = new File(Url::to_rel('/' . $this->module_id . '/templates/admin_gallery_cat_edit2.tpl')); $file->delete(); $folder = new Folder(Url::to_rel('/' . $this->module_id . '/templates/js')); if ($folder->exists()) { $folder->delete(); } }
$path = str_replace('.html', '', $path); } $app->config['current_path'] = $path; // init some variables for below $content_root = Config::getContentRoot(); $content_type = Config::getContentType(); $response_code = 200; $visible = true; $add_prev_next = false; $template_list = array('default'); // set up the app based on if a if (File::exists("{$content_root}/{$path}.{$content_type}") || Folder::exists("{$content_root}/{$path}")) { // endpoint or folder exists! } else { // $path = Path::resolve($path); $app->config['current_url'] = $app->config['current_path']; // $app->config['current_path'] = $path; # override global current_path } // check for routes // allows the route file to run without "route:" as the top level array key (backwards compatibility) $found_route = null; $routes = array_get($app->config, '_routes:routes', array_get($app->config, '_routes')); $parsed_route_data = array(); // look for matching routes if (is_array($routes)) {
/** * Gets the count of messages with speciefied attribute * or all messages when no attribute was specified * * @param peer.mail.Mailfolder f * @param int attr default 0xFFFF * @return int count */ public function getMessageCount($f, $attr = 0xffff) { $this->openFolder($f); $f = new Folder($f->name . DIRECTORY_SEPARATOR . 'cur'); if (!$f->exists()) { return 0; } $cnt = 0; $f->open(); while ($e = $f->getEntry()) { if ($attr & $this->_getMailFlags($e)) { $cnt++; } } $f->close(); return $cnt; }
/** * Copy a file, or recursively copy a folder and its contents * * @param string $source Source path * @param string $dest Destination path * @return bool Returns TRUE on success, FALSE on failure */ private function copyRecursive($source, $dest) { if (is_file($source)) { $file = new File($source); return $file->copy($dest); } elseif (is_dir($source)) { if (!is_dir($dest)) { $folder = new Folder($dest); if (!$folder->create()) { return false; } } $folder = new Folder($source); $ret = true; if ($folder->exists() && !$folder->isEmpty()) { foreach ($folder->getContents() as $content) { if ($content instanceof File || $content instanceof Folder) { $name = $content->name(); $ret2 = $content->copy("{$dest}/{$name}"); if ($ret2 == false) { $ret = false; } } } } return $ret; } else { return false; } }
/** * Load the config (yaml) files in a specified order: * * 1. Loose per-site configs * 2. Routes * 3. Settings * 4. Theme overrides */ public static function loadAllConfigs($admin = false) { $hash = Debug::markStart('config', 'finding'); /* |-------------------------------------------------------------------------- | YAML Mode |-------------------------------------------------------------------------- | | We need to know the YAML mode first (loose, strict, transitional), | so we parse the settings file once to check before doing anything else. | */ $preload_config = YAML::parse(Config::getConfigPath() . '/settings.yaml'); $yaml_mode = array_get($preload_config, '_yaml_mode', 'loose'); /* |-------------------------------------------------------------------------- | Default Settings |-------------------------------------------------------------------------- | | We keep a set of default options that the user config overrides, allowing | us to always have clean defaults. | */ $settings_to_parse = File::get(Config::getAppConfigPath() . '/default.settings.yaml'); /* |-------------------------------------------------------------------------- | User Site Settings |-------------------------------------------------------------------------- | | Next we parse and override the user's settings. | */ $settings_to_parse .= "\n\n" . File::get(Config::getConfigPath() . '/settings.yaml'); /* |-------------------------------------------------------------------------- | Routes and vanity URLs |-------------------------------------------------------------------------- | | Any URL can be manipulated by routes or vanity urls. We need this info | early on, before content parsing begins. | */ $settings_to_parse .= "\n\n_routes:\n " . trim(preg_replace("/\n/", "\n ", File::get(Config::getConfigPath() . '/routes.yaml'))); $settings_to_parse .= "\n\n_vanity_urls:\n " . trim(preg_replace("/\n/", "\n ", File::get(Config::getConfigPath() . '/vanity.yaml'))); /* |-------------------------------------------------------------------------- | Global Variables |-------------------------------------------------------------------------- | | We parse all the yaml files in the root (except settings and routes) of | the config folder and make them available as global template variables. | */ if (Folder::exists($config_files_location = Config::getConfigPath())) { $files = glob($config_files_location . '/*.yaml'); if ($files) { foreach ($files as $file) { if (strpos($file, 'routes.yaml') !== false || strpos($file, 'vanity.yaml') !== false || strpos($file, 'settings.yaml')) { continue; } $settings_to_parse .= "\n\n" . File::get($file); } } } /* |-------------------------------------------------------------------------- | Parse settings up until now |-------------------------------------------------------------------------- | | Parses the concatenated settings string we've made so far. | */ $config = YAML::parse($settings_to_parse, $yaml_mode); /* |-------------------------------------------------------------------------- | Theme Variables |-------------------------------------------------------------------------- | | Theme variables need to specifically parsed later so they can override | any site/global defaults. | */ $themes_path = array_get($config, '_themes_path', '_themes'); $theme_name = array_get($config, '_theme', 'acadia'); // reset $settings_to_parse = ''; if (Folder::exists($theme_files_location = Path::assemble(BASE_PATH, $themes_path, $theme_name))) { $theme_files = glob(Path::tidy($theme_files_location . '/*.yaml')); if ($theme_files) { foreach ($theme_files as $file) { $settings_to_parse .= "\n\n" . File::get($file); } } } Debug::markEnd($hash); // parse theme settings if any if ($settings_to_parse) { $config = YAML::parse($settings_to_parse, $yaml_mode) + $config; } /* |-------------------------------------------------------------------------- | Load Environment Configs and Variables |-------------------------------------------------------------------------- | | Environments settings explicitly overwrite any existing settings, and | therefore must be loaded late. We also set a few helper variables | to make working with environments even easier. | */ _Environment::establish($config); /* |-------------------------------------------------------------------------- | MIME Types |-------------------------------------------------------------------------- */ $config = array('_mimes' => require Config::getAppConfigPath() . '/mimes.php') + $config; /* |-------------------------------------------------------------------------- | Localization |-------------------------------------------------------------------------- | | We load up English by default. We're American after all. Doesn't the | world revolve around us? Hello? Bueller? More hamburgers please. | */ $config['_translations'] = array(); $config['_translations']['en'] = YAML::parse(Config::getAppConfigPath() . '/default.en.yaml'); if ($lang = array_get($config, '_language', false)) { if (File::exists(Config::getTranslation($lang))) { $translation = YAML::parse(Config::getTranslation($lang)); $config['_translations'][$lang] = Helper::arrayCombineRecursive($config['_translations']['en'], $translation); } } $finder = new Finder(); // clear previous Finder interator results try { $translation_files = $finder->files()->in(BASE_PATH . Config::getAddonsPath() . '/*/translations')->name($lang . '.*.yaml')->depth(0)->followLinks(); foreach ($translation_files as $file) { $translation = YAML::parse($file->getRealPath()); $config['_translations'][$lang] = Helper::arrayCombineRecursive($translation, $config['_translations'][$lang]); } } catch (Exception $e) { // meh. not important. } /* |-------------------------------------------------------------------------- | Set Slim Config |-------------------------------------------------------------------------- | | Slim needs to be initialized with a set of config options, so these | need to be set earlier than the set_default_tags() method. | */ // $config['view'] = new Statamic_View(); $config['cookies.lifetime'] = $config['_cookies.lifetime']; if ($admin) { $admin_theme = array_get($config, '_admin_theme', 'ascent'); if (!Folder::exists(BASE_PATH . Path::tidy('/' . $config['_admin_path'] . '/' . 'themes/' . $admin_theme))) { $admin_theme = 'ascent'; } $theme_path = Path::tidy('/' . $config['_admin_path'] . '/' . 'themes/' . $admin_theme . '/'); $config['theme_path'] = $theme_path; $config['templates.path'] = '.' . $theme_path; } else { $public_path = isset($config['_public_path']) ? $config['_public_path'] : ''; $config['theme_path'] = $themes_path . '/' . $config['_theme'] . '/'; $config['templates.path'] = Path::tidy($public_path . $themes_path . '/' . $config['_theme'] . '/'); } if (!array_get($config, '_display_debug_panel', false)) { Debug::disable(); } return $config; }
} if ($count > 1) { $admin_app->flash('success', Localization::fetch('entries_deleted')); } else { $admin_app->flash('success', Localization::fetch('entry_deleted')); } $url = $admin_app->request()->getReferrer(); $admin_app->redirect($url); })->name('delete_entry')->via('GET', 'POST'); // GET: DELETE PAGE $admin_app->get('/delete/page', function () use($admin_app) { authenticateForRole('admin'); doStatamicVersionCheck($admin_app); $path = Path::assemble(BASE_PATH, Config::getContentRoot(), $admin_app->request()->get('path')); $type = $admin_app->request()->get('type'); if ($type == "folder" && Folder::exists($path)) { Folder::delete($path); $admin_app->flash('success', Localization::fetch('page_deleted')); } else { if (!Pattern::endsWith($path, Config::getContentType())) { $path .= Config::getContentType(); } if (File::exists($path)) { /* |-------------------------------------------------------------------------- | Delete Hook |-------------------------------------------------------------------------- | | Runs the delete hook, passing the file path | */
/** * Check if a Folder object is secure * * @param Folder $folder * @return boolean */ protected function isFolderSecured($folder) { if (!$folder instanceof Folder || !$folder->exists()) { return false; } switch ($folder->CanViewType) { case 'OnlyTheseUsers': return true; case 'Inherit': $parent = $folder->Parent(); return $parent && $parent->exists() && $this->isFolderSecured($parent); case 'Anyone': case 'LoggedInUsers': default: return false; } }