Exemple #1
0
 /**
  * Create the new notification email.
  * 
  * @param Member $customer
  * @param Order $order
  * @param String $from
  * @param String $to
  * @param String $subject
  * @param String $body
  * @param String $bounceHandlerURL
  * @param String $cc
  * @param String $bcc
  */
 public function __construct(Member $customer, Order $order, $from = null, $to = null, $subject = null, $body = null, $bounceHandlerURL = null, $cc = null, $bcc = null)
 {
     $siteConfig = ShopConfig::get()->first();
     if ($siteConfig->NotificationTo) {
         $this->to = $siteConfig->NotificationTo;
     }
     if ($siteConfig->NotificationSubject) {
         $this->subject = $siteConfig->NotificationSubject . ' - Order #' . $order->ID;
     }
     if ($siteConfig->NotificationBody) {
         $this->body = $siteConfig->NotificationBody;
     }
     if ($customer->Email) {
         $this->from = $customer->Email;
     } elseif (Email::getAdminEmail()) {
         $this->from = Email::getAdminEmail();
     } else {
         $this->from = 'no-reply@' . $_SERVER['HTTP_HOST'];
     }
     $this->signature = '';
     $adminLink = Director::absoluteURL('/admin/shop/');
     //Get css for Email by reading css file and put css inline for emogrification
     $this->setTemplate('Order_NotificationEmail');
     if (file_exists(Director::getAbsFile($this->ThemeDir() . '/css/ShopEmail.css'))) {
         $css = file_get_contents(Director::getAbsFile($this->ThemeDir() . '/css/ShopEmail.css'));
     } else {
         $css = file_get_contents(Director::getAbsFile('swipestripe/css/ShopEmail.css'));
     }
     $this->populateTemplate(array('Message' => $this->Body(), 'Order' => $order, 'Customer' => $customer, 'InlineCSS' => "<style>{$css}</style>", 'Signature' => $this->signature, 'AdminLink' => $adminLink));
     parent::__construct($from, null, $subject, $body, $bounceHandlerURL, $cc, $bcc);
 }
	function FeedItems() {
		$output = new DataObjectSet();
		
		include_once(Director::getAbsFile(SAPPHIRE_DIR . '/thirdparty/simplepie/SimplePie.php'));
		
		$t1 = microtime(true);
		$this->feed = new SimplePie($this->AbsoluteRssUrl, TEMP_FOLDER);
		$this->feed->init();
		if($items = $this->feed->get_items(0, $this->NumberToShow)) {
			foreach($items as $item) {
				
				// Cast the Date
				$date = new Date('Date');
				$date->setValue($item->get_date());

				// Cast the Title
				$title = new Text('Title');
				$title->setValue($item->get_title());

				$output->push(new ArrayData(array(
					'Title' => $title,
					'Date' => $date,
					'Link' => $item->get_link()
				)));
			}
			return $output;
		}
	}
 function css($file, $media = null)
 {
     /* If file is CSS, check if there is a LESS file */
     if (preg_match('/\\.css$/i', $file)) {
         $less = preg_replace('/\\.css$/i', '.less', $file);
         if (is_file(Director::getAbsFile($less))) {
             $file = $less;
         }
     }
     /* If less file, then check/compile it */
     if (preg_match('/\\.less$/i', $file)) {
         $compiler = 'checkedCompile';
         $out = preg_replace('/\\.less$/i', '.css', $file);
         /* Force recompile if ?flush */
         if (isset($_GET['flush'])) {
             $compiler = 'compileFile';
         }
         /* Create instance */
         $less = new lessc();
         /* Automatically compress if in live mode */
         if (DIRECTOR::isLive()) {
             $less->setFormatter("compressed");
         }
         try {
             $less->{$compiler}(Director::getAbsFile($file), Director::getAbsFile($out));
         } catch (Exception $ex) {
             trigger_error("lessphp fatal error: " . $ex->getMessage(), E_USER_ERROR);
         }
         $file = $out;
     }
     /* Return css path */
     return parent::css($file, $media);
 }
 /**
  * Open a CSV file for parsing.
  * You can use the object returned in a foreach loop to extract the data
  * @param $filename The name of the file.  If relative, it will be relative to the site's base dir
  * @param $delimiter The character for seperating columns
  * @param $enclosure The character for quoting or enclosing columns
  */
 function __construct($filename, $delimiter = ",", $enclosure = '"')
 {
     $filename = Director::getAbsFile($filename);
     $this->filename = $filename;
     $this->delimiter = $delimiter;
     $this->enclosure = $enclosure;
     parent::__construct();
 }
