Problem in down loading all certificates in Php(moodle) - php

Code to download all certificates:
<?php
require_once('../../config.php');
global $DB,$CFG;
$certlist = $_POST['select_cert'];
print_r($certlist);
$files = array('niBMkaooT.jpg');
$zip = new ZipArchive();
$zip_name = time().".zip";
$zip->open($zip_name, ZipArchive::CREATE);
foreach ($files as $file) {
$path = $file;
if(file_exists($path)){
$zip->addFromString(basename($path), file_get_contents($path));
}
else{
echo"file does not exist";
}
}
$zip->close();
?>
if($certificate!=''){
echo "<input type='checkbox' class='checkboxcert' name='select_cert[]' value='$certificate'>";
}
echo "</td>";
echo "<td>";
Also below i am getting $certificate and when i am downloading individual certificates this is working fine . But when selecting multiple document i am not able to download all
$certificate = get_certificate($userid,$c_id);
Please find the array which i have printed (print_r($certlist))
Array ( [0] => https://google.com/lms/plufile.php/69402/mod_certificate/issue/484123/Abu 2021_Abu, Neglecting, and Exploitation.pdf [1] =>
Please advise what changes are required?`

The certificate PDF isn't always saved, so the file might not always be available
I'd suggest creating and saving the PDF in your own code
Have a look at how the PDF is saved in the view code
https://github.com/mdjnelson/moodle-mod_certificate/blob/master/view.php
if ($certificate->savecert == 1) {
certificate_save_pdf($filecontents, $certrecord->id, $filename, $context->id);
}
Then work backwards from there to see how the variables are created
eg. $USER is the current user
$certrecord = certificate_get_issue($course, $USER, $certificate, $cm);
So you will need to replace that with the required $user in your code
$certrecord = certificate_get_issue($course, $user, $certificate, $cm);

Related

PHP – ZIP-file creation results in ZIP-file zipping itself

The script I'm using to create a ZIP-file out of multiple files results in a russian ZIP doll: instead of overwriting a current ZIP-file with the same name as intended, it's zipping the existing ZIP-file plus the actual files.
The ZIP-file (always with the same name) is being created after a page update (= file-upload/deletion) in the CMS.
Although it's the CMS' syntax, I hope it's readable;
'file.create:after' => function ($file) {
$page = $file->page();
$files_to_zip = $page->files(); // array
$parent_folder = $page->parent()->dirname(); // string
$target_folder = $page->dirname(); // string
$zip = new ZipArchive();
$zip_file = "content/" . $parent_folder . "/" . $target_folder . "/somefile.zip";
$zip->open($zip_file, (ZipArchive::CREATE | ZipArchive::OVERWRITE));
foreach ($files_to_zip as $file_to_zip) {
$zip->addFile($file_to_zip->root(), basename($file_to_zip->filename()));
}
$zip->close();
}
Am I missing something concerning the overwriting if existing of the file?
Thanks for any input!
AFTER "rotation" you need to call $file->page->files()
You need to manually "rotate" the zip archives, or just delete it (not recomended since it can result in data loss)
'file.create:after' => function ($file) {
$page = $file->page();
$parent_folder = $page->parent()->dirname(); // string
$target_folder = $page->dirname(); // string
$zip = new ZipArchive();
$zip_file = "content/" . $parent_folder . "/" . $target_folder ."/somefile.zip";
//delete old rotation if exists
unlink($zip_file.'.backup');
//rotate current zip file to '****.backup'
rename($zip_file, $zip_file.'.backup');
$files_to_zip = $file->page()->files(); // array
$zip->open($zip_file, (ZipArchive::CREATE | ZipArchive::OVERWRITE));
foreach ($files_to_zip as $file_to_zip) {
$zip->addFile($file_to_zip->root(), basename($file_to_zip->filename()));
}
$zip->close();
}

How to save extracted zip file with specific filename

I have zip files with only one file inside it, but it has new name every time. I need to extract file and save it with specific file name, not extracted one.
$zip = new ZipArchive;
$res = $zip->open($tmp_name);
if ($res === TRUE) {
$path = _PATH."/files/";
$zip->extractTo($path);
$zip->close();
echo 'Unzip!';
}
Abowe code works, but I need to have specific filename. For example anyfile located under zip (eg. pricelist025.xml should be named temp.xml
Rename your specific file before you extract it.
$zip = new ZipArchive;
$res = $zip->open($tmp_name);
if ($res === TRUE) {
$zip->renameName('pricelist025.xml','temp.xml');
$path = _PATH."/files/";
$zip->extractTo($path);
$zip->close();
echo 'Unzip!';
} else {
echo 'failed, code:' . $res;
}
I hope this works.
UPDATE 1
There is two options if you want to change the file names.
1. change the file names before extracting -This way zip files will be modified
2. change the file names after extracting -Zip files will remain as they were before
Changing file names before extracting
We have to define a pattern for filenames. Here, Files will be in this patter : myfile0.xml, myfile1.html, adn so on..
Note: extension will be preserved.
$zip = new ZipArchive;
$res = $zip->open('hello.zip');
$newfilename = 'myfile';
for($i=0;$i<$zip->count();$i++)
{
$extension = pathinfo($zip->getNameIndex($i))['extension'];
$zip->renameName($zip->getNameIndex($i), $newfilename.$i.'.'.$extension);
}
Chaning file names after extracting
File names will in the same pattern as above.
$directory = 'hello/'; //your extracted directory
$newfilename = 'myfile';
foreach (glob($directory."*.*") as $index=>$filename) {
$basename = pathinfo($filename)['basename'];
if(!preg_match('/myfile\d\./', $basename)) {
$extension = pathinfo($filename)['extension'];
rename($filename,$newfilename.$index.'.'.$extension);
}
}
What we are here scanning the all the files from the extracted directory for which doesn't have a filename in the patter myfile[num]. and then we are changing it's name.
UPDATE 2
I just noticed you have updated your question.
As you have just one file and you want to extract it every time with different name. You should rename it every time you extract.
$zip = new ZipArchive;
$newfilename = "myfile".rand(1,999); //you can define any safe pattern here that suites you
if($zip->open('help.zip')===TRUE)
{
$path = '/your/path/to/directory';
$filename = $zip->getNameIndex(0);
if($zip->extractTo($path))
{
echo "Extracted";
}else{
echo "Extraction Failed";
exit();
}
$extension = pathinfo($filename)['extension'];
rename($path."/$filename",$path."/$newfilename".'.'.$extension);
echo "Extracted with different name successfully!";
} else {
echo "Failed";
}

How do I unzip an archive file via ZipArchive

So far after looking of multiple examples of how to unzip a file i'm a little confused on what i'm missing for this to work now.
Im using WordPress and AdvancedCustomFields to designate what kind of file i'm going to be uploading. I need to unzip this file and figure out the internal files to use one as a source.
} else if(get_sub_field('media_type') == 'Zip'){
/* Get Path Name */
$file = get_sub_field('file');
$pieces = explode("/", $file);
$lastZip = end($pieces);
array_pop($pieces ); //removes last
$path = implode("/", $pieces);
$path = $path."/";
/* Get Name of File and concat .png */
$last = explode(".", $lastZip);
$last = $last[0].".png";
/* Append new filename to proper pathing */
$pathFile = $path.$last;
$zip = new ZipArchive;
$zip->open($lastZip, ZipArchive::CREATE);
print_r($zip);
if ($zip === TRUE) {
$zip->extractTo($path);
$zip->close();
echo 'File extracted to: $path';
} else {
echo "does not work!";
}
?><span><img src="<?php echo $pathFile; ?>" /></span>
<?php
}
My outcome of print_r($zip) is:
ZipArchive Object (
[status] => 0
[statusSys] => 0
[numFiles] => 0
[filename] => /var/www/vhosts/domain.com/httpdocs/example.zip
[comment] =>
)

PHP creating zip archive

I am creating a zip archive, but it doesn't work. There is no error logged into Error_log.txt. I am requesting a zip archive over ajax and response from ajax is empty, the $_SESSION['uid'] code looks like this.
$folder = md5($array->id);
$this->deleteIfExists($folder);
$zip = new ZipArchive();
$name = "users/".$folder."/".$_SESSION['uid'].".zip";
if($zip->open("users/".$folder."/".$_SESSION['uid'].".zip", ZIPARCHIVE::CREATE) != TRUE){
echo "Doesn't work :-(";
}
$zip->addFile("users/".$folder."/client_agree/original_".$array->id.".jpg", "agree.jpg");
/*
foreach(json_decode($array->imgs) as $key => $val){
$zip->addFile("users/".$folder."/client_agree/original_".$val.".jpg", $val.".jpg");
}
*/
$zip->close();
echo $_SESSION['uid'];

How to auto delete a zip file after using stream_get_contents(); to view a file in php?

I have this code to read a file for preview, but the downside is I have to download the file first from cloud and read from it, but it's a waste of space so I want to delete it after viewing a certain file. Is there an automatic way of doing this? Or do I have to integrate it to a close button?
// Get the container we want to use
$container = $conn->get_container('mailtemplate');
//$filename = 'template1.zip';
// upload file to Rackspace
$object = $container->get_object($filename);
//var_dump($object);
//echo '<pre>' . print_r($object,true) . '</pre>';
$localfile = $dir.$filename;
//echo $localfile;
$object->save_to_filename($localfile);
if($_GET['preview'] == "true")
{
$dir = "../mailtemplates/";
$file1 = $_GET['tfilename'];
$file = $dir.$file1;
$file2 = "index.html";
$info = pathinfo($file);
$file_name = basename($file,'.'.$info['extension']);
$path = $file_name.'/'.$file2;
$zip = new ZipArchive();
$zip->open($file);
$fp = $zip->getStream($path);
if(!$fp)
{
exit("faileds\n");
$zip->close();
unlink($dir.$filename);
}
else
{
$stuff = stream_get_contents($fp);
echo $stuff;
$zip->close();
if($stuff != null)
{
unlink($dir.$filename);
}
}
}
else
{
unlink($dir.$filename);
}
You didn't google this did ya?
Try Unlink
Edit:
Taking a look at this code, $zip->open($file); <-- is where you open the file. The file variable is set by:
"../mailtemplates/" . basename($_GET['tfilename'], '.' . $info['extension']) . '/' . "index.html"
So you're grabbing a relative directory and grabbing a filename as a folder, and going to that folder /index.html. Here's an example:
if you're in c:\ testing and you go to ../mailtemplates/ you'll be in c:\mailtemplates and then you're looking at file test.php but you're removing the file extension, so you'll be opening the location c:\mailtemplates\test\index.html so you open up that html file and read it. Then, you're trying to delete c:\mailtemplates\test.php
can you explain how any of that makes sense to you? 'cause that seems very odd to me.

Categories