Uploading files and folders in a course programatically in Moodle - php

I need to upload files and folders into a course in moodle from a zip file, I have been searching and I found how to upload files. I try to upload, and the files are uploaded correctly into the database and in the file repository, but this files are not showed in the course when I enter to the course.
The code below is what I trying
$packer = get_file_packer('application/zip');
$files = $packer->extract_to_pathname($archivo_zip, $carpeta_unzip );
foreach($files as $path => $status){
$fs = get_file_storage();
$context = context_course::instance($courseid);
$filename = basename($path);
$path_directory = "/" . str_replace($filename, "", $path);
$author = $DB->get_record('user', array('id'=>$userid ), '*', MUST_EXIST);
$file_record = new stdClass;
$file_record->component = 'mod_folder'; //mod_resource
$file_record->contextid = $context->id;
$file_record->userid = $userid ;
$file_record->filearea = 'content'; //draft, attachment
$file_record->filename = $filename;
$file_record->filepath = $path_directory;
$file_record->itemid = 0;
$file_record->author = fullname($author);
$file_record->license = $CFG->sitedefaultlicense;
$file_record->source = $filename;
//$file_record->timecreated = time();
//$file_record->timemodified = time();
$existingfile = $fs->file_exists($file_record->contextid, $file_record->component, $file_record->filearea,
$file_record->itemid, $file_record->filepath, $file_record->filename);
if ($existingfile) {
//throw new file_exception('filenameexist');
} else {
$stored_file = $fs->create_file_from_pathname($file_record, $path_upload);
}
}
I try to upload the files manually through the website and I've noticed that the folders ara created in another table called mdl_folder or in the table called mdl_file, but i don't know how do that and the best way to create and relate folders with files programatically for then displayed in the website well.
So if anyone knows how to do it or have any examples or documentation that may be useful, it would be helpful.
Thanks in advance.

I found a solution that works for me, I don't know if it is the most appropriate or not, if someone can take a look and tell me if it is correct or not, or what changes could make would be grateful.
The solution i found is:
Create or get it back the folder who will contain the files
Upload the files
Code:
$packer = get_file_packer('application/zip');
$files = $packer->extract_to_pathname($archivo_zip, $carpeta_unzip );
foreach($files as $path => $status){
$fs = get_file_storage();
$folder = get_folder($courseid, 'Upload Test');
$filename = basename($path);
$path_directory = "/" . str_replace($filename, "", $path);
$author = $DB->get_record('user', array('id'=>$userid ), '*', MUST_EXIST);
$file_record = new stdClass;
$file_record->component = 'mod_folder'; //mod_resource
$file_record->contextid = $folder->id;
$file_record->userid = $userid ;
$file_record->filearea = 'content'; //draft, attachment
$file_record->filename = $filename;
$file_record->filepath = $path_directory;
$file_record->itemid = 0;
$file_record->author = fullname($author);
$file_record->license = $CFG->sitedefaultlicense;
$file_record->source = $filename;
//$file_record->timecreated = time();
//$file_record->timemodified = time();
$existingfile = $fs->file_exists($file_record->contextid, $file_record->component, $file_record->filearea,
$file_record->itemid, $file_record->filepath, $file_record->filename);
if ($existingfile) {
//throw new file_exception('filenameexist');
} else {
$stored_file = $fs->create_file_from_pathname($file_record, $path_upload);
}
}
And the function to create or get it back the folder is:
function get_folder($courseid, $resource_name) {
global $DB, $CFG;
//Comprobamos si la carpeta ya existe ya existe
$sql = "SELECT cm.id as cmid FROM {course_modules} cm, {folder} res
WHERE res.name = '" . $resource_name . "'
AND cm.course = " . $courseid . "
AND cm.instance = res.id";
if (! $coursemodule = $DB->get_record_sql($sql)) {
require_once($CFG->dirroot.'/course/lib.php');
echo "\tCreate new folder\n";
$course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
// get module id
$module = $DB->get_record('modules', array('name' => 'folder'), '*', MUST_EXIST);
// get course section
/*course_create_sections_if_missing($course->id, 0);
$modinfo = get_fast_modinfo($course->id);
$cw = $modinfo->get_section_info(0);
echo "section id: " . $cw->id;*/
$sectionid = $DB->get_record('course_sections', array('course' => $course->id, 'name' => 'Recursos'), '*', MUST_EXIST);
$folder_data = new stdClass();
$folder_data->course = $course->id;
$folder_data->name = $resource_name;
$folder_data->intro = '<p>'.$resource_name.'</p>';
$folder_data->introformat = 1;
$folder_data->revision = 1;
$folder_data->timemodified = time();
$folder_data->display = 0;
$folder_data->showexpanded = 1;
$folder_data->showdownloadfolder = 1;
$folder_id = $DB->insert_record('folder', $folder_data);
echo "folder id: " . $folder_id;
// add course module
$cm = new stdClass();
$cm->course = $courseid;
$cm->module = $module->id; // should be retrieved from mdl_modules
$cm->instance = $folder_id; // from mdl_resource
$cm->section = $sectionid->id; // from mdl_course_sections
$cm->visible = 1;
$cm->visibleold = 1;
$cm->showavailability = 1;
$cm->added = time();
$cmid = $DB->insert_record('course_modules', $cm);
// add module to course section so it'll be visible
if ($DB->record_exists('course_sections', array('course' => $courseid, 'section' => 1))) {
$sectionid = $DB->get_record('course_sections', array('course' => $courseid, 'section' => 1));
// if sequence is not empty, add another course_module id
if (!empty($sectionid->sequence)) {
$sequence = $sectionid->sequence . ',' . $cmid;
} else {
// if sequence is empty, add course_module id
$sequence = $cmid;
}
$course_section = new stdClass();
$course_section->id = $sectionid->id;
$course_section->course = $courseid;
$course_section->section = 1;
$course_section->sequence = $sequence;
$csid = $DB->update_record('course_sections', $course_section);
} else {
$sequence = $cmid;
$course_section = new stdClass();
$course_section->course = $courseid;
$course_section->section = 1;
$course_section->sequence = $sequence;
$csid = $DB->insert_record('course_sections', $course_section);
}
rebuild_course_cache($courseid, true);
// get context again, this time with all resources present
$context = get_folder($courseid, $resource_name);
return $context;
} else {
$context = context_module::instance($coursemodule->cmid);
return $context;
}
} // get_folder