Exemple #5
0
 /**
  * Load the given javascript template with the page.
  * @param file The template file to load.
  * @param vars The array of variables to load.  These variables are loaded via string search & replace.
  */
 static function javascriptTemplate($file, $vars, $uniquenessID = null)
 {
     $script = file_get_contents(Director::getAbsFile($file));
     foreach ($vars as $k => $v) {
         $search[] = '$' . $k;
         $replace[] = str_replace("\\'", "'", Convert::raw2js($v));
     }
     $script = str_replace($search, $replace, $script);
     Requirements::customScript($script, $uniquenessID);
 }
 function css($file, $media = null)
 {
     /* Only initiate if webiste is in dev mode or a ?flush is called */
     if (preg_match('/\\.less$/i', $file) || Director::isDev() || isset($_GET['flush'])) {
         /* If file is CSS, check if there is a LESS file */
         if (preg_match('/\\.css$/i', $file)) {
             $less = preg_replace('/\\.css$/i', '.less', $file);
             if (is_file(Director::getAbsFile($less))) {
                 $file = $less;
             }
         }
         /* If less file exists, then check/compile it */
         if (preg_match('/\\.less$/i', $file)) {
             $out = preg_replace('/\\.less$/i', '.css', $file);
             $css_file = Director::getAbsFile($out);
             $options = array();
             /* Automatically compress if in live mode */
             if (Director::isLive()) {
                 $options['compress'] = true;
             }
             try {
                 /* Force recompile & only write to css if updated */
                 if (isset($_GET['flush']) || !Director::isLive()) {
                     /* Force deleting of all cache files on flush */
                     if (file_exists(self::$cacheDir) && isset($_GET['flush']) && !self::$already_flushed) {
                         $paths = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(self::$cacheDir, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST);
                         foreach ($paths as $path) {
                             $path->isDir() && !$path->isLink() ? rmdir($path->getPathname()) : unlink($path->getPathname());
                         }
                         /* make sure we only flush once per request and not for each *.less */
                         self::$already_flushed = true;
                     }
                     /* Set cache directory */
                     $options['cache_dir'] = self::$cacheDir;
                     /* Set cache method */
                     $options['cache_method'] = self::$cacheMethod;
                     /* Calculate the LESS file's parent URL */
                     $css_dir = dirname(Director::baseURL() . $file) . '/';
                     /* Generate and return cached file path */
                     $cached_file = self::$cacheDir . '/' . Less_Cache::Get(array(Director::getAbsFile($file) => $css_dir), $options, self::$variables);
                     /* check cache vs. css and overwrite if necessary */
                     if (!is_file($css_file) || md5_file($css_file) != md5_file($cached_file)) {
                         copy($cached_file, $css_file);
                     }
                 }
             } catch (Exception $ex) {
                 trigger_error('Less.php fatal error: ' . $ex->getMessage(), E_USER_ERROR);
             }
             $file = $out;
         }
     }
     /* Return css file path */
     return parent::css($file, $media);
 }
 /**
  * Sends download request to registered members
  * 
  * @param	object	GET 'filename' request 
  * @return	object	HTTP request
  */
 public function download(SS_HTTPRequest $request)
 {
     $filename = $request->param('Filename');
     if (Member::currentUserID() && $request->isGET() && !empty($filename)) {
         $file = DB::query("SELECT Filename FROM File  WHERE Name = '" . Convert::raw2sql($filename) . "'")->value();
         if (!empty($file) && Director::fileExists($file)) {
             $file_contents = file_get_contents(Director::getAbsFile($file));
             return SS_HTTPRequest::send_file($file_contents, $filename);
         }
     }
     return Security::permissionFailure($this);
 }
 /**
  * Gets the GAPI object. Creates if necessary.
  *
  * @return gapi
  */
 public function api()
 {
     if (!$this->gapi) {
         try {
             $this->gapi = new gapi(self::config()->email, Director::getAbsFile(self::config()->key_file_path));
         } catch (Exception $e) {
             $this->error = $e->getMessage();
             return $this->gapi;
         }
     }
     return $this->gapi;
 }
 /**
  * Set options for Crypt_GPG.
  *
  * @see Crypt_GPGAbstract::__construct() for available options
  */
 private function setOptions()
 {
     $options = GPGMailer::config()->options;
     if (isset($options[0]) && is_array($options[0])) {
         $this->options = $options[0];
     }
     // Option to override home dir and provide a relative path instead
     if (isset($this->options['relative_homedir'])) {
         $this->options['homedir'] = Director::getAbsFile($this->options['relative_homedir']);
         unset($this->options['relative_homedir']);
     }
 }
 public function attachFile($filename, $attachedFilename = null, $mimetype = null)
 {
     if (!$attachedFilename) {
         $attachedFilename = str_replace(Director::baseFolder(), '', $filename);
     }
     $absoluteFileName = Director::getAbsFile($filename);
     if (file_exists($absoluteFileName)) {
         $this->attachFileFromString(file_get_contents($absoluteFileName), $attachedFilename, $mimetype);
     } else {
         user_error("Could not attach '{$absoluteFileName}' to email. File does not exist.", E_USER_NOTICE);
     }
     return $this;
 }
 /**
  * Returns EXIF info defined by $field from images (JPEG, TIFF) stored by the camera.
  *
  * @param string $field String with EXIF field to be returned
  * @return EXIF data or null
  */
 public function ExifData($field = 'DateTimeOriginal')
 {
     // only JPEG and TIFF files contain EXIF data
     $image_extension = strtolower($this->owner->Extension);
     if (!in_array($image_extension, array('jpg', 'jpeg', 'tif', 'tiff'))) {
         return null;
     }
     // extract requested EXIF field
     $image_path = Director::getAbsFile($this->owner->Filename);
     $exif_data = @exif_read_data($image_path, 'EXIF', false, false);
     $exif_field = isset($exif_data[$field]) ? $exif_data[$field] : null;
     return $exif_field;
 }
 /**
  * Set up for interacting with Stomp, icnluding creating the connection. Configuration
  * info is taken from the interface configuration.
  * @param <type> $config
  * @return void
  */
 protected function init($config)
 {
     if (self::$conn) {
         return;
     }
     require_once Director::getAbsFile("messagequeue/thirdparty/stomp-php-1.0.0/Stomp.php");
     $conf = $config["stomp"];
     self::$conn = new Stomp($conf["server"]);
     if (isset($conf["durableClientId"])) {
         self::$conn->clientId = $conf["durableClientId"];
     }
     // @TODO: handle authentication and any other connection properties
     self::$conn->connect();
 }
 function process()
 {
     $dir = Director::getAbsFile(VirutalProductDecorator::$downloadFolder);
     $files = scandir($dir);
     foreach ($files as $file) {
         $filelastmodified = filemtime($dir . $file);
         //Skip ., .. and .htaccess files
         if (strpos($file, '.') !== 0) {
             if ($filelastmodified < strtotime('-' . VirutalProductDecorator::$downloadWindow)) {
                 unlink($dir . $file);
             }
         }
     }
 }
 function css($file, $media = null)
 {
     /**
      * Only initiate automatically if:
      * - webiste is in dev mode
      * - or a ?flush is called
      */
     if (preg_match('/\\.less$/i', $file) || Director::isDev() || isset($_GET['flush'])) {
         /* If file is CSS, check if there is a LESS file */
         if (preg_match('/\\.css$/i', $file)) {
             $less = preg_replace('/\\.css$/i', '.less', $file);
             if (is_file(Director::getAbsFile($less))) {
                 $file = $less;
             }
         }
         /* If less file exists, then check/compile it */
         if (preg_match('/\\.less$/i', $file)) {
             $out = preg_replace('/\\.less$/i', '.css', $file);
             $css_file = Director::getAbsFile($out);
             $options = array();
             /* Automatically compress if in live mode */
             if (Director::isLive()) {
                 $options['compress'] = true;
             }
             try {
                 /* Force recompile & only write to css if updated */
                 if (isset($_GET['flush']) || !Director::isLive()) {
                     /* Create instance */
                     $parser = new Less_Parser($options);
                     if (!empty(self::$variables)) {
                         $parser->ModifyVars(self::$variables);
                     }
                     /* calculate the LESS file's parent URL */
                     $css_dir = rtrim(Director::baseURL(), '/') . Director::makeRelative(dirname(Director::getAbsFile($file)) . '/');
                     $parser->parseFile(Director::getAbsFile($file), $css_dir);
                     $css = $parser->getCss();
                     if (!is_file($css_file) || md5_file($css_file) != md5($css)) {
                         file_put_contents($css_file, $css);
                     }
                 }
             } catch (Exception $ex) {
                 trigger_error("Less.php fatal error: " . $ex->getMessage(), E_USER_ERROR);
             }
             $file = $out;
         }
     }
     /* Return css path */
     return parent::css($file, $media);
 }
 /**
  * Finds the path for specified file.
  *
  * @param string $fileOrUrl
  * @return string|boolean
  */
 protected function path_for_file($fileOrUrl)
 {
     if (preg_match('{^//|http[s]?}', $fileOrUrl)) {
         return $fileOrUrl;
     } elseif (Director::fileExists($fileOrUrl)) {
         $path = pathinfo($fileOrUrl);
         $absoluteFile = Director::getAbsFile(preg_replace('/([^\\?]*)?.*/', '$1', $fileOrUrl));
         $v = '.' . filemtime($absoluteFile) . '.';
         $prefix = Director::baseURL();
         $fileOrUrl = $path['dirname'] . '/' . str_replace('.', $v, $path['basename']);
         return "{$prefix}{$fileOrUrl}";
     } else {
         return false;
     }
 }
 public function ticketfile()
 {
     if (!$this->HasTicketFile() || $this->registration->Status != 'Valid') {
         $this->httpError(404);
     }
     $generator = $this->registration->Time()->Event()->TicketGenerator;
     $generator = new $generator();
     $path = $generator->generateTicketFileFor($this->registration);
     $path = Director::getAbsFile($path);
     $name = $generator->getTicketFilenameFor($this->registration);
     $mime = $generator->getTicketMimeTypeFor($this->registration);
     if (!$path || !file_exists($path)) {
         $this->httpError(404, 'The ticket file could not be generated.');
     }
     return SS_HTTPRequest::send_file(file_get_contents($path), $name, $mime);
 }
 /**
  * proxy method for file attachments
  * @param  [type] $filename         [description]
  * @param  [type] $attachedFilename [description]
  * @param  [type] $mimetype         [description]
  * @return [type]                   [description]
  */
 public function attachFile($filename, $attachedFilename = null, $mimetype = null)
 {
     // generate a name for the file if we aren't supplied one
     if (!$attachedFilename) {
         $attachedFilename = trim(str_replace(Director::baseFolder(), '', $filename), '/');
     }
     // Get the full path
     if (!file_exists($filename)) {
         $filename = Director::getAbsFile($filename);
     }
     // try to attach the file
     if (file_exists($filename)) {
         $this->attachFileFromString(file_get_contents($filename), $attachedFilename, $mimetype);
     } else {
         throw new Exception("Could not attach '{$filename}' to email. File does not exist.");
     }
     return $this;
 }
 /**
  * Returns an array of all selectable template files.
  * 
  * @param string $directory
  * @return array
  */
 public function getSelectableTemplates($directory = 'Layout/')
 {
     $temp = array("" => "None");
     $pre = "";
     if ($TemplateFiles = glob(Director::getAbsFile($this->TemplateDir($directory)) . $pre . "*.ss")) {
         foreach ($TemplateFiles as $TemplateFile) {
             $filename = basename($TemplateFile, ".ss");
             if ($filename != $pre) {
                 $filenicename = $filename;
             } else {
                 $filenicename = "Default";
             }
             $filenicename = str_replace("col", " Column", $filenicename);
             $temp[$filename] = ucwords($filenicename);
         }
     }
     return $temp;
 }
 public function generatePreviewImage($pdfFile, $saveTo)
 {
     try {
         $img = new imagick(Director::getAbsFile($pdfFile) . "[0]");
         //we only take first page
         // -flatten option, this is necessary for images with transparency, it will produce white background for transparent regions
         $img = $img->flattenImages();
         //set new format
         //@Todo detect format from filename
         $img->setImageFormat('jpg');
         $img->setCompressionQuality(100);
         //save image file
         $img->writeImages($saveTo, false);
     } catch (\Exception $e) {
         error_log($e->getMessage());
         return false;
     }
     return true;
 }
 public function generatePreviewImage($pdfFile, $saveTo)
 {
     try {
         $img = new imagick(Director::getAbsFile($pdfFile) . "[0]");
         //we only take first page
         // -flatten option, this is necessary for images with transparency, it will produce white background for transparent regions
         $img->setImageAlphaChannel(11);
         //Imagick::ALPHACHANNEL_REMOVE has been added in 3.2.0b2
         $img->mergeImageLayers(imagick::LAYERMETHOD_FLATTEN);
         //set new format
         //@Todo detect format from filename
         $img->setImageFormat('jpg');
         $img->setCompressionQuality(100);
         //save image file
         $img->writeImages($saveTo, false);
     } catch (\Exception $e) {
         error_log($e->getMessage());
         return false;
     }
     return true;
 }
 public function getPdfPreviewImage()
 {
     $pdfFile = Director::getAbsFile($this->owner->getFileName());
     $pathInfo = pathinfo($pdfFile);
     if (strtolower($pathInfo['extension']) != 'pdf') {
         //@Todo if dev then exception? else fail silently
         return null;
     }
     $fileName = $pathInfo['filename'];
     $savePath = __DIR__ . '/../../';
     $saveImage = $this->imagePrefix . '-' . $fileName . '.jpg';
     // Fix illegal characters
     $filter = FileNameFilter::create();
     $saveImage = $filter->filter($saveImage);
     $saveTo = $savePath . $this->folderToSave . $saveImage;
     $image = DataObject::get_one('Image', "`Name` = '{$saveImage}'");
     if (!$image) {
         $folderObject = DataObject::get_one("Folder", "`Filename` = '{$this->folderToSave}'");
         if ($folderObject) {
             if ($this->generator->generatePreviewImage($pdfFile, $saveTo)) {
                 $image = new Image();
                 $image->ParentID = $folderObject->ID;
                 $image->setName($saveImage);
                 $image->write();
             }
         }
     } else {
         //check LastEdited to update
         $cacheInValid = false;
         if (strtotime($image->LastEdited) < strtotime($this->owner->LastEdited)) {
             $cacheInValid = true;
         }
         if ($cacheInValid) {
             $this->generator->generatePreviewImage($pdfFile, $saveTo);
             $image->setName($saveImage);
             $image->write(false, false, true);
         }
     }
     return $image;
 }
 /**
  * @param string $filepath
  * @param boolean $preview
  *
  * @return null|BulkLoader_Result
  */
 protected function processAll($filepath, $preview = false)
 {
     $filepath = Director::getAbsFile($filepath);
     $files = $this->splitFile($filepath);
     $result = null;
     $last = null;
     try {
         foreach ($files as $file) {
             $last = $file;
             $next = $this->processChunk($file, false);
             if ($result instanceof BulkLoader_Result) {
                 $result->merge($next);
             } else {
                 $result = $next;
             }
             @unlink($file);
         }
     } catch (Exception $e) {
         print "Failed to parse {$last}\n";
     }
     return $result;
 }
 public function getResizedImages()
 {
     $generatedImages = array();
     $cachedFiles = array();
     $folder = $this->owner->ParentID ? $this->owner->Parent()->Filename : ASSETS_DIR . '/';
     $cacheDir = Director::getAbsFile($folder . '_resampled/');
     if (is_dir($cacheDir)) {
         if ($handle = opendir($cacheDir)) {
             while (($file = readdir($handle)) !== false) {
                 // ignore all entries starting with a dot
                 if (substr($file, 0, 1) != '.' && is_file($cacheDir . $file)) {
                     $cachedFiles[] = $file;
                 }
             }
             closedir($handle);
         }
     }
     $pattern = $this->owner->getImageFilenamePatterns($this->owner->Name);
     foreach ($cachedFiles as $cfile) {
         if (preg_match($pattern['FullPattern'], $cfile, $matches)) {
             if (Director::fileExists($cacheDir . $cfile)) {
                 $subFilename = substr($cfile, 0, -1 * strlen($this->owner->Name));
                 preg_match_all($pattern['GeneratorPattern'], $subFilename, $subMatches, PREG_SET_ORDER);
                 $generatorArray = array();
                 foreach ($subMatches as $singleMatch) {
                     $generatorArray[] = array('Generator' => $singleMatch['Generator'], 'Args' => $this->owner->base64url_decode($singleMatch['Args']));
                 }
                 // Using array_reverse is important, as a cached image will
                 // have the generators settings in the filename in reversed
                 // order: the last generator given in the filename is the
                 // first that was used. Later resizements are prepended
                 $generatedImages[] = array('FileName' => $cacheDir . $cfile, 'Generators' => array_reverse($generatorArray));
             }
         }
     }
     return $generatedImages;
 }
