php arrays / resource ids - delete associated file

I'm trying to create a plugin for MODX that automotically deletes files associated with a resource (when the resource is deleted) - the ids should be accessible by the OnEmptyTrash Event.

Problem is I'm now getting a PHP Fatal error:  Allowed memory size of ............ exhaused
I expect this will be down to my newbie php code rather than a need to adjust the memory limit!..

hope someone can spot my mistake here....thanks
if(!function_exists('delete_files')) {
  function delete_files($filename) {
  unlink($filename);
  return true;
  }
}
$modx->invokeEvent("OnEmptyTrash",
    array(
	"ids"=>$ids
));
global $modx;
$deletedids = $modx->event->params['ids'];
$countid = count($deletedids);
$i = 0;
while ($i <= $countid-1):

$table = $modx->getFullTableName("site_tmplvar_contentvalues");
$rows_affected = $modx->db->delete($table, "contentid = $deletedids[$i] AND tmplvarid = '26'");

$dir = $modx->$deletedids[$i];
delete_files($dir);
$i++;
endwhile;
return;

Open in new window

freshwaterwestAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
Ray PaseurConnect With a Mentor Commented:
Look at line 4 - please use var_dump() to print out the contents of $deletedids array.

Look at line 8 and make a change as follows.

This will give us some data visualization, and that may be helpful to the process.  Thanks, ~Ray
// CHANGE FROM THIS
    $result = $modx->db->query('SELECT id, value FROM `modx_site_tmplvar_contentvalues` WHERE contentid = \'' .$modx->db->escape($value). '\' AND tmplvarid = \'' .$modx->db->escape($tvID1). '\'');

// TO THIS
    $v = $modx->db->escape($value);
    $t = $modx->db->escape($tvID1);
    $s = "SELECT id, value FROM `modx_site_tmplvar_contentvalues` WHERE contentid = '$v' AND tmplvarid = '$t' ";
    var_dump($s);

    $result = $modx->db->query($s);
    var_dump($result);

Open in new window

0
 
Ray PaseurCommented:
This appears to be something inside a function, maybe?  Where is the rest of the code?  It seems unlikely that this is the code that is gobbling up the memory, unless it is happening on line 7-10.  A general strategy might be to try printing out the contents of arrays with var_dump() to see if there are some VERY LONG or VERY COMPLICATED arrays involved here.  One array that would be good to see would be $deletedids.

Not sure I understand why there is a function definition for "delete_files" when the only thing it does is "unlink" - suggest you remove that and just use the native PHP function.  Simpler is almost always better when it comes to computer code.

Best regards, ~Ray
0
 
freshwaterwestAuthor Commented:
thanks Ray, this has moved on quite a bit on the MODx forum but still not working - here is the simplified code, it takes ids from the OnEmptyTrash Event in the MODx manager (i.e. when resources are properly deleted by clicking the bin), the intention is that it finds the associated file (a template variable) and deletes it at the same time so not having to manually delete every time.

I can echo the $deletedids but for some reason I get nothing when trying to echo the $output from the query - I think there is an issue with the array/query - I must be doing something wrong.

I can make this work by manually adding an id but as soon as the array is used it does nothing..
//Set the associated template variable ids that need to be deleted
$tvID1 = "26";
global $modx;
$deletedids = (array) $modx->event->params['ids'];
foreach ($deletedids as $key=>$value) {

    //Get the filepath of the tv1 (tvID1)
    $result = $modx->db->query('SELECT id, value FROM `modx_site_tmplvar_contentvalues` WHERE contentid = \'' .$modx->db->escape($value). '\' AND tmplvarid = \'' .$modx->db->escape($tvID1). '\'');
    while($row = $modx->db->getRow($result)) {
	$output = $row['value'];
unlink($output);
}
}
return;

Open in new window

0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
freshwaterwestAuthor Commented:
great - that's now printing out some information on screen which is something I haven't been able to do yet... here's the results:


var_dump($deletedids);

