Sunday 7 December 2014

Moodle: custom CSS in Essential theme

When you want to custom a moodle instance, you could need to modify Essential theme, for example, I don't want to see headers in SCORM content. The best option is use customcss property.

We go to admin/settings.php?section=theme_essential_generic in our site and we search for customcss textarea. To avoid seeing headers in SCORM, we add:

#page-mod-scorm-player div[role=main] h2 {display: none;}
#page-mod-scorm-player header[role=banner] {display: none;}


Best regards!

Tuesday 2 December 2014

Install MAMP + Laravel 4

Hello,

Today I installed in Mac OS X (10.7.5) server MAMP (3.0.4) + Laravel 4. I did these steps:
  • First, I downloaded and installed MAMP from http://www.mamp.info. I modified default conf changin ports to 80 and 3306.
  • Next, I modified file bash_profile (vim ~/.bash_profile): export PATH=/Applications/MAMP/bin/php/php5.5.10/bin:$PATH alias composer="php /usr/bin/composer.phar" alias laravel="~/.composer/vendor/bin/laravel"
  • Then, I reset terminal and downloaded composer: curl -sS getcomposer.org/installer | php.
  • Next step, move composer.phar: sudo mv composer.phar /usr/bin/
  • I donwloaded Laravel 4 installer: composer global require "laravel/installer=~1.1"
  • I went to /Applications/MAMP/htdocs and I created a new Laravel project: laravel new ibancardonasubiela.tk
  • Then, I created a new virtual host in my MAMP. To do that, I edited file Applications/MAMP/conf/apache/httpd.conf and I uncommented "Include /Applications/MAMP/conf/apache/extra/httpd-vhosts.conf". Then I edited file Applications/MAMP/conf/apache/extra/httpd-vhosts.conf and I added: <VirtualHost *:80>                     DocumentRoot /Applications/MAMP/htdocs/ibancardonasubiela.tk/public                                   ServerName wwww.ibancardonasubiela.local </VirtualHost>
  • I restarted MAMP service.
  • I edited file  /etc/hosts (sudo vim /etc/hosts) adding: 127.0.0.1 www.ibancardonasubiela.local
  • And, finally, Laravel installed in http://www.ibancardonasubiela.local/

Moodle: Delete one file in moodle filesystem

Hola,

After seeing how to add files and how to list them. Today we will see how to delete them:

$fs = get_file_storage();

// Prepare file record object
$fileinfo = array(
'component' => 'backup',
'filearea' => 'course',
'itemid' => 0,
'contextid' => 0,
'filepath' => '/',
'filename' => 'filename.xlsx'
); 


// Get file
$file = $fs->get_file($fileinfo['contextid'], $fileinfo['component'], $fileinfo['filearea'], $fileinfo['itemid'], $fileinfo['filepath'],
$fileinfo['filename']);

// Delete it if it exists
if ($file) {
if ($file->delete()) {
return true;
} else {
return false;
}
}


Best regards!

Monday 1 December 2014

Moodle: list files in moodle filesystem

Hello,

Last day we saw how to create an excel file in modle: http://icsbcn.blogspot.com/2014/11/moodle-create-and-save-excel-file-in.html

If we want to list that files, we can do this:

// List excel files
$table = new html_table();
$table->head = array('filename', 'filedate', 'filesize', '');
$table->align = array('left', 'left', 'left','left');


// Get files
$fs = get_file_storage();
$files = $fs->get_area_files(0,  'backup', 'course', 0, 'timemodified DESC', false);
foreach ($files as $file) {
$filename = $file->get_filename();


$row = array();
$row[] = $filename; // filename
$row[] = date('d/m/Y H:i:s', $file->get_timecreated()); // creation date
$row[] = $this->formatSizeUnits($file->get_filesize()); // file size as human view


// Download link
$url = moodle_url::make_pluginfile_url($file->get_contextid(), $file->get_component(), $file->get_filearea(), $file->get_itemid(), $file->get_filepath(), $filename);
$row[] = html_writer::link($url, get_string('downloadfile', 'moodle'));


$table->data[] = $row;
}
// End get files


