How do i store pictures in moodle? - moodle

I'm trying to create my own Activity in moodle where students can take pictures of their Drivers License and that pictures get stored in moodle, then later opended and shown to the teacher.
My Problem is to store the picture on the moodle side and not downloading it.(like i'm doing right now)
Hopfully someone can help me figure out a way to use the file_storage given by moodle to safe the pictures.
kind regards
J
This is my code for now (view.php) ... I know its not realy in a moodle way but im trying to get it to work first then then clean up the code
require_once('../../config.php');
require_once($CFG->dirroot . '/mod/driverslicense/lib.php');
require_once($CFG->dirroot . '/mod/assign/locallib.php');
require_once($CFG->dirroot . '/mod/driverslicense/classes/submit/submit.php');
require_once("$CFG->libdir/formslib.php");
$id = required_param('id', PARAM_INT);
list ($course, $cm) = get_course_and_cm_from_cmid($id, 'driverslicense');
require_login($course, true, $cm);
$context = context_module::instance($cm->id);
require_capability('mod/driverslicense:view', $context);
$driverslicense = new assign($context, $cm, $course);
$urlparams = array('id' => $id,
'action' => optional_param('action', '', PARAM_ALPHA),
'rownum' => optional_param('rownum', 0, PARAM_INT),
'useridlistid' => optional_param('useridlistid', $driverslicense->get_useridlist_key_id(), PARAM_ALPHANUM));
$url = new moodle_url('/mod/driverslicense/view.php', $urlparams);
$PAGE->set_url($url);
// Update module completion status.
$driverslicense->set_module_viewed();
// Apply overrides.
$driverslicense->update_effective_access($USER->id);
// Get the driverslicense class to
// render the page.
//echo $driverslicense->view(optional_param('action', '', PARAM_ALPHA));
$mform = new submit();
echo $OUTPUT->header();
echo '<body>
<div id="container">
<video autoplay="true" id="video"></video>
<button id="btn"> Take Picture </button>
<canvas id="canvas" class="hidden"></canvas>
<a id="dl-btn" href="frontpic" download="image.png" class="hidden"></a>
</div>
</body>';
$fs = get_file_storage();
// Prepare file record object
$fileinfo = array(
'contextid' => $context->id, // ID of context
'component' => 'mod_driverslicense', // usually = table name
'filearea' => 'driverslicense', // usually = table name
'itemid' => 0, // usually = ID of row in table
'filepath' => '/', // any path beginning and ending in /
'filename' => 'driverslicensefront.png'); // any filename
$fs->create_file_from_url($fileinfo, imgURL );
echo $OUTPUT->footer();
?>
<script type="text/javascript">
const video = document.querySelector('#video')
const btn = document.querySelector('#btn')
const canvas = document.querySelector('#canvas')
if ('mediaDevices' in navigator && 'getUserMedia' in navigator.mediaDevices) {
navigator.mediaDevices.getUserMedia({video: true})
.then(stream => {
video.srcObject = stream
})
.catch(error => {
console.log('An error occured while accessing webcam.')
})
}
btn.addEventListener('click', () =>{
const width = video.videoWidth, height = video.videoHeight
const context = canvas.getContext('2d')
canvas.width = width
canvas.height = height
context.drawImage(video, 0, 0, width, height)
const imgURL = canvas.toDataURL('image/png')
document.querySelector('#dl-btn').href = imgURL
document.querySelector('#dl-btn').click()
})
</script>

Related

Rest API : #1062 - duplicate entry for key 'primary'

I want upload some image to server with rest API using Codeigniter.
But I have a problem after upload image / refresh phpmyadmin on this table.
I know this problem is classic, what I'm already todo:
Re-Create the table 2 times.
Make ID to Autoincrement (actually I'm make it AI at first make table)
Not include ID on insert operation, and make it AI automatic.
I'm already truncate the table 2 times
but nothing change anything, at I'm refresh page phpmyadmin this error always appear.
What's my mistake ?
Thanks
If you think my error because my code Rest-API, here's my code:
Controller:
public function upload_post()
{
// $config['max_size'] = '100';
// $config['max_width'] = '1024';
// $config['max_height'] = '768';
$msgCreated = ['status' => true, 'message' => 'Image Has Been Upload'];
$msgFailCreated = ['status' => false, 'message' => 'Failed to Upload Image !'];
$config['upload_path'] = './image/';
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('file')) {
$this->set_response($msgFailCreated, 404);
} else {
$info = $this->upload->data();
$image_path = base_url("image/" . $info['raw_name'] . $info['file_ext']);
$data = [
"name_image" => $this->input->post('name_image'),
"image" => $image_path
];
if ($this->mahasiswa->insertImage($data)) {
$this->set_response($msgCreated, 201);
} else {
$this->set_response($msgFailCreated, 400);
}
}
}
Model:
//? Membuat Upload Image
public function insertImage($data){
return $this->db->insert('image', $data);
}

Yii2 Menu widget disable parent item link

How can I disable only the parent item link and leave its children clickable ? For example - when I click on my parent it should open the submenu and not redirect to somewhere else. And if I click on children it should redirect me.
P.S I red the documentation, searched around google but nothing comes out.
This is my code:
<?php
use backend\models\PageAdmin;
use backend\helpers\BackendPrefix;
use yii\widgets\Menu;
$menu_pages = PageAdmin::find()->where('active=1 AND id_in IS NULL')->all();
$widget_menu_content = [];
foreach ($menu_pages as $key => $page){
$related_pages = PageAdmin::find()->where(['active' => 1, 'id_in' => $page->id])->all();
$widget_menu_content[$key]['label'] = "<i class='{$page->icon}'></i>";
$widget_menu_content[$key]['icon'] = $page->icon;
$widget_menu_content[$key]['url'] = BackendPrefix::PREFIX .'/'. $page->url;
if(!empty($related_pages)){
foreach ($related_pages as $key2 => $rel_page) {
$widget_menu_content[$key]['items'][$key2]['label'] = $rel_page->title;
$widget_menu_content[$key]['items'][$key2]['icon'] = "caret-right";
$widget_menu_content[$key]['items'][$key2]['url'] = BackendPrefix::PREFIX . "/" . $rel_page->url;
}
}
}
?>
<div class="side-mini-panel">
<?=
Menu::widget([
'encodeLabels' => false,
'options' => [
'class' => 'mini-nav',
],
'activeCssClass' => 'selected',
'items' => $widget_menu_content,
'submenuTemplate' => "
\n<div class='sidebarmenu'>
\n<h3 class='menu-title'>{label}</h3>
\n<div class='searchable-menu'>
\n<form role='search' class='menu-search'>
\n<input type='text' placeholder='Search...' class='form-control' />
\n<a href='javascript:void(0)'><i class='fa fa-search'></i></a>
\n</form>
\n<div>
\n<ul class='sidebar-menu'>
\n{items}
\n</ul>
\n</div>",
'linkTemplate' => "<a href='javascript:void(0)'>{label}</a>",
'activateParents' => true,
])
?>
</div
Whit my 'linkTemplate' I am disabling all the links which obviously is not my goal :) ( It should disable the parents only ). Alsom, with what token ( or some other option, because I think items is the only token for the children ) I should append the child item label on this line : \n<h3 class='menu-title'>{label}</h3>. In my case what I get echoed is just {label} like a string.
Many thanks!

