Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is PHP used to parse comments / headers for themes and plugins?

Wordpress plugins and themes have comments like these at the top:

/**
 * @package Akismet
 */
/*
Plugin Name: Akismet
Plugin URI: http://akismet.com/?return=true
Description: Used by millions, Akismet is quite possibly the best way in the world to <strong>protect your blog from comment and trackback spam</strong>. It keeps your site protected from spam even while you sleep. To get started: 1) Click the "Activate" link to the left of this description, 2) <a href="http://akismet.com/get/?return=true">Sign up for an Akismet API key</a>, and 3) Go to your <a href="admin.php?page=akismet-key-config">Akismet configuration</a> page, and save your API key.
Version: 2.5.6
Author: Automattic
Author URI: http://automattic.com/wordpress-plugins/
License: GPLv2 or later
*/

And when you visit the plugins' page in the admin interface, the plugins are listed like this:

screenshot-with-shadow.png http://img854.imageshack.us/img854/4526/screenshotwithshadow.png

Is that a standard syntax for documentation? I'm assuming it does a file_get_contents on the plugin files to read them, but how does Wordpress parse that into manipulatable, standardized information to be used in PHP?

like image 358
Steve Brown Avatar asked Nov 15 '12 04:11

Steve Brown


1 Answers

See get_plugin_data() in wp-admin/includes/plugin.php for the WordPress parser. More specifically the extraction happens in get_file_data() of wp-includes/functions.php:

function get_file_data( $file, $default_headers, $context = '' ) {
        // We don't need to write to the file, so just open for reading.
        $fp = fopen( $file, 'r' );

        // Pull only the first 8kiB of the file in.
        $file_data = fread( $fp, 8192 );

        // PHP will close file handle, but we are good citizens.
        fclose( $fp );

        // Make sure we catch CR-only line endings.
        $file_data = str_replace( "\r", "\n", $file_data );

        if ( $context && $extra_headers = apply_filters( "extra_{$context}_headers", array() ) ) {
                $extra_headers = array_combine( $extra_headers, $extra_headers ); // keys equal values
                $all_headers = array_merge( $extra_headers, (array) $default_headers );
        } else {
                $all_headers = $default_headers;
        }

        foreach ( $all_headers as $field => $regex ) {
                if ( preg_match( '/^[ \t\/*#@]*' . preg_quote( $regex, '/' ) . ':(.*)$/mi', $file_data, $match ) && $ma
                        $all_headers[ $field ] = _cleanup_header_comment( $match[1] );
                else
                        $all_headers[ $field ] = '';
        }

There are similar implementations outside of WP. See How can plugin systems be designed so they don't waste so many resources? for an example.

like image 138
mario Avatar answered Oct 20 '22 01:10

mario