Cestfait.ch

  • Home
  • Drupal
  • PHP 5
  • Jquery
  • Web Dev
  • Sys admin
  • Logiciels libres
  • Videos
  • Divers
  • Nous contacter
  • Mon c'est fait!
Notre mission est de promouvoir le développement à base de Drupal, Bière et Burger ! Cela nous réussi plutôt bien, vu qu'on fait ce qu'on veut sur Drupal, à titre d'exemple : www.lematin.ch, www.24heures.ch, www.terrenature.ch, etc...
PHP SoapClient et le chunked transfer

Quandle SoapClient de PHP reçoit un contenu en plusieurs parties (chunked), il flippe. Grave. Genre FATAL ERROR. Le fichier .wsdl demandé n'est pas forcément toujours envoyé en plusieurs parties, ça dépend de sa taille par rapport à la fenètre d'émission. PHP 5.3 permet la requête en HTTP1.1, mais ne gère pas la réponse chunked. C'est moche. PHP5.2 lui faisait la requête en HTTP 1.0, ce qui passait correctement. Ce qui peut donner :

FATAL ERROR: SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://www.example.com/file.wsdl' : Start tag expected, '<' ...

Donc pour forcer cette petite fouine à ne demander que ce qu'elle peut se mettre dans le bec, un magnifique

$opts = array('http' => array('protocol_version' => '1.0')); $context = stream_context_create($opts); $o = new SoapClient($wsdl, array('stream_context' => $context));

Va règler le problème en forçant le truc à demander du HTTP 1.0, le protégeant des chunks dispo dans la version HTTP1.1. Merci Benoit M !

Voila, le SoapClient qui ne se fait pas mettre profond par le premier chunk qui passe, c'est fait !

Get the list of all enabled module

With drush type this command:

drush pm-list --status="enabled" | grep -o '(.\+)' | grep -o '[^()]\+'

Yeah, c'est fait !

Chat webapp with node.js
Node.js is great, if you don't know it yet check the description on nodejs.org.

I was particularly interested to understand how the socket plug-in works in Node.js. The goal of this blog post is to explain to you how to great a basic chat system.