Setting starting value for Google Line Chart dynamically and redrawing chart

I am using the code below to generate a line chart for a projected financial balance. Data is generated from information in a MySQL database. What I would like to be able to do is to have a form with an input field on the page that allows the user to set the starting balance dynamically once the page is loaded, such that the chart is redrawn with the correct starting balance, but I can't work out how to do this:
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'Date', 'type' => 'string'),
array('label' => 'Amount', 'type' => 'number')
);
[code to generate data goes here - i.e. calculating a balance for each date in the chart]
$balance = $balance - $monthly - $weekly + $session_total;
$temp = array();
$temp[] = array('v' => (string) $date_display);
$temp[] = array('v' => (string) $balance);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
//echo $jsonTable;
?>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var formatter = new google.visualization.NumberFormat({fractionDigits:2,prefix:'\u00A3'});
formatter.format(data, 1);
var options = {
pointSize: 5,
legend: 'none',
hAxis: { showTextEvery:31 },
series: {0:{color:'2E838F',lineWidth:2}},
chartArea: {left:50,width:"95%",height:"80%"},
backgroundColor: '#F7FBFC',
height: 400
};
// Instantiate and draw our chart, passing in some options.
//do not forget to check ur div ID
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<div id="chart_div"></div>
Hopefully there's a fairly simple way to refresh the chart when new data is available. It requires a small change to your PHP and a few JavaScript tweaks.
The nice thing about using Google Charts is that you can just re-draw them by calling drawChart() again, you just need to be able to modify the data before you do it.
The change I would make the PHP would be to store the original value, so that when you want to change the value according to the user's input you can always have something to refer back to:
// display the date
$temp[] = array('v' => (string) $date_display);
// the data used by the chart
$temp[] = array('v' => (string) $balance);
// the original value
$temp[] = array('v' => (string) $balance);
I would also make the table data global rather than drawing it directly into the function, this way you can change it and refresh the chart quite easily.
var table = <?php echo $jsonTable; ?>;
function drawChart() {
var data = new google.visualization.DataTable(table);
......
}
I tested this with a basic form that looks like this:
<form method="post" action="#" onsubmit="return false;">
<input type="text" id="balance1" />
<input type="text" id="balance2" />
<button onclick="return refreshChart()">Go</button>
</form>
Clicking on the button cancels the default action and calls a function called refreshChart(). This function takes the value and adds it to the original values on the fly before re-drawing the chart:
function refreshChart() {
var balance1 = document.getElementById('balance1').value;
var balance2 = document.getElementById('balance2').value;
if(!balance1) {
balance1 = 0;
}
if(!balance2) {
balance2 = 0;
}
for(var i = 0, length = table.rows.length; i < length; i++) {
table.rows[i].c['1'].v = parseFloat(table.rows[i].c['2'].v) + parseFloat(balance1) + parseFloat(balance2);
}
drawChart();
return false;
}
It takes the balance entered and adds it to the original value stored in table.rows[i].c['2'].v and overwrites the value in table.rows[i].c['1'].v which is used by the chart. It then calls the original drawChart() function but the new data is used.
I played around with some default data and this is the output I tested it with on JSFiddle.

