Derniers snippets latest snippets

replace url by links in a text

  static function urlMe($text){
    $pattern = "@(http://|https://){1}((www\.?)[a-zA-Z0-9\-\.]+\.[a-z]{2,6})/?([^\s]*)@";
    preg_match_all($pattern,' '.$text.' ',$matches);
    foreach($matches[2] as $offset => $link){
      $text = str_replace($matches[0][$offset],'<a href="'.$matches[0][$offset].'" title="'.$matches[0][$offset].'">'.$link.'</a>',$text);
    }
    return($text);
  }
by Leroux de Lens Amaury on 2009-11-18, tagged links  regexp  tools 

Utiliser un retour charriot dans un remplacement sed

Quand on veut utiliser un retour charriot (\n) dans un remplacement avec sed, on commence généralement par essayer ce genre de truc :

$ echo "one,two,three" | sed "s/,/\n/g"

Mais ça ne fonctionne pas ; il faut donc émuler le retour charriot, ce qui est faisable de cette façon :

$ echo "one,two,three" | sed "s/,/\\`echo -e '\n\r'`/g"
by Nicolas Perriault on 2009-06-04, tagged bash  cli  linux  sed  shell 

Bannir les cronmails

Si vous utilisez crontab, vous recevez sans doute souvent des emails à l'adresse du propriétaire du compte avec le détail des sorties standards et d'erreurs suite à l'execution des commandes programmées.

Pour éviter ces emails, on peut systématiquement masquer ces sorties lors de l'appel à la ligne, par exemple dans un crontab :

*/10 * * * * ./myprogram 1> /dev/null 2> /dev/null
by Nicolas Perriault on 2009-06-01, tagged bash  crontab  linux  sysadmin  unix 

Récupérer le nombre d'abonnés feedburner

Pour récupérer le nombre d'abonnés à un flux Feedburner, par exemple celui du flux de prendreuncafe.com :

<?php
$feedName = 'prendreuncafe'; // identifiant feedburner
$xml = @simplexml_load_file(sprintf('https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=%s&dates=%s,%s',
  $feedName,
  date('Y-m-d', strtotime('-2 day')),
  date('Y-m-d', strtotime('-1 day'))));
if (!$xml) throw new RuntimeException('Feed unavailable');
var_dump((int) $xml->feed->entry[0]['circulation']);

Source d'inspiration : Oncle Tom

by Nicolas Perriault on 2009-05-14, tagged api  feedburner  php 

pngFix IE 5.5 => 6

var arVersion = navigator.appVersion.split("MSIE");
var version = parseFloat(arVersion[1]);
 
function fixPNG(myImage)
{
    if ((version >= 5.5) && (version < 7) && (document.body.filters)) 
    {
        var node = document.createElement('span');
        node.id = myImage.id;
        node.className = myImage.className;
        node.title = myImage.title;
        node.style.cssText = myImage.style.cssText;
        node.style.setAttribute('filter', "progid:DXImageTransform.Microsoft.AlphaImageLoader"
                                        + "(src=\'" + myImage.src + "\', sizingMethod='scale')");
        node.style.fontSize = '0';
        node.style.width = myImage.width.toString() + 'px';
        node.style.height = myImage.height.toString() + 'px';
        node.style.display = 'inline-block';
        return node;
    }
    else
    {
        return myImage.cloneNode(false);
    }
}

src : colorpicker.com

by Amaury Leroux de Lens on 2009-03-06, tagged ie  javascript  png 

Générer automatiquement des liens internationnalisés avec symfony 1.2

Par exemple, dans le layout :

<ul>
  <li><?php echo link_to(__('French'),  sprintf('@%s?sf_culture=fr', $r = $sf_context->getRouting()->getCurrentRouteName())) ?></li>
  <li><?php echo link_to(__('English'), sprintf('@%s?sf_culture=en', $r)) ?></li>
</ul>
by Nicolas Perriault on 2009-02-06, tagged i18n  symfony 

SVN based CSS/JS Caching trick

You want to be sure client (browser or real one) uses the very last css/js file everytime you update svn repository.

Here's my proposition :

Make a sfSVN.class.php

<?php
/**
 *  sfSVN : sf+SVN based CSS/JS caching trick
 *
 * @author [MA]Pascal <pborreli@sqli.com>
 */
class sfSVN
{
    /**
     * returns the last revision number
     *
     * @return integer
     */
    public static function getHeadRevision ()
    {
        if (! file_exists($file = sfConfig::get('sf_root_dir') . DIRECTORY_SEPARATOR . '.svn/entries')) {
            return date('Ymd');
        }
        $svn = file($file);
        return isset($svn[3]) ? (int) $svn[3] : date('Ymd');
    }
}

