Code snippets for symfony 1.x

Navigation

Refine Tags

Snippets tagged "plugin"

LightWindow, SwfObject and Flash together

Hi, buddies!

It's my first snippet here, and, please, let me know if there's some bad or wrong code in your testings. Also, let me know if I make any mistakes about concepts here, or anything else. :-)

Well, this snippet is about how to get LightWindow, a wonderfull library, and Flash (I mean Adobe's) working together. This can be accomplished by using sfUFOPlugin as unobstrusive Flash content placement and ActionScript 2 inside the Flash animation, but I'll use sfSwfObjectHelperPlugin and ActionScript 3, which are my favorite ones. So, I'm assuming that you have these installed on your Symfony project:

and also knows how to program in ActionScript 3.

Now, let's start with the LightWindow portion of this snippet. If you are already using this plugin's helpers in the view, you don't need to do anything, since the library and CSS will be already loaded. If not, use the helper function, to load the resources, inside the view:

<?php 
 
use_helper('LightWindow'); // load the LW helpers
_lwAddResources(); // load the LW resources (JS and CSS)
 

Alright, now the library is available for use by some JavaScript calls that we'll put inside our Flash project. But wait, there's a little catch here: I do not advise one to put a direct call to a LightWindow JS function as a command under an event listener, on Flash, because by the time the ActionScript is read in the compiled SWF the LW library may not be fully loaded; Instead of the direct call, I recommend you to create a simple JS function, right inside the view, that will delegate the call to the LW function, such as this:

<?php
 
use_helper('Javascript');
 
echo javascript_tag('
function showWindowFromJS()
{
   myLightWindow.activateWindow({href: "path/to/my/image.extension"}); // auxiliary function to be called from inside ActionScript
}
');
 

The path can be assigned to a PHP variable, of course – normally I use $sf_request->getRelativeUrlRoot() to get to the root of the web folders, so that I can access my images easilly -. Also, read the API documentation on LW site to know more about the options to go inside the argument's object.

Now, how about some ActionScript? Let's say:

import flash.events.*;
 
function showWindowFromFlash(event:MouseEvent):void
{
  ExternalInterface.call('showWindowFromJS'); // using EI to communicate to the outside world
}
 
mMyLightWindowLauncher.buttonMode = true; // just to make the user sure that it's clickable.
 
mMyLightWindow.addEventListener(MouseEvent.CLICK, showWindowFromFlash); // assigning the function to the button event
 

We're almost there! Now, just load the Flash movie (SWF file) inside the view using sfSwfObjectHelperPlugin:

<?php
 
use_helper('Flash');
 
$id = 'flash_container_id'; // div to be replaced by Flash content.
 
$params = array( 'id'               => 'flash_object_id',
                 'movie'            => 'path/to/my/movie.swf'
                 'size'             => 'WIDTHxHEIGHT', // replace the dimensions here
                 'version'          => '9',
                 'background_color' => '#ffffff',
                 'params'           => array(
                   'allowScriptAccess' => 'sameDomain',
                   'wmode'             => 'transparent',
                   'quality'           => 'high' ),
                 'variables'        => array(
                   // a bunch of variables, can be an array with links to several images, just catch the vars inside the movie and use them passing as arguments in the ExternalInterface code.
                   ),
                 'create_proxy'     => true );
 

That's it!

See you later, guys!

by Diogo Baeder on 2008-03-24, tagged ajax  flash  lightwindow  plugin  swfobject 
(1 comment)

Tree Rebuild for sfPropelActAsNestedSetBehaviorPlugin plugin

Tree managed by sfPropelActAsNestedSetBehaviorPlugin plugin can be corrupted. In this case, the left & right value are not well numbered (there is hole in numbering) then some method like retrieveFirstChild() or hasChildren() can return incorrect results.

This is a method that scan all the tree and correct left & right numbering. It modify the left & right number only if necessary. It make at maximum one Select SQL request and one update SQL request by node.

It can work for any subtree of the given node or for entire tree if you give the root node as parameter. Second parameter indicate from which number, the numbering start.

  public static function rebuildSubTree($base_node,$number=1)
  {
    $left=$number;
    $children=$base_node->getChildren();
    if (is_array($children))
    {
      foreach ($children as $child)
      {
        $number=self::rebuildSubTree($child,$number+1);
      }
    }
    $right=$number+1;
    if($base_node->getLeftValue()!=$left || $base_node->getRightValue()!=$right)
    {
      $base_node->setLeftValue($left);
      $base_node->setRightValue($right);
      $base_node->save();
    }
    return $number+1;
  }
 
by Sylvain PAPET on 2008-02-13, tagged plugin  rebuild  sfpropelactasnestedsetbehaviorplugin  tree 

TCPDF filter to transform pages to PDF

[DEPRECATED SEE COMMENTS]

{-- DEPRECATED SEE COMMENTS --}

---DEPRECATED SEE COMMENTS---

This basic filter can transform pages into pdf using the sfTCPDFPlugin. You can also save the generated PDF to the database using the sfPropelFileStoragePlugin.

this is the first version so please post comments if you like it or use it !

Create a file in apps/myapp/lib/pdfFilter.class.php

<?php
/**
 * Filter for redirecting to PDF for the pages that need it
 *
 * @author Laurent Marchal
 * @version 1
 */
 
class pdfFilter extends sfFilter
{
    /**
     * Execute filter
     *
     * @param FilterChain $filterChain The symfony filter chain
     */
 
    public function execute ($filterChain)
    {
 
        if ($this->getContext()->getActionName() == 'pdf')
        {
        $pdf = $this->initPDF();
 
        // Next filter
        $filterChain->execute();
 
        $rawpdf = $this->writePDF($pdf, $this->getContext()->getResponse()->getContent());
 
        $pdf->Output(); //shows the pdf to the user
        //$this->savePdfToDatabase($rawpdf);
        return;
        }
        $filterChain->execute();
    }
 
    /**
     * initialyse the TCPDF object, must be instanciated before
     * filterChain->execute() in order to analyse the request.
     *
     */
    protected function initPDF()
    {
        //create new PDF document
        $pdf = new sfTCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true);
        $pdf->SetFont("FreeSerif", "", 12);
        return $pdf;
    }
 
    /**
     * write the contents to the PDF generally
     * getContext()->getResponse()->getContent()
     *
     *@param sfTCPDF $pdf the TCPDF object created with function initPDF()
     *@param stream $html_content the contents to transform to PDF
     */
    protected function writePDF($pdf, $html_content)
    {
        $pdf->AddPage();
        $pdf->writeHTML($html_content, true, 0);
        //$this->logMessage('ficheduActions::createPDF '.$html_content , 'info');
        //$document = $pdf->Output('test.pdf', 's');
        return $pdf->Output('test.pdf', 's');
    }
 
    /**
     * Save the PDF in the database using sfPropelFileStoragePlugin
     *
     *@param stream $pdf_content output of function writePDF()
     */
    protected function  savePdfToDatabase($pdf_content)
    {
        //File Info
      $file_info = new sfPropelFileStorageInfo();
      $file_info->setName('DU_Entreprise_v'.$fichedu->getFdVersion().'.pdf');
      $file_info->setSize(null);
      $file_info->setMimeType('application/pdf');
        //File Data
      $file_data = new sfPropelFileStorageData();
      $file_data->setBinaryData($pdf_content);
      $file_info->addsfPropelFileStorageData($file_data);
      $file_info->save();
    }
 
}

and in apps/myapp/config/filters.yml

rendering: ~
web_debug: ~
security:  ~
 
pdfFilter:
    class:  pdfFilter
 
cache:     ~
common:    ~
flash:     ~
execution: ~

then in your module,you will have to create this function in the action.class.php :

  public function executePdf()
  {
    $this->renderPDF = true;
    //use a special layout to clean the pdf
    //remove if you want your entire layout to be generated into pdf
    $this->setLayout ('pdf');
    //the show action generally fit
    $this->setTemplate ('show');
  }

then go to http://mywebsite/yourmodule/pdf to generate the pdf

H@ve Fun !

by Laurent Marchal on 2007-05-07, tagged database  filter  pdf  plugin  sfpropelfilestorageplugin  sftcpdfplugin  tcpdf 
(4 comments)

foreignkey to sf_guard_user

if you won´t to add a foreignkey to sf_guard_user put this on top off you schema.yml file ;)