Exemple #24
0
 function FeedItems()
 {
     $output = new DataObjectSet();
     // Protection against infinite loops when an RSS widget pointing to this page is added to this page
     if (stristr($_SERVER['HTTP_USER_AGENT'], 'SimplePie')) {
         return $output;
     }
     include_once Director::getAbsFile(SAPPHIRE_DIR . '/thirdparty/simplepie/simplepie.inc');
     $t1 = microtime(true);
     $feed = new SimplePie($this->AbsoluteRssUrl, TEMP_FOLDER);
     $feed->init();
     if ($items = $feed->get_items(0, $this->NumberToShow)) {
         foreach ($items as $item) {
             // Cast the Date
             $date = new Date('Date');
             $date->setValue($item->get_date());
             // Cast the Title
             $title = new Text('Title');
             $title->setValue($item->get_title());
             $output->push(new ArrayData(array('Title' => $title, 'Date' => $date, 'Link' => $item->get_link())));
         }
         return $output;
     }
 }
Exemple #25
0
 /**
  * Returns all classes contained in a certain folder.
  *
  * @todo Doesn't return additional classes that only begin
  *  with the filename, and have additional naming separated through underscores.
  * 
  * @param string $folderPath Relative or absolute folder path
  * @return array Array of class names
  */
 static function classes_for_folder($folderPath)
 {
     $absFolderPath = Director::getAbsFile($folderPath);
     global $_CLASS_MANIFEST;
     $matchedClasses = array();
     foreach ($_CLASS_MANIFEST as $class => $compareFilePath) {
         if (stripos($compareFilePath, $absFolderPath) === 0) {
             $matchedClasses[] = $class;
         }
     }
     return $matchedClasses;
 }
 /**
  * Moving the file if appropriate according to updated database content.
  * Throws an Exception if the new file already exists.
  *
  * Caution: This method should just be called during a {@link write()} invocation,
  * as it relies on {@link DataObject->isChanged()}, which is reset after a {@link write()} call.
  * Might be called as {@link File->updateFilesystem()} from within {@link Folder->updateFilesystem()},
  * so it has to handle both files and folders.
  *
  * Assumes that the "Filename" property was previously updated, either directly or indirectly.
  * (it might have been influenced by {@link setName()} or {@link setParentID()} before).
  */
 public function updateFilesystem()
 {
     if (!$this->config()->update_filesystem) {
         return false;
     }
     // Regenerate "Filename", just to be sure
     $this->setField('Filename', $this->getRelativePath());
     // If certain elements are changed, update the filesystem reference
     if (!$this->isChanged('Filename')) {
         return false;
     }
     $changedFields = $this->getChangedFields();
     $pathBefore = $changedFields['Filename']['before'];
     $pathAfter = $changedFields['Filename']['after'];
     // If the file or folder didn't exist before, don't rename - its created
     if (!$pathBefore) {
         return;
     }
     $pathBeforeAbs = Director::getAbsFile($pathBefore);
     $pathAfterAbs = Director::getAbsFile($pathAfter);
     // TODO Fix Filetest->testCreateWithFilenameWithSubfolder() to enable this
     // // Create parent folders recursively in database and filesystem
     // if(!is_a($this, 'Folder')) {
     // 	$folder = Folder::findOrMake(dirname($pathAfterAbs));
     // 	if($folder) $this->ParentID = $folder->ID;
     // }
     // Check that original file or folder exists, and rename on filesystem if required.
     // The folder of the path might've already been renamed by Folder->updateFilesystem()
     // before any filesystem update on contained file or subfolder records is triggered.
     if (!file_exists($pathAfterAbs)) {
         if (!is_a($this, 'Folder')) {
             // Only throw a fatal error if *both* before and after paths don't exist.
             if (!file_exists($pathBeforeAbs)) {
                 throw new Exception("Cannot move {$pathBeforeAbs} to {$pathAfterAbs} - {$pathBeforeAbs} doesn't exist");
             }
             // Check that target directory (not the file itself) exists.
             // Only check if we're dealing with a file, otherwise the folder will need to be created
             if (!file_exists(dirname($pathAfterAbs))) {
                 throw new Exception("Cannot move {$pathBeforeAbs} to {$pathAfterAbs} - Directory " . dirname($pathAfter) . " doesn't exist");
             }
         }
         // Rename file or folder
         $success = rename($pathBeforeAbs, $pathAfterAbs);
         if (!$success) {
             throw new Exception("Cannot move {$pathBeforeAbs} to {$pathAfterAbs}");
         }
     }
     // Update any database references
     $this->updateLinks($pathBefore, $pathAfter);
 }
 /**
  * Returns true if the given file exists. Filename should be relative to the site root.
  *
  * @param $file
  *
  * @return bool
  */
 public static function fileExists($file)
 {
     // replace any appended query-strings, e.g. /path/to/foo.php?bar=1 to /path/to/foo.php
     $file = preg_replace('/([^\\?]*)?.*/', '$1', $file);
     return file_exists(Director::getAbsFile($file));
 }
