1<?php
2/**
3 * PEAR_Builder for building PHP extensions (PECL packages)
4 *
5 * PHP versions 4 and 5
6 *
7 * @category   pear
8 * @package    PEAR
9 * @author     Stig Bakken <ssb@php.net>
10 * @author     Greg Beaver <cellog@php.net>
11 * @copyright  1997-2009 The Authors
12 * @license    http://opensource.org/licenses/bsd-license.php New BSD License
13 * @link       http://pear.php.net/package/PEAR
14 * @since      File available since Release 0.1
15 *
16 * TODO: log output parameters in PECL command line
17 * TODO: msdev path in configuration
18 */
19
20/**
21 * Needed for extending PEAR_Builder
22 */
23require_once 'PEAR/Common.php';
24require_once 'PEAR/PackageFile.php';
25require_once 'System.php';
26
27/**
28 * Class to handle building (compiling) extensions.
29 *
30 * @category   pear
31 * @package    PEAR
32 * @author     Stig Bakken <ssb@php.net>
33 * @author     Greg Beaver <cellog@php.net>
34 * @copyright  1997-2009 The Authors
35 * @license    http://opensource.org/licenses/bsd-license.php New BSD License
36 * @version    Release: @PEAR-VER@
37 * @link       http://pear.php.net/package/PEAR
38 * @since      Class available since PHP 4.0.2
39 * @see        http://pear.php.net/manual/en/core.ppm.pear-builder.php
40 */
41class PEAR_Builder extends PEAR_Common
42{
43    var $php_api_version = 0;
44    var $zend_module_api_no = 0;
45    var $zend_extension_api_no = 0;
46
47    var $extensions_built = array();
48
49    /**
50     * @var string Used for reporting when it is not possible to pass function
51     *             via extra parameter, e.g. log, msdevCallback
52     */
53    var $current_callback = null;
54
55    // used for msdev builds
56    var $_lastline = null;
57    var $_firstline = null;
58
59    /**
60     * PEAR_Builder constructor.
61     *
62     * @param object $ui user interface object (instance of PEAR_Frontend_*)
63     *
64     * @access public
65     */
66    function __construct(&$ui)
67    {
68        parent::__construct();
69        $this->setFrontendObject($ui);
70    }
71
72    /**
73     * Build an extension from source on windows.
74     * requires msdev
75     */
76    function _build_win32($descfile, $callback = null)
77    {
78        if (is_object($descfile)) {
79            $pkg = $descfile;
80            $descfile = $pkg->getPackageFile();
81        } else {
82            $pf = new PEAR_PackageFile($this->config, $this->debug);
83            $pkg = &$pf->fromPackageFile($descfile, PEAR_VALIDATE_NORMAL);
84            if (PEAR::isError($pkg)) {
85                return $pkg;
86            }
87        }
88        $dir = dirname($descfile);
89        $old_cwd = getcwd();
90
91        if (!file_exists($dir) || !is_dir($dir) || !chdir($dir)) {
92            return $this->raiseError("could not chdir to $dir");
93        }
94
95        // packages that were in a .tar have the packagefile in this directory
96        $vdir = $pkg->getPackage() . '-' . $pkg->getVersion();
97        if (file_exists($dir) && is_dir($vdir)) {
98            if (!chdir($vdir)) {
99                return $this->raiseError("could not chdir to " . realpath($vdir));
100            }
101
102            $dir = getcwd();
103        }
104
105        $this->log(2, "building in $dir");
106
107        $dsp = $pkg->getPackage().'.dsp';
108        if (!file_exists("$dir/$dsp")) {
109            return $this->raiseError("The DSP $dsp does not exist.");
110        }
111        // XXX TODO: make release build type configurable
112        $command = 'msdev '.$dsp.' /MAKE "'.$pkg->getPackage(). ' - Release"';
113
114        $err = $this->_runCommand($command, array(&$this, 'msdevCallback'));
115        if (PEAR::isError($err)) {
116            return $err;
117        }
118
119        // figure out the build platform and type
120        $platform = 'Win32';
121        $buildtype = 'Release';
122        if (preg_match('/.*?'.$pkg->getPackage().'\s-\s(\w+)\s(.*?)-+/i',$this->_firstline,$matches)) {
123            $platform = $matches[1];
124            $buildtype = $matches[2];
125        }
126
127        if (preg_match('/(.*)?\s-\s(\d+).*?(\d+)/', $this->_lastline, $matches)) {
128            if ($matches[2]) {
129                // there were errors in the build
130                return $this->raiseError("There were errors during compilation.");
131            }
132            $out = $matches[1];
133        } else {
134            return $this->raiseError("Did not understand the completion status returned from msdev.exe.");
135        }
136
137        // msdev doesn't tell us the output directory :/
138        // open the dsp, find /out and use that directory
139        $dsptext = join(file($dsp),'');
140
141        // this regex depends on the build platform and type having been
142        // correctly identified above.
143        $regex ='/.*?!IF\s+"\$\(CFG\)"\s+==\s+("'.
144                    $pkg->getPackage().'\s-\s'.
145                    $platform.'\s'.
146                    $buildtype.'").*?'.
147                    '\/out:"(.*?)"/is';
148
149        if ($dsptext && preg_match($regex, $dsptext, $matches)) {
150            // what we get back is a relative path to the output file itself.
151            $outfile = realpath($matches[2]);
152        } else {
153            return $this->raiseError("Could not retrieve output information from $dsp.");
154        }
155        // realpath returns false if the file doesn't exist
156        if ($outfile && copy($outfile, "$dir/$out")) {
157            $outfile = "$dir/$out";
158        }
159
160        $built_files[] = array(
161            'file' => "$outfile",
162            'php_api' => $this->php_api_version,
163            'zend_mod_api' => $this->zend_module_api_no,
164            'zend_ext_api' => $this->zend_extension_api_no,
165            );
166
167        return $built_files;
168    }
169    // }}}
170
171    // {{{ msdevCallback()
172    function msdevCallback($what, $data)
173    {
174        if (!$this->_firstline)
175            $this->_firstline = $data;
176        $this->_lastline = $data;
177        call_user_func($this->current_callback, $what, $data);
178    }
179
180    /**
181     * @param string
182     * @param string
183     * @param array
184     * @access private
185     */
186    function _harvestInstDir($dest_prefix, $dirname, &$built_files)
187    {
188        $d = opendir($dirname);
189        if (!$d)
190            return false;
191
192        $ret = true;
193        while (($ent = readdir($d)) !== false) {
194            if ($ent{0} == '.')
195                continue;
196
197            $full = $dirname . DIRECTORY_SEPARATOR . $ent;
198            if (is_dir($full)) {
199                if (!$this->_harvestInstDir(
200                        $dest_prefix . DIRECTORY_SEPARATOR . $ent,
201                        $full, $built_files)) {
202                    $ret = false;
203                    break;
204                }
205            } else {
206                $dest = $dest_prefix . DIRECTORY_SEPARATOR . $ent;
207                $built_files[] = array(
208                        'file' => $full,
209                        'dest' => $dest,
210                        'php_api' => $this->php_api_version,
211                        'zend_mod_api' => $this->zend_module_api_no,
212                        'zend_ext_api' => $this->zend_extension_api_no,
213                        );
214            }
215        }
216        closedir($d);
217        return $ret;
218    }
219
220    /**
221     * Build an extension from source.  Runs "phpize" in the source
222     * directory, but compiles in a temporary directory
223     * (TMPDIR/pear-build-USER/PACKAGE-VERSION).
224     *
225     * @param string|PEAR_PackageFile_v* $descfile path to XML package description file, or
226     *               a PEAR_PackageFile object
227     *
228     * @param mixed $callback callback function used to report output,
229     * see PEAR_Builder::_runCommand for details
230     *
231     * @return array an array of associative arrays with built files,
232     * format:
233     * array( array( 'file' => '/path/to/ext.so',
234     *               'php_api' => YYYYMMDD,
235     *               'zend_mod_api' => YYYYMMDD,
236     *               'zend_ext_api' => YYYYMMDD ),
237     *        ... )
238     *
239     * @access public
240     *
241     * @see PEAR_Builder::_runCommand
242     */
243    function build($descfile, $callback = null)
244    {
245        if (preg_match('/(\\/|\\\\|^)([^\\/\\\\]+)?php([^\\/\\\\]+)?$/',
246                       $this->config->get('php_bin'), $matches)) {
247            if (isset($matches[2]) && strlen($matches[2]) &&
248                trim($matches[2]) != trim($this->config->get('php_prefix'))) {
249                $this->log(0, 'WARNING: php_bin ' . $this->config->get('php_bin') .
250                           ' appears to have a prefix ' . $matches[2] . ', but' .
251                           ' config variable php_prefix does not match');
252            }
253
254            if (isset($matches[3]) && strlen($matches[3]) &&
255                trim($matches[3]) != trim($this->config->get('php_suffix'))) {
256                $this->log(0, 'WARNING: php_bin ' . $this->config->get('php_bin') .
257                           ' appears to have a suffix ' . $matches[3] . ', but' .
258                           ' config variable php_suffix does not match');
259            }
260        }
261
262        $this->current_callback = $callback;
263        if (PEAR_OS == "Windows") {
264            return $this->_build_win32($descfile, $callback);
265        }
266
267        if (PEAR_OS != 'Unix') {
268            return $this->raiseError("building extensions not supported on this platform");
269        }
270
271        if (is_object($descfile)) {
272            $pkg = $descfile;
273            $descfile = $pkg->getPackageFile();
274            if (is_a($pkg, 'PEAR_PackageFile_v1')) {
275                $dir = dirname($descfile);
276            } else {
277                $dir = $pkg->_config->get('temp_dir') . '/' . $pkg->getName();
278                // automatically delete at session end
279                self::addTempFile($dir);
280            }
281        } else {
282            $pf = new PEAR_PackageFile($this->config);
283            $pkg = &$pf->fromPackageFile($descfile, PEAR_VALIDATE_NORMAL);
284            if (PEAR::isError($pkg)) {
285                return $pkg;
286            }
287            $dir = dirname($descfile);
288        }
289
290        // Find config. outside of normal path - e.g. config.m4
291        foreach (array_keys($pkg->getInstallationFileList()) as $item) {
292          if (stristr(basename($item), 'config.m4') && dirname($item) != '.') {
293            $dir .= DIRECTORY_SEPARATOR . dirname($item);
294            break;
295          }
296        }
297
298        $old_cwd = getcwd();
299        if (!file_exists($dir) || !is_dir($dir) || !chdir($dir)) {
300            return $this->raiseError("could not chdir to $dir");
301        }
302
303        $vdir = $pkg->getPackage() . '-' . $pkg->getVersion();
304        if (is_dir($vdir)) {
305            chdir($vdir);
306        }
307
308        $dir = getcwd();
309        $this->log(2, "building in $dir");
310        if (!preg_match('@(^|:)' . $this->config->get('bin_dir') . '(:|$)@', getenv('PATH'))) {
311            putenv('PATH=' . $this->config->get('bin_dir') . ':' . getenv('PATH'));
312        }
313        $err = $this->_runCommand($this->config->get('php_prefix')
314                                . "phpize" .
315                                $this->config->get('php_suffix'),
316                                array(&$this, 'phpizeCallback'));
317        if (PEAR::isError($err)) {
318            return $err;
319        }
320
321        if (!$err) {
322            return $this->raiseError("`phpize' failed");
323        }
324
325        // {{{ start of interactive part
326        $configure_command = "$dir/configure";
327
328        $phpConfigName = $this->config->get('php_prefix')
329            . 'php-config'
330            . $this->config->get('php_suffix');
331        $phpConfigPath = System::which($phpConfigName);
332        if ($phpConfigPath !== false) {
333            $configure_command .= ' --with-php-config='
334                . $phpConfigPath;
335        }
336
337        $configure_options = $pkg->getConfigureOptions();
338        if ($configure_options) {
339            foreach ($configure_options as $o) {
340                $default = array_key_exists('default', $o) ? $o['default'] : null;
341                list($r) = $this->ui->userDialog('build',
342                                                 array($o['prompt']),
343                                                 array('text'),
344                                                 array($default));
345                if (substr($o['name'], 0, 5) == 'with-' &&
346                    ($r == 'yes' || $r == 'autodetect')) {
347                    $configure_command .= " --$o[name]";
348                } else {
349                    $configure_command .= " --$o[name]=".trim($r);
350                }
351            }
352        }
353        // }}} end of interactive part
354
355        // FIXME make configurable
356        if (!$user=getenv('USER')) {
357            $user='defaultuser';
358        }
359
360        $tmpdir = $this->config->get('temp_dir');
361        $build_basedir = System::mktemp(' -t "' . $tmpdir . '" -d "pear-build-' . $user . '"');
362        $build_dir = "$build_basedir/$vdir";
363        $inst_dir = "$build_basedir/install-$vdir";
364        $this->log(1, "building in $build_dir");
365        if (is_dir($build_dir)) {
366            System::rm(array('-rf', $build_dir));
367        }
368
369        if (!System::mkDir(array('-p', $build_dir))) {
370            return $this->raiseError("could not create build dir: $build_dir");
371        }
372
373        self::addTempFile($build_dir);
374        if (!System::mkDir(array('-p', $inst_dir))) {
375            return $this->raiseError("could not create temporary install dir: $inst_dir");
376        }
377        self::addTempFile($inst_dir);
378
379        $make_command = getenv('MAKE') ? getenv('MAKE') : 'make';
380
381        $to_run = array(
382            $configure_command,
383            $make_command,
384            "$make_command INSTALL_ROOT=\"$inst_dir\" install",
385            "find \"$inst_dir\" | xargs ls -dils"
386            );
387        if (!file_exists($build_dir) || !is_dir($build_dir) || !chdir($build_dir)) {
388            return $this->raiseError("could not chdir to $build_dir");
389        }
390        putenv('PHP_PEAR_VERSION=@PEAR-VER@');
391        foreach ($to_run as $cmd) {
392            $err = $this->_runCommand($cmd, $callback);
393            if (PEAR::isError($err)) {
394                chdir($old_cwd);
395                return $err;
396            }
397            if (!$err) {
398                chdir($old_cwd);
399                return $this->raiseError("`$cmd' failed");
400            }
401        }
402        if (!($dp = opendir("modules"))) {
403            chdir($old_cwd);
404            return $this->raiseError("no `modules' directory found");
405        }
406        $built_files = array();
407        $prefix = exec($this->config->get('php_prefix')
408                        . "php-config" .
409                       $this->config->get('php_suffix') . " --prefix");
410        $this->_harvestInstDir($prefix, $inst_dir . DIRECTORY_SEPARATOR . $prefix, $built_files);
411        chdir($old_cwd);
412        return $built_files;
413    }
414
415    /**
416     * Message callback function used when running the "phpize"
417     * program.  Extracts the API numbers used.  Ignores other message
418     * types than "cmdoutput".
419     *
420     * @param string $what the type of message
421     * @param mixed $data the message
422     *
423     * @return void
424     *
425     * @access public
426     */
427    function phpizeCallback($what, $data)
428    {
429        if ($what != 'cmdoutput') {
430            return;
431        }
432        $this->log(1, rtrim($data));
433        if (preg_match('/You should update your .aclocal.m4/', $data)) {
434            return;
435        }
436        $matches = array();
437        if (preg_match('/^\s+(\S[^:]+):\s+(\d{8})/', $data, $matches)) {
438            $member = preg_replace('/[^a-z]/', '_', strtolower($matches[1]));
439            $apino = (int)$matches[2];
440            if (isset($this->$member)) {
441                $this->$member = $apino;
442                //$msg = sprintf("%-22s : %d", $matches[1], $apino);
443                //$this->log(1, $msg);
444            }
445        }
446    }
447
448    /**
449     * Run an external command, using a message callback to report
450     * output.  The command will be run through popen and output is
451     * reported for every line with a "cmdoutput" message with the
452     * line string, including newlines, as payload.
453     *
454     * @param string $command the command to run
455     *
456     * @param mixed $callback (optional) function to use as message
457     * callback
458     *
459     * @return bool whether the command was successful (exit code 0
460     * means success, any other means failure)
461     *
462     * @access private
463     */
464    function _runCommand($command, $callback = null)
465    {
466        $this->log(1, "running: $command");
467        $pp = popen("$command 2>&1", "r");
468        if (!$pp) {
469            return $this->raiseError("failed to run `$command'");
470        }
471        if ($callback && $callback[0]->debug == 1) {
472            $olddbg = $callback[0]->debug;
473            $callback[0]->debug = 2;
474        }
475
476        while ($line = fgets($pp, 1024)) {
477            if ($callback) {
478                call_user_func($callback, 'cmdoutput', $line);
479            } else {
480                $this->log(2, rtrim($line));
481            }
482        }
483        if ($callback && isset($olddbg)) {
484            $callback[0]->debug = $olddbg;
485        }
486
487        $exitcode = is_resource($pp) ? pclose($pp) : -1;
488        return ($exitcode == 0);
489    }
490
491    function log($level, $msg, $append_crlf = true)
492    {
493        if ($this->current_callback) {
494            if ($this->debug >= $level) {
495                call_user_func($this->current_callback, 'output', $msg);
496            }
497            return;
498        }
499        return parent::log($level, $msg, $append_crlf);
500    }
501}
502