Tweak your view.yml

stylesheets:
    - style.css?<?php echo sfSVN::getHeadRevision().PHP_EOL ?>
  javascripts:
    - functions.js?<?php echo sfSVN::getHeadRevision().PHP_EOL ?>
    - set.js?<?php echo sfSVN::getHeadRevision().PHP_EOL ?>

Clear the cache

$ symfony cc

The result

<script type="text/javascript" src="/js/functions.js?158"></script>
<script type="text/javascript" src="/js/set.js?158"></script>
<link rel="stylesheet" type="text/css" media="screen" href="/css/style.css?158" />

Notes

This little script go read inside SVN file what's the last SVN revision number of your project everytime you clear the cache so it doesn't add much i/o.

Help me to get this script better if you have any idea :)

Cheers,

[MA]Pascal

by Pascal Borreli on 2008-10-21, tagged caching  css  js  subversion  svn 

Autocomplétion au sein d'eclipse

Copier-coller le code suivant dans un fichier xml :

<?xml version="1.0" encoding="UTF-8" standalone="no"?><templates><template autoinsert="true" context="php" deleted="false" description="create a Symfony Action" enabled="true" name="action">public function execute${Action} {
  ${body}
}</template><template autoinsert="true" context="php" deleted="false" description="Create a class controller" enabled="true" name="controller">class ${ControllerName}Actions extends sfActions  {
 
    public  function execute${action}()
 
    {
      ${body}
    }
 
}
</template><template autoinsert="true" context="php" deleted="false" description="criteria doSelect" enabled="true" name="doselect">$$c = new Criteria;
$$${objects} = ${propelObject}Peer::doSelect($$c);</template></templates>

Installation au sein d'eclipse

  • Dans eclipse allez dans Window > Preferences
  • Choisir PHP dans la liste des préférences
  • Choisir Template et cliquer sur Import
  • Selectionner le fichier xml puis accepter

Note: Le mieux serait de s'inspirer des templates de texmate afin de se monter un système de templating complet pour Eclipse. Ajout également de commentaires compatibles phpdocumentor

by Samuel MARTIN on 2008-07-22, tagged autocompletion  completion  eclipse  php  snippet  symfony  template 

[Symfony] Effacer partiellement le cache d'une application

Toujours utile depuis un contexte d'application différent de celui visé :

sfToolkit::clearGlob(sfConfig::get('sf_cache_dir').'/frontend/*/all/*/templates/toto.cache');
by Nicolas Perriault on 2008-05-26, tagged cache  php  symfony 

Gestion des tags en SQL

Un schema classique de gestion de tags :

CREATE TABLE Project ( 
  project_id INT UNSIGNED NOT NULL AUTO_INCREMENT, 
  name VARCHAR(50) NOT NULL, 
  url TEXT NOT NULL, 
  PRIMARY KEY (project_id) 
) ENGINE=MyISAM;
 
CREATE TABLE Tags ( 
  tag_id INT UNSIGNED NOT NULL AUTO_INCREMENT, 
  tag_text VARCHAR(50) NOT NULL, 
  PRIMARY KEY (tag_id), 
  INDEX (tag_text) 
) ENGINE=MyISAM; 
 
CREATE TABLE Tag2Project ( 
  tag INT UNSIGNED NOT NULL, 
  project INT UNSIGNED NOT NULL, 
  PRIMARY KEY (tag, project), 
  INDEX rv_primary (project, tag) 
) ENGINE=MyISAM;

Pour récupérer tous les projets taggué php ou mysql :

SELECT p.name 
FROM Project p 
  INNER JOIN Tag2Project t2p 
    ON p.project_id = t2p.project 
  INNER JOIN Tag t 
    ON t2p.tag = t.tag_id 
WHERE t.tag_text IN ('mysql', 'php');

Pour récupérer tous les projets taggué php et mysql :

SELECT p.name 
FROM Project p 
  CROSS JOIN Tag t1 
  CROSS JOIN Tag t2 
  INNER JOIN Tag2Project t2p 
    ON p.project_id = t2p.project 
      AND t2p.tag = t1.tag_id 
  INNER JOIN Tag2Project t2p2 
    ON t2p.project = t2p2.project 
      AND t2p2.tag = t2.tag_id 
WHERE t1.tag_text = "php" 
  AND t2.tag_text = "mysql";

Tiré et adapté de la présentation Join-fu de Jay Pipes

by Nicolas Perriault on 2008-05-15, tagged join  mysql  sql  tags 
(1 comment)