$content .= html_writer::start_tag('div', array('id' => 'list_files'));
$content .= html_writer::table($table);
$content .= html_writer::end_tag('div');
// End list excel files

Best regards!

Sunday 30 November 2014

Moodle: Create and save an excel file in moodle filesystem

Hello,

Moodle filesystem is powerful but it's hard to understand too. In this code we will see how to create an excel file and save it in the moodle filesystem:

Documentation:
https://docs.moodle.org/dev/File_API_internals
https://docs.moodle.org/dev/File_API

// Create excel file
require_once("$CFG->libdir/phpexcel/PHPExcel.php");
$filenameTmp = tempnam(sys_get_temp_dir(), time());

$objPHPExcel = new PHPExcel();

// Excel metadata $objPHPExcel->getProperties()->setCreator("www.ibancardonasubiela.tk") ->setLastModifiedBy("www.ibancardonasubiela.tk") ->setTitle("www.ibancardonasubiela.tk") ->setSubject("www.ibancardonasubiela.tk") ->setDescription("www.ibancardonasubiela.tk")

// Crear the first sheet

$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setTitle("www.ibancardonasubiela.tk");


// Header
$arrayHeader = array('aaa', 'bbb');
$countHeader = count($arrayHeader);
foreach ($arrayHeader as $pos => $value) {
$excelLetter = PHPExcel_Cell::stringFromColumnIndex($pos);
$objPHPExcel->getActiveSheet()->getStyle($excelLetter.'1')->getFont()->setSize(14);
$objPHPExcel->getActiveSheet()->getStyle($excelLetter.'1')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->setCellValue($excelLetter.'1', $value);
$objPHPExcel->getActiveSheet()->getColumnDimension($excelLetter)->setAutoSize(true);
}

// Add content

// Save excel in a temporal file
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter->save($filenameTmp);

// Copy excel to moodle filesystem
$fs = get_file_storage();
$file_record = array(
'contextid' => 0,
'component' => 'backup', // "mod_forum", "course", "mod_assignment", "backup"...
'filearea' => 'course', // "submissions", "intro" and "content" , "blogs","userfiles"...
'itemid' => 0,
'filepath' => '/',
'timecreated' => time(),
'timemodified' => time(),
'filename' => 'excel'.'_'.time().'.xlsx'
);
$fs->create_file_from_pathname($file_record, $filenameTmp);

// Delete temp file
unlink($filenameTmp);


Best regards!

Monday 17 November 2014

Datatables in a bootstrap 3 modal window

Datatables is an important javascript plugin for jQuery to improve behaviour of our website tables.

Recently I saw that using tables (datatables tables) in a bootstrap modal window, after init the table, part of table was shown outside of the window.

I'm using version 1.9.3 of datatables, version 1.10.2 of jQuery and versio 3.0.1 of bootstrap.

My solution was use "fnDrawCallback" function in order to change the window's size after "drawing" the table:

tableObject = $('#idTable').dataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "ajaxSource",
"fnDrawCallback": function( oSettings ) {
$('#idTable').find('.modal-dialog').css(
{
width:'auto',
height:'auto',
'max-height':'100%'
});
},
'aaSorting': [[ 0, "asc" ]]
});


Kind regards!

Sunday 9 November 2014

Moodle: get top category from course data

Hello!

If we have course data and we want to get top category from that, we can do this:

$category = $DB->get_record('course_categories', array('id' => $courseObj->category));
$arrCats = explode("/", ($category->path));
$topCategory = $DB->get_record('course_categories', array('id' => intval($arrCats[1])));


Best regards!

Sunday 26 October 2014

Moodle: purge all caches by console

Hello,

If we have a moodle installed, a very interesting method to delete all caches is to use system console. To do that, we have to go to our moodle route and execute:

php admin/cli/purge_caches.php

Best regards!

Saturday 18 October 2014

Backup with rsync

Hello,

Today I set up a bash script in order to create backups with rsync. I created it in a OS 10.7.x (Lion) environment. Steps I did are:
Best regards!

