Category Archives: News

Fix bug Foundation 6 doesn’t show Filename when choosing file

$(document).on('change', '[type=file]', function () {
    var $me = $(this),
        classFileName = 'file-name',
        $fileNameContainer = $me.next('.' + classFileName),
        fileName = baseName($me.get(0) && $(this).get(0).value),
        maxLength = 20;
    if (fileName.length > maxLength) {
        fileName = fileName.substring(0, maxLength - 1) + '...';
    }
    if (isEmpty($fileNameContainer)) {
        $fileNameContainer = $('<span class="' + classFileName + '">' + fileName + '</span>');
        $fileNameContainer.insertAfter($me);
    } else {
        $fileNameContainer.text(fileName);
    }
});

Simple Captcha in PHP

This captcha is simple and can use for any website ^^

<?php
require_once BASE_PATH . '/Code/claviska/simple-php-captcha.php';
class Captcha {
    /**
     * Document: https://github.com/claviska/simple-php-captcha
     */
    public static function checkCaptcha () {
        $isSuccess = FALSE;
        if (
            empty($_POST['simple_captcha_client']) === FALSE &&
            empty($_SESSION['simpleCaptcha']['code']) === FALSE &&
            strtolower($_POST['simple_captcha_client']) == strtolower($_SESSION['simpleCaptcha']['code'])
        ) {
            $isSuccess = TRUE;
        }
        return $isSuccess;
    }
    public static function generateCaptcha () {
        $_SESSION['simpleCaptcha'] = simple_php_captcha([
            'min_length' => 6,
            'max_length' => 6,
            'characters' => '123456789'
        ]);
        return $_SESSION['simpleCaptcha']['image_src'];
    }
    public static function showCaptcha ($class = NULL) {
        return '<div class="captcha-holder ' . $class . '"><img src="' . Captcha::generateCaptcha() . '" class="captcha-img" /><input type="text" name="simple_captcha_client" placeholder="' . convertCase(trans('validation.enter_captcha'), 3) . '" /><a data-href="' . BASE_URL . '/captcha/reset" class="captcha-refresh"><i class="icons fi-refresh"></i></a></div>';
    }
}
class Default_CaptchaController {
    function resetAction() {
        require_once BASE_PATH . '/Code/Captcha.php';
        echo Captcha::generateCaptcha();
    }
}
$('.captcha-refresh').on('click', function () {
	var $me = $(this);
	$.ajax({
		url: $(this).data('href')
	})
	.done(function(src) {
		$me.closest('.captcha-holder').find('.captcha-img').attr('src', src);
	});
});
.captcha-holder {
    &> * {
        display: inline-block;
        width: auto;
        height: 39px;
    }
    &> input {
        width: 125px;
    }
    .captcha-refresh {
        cursor: pointer;
        .icons {
            @include font-size(22px);
            margin-left: 5px;
            position: relative;
            top: 3px;
        }
    }
}

Continue reading Simple Captcha in PHP

Login bằng php-jwt thay cho session, cookie truyền thống

install:

composer require firebase/php-jwt:dev-master
composer require zendframework/zend-config:~2.3
composer require zendframework/zend-http:~2.3

Tham khảo: sitepoint Continue reading Login bằng php-jwt thay cho session, cookie truyền thống

Gulp run as series of tasks

// task cleanDist
gulp.task('cleanDist', function(cb) {
  return del([
    './www/js/configuration.js'
  ]);
});
// task copy-local-files: require 'cleanDist' task
gulp.task('copy-local-files', ['cleanDist'], function(cb) {
  return gulp.src('./../config/local/**/*').pipe(gulp.dest('./www'));
});
// task lint: require 'copy-local-file' task
gulp.task('lint', ['copy-local-files'], function() {
  return gulp.src(paths.js)
    .pipe(jshint('.jshintrc'))
    .pipe(jshint.reporter('jshint-stylish'));
});

Bonus: Ionic run task before server and after serve: config in ionic.project file

{
  "name": "songpham",
  "app_id": "20002005",
  "gulpDependantTasks": [ // before serve
    "lint"
  ],
  "gulpStartupTasks": [ // after serve
    "watch"
  ],
  "watchPatterns": [
    "www/**/*",
    "!www/lib/**/*"
  ]
}

Creating login middleware in Express Node js

app.js

...
app.use(require('./login')); /* include middleware login */
...

index.js

var express = require('express');
var router = express.Router();
router.all('/', function (req, res) {
  res.render('index', {
    title: 'Express'
  });
});
module.exports = router;

Continue reading Creating login middleware in Express Node js

Khai báo hàm callback gọi lại trong Javascript