Exemple #28
0
 /**
  * Include a locale file determined by module name and locale 
  * 
  * @deprecated 3.0 Use Zend_Translate instead
  * 
  * @param string $module Module that contains the locale file
  * @param string $locale Locale to be loaded
  */
 public static function include_locale_file($module, $locale)
 {
     Deprecation::notice('3.0', 'Use Zend_Translate instead.');
     if (file_exists($file = Director::getAbsFile("{$module}/lang/{$locale}.php"))) {
         include_once $file;
     }
 }
 /**
  * Include the content of the given JavaScript file in the list of requirements. Dollar-sign
  * variables will be interpolated with values from $vars similar to a .ss template.
  *
  * @param string         $file         The template file to load, relative to docroot
  * @param string[] $vars The array of variables to interpolate.
  * @param string $uniquenessID A unique ID that ensures a piece of code is only added once
  */
 public function javascriptTemplate($file, $vars, $uniquenessID = null)
 {
     $script = file_get_contents(Director::getAbsFile($file));
     $search = array();
     $replace = array();
     if ($vars) {
         foreach ($vars as $k => $v) {
             $search[] = '$' . $k;
             $replace[] = str_replace("\\'", "'", Convert::raw2js($v));
         }
     }
     $script = str_replace($search, $replace, $script);
     $this->customScript($script, $uniquenessID);
 }
