Jump to content

PHP Function


ahmed786

Recommended Posts

Hello,

 

I am a new in PHP:-(. I need help with this task. I want to change ../default/test.png -> /image/default/test.png relative path to ansolute.

this is my script please have a look.

 

<?php

/**

* A small example file to find images that are referenced in template

* files, but not exists in the file system

*

* @author Leander Hanwald

*/

 

error_reporting(E_ALL);

 

/**

* Scans the given directory for all available designs

*

* @param String    $designDirectory  root directory of the designs

* @return Array  list of designs found

*/

function getDesignList($designDirectory)

{

  $result = array();

  $d = dir($designDirectory);

  while (false !== ($entry = $d->read()))

    if ($entry != '..' && $entry != '.' && is_dir($designDirectory.$entry))

      $result[] = $entry;

  return $result;

}

 

/**

* Returns a list of templates for the given design. If the design is not the

* default design, this design is also scaned, the result list is a mix of

* files from both directories (specific design "overwritted" default design)

*

* @param String  $designDirectory  root directory of the designs

* @param String  $designName  name of the current design to scan

* @param Array    $ignoreDirectories  list of directories not to scan

* @return Array  list of templates found in design (and default design)

*/

function getTemplates($designDirectory, $designName, $ignoreDirectories = array())

{

  /* if this is not the default design, we start with all files inside of the

    default design as start array. Our new design will only overwrite these

    entries. */

  $result = array();

  if ($designName != 'default')

    $result = getTemplates($designDirectory, 'default', $ignoreDirectories);

 

  $result = _scanDirectory('', $designDirectory.$designName.'/',

                                $ignoreDirectories, $result);

  return $result;

}

 

/**

* Scans a given directory recursive and extends the given data array with the

* found template files. Works relative to a given root directory.

*

* @param String  $directory  path relative to root of current dir to scan

* @param String  $root  base dir to scan (design directory)

* @param Array  $ignoreDirectories  list of directories not to scan

* @param Array  $data  extend with the new found templates        return true;

* @return array  known and new found templates, key is the relative name to

                  root, value the full filename

*/

function _scanDirectory($directory, $root, $ignoreDirectories, &$data)

{

  if (in_array($directory, $ignoreDirectories))

    return $data;

 

  $d = dir($root.$directory);

  while (false !== ($entry = $d->read()))

  {

    if ($entry == '..' || $entry == '.')

      continue;

 

    if (is_dir($root.$directory.$entry))

      $data = _scanDirectory($directory.$entry.'/', $root, $ignoreDirectories,

                            $data);

 

    $info = pathinfo($root.$directory.$entry);

    $lookup = array('html', 'css');

    if (is_file($root.$directory.$entry) && in_array($info['extension'], $lookup))

      $data[$directory.$entry] = $root.$directory.$entry;

  }

 

  return $data;

}

 

/**

* Trys to find images reference in the given templates, that do not exists

* in the image directory (also given als parameter)

*

* @param String $imageDirectory  root directory of the images of designs

* @param String $designName  name of the current design, needed for replace

*                            variables like {$designName} in the templates.

* @param Array $templates  list of templates to search for missing images

* @return Array  list of images that are reference but not exists

*/

function findMissingImages($imageDirectory, $designName, $templates)

{

  $result = array();

  foreach ($templates as $template)

  {

    $rs = findMissingImagesInTemplate($imageDirectory, $designName, $template);

    $result = array_merge($rs, $result);

  }

 

  return $result;

}

 

/**

* Scans a single template for missing images

*

* @param String  $imageDirectory  root directory of the images of designs

* @param String  $designName  name of the current design, needed for replace

*                              variables like {$designName} in the templates.

* @param $templateFullFileName  complete path to the template to scan

* @return Array  list of images that are reference but not exists in this

*                template

*/

function findMissingImagesInTemplate($imageDirectory, $designName,

                                    $templateFullFileName)

{

      /* TODO 1: Find images in templates*/

  $result = array();

 

  $handle = @fopen($templateFullFileName, "r");

  while (!feof($handle))

  {

    $buffer = fgets($handle);

    $matching = str_replace('{$designName}', $designName, $buffer);

 

    $pattern1 = '/"background-image:+\s*[\(a-z]*+(\s*([\/a-z0-9]*+[\.]*?

                  (jpg|png)))/';             

    $pattern2 = '/([\""\'])*((([^\.\$\: ]*\.)*?(jpg|png)))\1/i';

 

    preg_match_all($pattern1, $matching, $matches1);

    preg_match_all($pattern2, $matching, $matches2);

 

    $matches = array_merge($matches2[0], $matches1[1]);

 

    foreach ($matches as $match)

    {

      $match = str_replace(array('"', '\'', '(', ')'), "", $match);

      $result[] = $match;

    }

  }

  fclose($handle);

  /* TODO 2: Test if images exists via function "imageExists" */

  foreach ($result as $imageUrl)

    $result[] = imageExists($imageDirectory, $imageUrl, $templateFullFileName)

                            === True;

                            print_r($result);

  return $result;

}

 