propel:
  _attributes :          { package: "plugins.sfGuardPlugin.lib.model" }
  sf_guard_user:
    _attributes:         { phpName: sfGuardUser }
    id:

now you can simple add a foreignkey

propel:
  tbl_user_profile:
    user_id:             { type: integer, primaryKey: true, foreignTable: sf_guard_user, foreignReference: id, onDelete: cascade }

or

propel:
  tbl_user_profile:
    sf_guard_user_id:
by Gordon Franke on 2007-04-27, tagged database  foreignkey  model  plugin  propel  schema  security  user  yml 
(1 comment)

package.xml file structure generator for plugins

It can be a hassle to write a package.yml for a plugin if it contains many files. Fortunately, with the help of the sfFinder class and a bit of programming, you can automate the generation of the <content> part in a batch.

Create a batch/package_generator.php with the following code:

<?php
 
define('SF_ROOT_DIR',    realpath(dirname(__FILE__).'/..'));
define('SF_APP',         'frontend');
define('SF_ENVIRONMENT', 'prod');
define('SF_DEBUG',       false);
 
require_once(SF_ROOT_DIR.DIRECTORY_SEPARATOR.'apps'.DIRECTORY_SEPARATOR.SF_APP.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'config.php');
 
$line          = array();
$lines         = array();
$previous_dirs = array();  
$files         = sfFinder::type('file')->relative()->in('path/to/plugin/files');
 