Related

Generate parent ID according to its first type of the group

I have a problem that I'm quite looking for a solution to. I want to generate a parent ID for its children. This list is coming from the CSV file.
CSV File
Database Data entries from an imported CSV file
The CSV file has no parent ID column. I wanted the user to minimize updating the CSV file instead the system will just generate it automatically during the importing process.
CONTROLLER:
public function update_atf_parent_id()
{
$financeDb = db_connect('finance');
$FinanceATFModel = new \App\Models\FinanceATFModel($financeDb);
$builder = $financeDb->table('atf');
$builder->where('type', 'Payout');
$query = $builder->get()->getResultObject();
foreach ($query as $row) {
$new_data = array('parent_id' => $row->id);
$builder->where('date', $row->date);
$builder->update($new_data);
}
}
public function atf_add()
{
/** HELPERS */
$financeDb = db_connect('finance');
/** HELPERS */
helper('form');
/** MODELS */
$FinanceATFModel = new \App\Models\FinanceATFModel($financeDb);
$FinanceATFFileModel = new \App\Models\FinanceATFFileModel($financeDb);
$UserModel = new \App\Models\UserModel();
$DataOptionModel = new \App\Models\DataOptionModel();
$FinanceDataOptionModel = new \App\Models\FinanceDataOptionModel($financeDb);
/** VARIABLES */
$subpage = $this->request->uri->getSegment(2);
$action = $this->request->uri->getSegment(3);
$uri_action = (strpos($this->request->uri->getSegment(2), 'add') !== false) ? 'add' : 'view';
$uri_action = (strpos($this->request->uri->getSegment(2), 'update') !== false) ? 'update' : $uri_action;
$current_page = ($uri_action == 'add') ? 'Add Finance Payouts' : 'View Finance Payouts';
$current_page = ($uri_action == 'update') ? 'Update Finance Payouts' : $current_page;
$airbnb_account = $this->request->getVar('airbnb_account');
$get_airbnb_account = $FinanceDataOptionModel->get_airbnb_account($airbnb_account);
$count_atf = $FinanceATFModel->where('airbnb_account', $get_airbnb_account)->countAllResults();
$atf_position_max =
$count_atf > 0
? $FinanceATFModel->where('airbnb_account', $get_airbnb_account)->selectMax('position')->get()->getRow()->position
: 0;
$data = array(
'title' => 'Add ATF - Finance',
'id' => '',
'subpage' => $subpage,
'uri_action' => $uri_action,
'page' => $this->request->uri->getSegment(1),
'current_page' => $current_page,
'disabled' => $uri_action === 'view' ? 'disabled' : '',
'action' => $action,
'getAirbnbAccounts' => $FinanceDataOptionModel->getAirbnbAccounts(),
);
// Validation
$input = $this->validate([
'atf_file' => 'uploaded[atf_file]|max_size[atf_file,4098]|ext_in[atf_file,csv]'
]);
if (!$input) { // Not valid
echo view('templates/header', $data);
echo view('templates/sidebar');
echo view('templates/navbar');
echo view('finance/atf/atf_add');
echo view('templates/footer');
} else {
// Valid
if ($file = $this->request->getFile('atf_file')) {
$dir = 'public/uploads/atf/';
$dir_exist = true; // flag for checking the directory exist or not
if (!is_dir($dir)) {
mkdir($dir, 0777, true);
$dir_exist = false; // dir not exist
}
if ($file->isValid() && !$file->hasMoved()) {
// Get random file name
$newName = $file->getRandomName();
// Store file in public/csvfile/ folder
$file->move($dir, $newName);
$file = fopen($dir . $newName, "r");
// insert imported csv file to 'atf_file' table
$fileData = array(
'file_name' => $newName,
'performed_by' => session()->get('id'),
'date_created' => date('Y-m-d h:i:s'),
);
$builder = $financeDb->table('atf_files');
$builder->insert($fileData);
$insertID = $financeDb->insertID();
$i = 0;
$numberOfFields = 15; // Total number of fields
$importData_arr = array();
// Initialize $importData_arr Array
while (($filedata = fgetcsv($file, 1000)) !== FALSE) {
// DATE
$ex_date = explode('/', $filedata[1]);
$d = isset($ex_date[0]) ? $ex_date[0] : '';
$m = isset($ex_date[1]) ? $ex_date[1] : '';
$y = isset($ex_date[2]) ? $ex_date[2] : '';
$date = $y . '-' . $m . '-' . $d;
// $date = $filedata[1];
// START DATE
$ex_date = explode('/', $filedata[4]);
$d = isset($ex_date[0]) ? $ex_date[0] : '';
$m = isset($ex_date[1]) ? $ex_date[1] : '';
$y = isset($ex_date[2]) ? $ex_date[2] : '';
$start_date = $y . '-' . $m . '-' . $d;
// $start_date = $filedata[4];
// OTHER VARIABLES
$position = $filedata[0];
$type = $filedata[2];
$confirmation_code = $filedata[3];
$nights = $filedata[5];
$guest_name = $filedata[6];
$listing = $filedata[7];
$details = $filedata[8];
$reference = $filedata[9];
$currency = $filedata[10];
$amount = $filedata[11];
$paid_out = str_replace(',', '', $filedata[12]);
$host_fee = $filedata[13];
$cleaning_fee = $filedata[14];
$created = date('Y-m-d H:i:s');
$updated = date('Y-m-d H:i:s');
$count_rows = count(file($dir . $newName, FILE_SKIP_EMPTY_LINES)) + $atf_position_max;
$parent_id = array_search('Payout', $importData_arr, 'position');
// Skip first row & check number of fields
$num = count($filedata);
if ($i > 0 && $num == $numberOfFields) {
// $position = $position + $count_rows - $i; // for position, starting from biggest to lowest number
$position = $count_rows - $i; // for position, starting from biggest to lowest number
// $_position = $count_rows; // for position, starting from biggest to lowest number
// $_position = $count_rows - $i; // for position, starting from biggest to lowest number
// $position = $filedata[0]; // for position, starting from biggest to lowest number
// Key names are the insert table field names - amount, description, ending_balance, status, link, notes, trusts_type, date_created
// $position = $position; // for position, starting from biggest to lowest number
// $importData_arr[$i]['parent_id'] = $parent_id;
$importData_arr[$i]['position'] = $position;
$importData_arr[$i]['date'] = $date;
$importData_arr[$i]['type'] = $type;
$importData_arr[$i]['confirmation_code'] = $confirmation_code;
$importData_arr[$i]['start_date'] = $start_date;
$importData_arr[$i]['nights'] = $nights;
$importData_arr[$i]['guest_name'] = $guest_name;
$importData_arr[$i]['listing'] = $listing;
$importData_arr[$i]['details'] = $details;
$importData_arr[$i]['reference'] = $reference;
$importData_arr[$i]['currency'] = $currency;
$importData_arr[$i]['amount'] = $amount;
$importData_arr[$i]['paid_out'] = $paid_out;
$importData_arr[$i]['host_fee'] = $host_fee;
$importData_arr[$i]['cleaning_fee'] = $cleaning_fee;
$importData_arr[$i]['airbnb_account'] = $airbnb_account;
$importData_arr[$i]['created'] = $created;
$importData_arr[$i]['updated'] = $updated;
}
$i++;
}
fclose($file);
// Process Insert / Update
$count = 0;
$importData_arr = array_reverse($importData_arr);
// ======================================================================================
$builder = $financeDb->table('atf');
foreach ($importData_arr as $atfdata) {
if ($FinanceATFModel->insert($atfdata)) {
$count++;
}
}
session()->setFlashdata('success', '<div class="alert alert-success w-100 shadow-lg border border-success"><i class="fa fa-check-circle"></i> Successfully imported.</div>');
$this->update_atf_position($get_airbnb_account);
/** LOGS */
helper('function_helpers');
logs('add', 'add finance atf::' . $airbnb_account, $financeDb->insertID());
} else {
// MESSAGE
session()->setFlashdata('success', '<div class="alert alert-danger w-100 shadow-lg border border-success"><i class="fa fa-check-circle"></i> File not imported.</div>');
}
} else {
// Set Session
// session()->setFlashdata('success', '<div class="alert alert-danger w-100 shadow-lg border border-success"><i class="fa fa-check-circle"></i> File not imported.</div>');
}
return redirect()->to(base_url("finance/atf/atf_entries?account=$airbnb_account"));
print_r('<pre>');
print_r($importData_arr);
print_r('</pre>');
}
}
In my current setup I imported the CSV file then the parent ID generation will be done after the file has been imported update_atf_parent_id() this controller is the one will generate the parent ID. I am referencing the date column as the group to be updated. But the downside is that once the other groups have the same date those groups will be considered as one group. That's why the parent ID will be the same. If you guys have some solution for this that would be a big help. Thanks in advance everyone!
P.S. I am using codeigniter framework version 4.

