summaryrefslogtreecommitdiff
path: root/src/HTTP_POST_multipart.php
blob: daeffcdfeb1720d9545e39ebc85aabd6aafff0dd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
<?php

#
# $Id$
#
# forum-list bridge 
# Copyright (C) 2010 Joel Uckelman
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

define('EOL', "\r\n");

class HTTP_POST_multipart {

  protected $_parts = array();

  public function addData($name, $data) {
    if ($name === null) throw new Exception('name is null');
    if ($data === null) throw new Exception('data is null');

    $this->_parts[] = array(
      'name' => $name,
      'data' => $data
    );
  }

  public function addFile($name, $filename, $mimetype,
                          $charset, $encoding, $data) {
    if ($name     === null) throw new Exception('name is null');
    if ($filename === null) throw new Exception('filename is null');
    if ($mimetype === null) throw new Exception('mimetype is null');
    if ($data     === null) throw new Exception('data is null');

    $this->_parts[] = array(
      'name'     => $name,
      'filename' => $filename,
      'mimetype' => $mimetype,
      'charset'  => $charset,
      'encoding' => $encoding,
      'data'     => $data
    );
  }

  protected static function buildDataPart($part) {
    return 'Content-Disposition: form-data; name="' . $part['name'] . '"' .
           EOL . EOL . $part['data'] . EOL;
  }

  protected static function buildFilePart($part) {
    # build Content-Disposition
    $p = 'Content-Disposition: form-data; name="' . $part['name'] . '"; ' .
           'filename="' . $part['filename'] . '"' . EOL;

    # build Content-Type
    $p .= 'Content-Type: ' . $part['mimetype'];
    if ($part['charset'] !== null) {
      $p .= '; charset="' . $part['charset'] . '"';
    }
    $p .= EOL;
   
    # build Content-Transfer-Encoding
    $data = null;

    if ($part['encoding'] !== null) {
      $p .= 'Content-Transfer-Encoding: ' . $part['encoding'] . EOL;

      switch ($part['encoding']) {
      case 'binary':
        $data = $part['data'];
        break;
      case 'base64':
        $data = chunk_split(base64_encode($part['data']));
        break;
      default:
        throw new Exception('unrecognized encoding: ' . $part['encoding']);
      }
    }
    else {
      $data = $part['data'];
    }

    # build data
    $p .= EOL . $data . EOL;

    return $p;
  }

  protected static function buildBoundary($postParts) {
    # This isn't guaranteed to terminate, but it's unlikely
    # to need more than one iteration on any real input.
    while (1) {
      $boundary = "---------------------------" .
                  base_convert(mt_rand(), 10, 36) .
                  base_convert(mt_rand(), 10, 36) .
                  base_convert(mt_rand(), 10, 36);

      foreach ($postParts as $part) {
        if (strpos($part, $boundary) !== false) {
          # the boundary already occurs in this part, try a new boundary
          continue 2;
        }
      }

      # boundary occurs in no part, use it
      return $boundary;
    }
  }

  protected static function buildPost($parts) {
    $postParts = array();

    foreach ($parts as $part) {
      if (array_key_exists('filename', $part)) {
        # this is a file part
        $postParts[] = self::buildFilePart($part);
      }
      else {
        # this is a simple data part
        $postParts[] = self::buildDataPart($part); 
      }
    }

    $boundary = self::buildBoundary($postParts);
  
    # put it all together 
    $bd = '--' . $boundary . EOL;  
    $final_bd = '--' . $boundary . '--' . EOL;

    return array($boundary, $bd . implode($bd, $postParts) . $final_bd);
  }

  public function dump() {
    list(/* skip */, $content) = self::buildPost($this->_parts);
    return $content;
  }

  public function post($url, $headers = array()) {
    list($boundary, $content) = self::buildPost($this->_parts);
    $ctype = 'Content-Type: multipart/form-data; boundary="' . $boundary . '"';

    $header = implode($headers, EOL) . $ctype . EOL;

    $ctx = stream_context_create(
      array('http' => 
        array(
          'method'  => 'POST',
          'header'  => $header,
          'content' => $content
        )
      )
    );

    return file_get_contents($url, false, $ctx);
  }
}

?>