29341cc6f6986bfded151c7f34a73b7339b52b2b
[pharext/pharext] / src / pharext / Task / Activate.php
1 <?php
2
3 namespace pharext\Task;
4
5 use pharext\Exception;
6 use pharext\ExecCmd;
7 use pharext\Task;
8 use pharext\Tempfile;
9
10 /**
11 * PHP INI activation
12 */
13 class Activate implements Task
14 {
15 /**
16 * @var string
17 */
18 private $cwd;
19
20 /**
21 * @var array
22 */
23 private $inis;
24
25 /**
26 * @var string
27 */
28 private $sudo;
29
30 /**
31 * @param string $cwd working directory
32 * @param array $inis custom INI or list of loaded/scanned INI files
33 * @param string $sudo sudo command
34 * @throws \pharext\Exception
35 */
36 public function __construct($cwd, array $inis, $sudo = null) {
37 $this->cwd = $cwd;
38 $this->sudo = $sudo;
39 if (!$this->inis = $inis) {
40 throw new Exception("No PHP INIs given");
41 }
42 }
43
44 /**
45 * @param bool $verbose
46 * @return boolean false, if extension was already activated
47 */
48 public function run($verbose = false) {
49 $extension = basename(current(glob("{$this->cwd}/modules/*.so")));
50 $pattern = preg_quote($extension);
51
52 foreach ($this->inis as $file) {
53 $temp = new Tempfile("phpini");
54 foreach (file($file) as $line) {
55 if (preg_match("/^\s*extension\s*=\s*[\"']?{$pattern}[\"']?\s*(;.*)?\$/", $line)) {
56 return false;
57 }
58 fwrite($temp->getStream(), $line);
59 }
60 }
61
62 /* not found; append to last processed file, which is the main by default */
63 fprintf($temp->getStream(), "extension=%s\n", $extension);
64 $temp->closeStream();
65
66 $path = $temp->getPathname();
67 $stat = stat($file);
68
69 // owner transfer
70 $ugid = sprintf("%d:%d", $stat["uid"], $stat["gid"]);
71 $cmd = new ExecCmd("chown", $verbose);
72 if (isset($this->sudo)) {
73 $cmd->setSu($this->sudo);
74 }
75 $cmd->run([$ugid, $path]);
76
77 // permission transfer
78 $perm = decoct($stat["mode"] & 0777);
79 $cmd = new ExecCmd("chmod", $verbose);
80 if (isset($this->sudo)) {
81 $cmd->setSu($this->sudo);
82 }
83 $cmd->run([$perm, $path]);
84
85 // rename
86 $cmd = new ExecCmd("mv", $verbose);
87 if (isset($this->sudo)) {
88 $cmd->setSu($this->sudo);
89 }
90 $cmd->run([$path, $file]);
91
92 return true;
93 }
94 }