laravel saving images start with comma

I have implemented dropzone js on my laravel project but af facing one issue on saving the images on the database
,/uploads/products/27/607f0fc0942b0_1618939840_fc3cde370d846c4d14b0200a29e9206f.png,/uploads/products/27/607f0fc0945e8_1618939840_copy-space-with-opened-quran_23-2148214357.jpg,/uploads/products/27/607f0fc09474d_1618939840_1 (1).jpg
the issue is the images start with a comma which is wrong and it must be after the image for example
image1.png,image2.png
Here is my Controller
$product_images = json_decode($request->product_images[0],true);
$images = [];
$path = "";
$productsPath = 'uploads/products/';
$productPath = 'uploads/products/'.$request->product_id;
if(!file_exists($productsPath)){
mkdir($productsPath);
}
if (!file_exists($productPath)) {
mkdir($productPath, 0777,true);
}
foreach($product_images as $img){
$file = $img['name'];
// $extension = $img->guessExtension();
$filename = uniqid() .'_'. time() .'_'. $file;
$img = explode(',',$img['file'])[1];
$img = str_replace('', '+', $img);
$data = base64_decode($img);
$file = $productPath .'/'. $filename;
$success = file_put_contents($file, $data);
// dd($file);
$images[] = '/'. $file;
}
// Update Product Information On "products" table
$product = Product::where('id', $request->product_id)->first();
$product->created_by = auth()->user()->id;
$product->name = request('name_en');
$product->name_ar = request('name_ar');
$product->description = request('description_en'); // Must be moved to "product_information"
$product->description_ar = request('description_ar'); // Must be moved to "product_information"
$product->youtube = request('youtube'); // Must be moved to "product_information"
$product->youtube_ar = request('youtube_ar'); // Must be moved to "product_information"
$product->slug = slugify($request->name_en, 'Product', '', '');
// $product->image = request('name_en');
$product->brand_id = request('brand');
$product->status = request('status');
$data = explode(',' ,$product->image);
$data = array_merge($data,$images);
$remove_images = json_decode($request->removed_images, true);
$temp = [];
$i = 0;
foreach($data as $key => $imag){
$i = $i + 1;
if(!empty($remove_images) && in_array($imag, $remove_images)){
if (file_exists($productPath .'/'. $imag)) {
unlink($productPath .'/'. $imag);
}
}else{
if($i < 8)
$temp[] = $imag;
}
}
$product->image = implode($temp, ',');
// dd (explode(',' ,$product->image));
$product->save();
thank you
use implode like this
implode(',', $temp);