Zend-Image Uploading at Wrong Destination

please help..I'm newbies and try to learn Zend Framework, but have problem when uploading image.
The script at file Application.ini
uploads.uploadPath = APPLICATION_PATH "/../public/uploads"
Form to upload Image:
$this->setAction('/data/personil/create')
->setMethod('post');
//Item input untuk gambar
$images = new Zend_Form_Element_File('images');
$images->setMultiFile(3)
->addValidator('IsImage')
->addValidator('Size', false, '204800')
->addValidator('Extension', false, 'jpg,png,gif')
->addValidator('ImageSize', false, array(
'minwidth' => 150,
'minheight' => 150,
'maxwidth' => 700,
'maxheight' => 700
))
->setValueDisabled(true);
// attach element to form
$this->addElement($images);
// create display group for file elements
$this->addDisplayGroup(array('images'), 'files');
$this->getDisplayGroup('files')
->setOrder(40)
->setLegend('Images');
Controller action create :
public function createAction()
{
$form = new Pengadilan_Form_PersonilCreate();
$this->view->form = $form;
$flashMessenger = $this->_helper->FlashMessenger;
//SImpan kedatabase
if($this->getRequest()->isPost()){
if($form->isValid($this->getRequest()->getPost())){
$personil = new Pengadilan_Model_Personil();
$personil->fromArray($form->getValues());
$personil->RecordDate = date('Y-m-d', mktime());
$personil->DisplayStatus = 0;
$personil->DisplayUntil = null;
$personil->save();
$id = $personil->RecordId;
$config = $this->getInvokeArg('bootstrap')->getOption('uploads');
$form->images->setDestination($config['uploadPath']);
$adapter = $form->images->getTransferAdapter();
for($x=0; $x<$form->images->getMultiFile(); $x++) {
$xt = #pathinfo($adapter->getFileName('images_'.$x.'_'), PATHINFO_EXTENSION);
$adapter->clearFilters();
$adapter->addFilter('Rename', array(
'target' => sprintf('%d_%d.%s', $id, ($x+1), $xt),
'overwrite' => true
));
$adapter->receive('images_'.$x.'_');
}
$this->_helper->getHelper('FlashMessenger')->addMessage('Data sekses diinput ke database #' . $id . '. Admin akan segera merivew, jika diterima, akan ditampilkan dalam waktu 48 jam, Terima kasih.');
$this->_redirect('/data/personil/sukses');
}
}
}
Controller action display :
public function displayAction()
{
//Pertama setting filters
$filters = array(
'id' => array('HtmlEntities', 'StripTags', 'StringTrim')
);
$validators = array(
'id' => array('NotEmpty', 'Int')
);
$input = new Zend_Filter_Input($filters, $validators);
$input->setData($this->getRequest()->getParams());
if($input->isValid()){
$q = Doctrine_Query::create()
->from('Pengadilan_Model_Personil p')
->leftJoin('p.Pengadilan_Model_Jabatan j')
->leftJoin('p.Pengadilan_Model_Tupoksi t')
->leftJoin('p.Pengadilan_Model_Golongan g')
->leftJoin('p.Pengadilan_Model_Agama a')
->leftJoin('p.Pengadilan_Model_Kelamin k')
->where('p.RecordId = ?', $input->id)
->addWhere('p.DisplayStatus = 1')
->addWhere('p.DisplayUntil >= CURDATE()');
$result = $q->fetchArray();
if(count($result) == 1){
$this->view->personil = $result[0];
$this->view->images = array();
$config = $this->getInvokeArg('bootstrap')->getOption('uploads');
foreach (glob("{$config['uploadPath']}/{$this->view->item['RecordID']}_*") as $file) {
$this->view->images[] = basename($file);
}
}else{
throw new Zend_Exception('Maaf, halaman tidak ditemukan, 404');
}
}else{
throw new Zend_Exception('Kesalahan Input');
}
}
The last script at view : display.phtml
<div id="images">
<?php foreach ($this->images as $image): ?>
<img src="/uploads/<?php echo $this->escape($image); ?>" width="150" height="150" />
<?php endforeach; ?>
Image upload Destination at config is /public/uploads
in my case image at /public
Image succes to upload and renamed but outside the directory and
Image won't displayed at display.phtml
Many thanks for your help..
First you need to set your form encoding File element link$form->setAttrib('enctype', 'multipart/form-data');
Also you should probably finish setting up your image element before you POST the form not after. So move the setDestination stuff up to where you initialize the form, you may have a better chance of it working.
public function createAction()
{
$form = new Pengadilan_Form_PersonilCreate();
//set form encoding
$form->setAttrib('enctype', 'multipart/form-data');
//get path and set destination for image element
$config = $this->getInvokeArg('bootstrap')->getOption('uploads');
$form->images->setDestination($config['uploadPath']);
$this->view->form = $form;
//consider intializing flash messenger in the init() method
$flashMessenger = $this->_helper->FlashMessenger;
//SImpan kedatabase
if($this->getRequest()->isPost()){
if($form->isValid($this->getRequest()->getPost())){
//more code...
$adapter = $form->images->getTransferAdapter();
for($x=0; $x<$form->images->getMultiFile(); $x++) {
$xt = #pathinfo($adapter->getFileName('images_'.$x.'_'), PATHINFO_EXTENSION);
$adapter->clearFilters();
$adapter->addFilter('Rename', array(
'target' => sprintf('%d_%d.%s', $id, ($x+1), $xt),
'overwrite' => true
));
$adapter->receive('images_'.$x.'_');
}
$this->_helper->getHelper('FlashMessenger')->addMessage('Data sekses diinput ke database #' . $id . '. Admin akan segera merivew, jika diterima, akan ditampilkan dalam waktu 48 jam, Terima kasih.');
$this->_redirect('/data/personil/sukses');
}
}
}
not sure if this will fix everything but it should be a start...