array(0) { }
(the resource id I was deleting was 94 - seems this is where the problem is? Not sure why I'm not getting the ids from the event here)

var_dump($result);

string(100) "SELECT id, value FROM `modx_site_tmplvar_contentvalues` WHERE contentid = '94' AND tmplvarid = '26' " resource(23) of type (mysql result)
//Set the associated template variable ids that need to be deleted
$tvID1 = "26";
global $modx;
$deletedids = (array) $modx->event->params['ids'];
var_dump($deletedids);
foreach ($deletedids as $key=>$value) {

    //Get the filepath of the tv1 (tvID1)
    $v = $modx->db->escape($value);
    $t = $modx->db->escape($tvID1);
    $s = "SELECT id, value FROM `modx_site_tmplvar_contentvalues` WHERE contentid = '$v' AND tmplvarid = '$t' ";
    var_dump($s);

   $result = $modx->db->query($s);
    var_dump($result);
//unlink($output);
}
return;

Open in new window

0
 
freshwaterwestAuthor Commented:
sorry just realised 0 would be the first array id - DOH!
0
 
Ray PaseurConnect With a Mentor Commented:
$deletedids prints array(0) { } and that means it is an array with zero elements.  It is merely coincidental that the zero-th position of the array is the first array ID.

The query looks good.

Try changing line 4 above to this and let's see what we get if we do not cast an array.
$deletedids = $modx->event->params['ids'];

Open in new window

0
 
freshwaterwestAuthor Commented:
I'm trying to get the field "value" which has a file link in it..

this is the result at the moment:
var_dump($result);
resource(23) of type (mysql result)
0
 
Ray PaseurCommented:
Right, the "mysql result" resource is used like this.
while ($row = mysql_fetch_assoc($result))
{
    $value = $row["value"];
    echo $value;
}

Open in new window

0
 
freshwaterwestAuthor Commented:
I replaced the 4th line and uncommented the
var_dump($deletedids); below
but now there is no feedback?

would that be correct if there is nothing to feedback?

thanks
0
 
Ray PaseurCommented:
Please post the code the way it looks now, thanks.
0
 
freshwaterwestAuthor Commented:
right gone back to the orig array 4th line and I'm getting:
array(1) { [0]=>  string(2) "82" }
0
 
freshwaterwestAuthor Commented:
here's the up to date:

I don't get anything when trying to     var_dump($value);

thanks Ray
//Set the associated template variable ids that need to be deleted
$tvID1 = "26";
global $modx;
$deletedids = (array) $modx->event->params['ids'];
//$deletedids = $modx->event->params['ids'];
//var_dump($deletedids);
foreach ($deletedids as $key=>$value) {

    //Get the filepath of the tv1 (tvID1)
    $v = $modx->db->escape($value);
    $t = $modx->db->escape($tvID1);
    $s = "SELECT id, value FROM `modx_site_tmplvar_contentvalues` WHERE contentid = '$v' AND tmplvarid = '$t' ";
//    var_dump($s);
   $result = $modx->db->query($s);
while ($row = mysql_fetch_assoc($result))
{
    $value = $row["value"];
    var_dump($value);
unlink($value);
}
//    var_dump($result);
}
return;

Open in new window

0
 
Ray PaseurConnect With a Mentor Commented:
The the while() loop is not being executed because the results set is empty.  In other words, teh query found nothing that matched the criteria of the SELECT statement
0
 
freshwaterwestAuthor Commented:
can't seem to get a value from the row
var_dump($value);


when I'm deleting / testing I'm only deleting one resource but in reality there could be one or several when the OnEmptyTrash event is fired (or at least that's what I was hoping to achieve)

thanks
0
 
freshwaterwestAuthor Commented:
here's a quick snapshot to show where the data is being searched -  just tested deleting resource 101 which should have matched the criteria
Picture-5.png
0
 
Ray PaseurConnect With a Mentor Commented:
I cannot really follow the logic of what you're trying to do.  If you deleted resource 101, it would seem reasonable to me that you would no longer be able to find resource 101, right?
0
 
freshwaterwestAuthor Commented:
just tried the non array 4th line again and got:

array(1) { [0]=>  string(2) "83" }
//$deletedids = (array) $modx->event->params['ids'];
$deletedids = $modx->event->params['ids'];
var_dump($deletedids);

Open in new window

0
 
freshwaterwestAuthor Commented:
sorry Ray, here's a run down of what I'm aiming for:

1. A resource can have a file field (template variable which is tmplvarid 26)

2. When a resource is deleted in modx manager there is an OnEmptyTrash Event

3. I'm trying to create a plugin so that when a resource is deleted, the associated file is automatically deleted  (with the id from the array provided by the OnEmptyTrash) the resource id matches our "contentid" field

The resource is only deleted after the OnEmptyTrash event has been fired as I understand it.. There is also an OnBeforeEmptyTrash event.

hope that makes sense..

thanks Ray



0
 
freshwaterwestAuthor Commented:
Hi Ray, this has moved on quite a bit now, I've changed to the OnBeforeEmptyTrash as you pointed out it seems by the time the sql was being called the resource had been deleted...!

I've managed to successfully echo the filepath which seems spot on, but when I comment out the echo $filepath / die and try get it to unlink then it comes up with the else - No File Exists..?

Here's the code up to date:
$tvID1 = "26";
global $modx;
$deletedids = (array) $modx->event->params['ids'];
//$deletedids = $modx->event->params['ids'];
//var_dump($deletedids);
foreach ($deletedids as $key=>$value) {

    $v = $modx->db->escape($value);
    $t = $modx->db->escape($tvID1);
    $res = $modx->db->select("value", $modx->getFullTableName('site_tmplvar_contentvalues'), 
    "contentid=$v AND tmplvarid=$t");
    if($modx->db->getRecordCount($res))
    {
       while($row = $modx->db->getRow($res))
         {
         $value = $row["value"];
         //var_dump($value);
         //echo    $modx->config['base_url'].$value;
          //die;
         $filepath = $modx->config['base_url'].$value;
                    if(file_exists($filepath)) {
                    //echo $filepath;
                    //die;
                    unlink($filepath);
                    } else {
                      die('No File Exists');
                    }
           }
    } else {
    die('Query failed');
    exit;
    }
}
return;

Open in new window

0
 
Ray PaseurCommented:
Still hard to understand what the data contains.  Let's try changing  line 26 so we can see what is going on.
// LINE 26
die("$filepath DOES NOT EXIST");

Open in new window

0
 
freshwaterwestAuthor Commented:
Hi Ray, this is the response so really can't understand why it's not deleting. Weird!.. Maybe something in the modx core / manager is affecting it although I don't see how or why. The search goes on...

/assets/files/CSS-for-iphone.pdf DOES NOT EXIST

(this file is available and exists at the location above - I checked the permissions too but didn't make any difference)

thanks for all your help on this Ray, I've learned lots just from this alone!... be nice to get this working tho : )
0
 
Ray PaseurConnect With a Mentor Commented:
Good, we are making progress.  The file_exists() function is documented here (please read, including the code examples and user-contributed notes):
http://us.php.net/manual/en/function.file-exists.php

/assets/files/CSS-for-iphone.pdf DOES NOT EXIST means that it did not find this path in the current working directory.  Perhaps it is relative to the DOCUMENT_ROOT?  Or perhaps file_exists() is crippled by one of the methods documented on the man page.
0
 
freshwaterwestAuthor Commented:
Brilliant - we finally got there!...
Thanks again - you've been a massive help Ray!

I had to enter the full path to the root

In my case I'm testing on MAMP / mac so needed to be:
"/Applications/MAMP/htdocs/".$filename;
0
 
freshwaterwestAuthor Commented:
took a while but got there in the end thanks for all your help with this... my php / sql knowledge has taken a small leap forward!
0
 
Ray PaseurCommented:
Thanks for the points, and good luck with your project! ~Ray
0
All Courses

From novice to tech pro — start learning today.