Assumption:
- node.js installed (https://github.com/joyent/node/wiki/Installation)
I recommend you to use the latest stable version (0.6.15)

If it's your first time with node.js I recommend you to follow the excellent tutorial for beginner: http://www.nodebeginner.org/

Fine, now you have your node.js server up and running, let's begin.
We are going to use two files: server.js which will be our backend part. And client.html, the frontend.
So, create the web server and read the html file.

server.js
// Require dependencies
var app = require('http').createServer(handler)
  , fs = require('fs');
 
// creating the server ( localhost:8000 )
app.listen(8000);
 
// on server started we can load our client.html page
function handler ( req, res ) {
  fs.readFile( __dirname + '/client.html' ,
  function ( err, data ) {
    if ( err ) {
      console.log( err );
      res.writeHead(500);
      return res.end( 'Error loading client.html' );
    }
    res.writeHead( 200 );
    res.end( data );
  });
}
client.html
<html>
    <body>
        <h1>Welcome on the chat</h1>
    </body>
</html>

Start the server and let's look if we have something here: http://localhost:8000/
Terminal
node server.js

Now we have a web server running and a page is displayed. Great but it's not enough. Let's continue by asking the user his nickname and store it. It's required to have the socket.io plug-in.

Terminal
npm install socket.io
client.html
<html>
  <body>
    <h1>Welcome on the chat</h1>
 
    <!-- Include the socket.io javascript on the client side -->
    <script src="socket.io/socket.io.js"></script>
 
    <script>
      // Establish the connection with the server
      var socket = io.connect('http://localhost:8000'); 
 
      // Create a new socket connection
      socket.on('connect', function() {
 
        socket.emit('set nickname', prompt('What is your nickname?'));
      });
    </script>
  </body>
</html>

server.js
// Require dependencies
var app = require('http').createServer(handler)
  , fs = require('fs')
  , io = require('socket.io').listen(app);
 
// creating the server ( localhost:8000 )
app.listen(8000);
 
// on server started we can load our client.html page
function handler ( req, res ) {
  fs.readFile( __dirname + '/client.html' ,
  function ( err, data ) {
    if ( err ) {
      console.log( err );
      res.writeHead(500);
      return res.end( 'Error loading client.html' );
    }
    res.writeHead( 200 );
    res.end( data );
  });
}
 
// creating a new websocket to keep the content updated without any AJAX request
io.sockets.on( 'connection', function ( socket ) {
 
  socket.on('set nickname', function (nickname) {
    // Save a variable 'nickname'
    socket.set('nickname', nickname, function () {
      var connected_msg = nickname + ' is now connected.';
      console.log(connected_msg);
    });
  });
});

Restart the server and refresh the page to check the update. You should be prompted to enter your nickname. While submitting your nickname, check the terminal logs to see the message.:

Damien is now connected.

Now, broadcast to all connected users a message when someone connect on the chat, by calling the emit() function.

server.js
// Require dependencies
var app = require('http').createServer(handler)
, fs = require('fs')
, io = require('socket.io').listen(app);
 
// creating the server ( localhost:8000 )
app.listen(8000);
 
// on server started we can load our client.html page
function handler(req, res) {
  fs.readFile(__dirname + '/client.html', function(err, data) {
    if(err) {
      console.log(err);
      res.writeHead(500);
      return res.end('Error loading client.html');
    }
    res.writeHead(200);
    res.end(data);
  });
}
 
// creating a new websocket to keep the content updated without any AJAX request
io.sockets.on('connection', function(socket) {
 
  socket.on('set nickname', function(nickname) {
    // Save a variable 'nickname'
    socket.set('nickname', nickname, function() {
      var connected_msg = nickname + ' is now connected.';
      console.log(connected_msg);
 
      io.sockets.volatile.emit('broadcast_msg', connected_msg);
    });
  });
});

And update the client to receive and display messages. We will also need to include jQuery.

client.html
<html>
  <body>
    <h1>Welcome on the chat</h1>
 
    <ul id="broadcast-msg"></ul>
 
    <!-- Include the socket.io javascript on the client side -->
    <script src="socket.io/socket.io.js"></script>
    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
 
    <script>
      // Establish the connection with the server
      var socket = io.connect('http://localhost:8000'); 
 
      // on every message recived we print the new datas inside the #broadcast-msg div
      socket.on('broadcast_msg', function (data) {
        console.log('Get broadcasted msg:', data);
        var msg = '<li>' + data + '</li>';
        $('#broadcast-msg').append(msg);
      });
 
      // Create a new socket connection
      socket.on('connect', function() {
 
        socket.emit('set nickname', prompt('What is your nickname?'));
      });
    </script>
  </body>
</html>

Again, restart the server and refresh the page to check the update.

Yeah, we have submit a string to the server and we got an answer to display on the client. The loop is done. We can add a text field to let users enter their messages. Moreover, on the server side, we will get the saved nickname before broadcasting the massage to all connected user.

server.js
// Require dependencies
var app = require('http').createServer(handler)
, fs = require('fs')
, io = require('socket.io').listen(app);
 
// creating the server ( localhost:8000 )
app.listen(8000);
 
// on server started we can load our client.html page
function handler(req, res) {
  fs.readFile(__dirname + '/client.html', function(err, data) {
    if(err) {
      console.log(err);
      res.writeHead(500);
      return res.end('Error loading client.html');
    }
    res.writeHead(200);
    res.end(data);
  });
}
 
// creating a new websocket to keep the content updated without any AJAX request
io.sockets.on('connection', function(socket) {
 
  socket.on('set nickname', function(nickname) {
    // Save a variable 'nickname'
    socket.set('nickname', nickname, function() {
      var connected_msg = nickname + ' is now connected.';
      console.log(connected_msg);
 
      io.sockets.volatile.emit('broadcast_msg', connected_msg);
    });
  });
 
 
  socket.on('emit_msg', function (msg) {
    // Get the variable 'nickname'
    socket.get('nickname', function (err, nickname) {
      console.log('Chat message by', nickname);
      io.sockets.volatile.emit( 'broadcast_msg' , nickname + ': ' + msg );
    });
  });
});

client.html
<html>
  <body>
    <h1>Welcome on the chat</h1>
 
    <label for="msg-input">Broadcast message</label>
    <input id="msg-input" name="msg-input" type="text" size="30" />
    <p>Press enter to submit your message</p>
 
    <ul id="broadcast-msg"></ul>
 
    <!-- Include the socket.io javascript on the client side -->
    <script src="socket.io/socket.io.js"></script>
    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
 
    <script>
      // Establish the connection with the server
      var socket = io.connect('http://localhost:8000'); 
 
      // on every message recived we print the new datas inside the #broadcast-msg div
      socket.on('broadcast_msg', function (data) {
        console.log('Get broadcasted msg:', data);
        var msg = '<li>' + data + '</li>';
        $('#broadcast-msg').append(msg);
      });
 
      // Create a new socket connection
      socket.on('connect', function() {
 
        socket.emit('set nickname', prompt('What is your nickname?'));
 
        $('#msg-input').change( function(){
          var txt = $(this).val();
          $(this).val('');
          socket.emit('emit_msg', txt, function (data){
            console.log('Emit Broadcast msg', data);
          });
        });
 
      });
    </script>
  </body>
</html>

Again, restart the server and refresh the page to check the update.

Congratulation, the base of your chat application is done. I will finish this tutorial by adding a last feature to broadcast a message when a user disconnect from our chat. For that I will use the reserved socket.on('disconnect', function () {});

server.js
// Require dependencies
var app = require('http').createServer(handler)
, fs = require('fs')
, io = require('socket.io').listen(app);
 
// creating the server ( localhost:8000 )
app.listen(8000);
 
// on server started we can load our client.html page
function handler(req, res) {
  fs.readFile(__dirname + '/client.html', function(err, data) {
    if(err) {
      console.log(err);
      res.writeHead(500);
      return res.end('Error loading client.html');
    }
    res.writeHead(200);
    res.end(data);
  });
}
 
// creating a new websocket to keep the content updated without any AJAX request
io.sockets.on('connection', function(socket) {
 
  socket.on('set nickname', function(nickname) {
    // Save a variable 'nickname'
    socket.set('nickname', nickname, function() {
      console.log('Connect', nickname);
      var connected_msg = '<b>' + nickname + ' is now connected.</b>';
 
      io.sockets.volatile.emit('broadcast_msg', connected_msg);
    });
  });
 
  socket.on('emit_msg', function (msg) {
    // Get the variable 'nickname'
    socket.get('nickname', function (err, nickname) {
      console.log('Chat message by', nickname);
      io.sockets.volatile.emit( 'broadcast_msg' , nickname + ': ' + msg );
    });
  });
 
  // Handle disconnection of clients
  socket.on('disconnect', function () {
    socket.get('nickname', function (err, nickname) {
      console.log('Disconnect', nickname);
      var disconnected_msg = '<b>' + nickname + ' has disconnected.</b>'
 
      // Broadcast to all users the disconnection message
      io.sockets.volatile.emit( 'broadcast_msg' , disconnected_msg);
    });
  });
});

For the last time, restart the server and refresh the page to check the update. You can improve the application by adding the time of the message. Also, the list of messages can be huge. With some jQuery kick you can kept the list bellow a define number of messages.

Thanks for ready and Keep Open Spirit.

Ultimate Battlefield 3 Simulator - Teaser Trailer - The Gadget Show
Le embed a été desactivé sinon je l'aurais ajouter comme video, mais voilà le lien: http://www.youtube.com/watch?v=nQR49JGySTM
Emacs php-mode.el color synthax for php 5.3 (namespace, use)
Pour ce qui cherchent une solutions temporaire pour le color synthax de php 5.3, il vous faut modifier le fichier php-mode.el : Line 287 :
(defconst php-block-stmt-2-kwds
  '("for" "if" "while" "switch" "foreach" "namespace" "use" "elseif" "catch all"))
Line 939
(defconst php-keywords
  (eval-when-compile
    (regexp-opt
     ;; "class", "new" and "extends" get special treatment
     ;; "case" and "default" get special treatment elsewhere
     '("and" "as" "break" "continue" "declare" "do" "echo" "else" "elseif"
       "endfor" "endforeach" "endif" "endswitch" "endwhile" "exit"
       "extends" "for" "foreach" "namespace" "use" "global" "if" "include" "include_once"
       "next" "or" "require" "require_once" "return" "static" "switch"
       "then" "var" "while" "xor" "throw" "catch" "try"
       "instanceof" "catch all" "finally")))
  "PHP keywords.")
Line 1005
(defconst php-font-lock-keywords-2
  (append
   php-font-lock-keywords-1
   (list
 
    ;; class declaration
    '("\\<\\(class\\|interface\\)\\s-+\\(\\sw+\\)?"
      (1 font-lock-keyword-face) (2 font-lock-type-face nil t))
    ;; handle several words specially, to include following word,
    ;; thereby excluding it from unknown-symbol checks later
    ;; FIX to handle implementing multiple
    ;; currently breaks on "class Foo implements Bar, Baz"
    '("\\<\\(new\\|extends\\|implements\\)\\s-+\\$?\\(\\sw+\\)"
      (1 font-lock-keyword-face) (2 font-lock-type-face))
 
    ;;namespace
    '("\\namespace[[:space:]]\\([^;]+\\)" . (1 font-lock-type-face) )
 
    ;;use
    '("\\use[[:space:]]\\([^;]+\\)" . (1 font-lock-type-face) )
 
    ;; function declaration
    '("\\<\\(function\\)\\s-+&?\\(\\sw+\\)\\s-*("
      (1 font-lock-keyword-face)
      (2 font-lock-function-name-face nil t))
 
    ;; class hierarchy
    '("\\<\\(self\\|parent\\)\\>" (1 font-lock-constant-face nil nil))
 
    ;; method and variable features
    '("\\<\\(private\\|protected\\|public\\)\\s-+\\$?\\sw+"
      (1 font-lock-keyword-face))
 
    ;; method features
    '("^\\s-*\\(abstract\\|static\\|final\\)\\s-+\\$?\\sw+"
      (1 font-lock-keyword-face))
 
    ;; variable features
    '("^\\s-*\\(static\\|const\\)\\s-+\\$?\\sw+"
      (1 font-lock-keyword-face))
    ))
  "Medium level highlighting for PHP mode.")