PHP Zend doesn't display correctly

I am trying to recreate the following blog's tabbed forms for my website.
http://zendguru.wordpress.com/2009/01/15/zend-framework-and-dojo-creating-tabbed-form/
I currently have the form displaying on my page, however instead of tabs it displays the whole form like normal. I know that the form is displaying the subforms as I have commented them out and they disappear. Can someone help me find the path to enlightenment? I believe everything relevant is below. I have included the dojo Base 1.4.0 located
http://www.dojotoolkit.org/downloads
I have a link to the html being created here if that helps as well.
http://shortText.com/tljfsq6l37
I have the following AdminController.php page.
class AdminController extends Zend_Controller_Action
{
public function init()
{
/* Initialize action controller here */
}
public function createeventAction()
{
$this->view->page = 'createEvent';
$this->view->title = "Early Signup Administration";
$this->view->headTitle($this->view->title, 'PREPEND');
$createEventForm = new Form_CreateEvent();
$this->view->form = $createEventForm;
}
}
?>
An CreateEvent.php Form
<?php
class Form_CreateEvent extends Form_Event
{
public function __construct($options = null)
{
parent::__construct($options = null);
$shirt_sizes = array('s' => 'Small', 'm' => 'medium', 'l' => 'large', 'xl' => 'X-Large', 'XX' => 'XX-Large', '3X' => 'XXX-Large');
$this->setDecorators(array(
'FormElements',
array('TabContainer', array(
'id' => 'tabContainer',
'style' => 'width: 600px; height: 500px;',
'dijitParams' => array(
'tabPosition' => 'top'
),
)),
'DijitForm',
));
$this->setName('createEvent');
$idEvent = new Zend_Form_Element_Hidden('idEvent');
$type = parent::setName($this->type);
$name = parent::setName($this->name);
$city = parent::setName($this->city);
$state = parent::setName($this->state);
$location = parent::setName($this->location);
$date = parent::setName($this->date);
$shirtRequired = parent::setName($this->shirtRequired);
$eventImage = parent::setName($this->eventImage);
$eventUrl = parent::setName($this->eventUrl);
//$submit = parent::setName($this->submit);
$shirtSize = new Zend_Form_Element_MultiCheckbox ('shirtSize');
$shirtSize->setLabel('Shirt Size')
->setRequired(false)
->addMultiOptions($shirt_sizes)
->setValue(array('s','m','l','xl'))
->addFilter('StripTags')
->addFilter('StringTrim');
$directorEmail = new Zend_Form_Element_Text('email');
$directorEmail->setLabel('Director\'s Email')
->setRequired(false)
->addFilter('StripTags')
->addFilter('StringTrim');
$waiverTitle = new Zend_Form_Element_Text('waiverTitle');
$waiverTitle->setLabel('Waiver Title')
->setRequired(false)
->addFilter('StripTags')
->addFilter('StringTrim');
$waiverText = new Zend_Form_Element_Text('waiverText');
$waiverText->setLabel('Waiver Text')
->setRequired(false)
->addFilter('StripTags')
->addFilter('StringTrim');
$eventClosedMessage = new Zend_Form_Element_Text('eventClosedMessage');
$eventClosedMessage->setLabel('Event Closed Message')
->setRequired(false)
->addFilter('StripTags')
->addFilter('StringTrim');
$logoFlag = new Zend_Form_Element_Radio('logoFlag');
$logoFlag->setLabel('Select Logo Image')
->setRequired(false)
->addMultiOptions(array(
'logo' => 'Logo',
'not_logo' => 'Not Logo'))
->addFilter('StripTags');
/* $this->addElements(array($shirtSize,
$directorEmail,
$waiverTitle,
$waiverText,
$eventClosedMessage,
$logoFlag
)); */
$subForm1 = new Zend_Dojo_Form_SubForm();
$subForm1->setAttribs(array(
'name' => 'textboxtab',
'legend' => 'Text Elements',
'dijitParams' => array(
'title' => 'Text Elements',
),
));
$subForm1->addElements(array($shirtSize,
$directorEmail,
$waiverTitle));
$subForm2 = new Zend_Dojo_Form_SubForm();
$subForm2->setAttribs(array(
'name' => 'toggletab',
'legend' => 'Toggle Elements',
));
$subForm2->addElements(array(
$waiverText,
$eventClosedMessage,
$logoFlag
));
$this->addSubForm($subForm1, 'textboxtab')
->addSubForm($subForm2, 'editortab');
}
}
?>
The following in the header.phtml that is included on that page.
<SCRIPT TYPE="text/javascript" SRC="/dojo/dojo.js"></SCRIPT>
<script type="text/javascript">
dojo.require("dojo.parser");
</script>
and the following on the createEvent.phtml page I am trying to view
<?php echo $this->form ;?>
Difficult to tell exactly what the problem might be without your CSS etc. - but you do seem to have some pretty serious issues in your HTML source, so would try to get them fixed before anything else.
For example, you have a duplicate <html> element inside the <div id="head"> element (including duplicated <head> and <body> elements), and that is bound to lead to somewhat unpredictable behaviour.
Have to say I'm not quite sure how you would have got that kind of output. Are you using layouts? It sort of looks like you may have created the inner <html> element in your view script, and then it's been wrapped in a second one by the layout script. Maybe just check you're definitely only creating the html, head, body elements in one place and see where that gets you to start with...