i am trying to make a quiz in moodle externally via webservice

I am trying to make a webservice in moodle that can be called externally. The webservice makes an entry in the database table mdl_quiz. But the quiz does not show up on the front-end.
Here is my code of the externallib file:
global $CFG, $DB;
$params = self::validate_parameters(
self::create_quiz_parameters(),
['quiz' => $quiz]
);
foreach ($params['quiz'] as $quiz) {
$courseid = $quiz['courseid'];
$quizname = $quiz['quizname'];
$intro = $quiz['intro'];
$attempts = $quiz['attempts'];
$timeopen = $quiz['timeopen'];
$timeclose = $quiz['timeclose'];
$quiz = new stdClass();
$quiz->course = $courseid;
$quiz->name = $quizname;
$quiz->timeopen = $timeopen;
$quiz->timeclose = $timeclose;
$quiz->attempts = $attempts;
$quiz->intro = $intro;
$rqa = $DB->insert_record('quiz', $quiz);
if (isset($rqa)) {
$moduleid = $DB->get_field('modules', 'id', ['name' => 'quiz'], MUST_EXIST);
$instanceid = 50;
$sectionid = 1;
$newcm = new stdClass();
$newcm->course = $courseid;
$newcm->module = $moduleid;
$newcm->section = $sectionid;
$newcm->added = time();
$newcm->instance = $instanceid;
$newcm->visible = 1;
$newcm->groupmode = 0;
$newcm->groupingid = 0;
$newcm->groupmembersonly = 0;
$newcm->showdescription = 0;
$cmid = $DB->insert_record('course_modules', $newcm);
}
}
You should use add_moduleinfo() instead of inserting records manually. This will do most of the work for you.
For an example see Create Moodle activities programmatically