// Prepare the list of files for nice hierarchy
foreach($files as $file)
{
  $file = str_replace('\\', '/', $file);
  $dirs = explode ('/', $file);
  $line['filename'] = array_pop($dirs);
  $temp_dirs = $dirs;
  foreach($dirs as $dir)
  {
    if($previous_dirs && $dir == $previous_dirs[0])
    {
      array_shift($previous_dirs); 
      array_shift($dirs);
    } 
  }
  foreach($dirs as $dir)
  {
    $line['open'][] = $dir;        
  }
  foreach($previous_dirs as $dir)
  {
    $line['close'][] = $dir;        
  }
  $lines[] = $line;
  $line = array();
  $previous_dirs = $temp_dirs;
}
$blanks = 0;
?>
 
<?php foreach($lines as $line): ?>
<?php if(isset($line['close'])): ?>
<?php foreach($line['close'] as $dir): ?>
<?php echo str_repeat('  ', --$blanks) ?></dir>
<?php endforeach; ?>
<?php endif; ?>
<?php if(isset($line['open'])): ?>
<?php foreach($line['open'] as $dir): $counter++ ?>
<?php echo str_repeat('  ', $blanks++) ?><dir name="<?php echo $dir ?>">
<?php endforeach; ?>
<?php endif; ?>
<?php echo str_repeat('  ', $blanks) ?><file name="<?php echo str_replace('\\', '/', $line['filename']) ?>" role="data"/>
<?php endforeach; ?>

Just run it with

> php batch/package_generator.php

and paste the output in your package.xml. That's all.

by Francois Zaninotto on 2007-01-04, tagged batch  package  plugin 
(2 comments)

unsharp mask for sfThumbnail plugin