/**

* Checks if an image, given as url, exists in filesystem.

*

* It is a not so simple task to check if an image found in the template really

* exists in the filesystem. Sometimes the urls contains relative pathes like

* ../default/counter/object.png, or started with an slash (/) or are relative

* at all (a template tries to use a image in the same folder).

*

* To handle this logic, we use an own function to lookup a single file from a

* url in the image directory given as parameter to this function.

*

* @param String $imageDirectory  root directory of the images of designs

* @param String $imageUrl  url of an image, found in a template

* @param $templateFullFileName  complete path to the template, could be needed

*                                in cases of relative image pathes

* @return Boolean  true if image exists, false if not

*/

function imageExists($imageDirectory, $imageUrl, $templateFullFileName)

{

  /* TODO 4: check if image url is relative, if yes make it absolute

  *        like: ../default/test.png -> /image/default/test.png */

    /* Check if url is relative and resolve it from templateFullFileName */

 

$absolute = "";

  if(preg_match('=^\/=',$imageUrl))

  {

    $absolute = $imageUrl;

  }

  $relative = "";

  if (!preg_match('=^\/=', $imageUrl))

  {

  $templateFullPath = dirname($templateFullFileName);

  $relative = $templateFullPath."/".basename($imageUrl);

  }

  $imageUrlAbsPath = $absolute.$relative;

 

/* TODO 5: Check if image in filesystem exist, AND if it is really an image */

 

  $imageDirPath = $imageDirectory."default/".basename($imageUrl);

  if(file_exists($imageDirPath))

  {

  return true;

  } else {

  return false;

  }

}       

 

/* Settings */

 

$designDirectory = '/home/domainusers/m.mujtaba/workspace/picfinder/html/';

$imageDirectory = '/home/domainusers/m.mujtaba/workspace/picfinder/image/';

  /* a lot of directories are not needed in our search, so we ignore them here*/

$ignoreDirectories = array('other/xinha_update/', 'website/themes/',

                          'other/xinha/', 'ecatalog/victorobjectedit/');

 

 

/* main */

 

echo("\nStart finding of missing images...\n");

 

$designList = getDesignList($designDirectory);

$missingImages = array();

foreach ($designList as $designName)

{

  echo(sprintf("Scan design '%s' \n", $designName));

  $templates = getTemplates($designDirectory, $designName, $ignoreDirectories);

  $missingImagesInTemplate = findMissingImages($imageDirectory, $designName,

                                              $templates);

  //print_r($missingImagesInTemplate);                                           

  /* TODO 6: Join $missingImages and $missingImagesInTemplate, bit in a way

            that it is possi*ble to see in which template a file was referenced.

 

            Example result after the join ( print_() output ) :

            array (

              '/image/default/test.png' => array(

                  [0] => 'default/counter/startpage.html'

                  [0] => 'default/counter/info.html'

                )

            )

 

            the list of templates for an image is multi dimensional because it

            is possible that different template reference the same - missing -

            image.

            */

 

}

   

 

print_r($missingImages);

 

Any help will be appreciated.

Thank u

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.