Exemple #30
0
 /**
  * Change a filename, moving the file if appropriate.
  * @param $renamePhysicalFile Set this to false if you don't want to rename the physical file. Used when calling resetFilename() on the children of a folder.
  */
 protected function resetFilename($renamePhysicalFile = true)
 {
     $oldFilename = $this->getField('Filename');
     $newFilename = $this->getRelativePath();
     if ($this->Name && $this->Filename && file_exists(Director::getAbsFile($oldFilename)) && strpos($oldFilename, '//') === false) {
         if ($renamePhysicalFile) {
             $from = Director::getAbsFile($oldFilename);
             $to = Director::getAbsFile($newFilename);
             // Error checking
             if (!file_exists($from)) {
                 user_error("Cannot move {$oldFilename} to {$newFilename} - {$oldFilename} doesn't exist", E_USER_WARNING);
             } else {
                 if (!file_exists(dirname($to))) {
                     user_error("Cannot move {$oldFilename} to {$newFilename} - " . dirname($newFilename) . " doesn't exist", E_USER_WARNING);
                 } else {
                     if (!rename($from, $to)) {
                         user_error("Cannot move {$oldFilename} to {$newFilename}", E_USER_WARNING);
                     } else {
                         $this->updateLinks($oldFilename, $newFilename);
                     }
                 }
             }
         } else {
             $this->updateLinks($oldFilename, $newFilename);
         }
     } else {
         // If the old file doesn't exist, maybe it's already been renamed.
         if (file_exists(Director::getAbsFile($newFilename))) {
             $this->updateLinks($oldFilename, $newFilename);
         }
     }
     $this->setField('Filename', $newFilename);
 }