Une couche de Varnish

Varnish (vernis), c'est un logiciel qui fait pas mal de chose en même temps. Il est très simple à installer ( apt-get install varnish ) et avec la bonne configuration ( https://www.lullabot.com/articles/varnish-multiple-web-servers-drupal ), va faires quelques trucs sympathiques:

  1. Répartir la charge entre plusieurs serveurs
  2. S'assurer que ces serveurs sont toujours "vivants" et répondent en moins que x secondes
  3. Si un de ces serveurs est mort ou lent, le sortir de la liste de serveurs vers lesquels le traffic est redirigé
  4. Cacher la réponse de certaines urls (par exemple les /files/ )
  5. Si aucun serveur n'est disponible, renvoyer les pages mises en cache
  6. Si tout échoue, afficher une page de maintenance ou un redirect vers un site de backup

De plus, en configurant varnish, on lui assigne quels cookies il forwarde a Drupal, ce qui peut évuentuellement aussi rajouter une couche de sécurité. Aussi, les serveurs (Apache ou autres) ne sont plus directement accessibles par le net.

Pour D6, il est nécessaire d'utiliser Pressflow et éventuellement http://drupal.org/project/varnish pour que Drupal puisse invalider le cache Varnish lorsque c'est nécessaire.

En configurant Varnish, même les utilisateurs authentifiés en bénéficient, certains files (genre les images) peuvent être cachés indépendamment de la session de l'utilisateur, seul leur path compte.