Codeigniter - The same md5 name on every upload

I have this annoying problem:
Below you will see my messy upload script in which, whenever I upload a video file, I use a md5 function to name it so there are no video files with the same names in my database/folder.
The problem is that when I upload a given file multiple times to the database, it gets stored with the same md5 file name every time. I would really appreciate it if you could help me fix this little bug. I may be tired or something. I tried a hundred different solutions, and nothing fixed it.
Here is my mess:
<?php
class Upload_model extends CI_Model {
var $gallery_path;
var $videos_path;
var $thumbnail;
var $video_name;
var $upload_data;
var $file_name;
var $name;
var $videos_folder = "http://localhost/upload/videos/";
//////////////////////////////
function Upload_model() {
parent::__construct();
$this->videos_path = realpath(APPPATH . '..\videos');
// $this->returnFromDatabase();
}
function do_upload() {
$name = $_FILES['userfile']['name']; // get file name from form
$fileNameParts = explode(".", $name); // explode file name to two part
$fileExtension = end($fileNameParts); // give extension
$fileExtension = strtolower($fileExtension); // convert to lower case
$encripted_pic_name = md5($name) . "." . $fileExtension; // new file name
$config['file_name'] = $encripted_pic_name; //set file name
$config = array(
'allowed_types' => 'avi|mp4|flw|mov',
'upload_path' => $this->videos_path,
'file_name' => $encripted_pic_name
);
$this->load->library('upload', $config);
if ($this->upload->do_upload()) {
$this->upload_data = $this->upload->data(); //Returns array of containing all of the data related to the file you uploaded.
$this->file_name = $this->upload_data['file_name'];
$this->getThumbImage('C:\\xampp\\htdocs\\upload\\videos\\' . $encripted_pic_name);
$insert_data = array(
'name' => $encripted_pic_name,
'path' => 'C:\\xampp\\htdocs\\upload\\videos\\' . $encripted_pic_name,
'thumb_path' => 'C:\\xampp\\htdocs\\upload\\videos\\' . $encripted_pic_name . "_t.jpeg",
'uploaded_by' => 'admin'
);
$this->db->insert('videos', $insert_data); //load array to database
redirect('/welcome');
}
}
function getVideoInformation($videoPath) {
$movie = new ffmpeg_movie($videoPath, false);
$this->videoDuration = $movie->getDuration();
$this->frameCount = $movie->getFrameCount();
$this->frameRate = $movie->getFrameRate();
$this->videoTitle = $movie->getTitle();
$this->author = $movie->getAuthor();
$this->copyright = $movie->getCopyright();
$this->frameHeight = $movie->getFrameHeight();
$this->frameWidth = $movie->getFrameWidth();
$this->pixelFormat = $movie->getPixelFormat();
$this->bitRate = $movie->getVideoBitRate();
$this->videoCodec = $movie->getVideoCodec();
$this->audioCodec = $movie->getAudioCodec();
$this->hasAudio = $movie->hasAudio();
$this->audSampleRate = $movie->getAudioSampleRate();
$this->audBitRate = $movie->getAudioBitRate();
}
function getAudioInformation($videoPath) {
$movie = new ffmpeg_movie($videoPath, false);
$this->audioDuration = $movie->getDuration();
$this->frameCount = $movie->getFrameCount();
$this->frameRate = $movie->getFrameRate();
$this->audioTitle = $movie->getTitle();
$this->author = $movie->getAuthor();
$this->copyright = $movie->getCopyright();
$this->artist = $movie->getArtist();
$this->track = $movie->getTrackNumber();
$this->bitRate = $movie->getBitRate();
$this->audioChannels = $movie->getAudioChannels();
$this->audioCodec = $movie->getAudioCodec();
$this->audSampleRate = $movie->getAudioSampleRate();
$this->audBitRate = $movie->getAudioBitRate();
}
function getThumbImage($videoPath) {
$movie = new ffmpeg_movie($videoPath, false);
$this->videoDuration = $movie->getDuration();
$this->frameCount = $movie->getFrameCount();
$this->frameRate = $movie->getFrameRate();
$this->videoTitle = $movie->getTitle();
$this->author = $movie->getAuthor();
$this->copyright = $movie->getCopyright();
$this->frameHeight = $movie->getFrameHeight();
$this->frameWidth = $movie->getFrameWidth();
$capPos = ceil($this->frameCount / 4);
if ($this->frameWidth > 120) {
$cropWidth = ceil(($this->frameWidth - 120) / 2);
} else {
$cropWidth = 0;
}
if ($this->frameHeight > 90) {
$cropHeight = ceil(($this->frameHeight - 90) / 2);
} else {
$cropHeight = 0;
}
if ($cropWidth % 2 != 0) {
$cropWidth = $cropWidth - 1;
}
if ($cropHeight % 2 != 0) {
$cropHeight = $cropHeight - 1;
}
$frameObject = $movie->getFrame($capPos);
if ($frameObject) {
$imageName = $this->file_name . "_t.jpeg";
$tmbPath = "C:\\xampp\\htdocs\\upload\\videos\\" . $imageName;
$frameObject->resize(120, 90, 0, 0, 0, 0);
imagejpeg($frameObject->toGDImage(), $tmbPath);
} else {
$imageName = "";
}
return $imageName;
}
}
For what matters, CI's upload class has a property called encrypt_name. You can set it to true and have your filename encrypted by default without you doing something else. Take a look: http://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html
Also, since you are using CI, please use the Upload Class, don't write your own when the one provided from CI is so easy to use.
md5 will always return the same value when used on the same string, so uploading the file with the same name will end up with the same hash, add a random string to the file name
$encripted_pic_name = md5(microtime() . $name) . '.' . $fileExtension
You also need to be aware that clashes can happen with md5() where two different strings will have the same output. I wouldn't worry about this too much though for your needs.
You'll need to attach some random characters to the name before you md5 it (though even then it'll still have the chance of a duplicate name).
E.g:
$encripted_pic_name = md5($name . $randomStringHere) . "." . $fileExtension; // new file name
md5 will always give the same output for the same input, so if you upload the same file twice, then yes, you have already used that hash.
If you just want random names, then you don't even need to use MD5 and could just dynamically create a random string everytime a file is uploaded (a, b, c, etc to z, then aa, ab, ac, etc).
If the file name is same then it will return the same md5 hash
For this you have to encrypt unique name or number
You can use
$encripted_pic_name = md5(strtotime()) . "." . $fileExtension; // new file name
or
$encripted_pic_name = md5(uniqid()) . "." . $fileExtension; // new file name