[script language=”javascript”]
var http = require(‘http’),
feed = ‘http://www.baomoi.com/&#8217;,
ready = false;
function decide (cb) {
console.log(‘deciding’);
setTimeout(function () {
if (Date.now() % 2) { return console.log(‘rejected’); }
ready = true;
cb();
}, 2000);
}
http.get(feed, function (res) {
res.on(‘readable’, function log () {
if (!ready) { return decide(log); }
console.log(res.read() + ”);
});
});
[/script]
Chú ý hàm log() được gọi lại nhiều lần

Cách xây dựng directive bằng Angular Js 1

Khi tạo 1 directive, đầu tiên ta phải suy nghĩ xem ta viết cái gì? Sau đó ta xem directive của ta hoạt động ra sao? Và cuối cùng là ta truyền vào cái gì để nó hoạt động?

Để mô tả luồng tư duy, mình thử viết 1 modal directive cơ bản nhất:
– Viết cái gì: Modal
– Hoạt động: Modal có tính năng click vào button thì hiện lên, click vào background thì tắt đi.
– Truyền vào: Biến bật/tắt và Content của modal.

Sau khi tư duy xong, ta có thể khái quát được mô hình như sau:
– name directive: modalWindow
– replace: true (dĩ nhiên)
– transclude: true (vì cần truyền content vào modal, sau này cứ khi nào directive cần truyền dynamic content vào thì transclude là true hết)
– biến bật/tắt: show (false là tắt, true là bật) Continue reading Cách xây dựng directive bằng Angular Js 1

Angular Js 1: Auth check when change state

Controller:

...
$stateProvider
  .state('home.contact', {
    url: '/contact',
    resolve: {
      currentAuth: function(AuthFactory) {
        return AuthFactory.authPromise();
      }
    }
  });
...

Service:

...
.factory('AuthFactory', function ($q, $timeout, $rootScope) {
  var factoryObject = {
    authPromise: function () { /* promise to check is login or not */
      // Initialize a new promise
      var deferred = $q.defer();
      $timeout(function () {
        if ($rootScope.isAuthenticated) {
          deferred.resolve();
        } else {
          deferred.reject('AUTH_REQUIRED');
        }
      });
      return deferred.promise;
    }
  };
  return factoryObject;
})
...

Root Controller:

...
$rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error) {
  if (error === 'AUTH_REQUIRED') {
    $state.go('home.dash');
  }
});
...

Use promise in Angular Js 1

// Story: One morning, a father says to his son: "Go and get the weather forecast, son!"
// Every Sunday morning, a father asks his son to go and find out the weather forecast for the afternoon, by using his super-strong telescope to look across the horizon from the tallest hill by their house. The son promises his dad he will go and get the weather forecast. He creates a promise with his dad at the door when he leaves.
// At that point, the dad decides if the weather tomorrow is good, he'll prepare a fishing trip for tomorrow. If it's bad he won't. Also, if the son is unable to get a forecast, he'll stay in as well.
// After 30mins or so, the son comes back. Different things happen from week-to-week
// ---------------------------------------------------------------------------
// can detect the result
var prepareFishingTrip = function (data) {
    console.log('the weather is fine');
    console.log(data);
};
var prepareSundayRoastDinner = function prepareSundayRoastDinner (data) {
    console.log('the weather is bad');
    console.log(data);
};
// can't detect the result
var dontKnowPrepareSundayRoastDinnerOrNot = function prepareSundayRoastDinner (res) {
    console.log('the son can\'t retrieve the weather, he return everything');
    console.log(res);
};
angular.module('myApp', [])
.factory('SonService', function ($http, $q) {
    return {
        getWeather: function() {
            // the $http API is based on the deferred/promise APIs exposed by the $q service
            // so it returns a promise for us by default
            return $http.get('http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=2de143494c0b295cca9337e1e96b00e0')
                .success(function(res) {
                    if (typeof res.data === 'object') {
                        return res.data;
                    } else {
                        // invalid response
                        return $q.reject(res);
                    }
                })
                .error(function(res) {
                    // something went wrong
                    return $q.reject(res);
                });
        }
    };
})
.controller('Ctrl', function($q, SonService) {
    SonService.getWeather()
        // success() called when son gets back
        .success(function(data) {
            // promise fulfilled
            if (data.wind && data.wind.speed > 2) { // if success
                prepareFishingTrip(data);
            } else {
                prepareSundayRoastDinner(data); // if the weather is not good
            }
        })
        .error(function(res) {
            // promise rejected
            dontKnowPrepareSundayRoastDinnerOrNot(res);
        });
});