I modified some found code (http://vikjavev.no/computing/ump.php?id=35) to add a sharpening feature to sfThumbnail.

Simply add this code to the sfThumbnail class:

  /**
   * Unsharp Mask for PHP
   * Unsharp mask algorithm by Torstein Hønsi
   * Please leave this notice.
   * @author     Torstein Hønsi <thoensi@netcom.no>
   * @author     Modified for use with Symfony by Dave Furfero <furf@furf.com>
   * @version    2.0, 2003-06
   *
   * WARNING! Due to a known bug in PHP 4.3.2 this script is not working
   * well in this version. The sharpened images get too dark. The bug is
   * fixed in version 4.3.3. 
   *
   * From version 2 (July 17 2006) the script uses the imageconvolution
   * function in PHP version >= 5.1, which improves the performance
   * considerably. 
   * 
   * Unsharp masking is a traditional darkroom technique that has proven
   * very suitable for digital imaging. The principle of unsharp masking
   * is to create a blurred copy of the image and compare it to the
   * underlying original. The difference in colour values between the
   * two images is greatest for the pixels near sharp edges. When this
   * difference is subtracted from the original image, the edges will be 
   * accentuated. 
   *
   * Amount simply says how much of the effect you want. 100 is
   * 'normal'
   *
   * Radius is the radius of the blurring circle of the mask.
   *
   * Threshold is the least difference in colour values that is allowed
   * between the original and the mask. In practice this means that
   * low-contrast areas of the picture are left unrendered whereas edges
   * are treated normally. This is good for pictures of e.g. skin or
   * blue skies. 
   *
   * Any suggenstions for improvement of the algorithm, expecially
   * regarding the speed and the roundoff errors in the Gaussian blur
   * process, are welcome. 
   * 
   * @param int amount (0-500)
   * @param float radius (0-50)
   * @param int threshold (0-255)
   * @return void
   * @access public
   */
  public function unsharpMask ($amount, $radius, $threshold)
  {
    // Attempt to calibrate the parameters to Photoshop:
    $amount    = min($amount, 500) * 0.016;
    $radius    = min($radius, 50) * 2;
    $radius    = abs(round($radius)); // Only integers make sense
    $threshold = min($threshold, 255);
 
    if ($amount == 0 || $radius == 0) {
      return;
    }
 
    $w = $this->getThumbWidth();
    $h = $this->getThumbHeight();
 
    $imgCanvas  = imagecreatetruecolor($w, $h);
    $imgCanvas2 = imagecreatetruecolor($w, $h);
    $imgBlur    = imagecreatetruecolor($w, $h);
    $imgBlur2   = imagecreatetruecolor($w, $h);
 
    imagecopy($imgCanvas,  $this->thumb, 0, 0, 0, 0, $w, $h);
    imagecopy($imgCanvas2, $this->thumb, 0, 0, 0, 0, $w, $h);
 
    // Gaussian blur matrix:
    //  1  2  1
    //  2  4  2
    //  1  2  1
 
    imagecopy($imgBlur, $imgCanvas, 0, 0, 0, 0, $w, $h); // background
 
    for ($i = 0; $i < $radius; $i++)  {
 
      if (function_exists('imageconvolution')) { // PHP >= 5.1
        $matrix = array(
          array(1, 2, 1),
          array(2, 4, 2),
          array(1, 2, 1)
        );
        imageconvolution($imgCanvas, $matrix, 16, 0);
      } else {
 
        // Move copies of the image around one pixel at the time
        // and merge them with weight according to the matrix.
        // The same matrix is simply repeated for higher radii.      
        imagecopy($imgBlur, $imgCanvas, 0, 0, 1, 1, $w - 1, $h - 1);
        imagecopymerge($imgBlur, $imgCanvas, 1, 1, 0, 0, $w, $h, 50);
        imagecopymerge($imgBlur, $imgCanvas, 0, 1, 1, 0, $w - 1, $h, 33.33333); 
        imagecopymerge($imgBlur, $imgCanvas, 1, 0, 0, 1, $w, $h - 1, 25);
        imagecopymerge($imgBlur, $imgCanvas, 0, 0, 1, 0, $w - 1, $h, 33.33333); 
        imagecopymerge($imgBlur, $imgCanvas, 1, 0, 0, 0, $w, $h, 25);
        imagecopymerge($imgBlur, $imgCanvas, 0, 0, 0, 1, $w, $h - 1, 20 );
        imagecopymerge($imgBlur, $imgCanvas, 0, 1, 0, 0, $w, $h, 16.666667);
        imagecopymerge($imgBlur, $imgCanvas, 0, 0, 0, 0, $w, $h, 50);
        imagecopy($imgCanvas, $imgBlur, 0, 0, 0, 0, $w, $h);
 
        // During the loop above the blurred copy darkens,
        // possibly due to a roundoff error. Therefore the sharp
        // picture has to go through the same loop to produce a
        // similar image for comparison. This is not a good
        // thing, as processing time increases heavily.
        imagecopy($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h);
        imagecopymerge($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h, 50);
        imagecopymerge($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h, 33.33333);
        imagecopymerge($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h, 25);
        imagecopymerge($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h, 33.33333);
        imagecopymerge($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h, 25);
        imagecopymerge($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h, 20 );
        imagecopymerge($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h, 16.666667);
        imagecopymerge($imgBlur2, $imgCanvas2, 0, 0, 0, 0, $w, $h, 50);
        imagecopy($imgCanvas2, $imgBlur2, 0, 0, 0, 0, $w, $h);
      }
    }
 
    // Calculate the difference between the blurred pixels
    // and the original and set the pixels
    for ($x = 0; $x < $w; $x++)  {
      for ($y = 0; $y < $h; $y++)  {
 
        $rgbOrig = imageColorAt($imgCanvas2, $x, $y);
        $rOrig = (($rgbOrig >> 16) & 0xFF);
        $gOrig = (($rgbOrig >> 8) & 0xFF);
        $bOrig = ($rgbOrig & 0xFF);
 
        $rgbBlur = imageColorAt($imgCanvas, $x, $y);
        $rBlur = (($rgbBlur >> 16) & 0xFF);
        $gBlur = (($rgbBlur >> 8) & 0xFF);
        $bBlur = ($rgbBlur & 0xFF);
 
        // When the masked pixels differ less from the original
        // than the threshold specifies, they are set to their original value.
        $rNew = (abs($rOrig - $rBlur) >= $threshold)
          ? max(0, min(255, ($amount * ($rOrig - $rBlur)) + $rOrig))
          : $rOrig;
        $gNew = (abs($gOrig - $gBlur) >= $threshold)
          ? max(0, min(255, ($amount * ($gOrig - $gBlur)) + $gOrig))
          : $gOrig;
        $bNew = (abs($bOrig - $bBlur) >= $threshold)
          ? max(0, min(255, ($amount * ($bOrig - $bBlur)) + $bOrig))
          : $bOrig;
 
        if (($rOrig != $rNew) || ($gOrig != $gNew) || ($bOrig != $bNew)) {
          $pixCol = imageColorAllocate($this->thumb, $rNew, $gNew, $bNew);
          imageSetPixel($this->thumb, $x, $y, $pixCol);
        }
      }
    }
  }

Then call it like this from your script:

$thumb = new sfThumbnail(160, 120);
$thumb->loadFile($original_img);
$thumb->unsharpMask(40, 0.5, 3);
$thumb->save($img_path, 'image/png');

The three parameters are amount (degree of sharpening from 0-500), radius (pixel radius of blur, from 0-50), and threshold (degree of difference between original and blur, from 0-255). Read the included comments for more info.

It could probably use some better validation and error checking, but it's worked flawlessly for me so far.

by dave furf on 2006-08-31, tagged plugin  sfthumbnail