IceCast Stats on website

I came across this php script to pull IceCast stats (listeners,current song) from my streaming server.
It was published here
Use PHP to show Icecast2 statistics
<?php
/*
* SCRIPT CONFIGURATIONS
*/
$SERVER = 'http://myserver.com:8000'; //URL TO YOUR ICECAST SERVER
$STATS_FILE = '/status.xsl'; //PATH TO STATUS.XSL PAGE YOU CAN SEE IN YOUR BROWSER (LEAVE BLANK UNLESS DIFFERENT)
///////////////////// END OF CONFIGURATION --- DO NOT EDIT BELOW THIS LINE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//create a new curl resource
$ch = curl_init();
//set url
curl_setopt($ch,CURLOPT_URL,$SERVER.$STATS_FILE);
//return as a string
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
//$output = our stauts.xsl file
$output = curl_exec($ch);
//close curl resource to free up system resources
curl_close($ch);
//build array to store our radio stats for later use
$radio_info = array();
$radio_info['server'] = $SERVER;
$radio_info['title'] = '';
$radio_info['description'] = '';
$radio_info['content_type'] = '';
$radio_info['mount_start'] = '';
$radio_info['bit_rate'] = '';
$radio_info['listeners'] = '';
$radio_info['most_listeners'] = '';
$radio_info['genre'] = '';
$radio_info['url'] = '';
$radio_info['now_playing'] = array();
$radio_info['now_playing']['artist'] = '';
$radio_info['now_playing']['track'] = '';
//loop through $ouput and sort into our different arrays
$temp_array = array();
$search_for = "<td\s[^>]*class=\"streamdata\">(.*)<\/td>";
$search_td = array('<td class="streamdata">','</td>');
if(preg_match_all("/$search_for/siU",$output,$matches)) {
foreach($matches[0] as $match) {
$to_push = str_replace($search_td,'',$match);
$to_push = trim($to_push);
array_push($temp_array,$to_push);
}
}
//sort our temp array into our ral array
$radio_info['title'] = $temp_array[0];
$radio_info['description'] = $temp_array[1];
$radio_info['content_type'] = $temp_array[2];
$radio_info['mount_start'] = $temp_array[3];
$radio_info['bit_rate'] = $temp_array[4];
$radio_info['listeners'] = $temp_array[5];
$radio_info['most_listeners'] = $temp_array[6];
$radio_info['genre'] = $temp_array[7];
$radio_info['url'] = $temp_array[8];
$x = explode(" - ",$temp_array[9]);
$radio_info['now_playing']['artist'] = $x[0];
$radio_info['now_playing']['track'] = $x[1];
?>
Dose someone know where to insert the script?
Everything you need will be found in $radio_info. You can easily output this wherever you want:
echo htmlspecialchars($radio_info['now_playing']['artist'] . ' - ' . $radio_info['now_playing']['track']);
We download the stats in xml then process the stats daily buy importing to sql
// download icecast stats
$username = '';
$password = '';
$url = 'localhost:8000/stats';
$file = 'h:\\stream\\stats\\' . date('Ymd_His') . '.xml';
c:\\stream\\curl.exe --user $username:$password $url -o $file;
//Process to sql by looping through the stats folder and get filenames...
foreach(glob($path . "*.xml") as $filename) {
$content = file_get_contents($filename);
$filename = substr($filename, strlen($path), -4);
process($db, $filename, $content);
}
function process($db, $filename, $content) {
$xml = new SimpleXMLElement($content);
if(!preg_match('/^(\d{4})(\d{2})(\d{2})_(\d{2})(\d{2})(\d{2})$/', $filename,
$date)) throw new Exception('Filename does not look like a date.');
foreach($xml->source as $source) {
$date_sql = $db->real_escape_string(sprintf("%04d-%02d-%02d %02d:%02d:%02d",
$date[1], $date[2], $date[3], $date[4], $date[5], $date[6]));
$stream_sql = $db->real_escape_string($source->genre);
$title_sql = $db->real_escape_string($source->title);
$listeners_sql = (int)$source->listeners;
$sql = "REPLACE INTO song_stats SET date_and_time = '$date_sql', stream =
'$stream_sql', title = '$title_sql', listeners = $listeners_sql";
$db->query($sql);
}
}

Categories