Wednesday 10 September 2014

PHP: Clean uploaded filenames

Hello,

When a file is uploaded to a server, you could have filenames with characters that can cause problems. To clear the filename you can use:

$filename = time().'_'.$_FILES["file"]["name"]; // File name.
$filename = preg_replace('/[[:^print:]]/', '', $filename); // Replace illegal chars


Regards!

Wednesday 9 July 2014

Laravel 4: Create multi language page with session

Laravel is a strong PHP framework that is widely used. Recently, I was developing with that framework and I needed to create a website with content in 2 languages: catalan and spanish.

To solve this problem you can use some options... like url with language or save language in session. I decided to use the last one.

I created this code:

filters.php

App::before(function($request) {
// We use the locale of the session
if ( Session::has('locale') ) { App::setLocale(Session::get('locale')); }
});

BaseController.php

class BaseController extends Controller {

public function switchLocale($lang) {
// We change the locale lang in the session and redirect back (see filter language in filters.php).
if ( in_array($lang, Config::get('app.available_language')) ) {
Session::put('locale', $lang);
}
return Redirect::back();
}
}

app.php

'locale' => 'es',
'fallback_locale' => 'ca',
'available_language' => array('es', 'ca'),

Finally,  in our view we use this code in the links used to change the language:

Catalan -> URL::action('BaseController@switchLocale', array('ca'))
Spanish -> URL::action('BaseController@switchLocale', array('es'))

Wednesday 4 June 2014

felogin: actions to do after login

Sometimes inside a TYPO3 website after install and config felogin, we would like to do some actions everytime that user would acces to website. To do that, we can use an extension hook. In this example we use TYPO3 4.5.32 and 1.3.1 felogin.

Inside ext_localconf.php of our extension:

$GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['felogin']['login_confirmed'][] = 'EXT:test_extension/hooks/class.feloginhook.php:test_extension_hooksHandler->onLogin';

Inside class.feloginhook.php:

class test_extension_hooksHandler { public function onLogin() { // Actions to do here... Insert in a database, in a log... redirections... } }

Regards!

Thursday 15 May 2014

jQuery: Send form by ajax

Hello,

Sometimes we want to send form data but we don't want to reload page. In this case best option is send data by ajax and jQuery. In this example we used version 1.10.2 of jQuery.

HTML code:

<form id="FORMID" accept-charset="UTF-8" action="action.php" method="POST"> <input type="text" name="username" id="username" placeholder="Write username"> </form>;

Javascript code:

$('#FORMID').on('submit', function(e)  {
$.post(
$(this).prop('action'),
{
"username": $(this).find('input[name=username]').val()
},
function(data) {
alert(data.result);
},
'json'
); return false;
});


php (action.php) code:

<?php
$username = $_POST['username'];
$ret = array();
$ret['result'] = 'OK';
return json_encode($ret);

Best regards!

Thursday 10 April 2014

HMENU: add class to li tag

Hello,

Today I was creating a new HMENU with Typoscript and I have found a problem. I had this HMENU already configured:

temp.links = HMENU temp.links.special = list temp.links.special.value = 1,2,3,4,5 temp.links { 1 = TMENU 1 { wrap = <ul>|</ul> NO.linkWrap = <li>|</li> } }

Then I saw that I wanted to add a class in the last li tag. The solution is:

temp.links = HMENU temp.links.special = list temp.links.special.value = 1,2,3,4,5 temp.links { 1 = TMENU 1 { wrap = <ul>|</ul> NO.linkWrap = <li>|</li>|*||*|<li class="specialClasss">|</li> } }

Best regards!

Monday 31 March 2014

TYPO3: Use session variables

Hello,

In TYPO3 is very useful to manage session variables in frontend plugins:
  • Get 'test' variable: $test = $GLOBALS['TSFE']->fe_user->getKey('ses', 'test');
  • Save  'test' variable: $GLOBALS['TSFE']->fe_user->setKey('ses', 'test', $test); $GLOBALS['TSFE']->fe_user->storeSessionData();
Regards!