Varnish, ça c'est fait !

Whopper Bar New York !
Premier burger testé : Whopper bacon, avec mozzarella, crispy onions et sauce bourbon : un régal ! Deuxième burger : Double whopper bacon, cheddar, onion rings, sauce bbq : Un peu plus relevé, ça dégouline partout, mais c'est comme ça qu'on aime. On sent bien la flamme dans celui-là !
Ranged LDAP query in PHP for Windows Server 2003

Une requète sur un LDAP fourni par l'AD de Windows Server 2003 ne renverra que 1500 résultats. (ou autre limite faite par l'admin). La fonction PHP ldap_search ne gère pas encore ce retour (en attendant qu'un patch soit accepté dans PHP). Donc voici une fonction qui va chercher tous les utilisateurs d'un groupe, détecte si c'est un résultat paginé, et va chercher le reste

 $filter = "(&amp;(objectcategory=group)(cn=$group))"; $attributes = array('member;range=0-*'); $base = 0; $users = array(); //First ldap request, to get either all entries or a paged result $sr = ldap_search($ldapconn, $dn, $filter, $attributes); $result = ldap_get_entries($ldapconn, $sr); $count = (int) $result[0][$result[0][0]]['count']; for ($i = 0; $i &lt; $count; $i++) { $users[] = $result[0][$result[0][0]][$i]; } //If we receive a paged result, the attribute member will be member;range=1-1400 //If the result is the last or only page, the attribute member will be member;range=1-* while (!preg_match("/\*$/", $result[0][0])) { $end = $base + $count; $attributes = array("member;range=$base-" . ($end - 1)); $sr = ldap_search($ldapconn, $dn, $filter, $attributes); $result = ldap_get_entries($ldapconn, $sr); $count = (int) $result[0][$result[0][0]]['count']; for ($i = 0; $i &lt; $count; $i++) { $users[] = $result[0][$result[0][0]][$i]; } $base = $end; }

Voilà, comme ça il est facile de récupérer les utilisateurs d'un groupe LDAP, par exemple pour obtenir le samaccountname et d'autres trucs !

Möchten Sie einen Kanonenputzer ?
Je suis en formation pour deux mois à Zürich et je profite un peu de la gastronomie locale... ! c'est là que ça se passe Zeughauskeller
The best Port in the world

Le meilleur porto est sans conteste le Taylor's 40 years old tawny, talloné de près par le 20 years. Pour l'archive, voici combien il coûte au départ de cave à Porto, ainsi qu'une comparaison de prix HT :

Taylo's 40 Year :
Cave: 97€
Delicatessa: 249.- 

Taylor's 30 Year:
Cave: 73€

Taylor's 20 Year: 
Cave: 30€
Delicatessa : 72.- CHF 
Nicolas: 32€ 

Taylor's 10 Year:
Cave: 12.95€ 

Cloudflare et Dropbox nommés Technology pioneers

Il y a des produits comme ça qui deviennent indispensables dès qu'on commence à utiliser: Dropbox et cloudflare. Dropbox on connait/utilise déjà, Cloudflare c'est plus nouveau, cela permet d'avoir un CDN/reverse proxy/firewall gratuitement pour son site. N'importe quel petit et grand site peut le tester, voir si ça claque ou pas et se rendre compte qu'avoir son site qui répond en dessous des 150 ms de partout dans le monde cela n'a pas de pareil.

Ainsi donc, ces deux sociétés (parmi d'autres) ont été désignées Technology Pioneers par le World Economic Forum !!! Deux autres font aussi partie de la sélection, Palantir et Kickstarter ( qui connaît bien ? )

Ton site n'est pas encore sur cloudflare ? T'attends quoi ? Que ce soit payant ?

Allez, ça, c'est fait !

Keep Calm, clear cache
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • …
  • next ›
  • last »
Syndicate content

User login

  • Create new account
  • Request new password
  • Sign in with Twitter

Translate

Sondage

Qu'elle version de drupal utilisez-vous ?

Submitted by Sir Squall on Tue, 04/10/2012 - 16:30
  • Login or register to post comments

Recent comments

  • Arf, je suis à l'armée!
    40 weeks 1 day ago
  • hahaha c'est juste! Il n'y a
    46 weeks 4 days ago
  • yeah comme sa fait plaisir de
    46 weeks 6 days ago
  • wouahou merciii :-) !
    50 weeks 4 days ago
  • J'y réponds aujourd'hui ici
    50 weeks 5 days ago
  • Salut, court article mais
    50 weeks 6 days ago
  • Oktoberfest power!!!
    1 year 3 weeks ago
  • yep je vais faire un petit
    1 year 5 weeks ago
  • It's regular approuved
    1 year 5 weeks ago
  • Pas d'exemple????
    1 year 5 weeks ago

Tags

cropping Divers drupal Drupal emacs firefox gmap Google Images Jquery jquery karmic koala La phrase du jour Lausanne Logiciels libres mysql PHP 5 RPG Sys admin ubuntu Web Dev yasnippet youtube Zend
more tags

Popular content

Today's:

  • Wallpaper drupal
  • Nice card
  • Clean les vilains tag word
  • Avec qu'elle outils préferez-vous faire des sites ?
  • Double Down
  • Chat webapp with node.js
  • Drupal date avec des formats custom
  • Boxxy likes Drupal
  • Iframe autoHeight
  • Vive la pub

All time:

  • Drupal 7 effet avec les jquery.ui.dialog sur Drupal 6 !
  • Dries Keynote DrupalCon Paris 2009
  • Drupal bridge zend yeah !!
  • Jquery slider c'est de la bonne !!!
  • Drupal and Zend, form validate :)
  • Jquery JSON en _POST
  • [Drupal] Lightbox avec une gmap! yeah
  • [Drupal] Domain Access & memcache sa donne quoi ?
  • viportuguese-shop.com
  • Node Import et Taxonomy CSV

Last viewed:

  • Wallpaper drupal
  • Nice card
  • Le vendredi Genevois
  • Emacs ouvrir fichiers distants
  • Emacs Transparent
  • Double Down
  • Evanescence (korn)
  • Billard a l'appart
  • viportuguese-shop.com
  • Burger king

Twitter

Latest Articles

Derniers liens publiés

  • Get the list of all enabled module
    http://drupal.org/node/440962
  • Cloudflare et Dropbox nommés Technology pioneers
    http://techcrunch.com/2011/09/01/cloudflare-dropbox-palantir-and-kickstarter-named-technology-pioneers-by-the-world-economic-forum/
  • Apprend le javascript en t'amusant
    http://www.codecademy.com
  • EPSACrop sur Drupal 7
    http://www.aswissidea.org/
  • Drupal solr attachement intégration
    http://tika.apache.org/

Pub

Google gadget

Add to Google

Facebook page

jiwa

all good song

Partenaires

Cyber Warfare

Drupal Factory

Dev Factory

I love Smashing Magazine!
Fervens Drupal theme by Leow Kah Thong. Designed by Design Disease and brought to you by Smashing Magazine.