1<?php
2/////////////////////////////////////////////////////////////////
3/// getID3() by James Heinrich <info@getid3.org>               //
4//  available at http://getid3.sourceforge.net                 //
5//            or http://www.getid3.org                         //
6//          also https://github.com/JamesHeinrich/getID3       //
7/////////////////////////////////////////////////////////////////
8// See readme.txt for more details                             //
9/////////////////////////////////////////////////////////////////
10///                                                            //
11// write.id3v2.php                                             //
12// module for writing ID3v2 tags                               //
13// dependencies: module.tag.id3v2.php                          //
14//                                                            ///
15/////////////////////////////////////////////////////////////////
16
17getid3_lib::IncludeDependency(GETID3_INCLUDEPATH.'module.tag.id3v2.php', __FILE__, true);
18
19class getid3_write_id3v2
20{
21	public $filename;
22	public $tag_data;
23	public $fread_buffer_size           = 32768;    // read buffer size in bytes
24	public $paddedlength                = 4096;     // minimum length of ID3v2 tag in bytes
25	public $majorversion                = 3;        // ID3v2 major version (2, 3 (recommended), 4)
26	public $minorversion                = 0;        // ID3v2 minor version - always 0
27	public $merge_existing_data         = false;    // if true, merge new data with existing tags; if false, delete old tag data and only write new tags
28	public $id3v2_default_encodingid    = 0;        // default text encoding (ISO-8859-1) if not explicitly passed
29	public $id3v2_use_unsynchronisation = false;    // the specs say it should be TRUE, but most other ID3v2-aware programs are broken if unsynchronization is used, so by default don't use it.
30	public $warnings                    = array();  // any non-critical errors will be stored here
31	public $errors                      = array();  // any critical errors will be stored here
32
33	public function __construct() {
34		return true;
35	}
36
37	public function WriteID3v2() {
38		// File MUST be writeable - CHMOD(646) at least. It's best if the
39		// directory is also writeable, because that method is both faster and less susceptible to errors.
40
41		if (!empty($this->filename) && (is_writeable($this->filename) || (!file_exists($this->filename) && is_writeable(dirname($this->filename))))) {
42			// Initialize getID3 engine
43			$getID3 = new getID3;
44			$OldThisFileInfo = $getID3->analyze($this->filename);
45			if (!getid3_lib::intValueSupported($OldThisFileInfo['filesize'])) {
46				$this->errors[] = 'Unable to write ID3v2 because file is larger than '.round(PHP_INT_MAX / 1073741824).'GB';
47				fclose($fp_source);
48				return false;
49			}
50			if ($this->merge_existing_data) {
51				// merge with existing data
52				if (!empty($OldThisFileInfo['id3v2'])) {
53					$this->tag_data = $this->array_join_merge($OldThisFileInfo['id3v2'], $this->tag_data);
54				}
55			}
56			$this->paddedlength = (isset($OldThisFileInfo['id3v2']['headerlength']) ? max($OldThisFileInfo['id3v2']['headerlength'], $this->paddedlength) : $this->paddedlength);
57
58			if ($NewID3v2Tag = $this->GenerateID3v2Tag()) {
59
60				if (file_exists($this->filename) && is_writeable($this->filename) && isset($OldThisFileInfo['id3v2']['headerlength']) && ($OldThisFileInfo['id3v2']['headerlength'] == strlen($NewID3v2Tag))) {
61
62					// best and fastest method - insert-overwrite existing tag (padded to length of old tag if neccesary)
63					if (file_exists($this->filename)) {
64
65						if (is_readable($this->filename) && is_writable($this->filename) && is_file($this->filename) && ($fp = fopen($this->filename, 'r+b'))) {
66							rewind($fp);
67							fwrite($fp, $NewID3v2Tag, strlen($NewID3v2Tag));
68							fclose($fp);
69						} else {
70							$this->errors[] = 'Could not fopen("'.$this->filename.'", "r+b")';
71						}
72
73					} else {
74
75						if (is_writable($this->filename) && is_file($this->filename) && ($fp = fopen($this->filename, 'wb'))) {
76							rewind($fp);
77							fwrite($fp, $NewID3v2Tag, strlen($NewID3v2Tag));
78							fclose($fp);
79						} else {
80							$this->errors[] = 'Could not fopen("'.$this->filename.'", "wb")';
81						}
82
83					}
84
85				} else {
86
87					if ($tempfilename = tempnam(GETID3_TEMP_DIR, 'getID3')) {
88						if (is_readable($this->filename) && is_file($this->filename) && ($fp_source = fopen($this->filename, 'rb'))) {
89							if (is_writable($tempfilename) && is_file($tempfilename) && ($fp_temp = fopen($tempfilename, 'wb'))) {
90
91								fwrite($fp_temp, $NewID3v2Tag, strlen($NewID3v2Tag));
92
93								rewind($fp_source);
94								if (!empty($OldThisFileInfo['avdataoffset'])) {
95									fseek($fp_source, $OldThisFileInfo['avdataoffset']);
96								}
97
98								while ($buffer = fread($fp_source, $this->fread_buffer_size)) {
99									fwrite($fp_temp, $buffer, strlen($buffer));
100								}
101
102								fclose($fp_temp);
103								fclose($fp_source);
104								copy($tempfilename, $this->filename);
105								unlink($tempfilename);
106								return true;
107
108							} else {
109								$this->errors[] = 'Could not fopen("'.$tempfilename.'", "wb")';
110							}
111							fclose($fp_source);
112
113						} else {
114							$this->errors[] = 'Could not fopen("'.$this->filename.'", "rb")';
115						}
116					}
117					return false;
118
119				}
120
121			} else {
122
123				$this->errors[] = '$this->GenerateID3v2Tag() failed';
124
125			}
126
127			if (!empty($this->errors)) {
128				return false;
129			}
130			return true;
131		} else {
132			$this->errors[] = 'WriteID3v2() failed: !is_writeable('.$this->filename.')';
133		}
134		return false;
135	}
136
137	public function RemoveID3v2() {
138		// File MUST be writeable - CHMOD(646) at least. It's best if the
139		// directory is also writeable, because that method is both faster and less susceptible to errors.
140		if (is_writeable(dirname($this->filename))) {
141
142			// preferred method - only one copying operation, minimal chance of corrupting
143			// original file if script is interrupted, but required directory to be writeable
144			if (is_readable($this->filename) && is_file($this->filename) && ($fp_source = fopen($this->filename, 'rb'))) {
145
146				// Initialize getID3 engine
147				$getID3 = new getID3;
148				$OldThisFileInfo = $getID3->analyze($this->filename);
149				if (!getid3_lib::intValueSupported($OldThisFileInfo['filesize'])) {
150					$this->errors[] = 'Unable to remove ID3v2 because file is larger than '.round(PHP_INT_MAX / 1073741824).'GB';
151					fclose($fp_source);
152					return false;
153				}
154				rewind($fp_source);
155				if ($OldThisFileInfo['avdataoffset'] !== false) {
156					fseek($fp_source, $OldThisFileInfo['avdataoffset']);
157				}
158				if (is_writable($this->filename) && is_file($this->filename) && ($fp_temp = fopen($this->filename.'getid3tmp', 'w+b'))) {
159					while ($buffer = fread($fp_source, $this->fread_buffer_size)) {
160						fwrite($fp_temp, $buffer, strlen($buffer));
161					}
162					fclose($fp_temp);
163				} else {
164					$this->errors[] = 'Could not fopen("'.$this->filename.'getid3tmp", "w+b")';
165				}
166				fclose($fp_source);
167			} else {
168				$this->errors[] = 'Could not fopen("'.$this->filename.'", "rb")';
169			}
170			if (file_exists($this->filename)) {
171				unlink($this->filename);
172			}
173			rename($this->filename.'getid3tmp', $this->filename);
174
175		} elseif (is_writable($this->filename)) {
176
177			// less desirable alternate method - double-copies the file, overwrites original file
178			// and could corrupt source file if the script is interrupted or an error occurs.
179			if (is_readable($this->filename) && is_file($this->filename) && ($fp_source = fopen($this->filename, 'rb'))) {
180
181				// Initialize getID3 engine
182				$getID3 = new getID3;
183				$OldThisFileInfo = $getID3->analyze($this->filename);
184				if (!getid3_lib::intValueSupported($OldThisFileInfo['filesize'])) {
185					$this->errors[] = 'Unable to remove ID3v2 because file is larger than '.round(PHP_INT_MAX / 1073741824).'GB';
186					fclose($fp_source);
187					return false;
188				}
189				rewind($fp_source);
190				if ($OldThisFileInfo['avdataoffset'] !== false) {
191					fseek($fp_source, $OldThisFileInfo['avdataoffset']);
192				}
193				if ($fp_temp = tmpfile()) {
194					while ($buffer = fread($fp_source, $this->fread_buffer_size)) {
195						fwrite($fp_temp, $buffer, strlen($buffer));
196					}
197					fclose($fp_source);
198					if (is_writable($this->filename) && is_file($this->filename) && ($fp_source = fopen($this->filename, 'wb'))) {
199						rewind($fp_temp);
200						while ($buffer = fread($fp_temp, $this->fread_buffer_size)) {
201							fwrite($fp_source, $buffer, strlen($buffer));
202						}
203						fseek($fp_temp, -128, SEEK_END);
204						fclose($fp_source);
205					} else {
206						$this->errors[] = 'Could not fopen("'.$this->filename.'", "wb")';
207					}
208					fclose($fp_temp);
209				} else {
210					$this->errors[] = 'Could not create tmpfile()';
211				}
212			} else {
213				$this->errors[] = 'Could not fopen("'.$this->filename.'", "rb")';
214			}
215
216		} else {
217
218			$this->errors[] = 'Directory and file both not writeable';
219
220		}
221
222		if (!empty($this->errors)) {
223			return false;
224		}
225		return true;
226	}
227
228
229	public function GenerateID3v2TagFlags($flags) {
230		switch ($this->majorversion) {
231			case 4:
232				// %abcd0000
233				$flag  = (!empty($flags['unsynchronisation']) ? '1' : '0'); // a - Unsynchronisation
234				$flag .= (!empty($flags['extendedheader']   ) ? '1' : '0'); // b - Extended header
235				$flag .= (!empty($flags['experimental']     ) ? '1' : '0'); // c - Experimental indicator
236				$flag .= (!empty($flags['footer']           ) ? '1' : '0'); // d - Footer present
237				$flag .= '0000';
238				break;
239
240			case 3:
241				// %abc00000
242				$flag  = (!empty($flags['unsynchronisation']) ? '1' : '0'); // a - Unsynchronisation
243				$flag .= (!empty($flags['extendedheader']   ) ? '1' : '0'); // b - Extended header
244				$flag .= (!empty($flags['experimental']     ) ? '1' : '0'); // c - Experimental indicator
245				$flag .= '00000';
246				break;
247
248			case 2:
249				// %ab000000
250				$flag  = (!empty($flags['unsynchronisation']) ? '1' : '0'); // a - Unsynchronisation
251				$flag .= (!empty($flags['compression']      ) ? '1' : '0'); // b - Compression
252				$flag .= '000000';
253				break;
254
255			default:
256				return false;
257				break;
258		}
259		return chr(bindec($flag));
260	}
261
262
263	public function GenerateID3v2FrameFlags($TagAlter=false, $FileAlter=false, $ReadOnly=false, $Compression=false, $Encryption=false, $GroupingIdentity=false, $Unsynchronisation=false, $DataLengthIndicator=false) {
264		switch ($this->majorversion) {
265			case 4:
266				// %0abc0000 %0h00kmnp
267				$flag1  = '0';
268				$flag1 .= $TagAlter  ? '1' : '0'; // a - Tag alter preservation (true == discard)
269				$flag1 .= $FileAlter ? '1' : '0'; // b - File alter preservation (true == discard)
270				$flag1 .= $ReadOnly  ? '1' : '0'; // c - Read only (true == read only)
271				$flag1 .= '0000';
272
273				$flag2  = '0';
274				$flag2 .= $GroupingIdentity    ? '1' : '0'; // h - Grouping identity (true == contains group information)
275				$flag2 .= '00';
276				$flag2 .= $Compression         ? '1' : '0'; // k - Compression (true == compressed)
277				$flag2 .= $Encryption          ? '1' : '0'; // m - Encryption (true == encrypted)
278				$flag2 .= $Unsynchronisation   ? '1' : '0'; // n - Unsynchronisation (true == unsynchronised)
279				$flag2 .= $DataLengthIndicator ? '1' : '0'; // p - Data length indicator (true == data length indicator added)
280				break;
281
282			case 3:
283				// %abc00000 %ijk00000
284				$flag1  = $TagAlter  ? '1' : '0';  // a - Tag alter preservation (true == discard)
285				$flag1 .= $FileAlter ? '1' : '0';  // b - File alter preservation (true == discard)
286				$flag1 .= $ReadOnly  ? '1' : '0';  // c - Read only (true == read only)
287				$flag1 .= '00000';
288
289				$flag2  = $Compression      ? '1' : '0';      // i - Compression (true == compressed)
290				$flag2 .= $Encryption       ? '1' : '0';      // j - Encryption (true == encrypted)
291				$flag2 .= $GroupingIdentity ? '1' : '0';      // k - Grouping identity (true == contains group information)
292				$flag2 .= '00000';
293				break;
294
295			default:
296				return false;
297				break;
298
299		}
300		return chr(bindec($flag1)).chr(bindec($flag2));
301	}
302
303	public function GenerateID3v2FrameData($frame_name, $source_data_array) {
304		if (!getid3_id3v2::IsValidID3v2FrameName($frame_name, $this->majorversion)) {
305			return false;
306		}
307		$framedata = '';
308
309		if (($this->majorversion < 3) || ($this->majorversion > 4)) {
310
311			$this->errors[] = 'Only ID3v2.3 and ID3v2.4 are supported in GenerateID3v2FrameData()';
312
313		} else { // $this->majorversion 3 or 4
314
315			switch ($frame_name) {
316				case 'UFID':
317					// 4.1   UFID Unique file identifier
318					// Owner identifier        <text string> $00
319					// Identifier              <up to 64 bytes binary data>
320					if (strlen($source_data_array['data']) > 64) {
321						$this->errors[] = 'Identifier not allowed to be longer than 64 bytes in '.$frame_name.' (supplied data was '.strlen($source_data_array['data']).' bytes long)';
322					} else {
323						$framedata .= str_replace("\x00", '', $source_data_array['ownerid'])."\x00";
324						$framedata .= substr($source_data_array['data'], 0, 64); // max 64 bytes - truncate anything longer
325					}
326					break;
327
328				case 'TXXX':
329					// 4.2.2 TXXX User defined text information frame
330					// Text encoding     $xx
331					// Description       <text string according to encoding> $00 (00)
332					// Value             <text string according to encoding>
333					$source_data_array['encodingid'] = (isset($source_data_array['encodingid']) ? $source_data_array['encodingid'] : $this->id3v2_default_encodingid);
334					if (!$this->ID3v2IsValidTextEncoding($source_data_array['encodingid'], $this->majorversion)) {
335						$this->errors[] = 'Invalid Text Encoding in '.$frame_name.' ('.$source_data_array['encodingid'].') for ID3v2.'.$this->majorversion;
336					} else {
337						$framedata .= chr($source_data_array['encodingid']);
338						$framedata .= $source_data_array['description'].getid3_id3v2::TextEncodingTerminatorLookup($source_data_array['encodingid']);
339						$framedata .= $source_data_array['data'];
340					}
341					break;
342
343				case 'WXXX':
344					// 4.3.2 WXXX User defined URL link frame
345					// Text encoding     $xx
346					// Description       <text string according to encoding> $00 (00)
347					// URL               <text string>
348					$source_data_array['encodingid'] = (isset($source_data_array['encodingid']) ? $source_data_array['encodingid'] : $this->id3v2_default_encodingid);
349					if (!$this->ID3v2IsValidTextEncoding($source_data_array['encodingid'], $this->majorversion)) {
350						$this->errors[] = 'Invalid Text Encoding in '.$frame_name.' ('.$source_data_array['encodingid'].') for ID3v2.'.$this->majorversion;
351					} elseif (!isset($source_data_array['data']) || !$this->IsValidURL($source_data_array['data'], false, false)) {
352						//$this->errors[] = 'Invalid URL in '.$frame_name.' ('.$source_data_array['data'].')';
353						// probably should be an error, need to rewrite IsValidURL() to handle other encodings
354						$this->warnings[] = 'Invalid URL in '.$frame_name.' ('.$source_data_array['data'].')';
355					} else {
356						$framedata .= chr($source_data_array['encodingid']);
357						$framedata .= $source_data_array['description'].getid3_id3v2::TextEncodingTerminatorLookup($source_data_array['encodingid']);
358						$framedata .= $source_data_array['data'];
359					}
360					break;
361
362				case 'IPLS':
363					// 4.4  IPLS Involved people list (ID3v2.3 only)
364					// Text encoding     $xx
365					// People list strings    <textstrings>
366					$source_data_array['encodingid'] = (isset($source_data_array['encodingid']) ? $source_data_array['encodingid'] : $this->id3v2_default_encodingid);
367					if (!$this->ID3v2IsValidTextEncoding($source_data_array['encodingid'], $this->majorversion)) {
368						$this->errors[] = 'Invalid Text Encoding in '.$frame_name.' ('.$source_data_array['encodingid'].') for ID3v2.'.$this->majorversion;
369					} else {
370						$framedata .= chr($source_data_array['encodingid']);
371						$framedata .= $source_data_array['data'];
372					}
373					break;
374
375				case 'MCDI':
376					// 4.4   MCDI Music CD identifier
377					// CD TOC                <binary data>
378					$framedata .= $source_data_array['data'];
379					break;
380
381				case 'ETCO':
382					// 4.5   ETCO Event timing codes
383					// Time stamp format    $xx
384					//   Where time stamp format is:
385					// $01  (32-bit value) MPEG frames from beginning of file
386					// $02  (32-bit value) milliseconds from beginning of file
387					//   Followed by a list of key events in the following format:
388					// Type of event   $xx
389					// Time stamp      $xx (xx ...)
390					//   The 'Time stamp' is set to zero if directly at the beginning of the sound
391					//   or after the previous event. All events MUST be sorted in chronological order.
392					if (($source_data_array['timestampformat'] > 2) || ($source_data_array['timestampformat'] < 1)) {
393						$this->errors[] = 'Invalid Time Stamp Format byte in '.$frame_name.' ('.$source_data_array['timestampformat'].')';
394					} else {
395						$framedata .= chr($source_data_array['timestampformat']);
396						foreach ($source_data_array as $key => $val) {
397							if (!$this->ID3v2IsValidETCOevent($val['typeid'])) {
398								$this->errors[] = 'Invalid Event Type byte in '.$frame_name.' ('.$val['typeid'].')';
399							} elseif (($key != 'timestampformat') && ($key != 'flags')) {
400								if (($val['timestamp'] > 0) && ($previousETCOtimestamp >= $val['timestamp'])) {
401									//   The 'Time stamp' is set to zero if directly at the beginning of the sound
402									//   or after the previous event. All events MUST be sorted in chronological order.
403									$this->errors[] = 'Out-of-order timestamp in '.$frame_name.' ('.$val['timestamp'].') for Event Type ('.$val['typeid'].')';
404								} else {
405									$framedata .= chr($val['typeid']);
406									$framedata .= getid3_lib::BigEndian2String($val['timestamp'], 4, false);
407								}
408							}
409						}
410					}
411					break;
412
413				case 'MLLT':
414					// 4.6   MLLT MPEG location lookup table
415					// MPEG frames between reference  $xx xx
416					// Bytes between reference        $xx xx xx
417					// Milliseconds between reference $xx xx xx
418					// Bits for bytes deviation       $xx
419					// Bits for milliseconds dev.     $xx
420					//   Then for every reference the following data is included;
421					// Deviation in bytes         %xxx....
422					// Deviation in milliseconds  %xxx....
423					if (($source_data_array['framesbetweenreferences'] > 0) && ($source_data_array['framesbetweenreferences'] <= 65535)) {
424						$framedata .= getid3_lib::BigEndian2String($source_data_array['framesbetweenreferences'], 2, false);
425					} else {
426						$this->errors[] = 'Invalid MPEG Frames Between References in '.$frame_name.' ('.$source_data_array['framesbetweenreferences'].')';
427					}
428					if (($source_data_array['bytesbetweenreferences'] > 0) && ($source_data_array['bytesbetweenreferences'] <= 16777215)) {
429						$framedata .= getid3_lib::BigEndian2String($source_data_array['bytesbetweenreferences'], 3, false);
430					} else {
431						$this->errors[] = 'Invalid bytes Between References in '.$frame_name.' ('.$source_data_array['bytesbetweenreferences'].')';
432					}
433					if (($source_data_array['msbetweenreferences'] > 0) && ($source_data_array['msbetweenreferences'] <= 16777215)) {
434						$framedata .= getid3_lib::BigEndian2String($source_data_array['msbetweenreferences'], 3, false);
435					} else {
436						$this->errors[] = 'Invalid Milliseconds Between References in '.$frame_name.' ('.$source_data_array['msbetweenreferences'].')';
437					}
438					if (!$this->IsWithinBitRange($source_data_array['bitsforbytesdeviation'], 8, false)) {
439						if (($source_data_array['bitsforbytesdeviation'] % 4) == 0) {
440							$framedata .= chr($source_data_array['bitsforbytesdeviation']);
441						} else {
442							$this->errors[] = 'Bits For Bytes Deviation in '.$frame_name.' ('.$source_data_array['bitsforbytesdeviation'].') must be a multiple of 4.';
443						}
444					} else {
445						$this->errors[] = 'Invalid Bits For Bytes Deviation in '.$frame_name.' ('.$source_data_array['bitsforbytesdeviation'].')';
446					}
447					if (!$this->IsWithinBitRange($source_data_array['bitsformsdeviation'], 8, false)) {
448						if (($source_data_array['bitsformsdeviation'] % 4) == 0) {
449							$framedata .= chr($source_data_array['bitsformsdeviation']);
450						} else {
451							$this->errors[] = 'Bits For Milliseconds Deviation in '.$frame_name.' ('.$source_data_array['bitsforbytesdeviation'].') must be a multiple of 4.';
452						}
453					} else {
454						$this->errors[] = 'Invalid Bits For Milliseconds Deviation in '.$frame_name.' ('.$source_data_array['bitsformsdeviation'].')';
455					}
456					foreach ($source_data_array as $key => $val) {
457						if (($key != 'framesbetweenreferences') && ($key != 'bytesbetweenreferences') && ($key != 'msbetweenreferences') && ($key != 'bitsforbytesdeviation') && ($key != 'bitsformsdeviation') && ($key != 'flags')) {
458							$unwrittenbitstream .= str_pad(getid3_lib::Dec2Bin($val['bytedeviation']), $source_data_array['bitsforbytesdeviation'], '0', STR_PAD_LEFT);
459							$unwrittenbitstream .= str_pad(getid3_lib::Dec2Bin($val['msdeviation']),   $source_data_array['bitsformsdeviation'],    '0', STR_PAD_LEFT);
460						}
461					}
462					for ($i = 0; $i < strlen($unwrittenbitstream); $i += 8) {
463						$highnibble = bindec(substr($unwrittenbitstream, $i, 4)) << 4;
464						$lownibble  = bindec(substr($unwrittenbitstream, $i + 4, 4));
465						$framedata .= chr($highnibble & $lownibble);
466					}
467					break;
468
469				case 'SYTC':
470					// 4.7   SYTC Synchronised tempo codes
471					// Time stamp format   $xx
472					// Tempo data          <binary data>
473					//   Where time stamp format is:
474					// $01  (32-bit value) MPEG frames from beginning of file
475					// $02  (32-bit value) milliseconds from beginning of file
476					if (($source_data_array['timestampformat'] > 2) || ($source_data_array['timestampformat'] < 1)) {
477						$this->errors[] = 'Invalid Time Stamp Format byte in '.$frame_name.' ('.$source_data_array['timestampformat'].')';
478					} else {
479						$framedata .= chr($source_data_array['timestampformat']);
480						foreach ($source_data_array as $key => $val) {
481							if (!$this->ID3v2IsValidETCOevent($val['typeid'])) {
482								$this->errors[] = 'Invalid Event Type byte in '.$frame_name.' ('.$val['typeid'].')';
483							} elseif (($key != 'timestampformat') && ($key != 'flags')) {
484								if (($val['tempo'] < 0) || ($val['tempo'] > 510)) {
485									$this->errors[] = 'Invalid Tempo (max = 510) in '.$frame_name.' ('.$val['tempo'].') at timestamp ('.$val['timestamp'].')';
486								} else {
487									if ($val['tempo'] > 255) {
488										$framedata .= chr(255);
489										$val['tempo'] -= 255;
490									}
491									$framedata .= chr($val['tempo']);
492									$framedata .= getid3_lib::BigEndian2String($val['timestamp'], 4, false);
493								}
494							}
495						}
496					}
497					break;
498
499				case 'USLT':
500					// 4.8   USLT Unsynchronised lyric/text transcription
501					// Text encoding        $xx
502					// Language             $xx xx xx
503					// Content descriptor   <text string according to encoding> $00 (00)
504					// Lyrics/text          <full text string according to encoding>
505					$source_data_array['encodingid'] = (isset($source_data_array['encodingid']) ? $source_data_array['encodingid'] : $this->id3v2_default_encodingid);
506					if (!$this->ID3v2IsValidTextEncoding($source_data_array['encodingid'])) {
507						$this->errors[] = 'Invalid Text Encoding in '.$frame_name.' ('.$source_data_array['encodingid'].') for ID3v2.'.$this->majorversion;
508					} elseif (getid3_id3v2::LanguageLookup($source_data_array['language'], true) == '') {
509						$this->errors[] = 'Invalid Language in '.$frame_name.' ('.$source_data_array['language'].')';
510					} else {
511						$framedata .= chr($source_data_array['encodingid']);
512						$framedata .= strtolower($source_data_array['language']);
513						$framedata .= $source_data_array['description'].getid3_id3v2::TextEncodingTerminatorLookup($source_data_array['encodingid']);
514						$framedata .= $source_data_array['data'];
515					}
516					break;
517
518				case 'SYLT':
519					// 4.9   SYLT Synchronised lyric/text
520					// Text encoding        $xx
521					// Language             $xx xx xx
522					// Time stamp format    $xx
523					//   $01  (32-bit value) MPEG frames from beginning of file
524					//   $02  (32-bit value) milliseconds from beginning of file
525					// Content type         $xx
526					// Content descriptor   <text string according to encoding> $00 (00)
527					//   Terminated text to be synced (typically a syllable)
528					//   Sync identifier (terminator to above string)   $00 (00)
529					//   Time stamp                                     $xx (xx ...)
530					$source_data_array['encodingid'] = (isset($source_data_array['encodingid']) ? $source_data_array['encodingid'] : $this->id3v2_default_encodingid);
531					if (!$this->ID3v2IsValidTextEncoding($source_data_array['encodingid'])) {
532						$this->errors[] = 'Invalid Text Encoding in '.$frame_name.' ('.$source_data_array['encodingid'].') for ID3v2.'.$this->majorversion;
533					} elseif (getid3_id3v2::LanguageLookup($source_data_array['language'], true) == '') {
534						$this->errors[] = 'Invalid Language in '.$frame_name.' ('.$source_data_array['language'].')';
535					} elseif (($source_data_array['timestampformat'] > 2) || ($source_data_array['timestampformat'] < 1)) {
536						$this->errors[] = 'Invalid Time Stamp Format byte in '.$frame_name.' ('.$source_data_array['timestampformat'].')';
537					} elseif (!$this->ID3v2IsValidSYLTtype($source_data_array['contenttypeid'])) {
538						$this->errors[] = 'Invalid Content Type byte in '.$frame_name.' ('.$source_data_array['contenttypeid'].')';
539					} elseif (!is_array($source_data_array['data'])) {
540						$this->errors[] = 'Invalid Lyric/Timestamp data in '.$frame_name.' (must be an array)';
541					} else {
542						$framedata .= chr($source_data_array['encodingid']);
543						$framedata .= strtolower($source_data_array['language']);
544						$framedata .= chr($source_data_array['timestampformat']);
545						$framedata .= chr($source_data_array['contenttypeid']);
546						$framedata .= $source_data_array['description'].getid3_id3v2::TextEncodingTerminatorLookup($source_data_array['encodingid']);
547						ksort($source_data_array['data']);
548						foreach ($source_data_array['data'] as $key => $val) {
549							$framedata .= $val['data'].getid3_id3v2::TextEncodingTerminatorLookup($source_data_array['encodingid']);
550							$framedata .= getid3_lib::BigEndian2String($val['timestamp'], 4, false);
551						}
552					}
553					break;
554
555				case 'COMM':
556					// 4.10  COMM Comments
557					// Text encoding          $xx
558					// Language               $xx xx xx
559					// Short content descrip. <text string according to encoding> $00 (00)
560					// The actual text        <full text string according to encoding>
561					$source_data_array['encodingid'] = (isset($source_data_array['encodingid']) ? $source_data_array['encodingid'] : $this->id3v2_default_encodingid);
562					if (!$this->ID3v2IsValidTextEncoding($source_data_array['encodingid'])) {
563						$this->errors[] = 'Invalid Text Encoding in '.$frame_name.' ('.$source_data_array['encodingid'].') for ID3v2.'.$this->majorversion;
564					} elseif (getid3_id3v2::LanguageLookup($source_data_array['language'], true) == '') {
565						$this->errors[] = 'Invalid Language in '.$frame_name.' ('.$source_data_array['language'].')';
566					} else {
567						$framedata .= chr($source_data_array['encodingid']);
568						$framedata .= strtolower($source_data_array['language']);
569						$framedata .= $source_data_array['description'].getid3_id3v2::TextEncodingTerminatorLookup($source_data_array['encodingid']);
570						$framedata .= $source_data_array['data'];
571					}
572					break;
573
574				case 'RVA2':
575					// 4.11  RVA2 Relative volume adjustment (2) (ID3v2.4+ only)
576					// Identification          <text string> $00
577					//   The 'identification' string is used to identify the situation and/or
578					//   device where this adjustment should apply. The following is then
579					//   repeated for every channel:
580					// Type of channel         $xx
581					// Volume adjustment       $xx xx
582					// Bits representing peak  $xx
583					// Peak volume             $xx (xx ...)
584					$framedata .= str_replace("\x00", '', $source_data_array['description'])."\x00";
585					foreach ($source_data_array as $key => $val) {
586						if ($key != 'description') {
587							$framedata .= chr($val['channeltypeid']);
588							$framedata .= getid3_lib::BigEndian2String($val['volumeadjust'], 2, false, true); // signed 16-bit
589							if (!$this->IsWithinBitRange($source_data_array['bitspeakvolume'], 8, false)) {
590								$framedata .= chr($val['bitspeakvolume']);
591								if ($val['bitspeakvolume'] > 0) {
592									$framedata .= getid3_lib::BigEndian2String($val['peakvolume'], ceil($val['bitspeakvolume'] / 8), false, false);
593								}
594							} else {
595								$this->errors[] = 'Invalid Bits Representing Peak Volume in '.$frame_name.' ('.$val['bitspeakvolume'].') (range = 0 to 255)';
596							}
597						}
598					}
599					break;
600
601				case 'RVAD':
602					// 4.12  RVAD Relative volume adjustment (ID3v2.3 only)
603					// Increment/decrement     %00fedcba
604					// Bits used for volume descr.        $xx
605					// Relative volume change, right      $xx xx (xx ...) // a
606					// Relative volume change, left       $xx xx (xx ...) // b
607					// Peak volume right                  $xx xx (xx ...)
608					// Peak volume left                   $xx xx (xx ...)
609					// Relative volume change, right back $xx xx (xx ...) // c
610					// Relative volume change, left back  $xx xx (xx ...) // d
611					// Peak volume right back             $xx xx (xx ...)
612					// Peak volume left back              $xx xx (xx ...)
613					// Relative volume change, center     $xx xx (xx ...) // e
614					// Peak volume center                 $xx xx (xx ...)
615					// Relative volume change, bass       $xx xx (xx ...) // f
616					// Peak volume bass                   $xx xx (xx ...)
617					if (!$this->IsWithinBitRange($source_data_array['bitsvolume'], 8, false)) {
618						$this->errors[] = 'Invalid Bits For Volume Description byte in '.$frame_name.' ('.$source_data_array['bitsvolume'].') (range = 1 to 255)';
619					} else {
620						$incdecflag .= '00';
621						$incdecflag .= $source_data_array['incdec']['right']     ? '1' : '0';     // a - Relative volume change, right
622						$incdecflag .= $source_data_array['incdec']['left']      ? '1' : '0';      // b - Relative volume change, left
623						$incdecflag .= $source_data_array['incdec']['rightrear'] ? '1' : '0'; // c - Relative volume change, right back
624						$incdecflag .= $source_data_array['incdec']['leftrear']  ? '1' : '0';  // d - Relative volume change, left back
625						$incdecflag .= $source_data_array['incdec']['center']    ? '1' : '0';    // e - Relative volume change, center
626						$incdecflag .= $source_data_array['incdec']['bass']      ? '1' : '0';      // f - Relative volume change, bass
627						$framedata .= chr(bindec($incdecflag));
628						$framedata .= chr($source_data_array['bitsvolume']);
629						$framedata .= getid3_lib::BigEndian2String($source_data_array['volumechange']['right'], ceil($source_data_array['bitsvolume'] / 8), false);
630						$framedata .= getid3_lib::BigEndian2String($source_data_array['volumechange']['left'],  ceil($source_data_array['bitsvolume'] / 8), false);
631						$framedata .= getid3_lib::BigEndian2String($source_data_array['peakvolume']['right'], ceil($source_data_array['bitsvolume'] / 8), false);
632						$framedata .= getid3_lib::BigEndian2String($source_data_array['peakvolume']['left'],  ceil($source_data_array['bitsvolume'] / 8), false);
633						if ($source_data_array['volumechange']['rightrear'] || $source_data_array['volumechange']['leftrear'] ||
634							$source_data_array['peakvolume']['rightrear'] || $source_data_array['peakvolume']['leftrear'] ||
635							$source_data_array['volumechange']['center'] || $source_data_array['peakvolume']['center'] ||
636							$source_data_array['volumechange']['bass'] || $source_data_array['peakvolume']['bass']) {
637								$framedata .= getid3_lib::BigEndian2String($source_data_array['volumechange']['rightrear'], ceil($source_data_array['bitsvolume']/8), false);
638								$framedata .= getid3_lib::BigEndian2String($source_data_array['volumechange']['leftrear'],  ceil($source_data_array['bitsvolume']/8), false);
639								$framedata .= getid3_lib::BigEndian2String($source_data_array['peakvolume']['rightrear'], ceil($source_data_array['bitsvolume']/8), false);
640								$framedata .= getid3_lib::BigEndian2String($source_data_array['peakvolume']['leftrear'],  ceil($source_data_array['bitsvolume']/8), false);
641						}
642						if ($source_data_array['volumechange']['center'] || $source_data_array['peakvolume']['center'] ||
643							$source_data_array['volumechange']['bass'] || $source_data_array['peakvolume']['bass']) {
644								$framedata .= getid3_lib::BigEndian2String($source_data_array['volumechange']['center'], ceil($source_data_array['bitsvolume']/8), false);
645								$framedata .= getid3_lib::BigEndian2String($source_data_array['peakvolume']['center'], ceil($source_data_array['bitsvolume']/8), false);
646						}
647						if ($source_data_array['volumechange']['bass'] || $source_data_array['peakvolume']['bass']) {
648								$framedata .= getid3_lib::BigEndian2String($source_data_array['volumechange']['bass'], ceil($source_data_array['bitsvolume']/8), false);
649								$framedata .= getid3_lib::BigEndian2String($source_data_array['peakvolume']['bass'], ceil($source_data_array['bitsvolume']/8), false);
650						}
651					}
652					break;
653
654				case 'EQU2':
655					// 4.12  EQU2 Equalisation (2) (ID3v2.4+ only)
656					// Interpolation method  $xx
657					//   $00  Band
658					//   $01  Linear
659					// Identification        <text string> $00
660					//   The following is then repeated for every adjustment point
661					// Frequency          $xx xx
662					// Volume adjustment  $xx xx
663					if (($source_data_array['interpolationmethod'] < 0) || ($source_data_array['interpolationmethod'] > 1)) {
664						$this->errors[] = 'Invalid Interpolation Method byte in '.$frame_name.' ('.$source_data_array['interpolationmethod'].') (valid = 0 or 1)';
665					} else {
666						$framedata .= chr($source_data_array['interpolationmethod']);
667						$framedata .= str_replace("\x00", '', $source_data_array['description'])."\x00";
668						foreach ($source_data_array['data'] as $key => $val) {
669							$framedata .= getid3_lib::BigEndian2String(intval(round($key * 2)), 2, false);
670							$framedata .= getid3_lib::BigEndian2String($val, 2, false, true); // signed 16-bit
671						}
672					}
673					break;
674
675				case 'EQUA':
676					// 4.12  EQUA Equalisation (ID3v2.3 only)
677					// Adjustment bits    $xx
678					//   This is followed by 2 bytes + ('adjustment bits' rounded up to the
679					//   nearest byte) for every equalisation band in the following format,
680					//   giving a frequency range of 0 - 32767Hz:
681					// Increment/decrement   %x (MSB of the Frequency)
682					// Frequency             (lower 15 bits)
683					// Adjustment            $xx (xx ...)
684					if (!$this->IsWithinBitRange($source_data_array['bitsvolume'], 8, false)) {
685						$this->errors[] = 'Invalid Adjustment Bits byte in '.$frame_name.' ('.$source_data_array['bitsvolume'].') (range = 1 to 255)';
686					} else {
687						$framedata .= chr($source_data_array['adjustmentbits']);
688						foreach ($source_data_array as $key => $val) {
689							if ($key != 'bitsvolume') {
690								if (($key > 32767) || ($key < 0)) {
691									$this->errors[] = 'Invalid Frequency in '.$frame_name.' ('.$key.') (range = 0 to 32767)';
692								} else {
693									if ($val >= 0) {
694										// put MSB of frequency to 1 if increment, 0 if decrement
695										$key |= 0x8000;
696									}
697									$framedata .= getid3_lib::BigEndian2String($key, 2, false);
698									$framedata .= getid3_lib::BigEndian2String($val, ceil($source_data_array['adjustmentbits'] / 8), false);
699								}
700							}
701						}
702					}
703					break;
704
705				case 'RVRB':
706					// 4.13  RVRB Reverb
707					// Reverb left (ms)                 $xx xx
708					// Reverb right (ms)                $xx xx
709					// Reverb bounces, left             $xx
710					// Reverb bounces, right            $xx
711					// Reverb feedback, left to left    $xx
712					// Reverb feedback, left to right   $xx
713					// Reverb feedback, right to right  $xx
714					// Reverb feedback, right to left   $xx
715					// Premix left to right             $xx
716					// Premix right to left             $xx
717					if (!$this->IsWithinBitRange($source_data_array['left'], 16, false)) {
718						$this->errors[] = 'Invalid Reverb Left in '.$frame_name.' ('.$source_data_array['left'].') (range = 0 to 65535)';
719					} elseif (!$this->IsWithinBitRange($source_data_array['right'], 16, false)) {
720						$this->errors[] = 'Invalid Reverb Left in '.$frame_name.' ('.$source_data_array['right'].') (range = 0 to 65535)';
721					} elseif (!$this->IsWithinBitRange($source_data_array['bouncesL'], 8, false)) {
722						$this->errors[] = 'Invalid Reverb Bounces, Left in '.$frame_name.' ('.$source_data_array['bouncesL'].') (range = 0 to 255)';
723					} elseif (!$this->IsWithinBitRange($source_data_array['bouncesR'], 8, false)) {
724						$this->errors[] = 'Invalid Reverb Bounces, Right in '.$frame_name.' ('.$source_data_array['bouncesR'].') (range = 0 to 255)';
725					} elseif (!$this->IsWithinBitRange($source_data_array['feedbackLL'], 8, false)) {
726						$this->errors[] = 'Invalid Reverb Feedback, Left-To-Left in '.$frame_name.' ('.$source_data_array['feedbackLL'].') (range = 0 to 255)';
727					} elseif (!$this->IsWithinBitRange($source_data_array['feedbackLR'], 8, false)) {
728						$this->errors[] = 'Invalid Reverb Feedback, Left-To-Right in '.$frame_name.' ('.$source_data_array['feedbackLR'].') (range = 0 to 255)';
729					} elseif (!$this->IsWithinBitRange($source_data_array['feedbackRR'], 8, false)) {
730						$this->errors[] = 'Invalid Reverb Feedback, Right-To-Right in '.$frame_name.' ('.$source_data_array['feedbackRR'].') (range = 0 to 255)';
731					} elseif (!$this->IsWithinBitRange($source_data_array['feedbackRL'], 8, false)) {
732						$this->errors[] = 'Invalid Reverb Feedback, Right-To-Left in '.$frame_name.' ('.$source_data_array['feedbackRL'].') (range = 0 to 255)';
733					} elseif (!$this->IsWithinBitRange($source_data_array['premixLR'], 8, false)) {
734						$this->errors[] = 'Invalid Premix, Left-To-Right in '.$frame_name.' ('.$source_data_array['premixLR'].') (range = 0 to 255)';
735					} elseif (!$this->IsWithinBitRange($source_data_array['premixRL'], 8, false)) {
736						$this->errors[] = 'Invalid Premix, Right-To-Left in '.$frame_name.' ('.$source_data_array['premixRL'].') (range = 0 to 255)';
737					} else {
738						$framedata .= getid3_lib::BigEndian2String($source_data_array['left'], 2, false);
739						$framedata .= getid3_lib::BigEndian2String($source_data_array['right'], 2, false);
740						$framedata .= chr($source_data_array['bouncesL']);
741						$framedata .= chr($source_data_array['bouncesR']);
742						$framedata .= chr($source_data_array['feedbackLL']);
743						$framedata .= chr($source_data_array['feedbackLR']);
744						$framedata .= chr($source_data_array['feedbackRR']);
745						$framedata .= chr($source_data_array['feedbackRL']);
746						$framedata .= chr($source_data_array['premixLR']);
747						$framedata .= chr($source_data_array['premixRL']);
748					}
749					break;
750
751				case 'APIC':
752					// 4.14  APIC Attached picture
753					// Text encoding      $xx
754					// MIME type          <text string> $00
755					// Picture type       $xx
756					// Description        <text string according to encoding> $00 (00)
757					// Picture data       <binary data>
758					$source_data_array['encodingid'] = (isset($source_data_array['encodingid']) ? $source_data_array['encodingid'] : $this->id3v2_default_encodingid);
759					if (!$this->ID3v2IsValidTextEncoding($source_data_array['encodingid'])) {
760						$this->errors[] = 'Invalid Text Encoding in '.$frame_name.' ('.$source_data_array['encodingid'].') for ID3v2.'.$this->majorversion;
761					} elseif (!$this->ID3v2IsValidAPICpicturetype($source_data_array['picturetypeid'])) {
762						$this->errors[] = 'Invalid Picture Type byte in '.$frame_name.' ('.$source_data_array['picturetypeid'].') for ID3v2.'.$this->majorversion;
763					} elseif (($this->majorversion >= 3) && (!$this->ID3v2IsValidAPICimageformat($source_data_array['mime']))) {
764						$this->errors[] = 'Invalid MIME Type in '.$frame_name.' ('.$source_data_array['mime'].') for ID3v2.'.$this->majorversion;
765					} elseif (($source_data_array['mime'] == '-->') && (!$this->IsValidURL($source_data_array['data'], false, false))) {
766						//$this->errors[] = 'Invalid URL in '.$frame_name.' ('.$source_data_array['data'].')';
767						// probably should be an error, need to rewrite IsValidURL() to handle other encodings
768						$this->warnings[] = 'Invalid URL in '.$frame_name.' ('.$source_data_array['data'].')';
769					} else {
770						$framedata .= chr($source_data_array['encodingid']);
771						$framedata .= str_replace("\x00", '', $source_data_array['mime'])."\x00";
772						$framedata .= chr($source_data_array['picturetypeid']);
773						$framedata .= (!empty($source_data_array['description']) ? $source_data_array['description'] : '').getid3_id3v2::TextEncodingTerminatorLookup($source_data_array['encodingid']);
774						$framedata .= $source_data_array['data'];
775					}
776					break;
777
778				case 'GEOB':
779					// 4.15  GEOB General encapsulated object
780					// Text encoding          $xx
781					// MIME type              <text string> $00
782					// Filename               <text string according to encoding> $00 (00)
783					// Content description    <text string according to encoding> $00 (00)
784					// Encapsulated object    <binary data>
785					$source_data_array['encodingid'] = (isset($source_data_array['encodingid']) ? $source_data_array['encodingid'] : $this->id3v2_default_encodingid);
786					if (!$this->ID3v2IsValidTextEncoding($source_data_array['encodingid'])) {
787						$this->errors[] = 'Invalid Text Encoding in '.$frame_name.' ('.$source_data_array['encodingid'].') for ID3v2.'.$this->majorversion;
788					} elseif (!$this->IsValidMIMEstring($source_data_array['mime'])) {
789						$this->errors[] = 'Invalid MIME Type in '.$frame_name.' ('.$source_data_array['mime'].')';
790					} elseif (!$source_data_array['description']) {
791						$this->errors[] = 'Missing Description in '.$frame_name;
792					} else {
793						$framedata .= chr($source_data_array['encodingid']);
794						$framedata .= str_replace("\x00", '', $source_data_array['mime'])."\x00";
795						$framedata .= $source_data_array['filename'].getid3_id3v2::TextEncodingTerminatorLookup($source_data_array['encodingid']);
796						$framedata .= $source_data_array['description'].getid3_id3v2::TextEncodingTerminatorLookup($source_data_array['encodingid']);
797						$framedata .= $source_data_array['data'];
798					}
799					break;
800
801				case 'PCNT':
802					// 4.16  PCNT Play counter
803					//   When the counter reaches all one's, one byte is inserted in
804					//   front of the counter thus making the counter eight bits bigger
805					// Counter        $xx xx xx xx (xx ...)
806					$framedata .= getid3_lib::BigEndian2String($source_data_array['data'], 4, false);
807					break;
808
809				case 'POPM':
810					// 4.17  POPM Popularimeter
811					//   When the counter reaches all one's, one byte is inserted in
812					//   front of the counter thus making the counter eight bits bigger
813					// Email to user   <text string> $00
814					// Rating          $xx
815					// Counter         $xx xx xx xx (xx ...)
816					if (!$this->IsWithinBitRange($source_data_array['rating'], 8, false)) {
817						$this->errors[] = 'Invalid Rating byte in '.$frame_name.' ('.$source_data_array['rating'].') (range = 0 to 255)';
818					} elseif (!$this->IsValidEmail($source_data_array['email'])) {
819						$this->errors[] = 'Invalid Email in '.$frame_name.' ('.$source_data_array['email'].')';
820					} else {
821						$framedata .= str_replace("\x00", '', $source_data_array['email'])."\x00";
822						$framedata .= chr($source_data_array['rating']);
823						$framedata .= getid3_lib::BigEndian2String($source_data_array['data'], 4, false);
824					}
825					break;
826
827				case 'RBUF':
828					// 4.18  RBUF Recommended buffer size
829					// Buffer size               $xx xx xx
830					// Embedded info flag        %0000000x
831					// Offset to next tag        $xx xx xx xx
832					if (!$this->IsWithinBitRange($source_data_array['buffersize'], 24, false)) {
833						$this->errors[] = 'Invalid Buffer Size in '.$frame_name;
834					} elseif (!$this->IsWithinBitRange($source_data_array['nexttagoffset'], 32, false)) {
835						$this->errors[] = 'Invalid Offset To Next Tag in '.$frame_name;
836					} else {
837						$framedata .= getid3_lib::BigEndian2String($source_data_array['buffersize'], 3, false);
838						$flag .= '0000000';
839						$flag .= $source_data_array['flags']['embededinfo'] ? '1' : '0';
840						$framedata .= chr(bindec($flag));
841						$framedata .= getid3_lib::BigEndian2String($source_data_array['nexttagoffset'], 4, false);
842					}
843					break;
844
845				case 'AENC':
846					// 4.19  AENC Audio encryption
847					// Owner identifier   <text string> $00
848					// Preview start      $xx xx
849					// Preview length     $xx xx
850					// Encryption info    <binary data>
851					if (!$this->IsWithinBitRange($source_data_array['previewstart'], 16, false)) {
852						$this->errors[] = 'Invalid Preview Start in '.$frame_name.' ('.$source_data_array['previewstart'].')';
853					} elseif (!$this->IsWithinBitRange($source_data_array['previewlength'], 16, false)) {
854						$this->errors[] = 'Invalid Preview Length in '.$frame_name.' ('.$source_data_array['previewlength'].')';
855					} else {
856						$framedata .= str_replace("\x00", '', $source_data_array['ownerid'])."\x00";
857						$framedata .= getid3_lib::BigEndian2String($source_data_array['previewstart'], 2, false);
858						$framedata .= getid3_lib::BigEndian2String($source_data_array['previewlength'], 2, false);
859						$framedata .= $source_data_array['encryptioninfo'];
860					}
861					break;
862
863				case 'LINK':
864					// 4.20  LINK Linked information
865					// Frame identifier               $xx xx xx xx
866					// URL                            <text string> $00
867					// ID and additional data         <text string(s)>
868					if (!getid3_id3v2::IsValidID3v2FrameName($source_data_array['frameid'], $this->majorversion)) {
869						$this->errors[] = 'Invalid Frame Identifier in '.$frame_name.' ('.$source_data_array['frameid'].')';
870					} elseif (!$this->IsValidURL($source_data_array['data'], true, false)) {
871						//$this->errors[] = 'Invalid URL in '.$frame_name.' ('.$source_data_array['data'].')';
872						// probably should be an error, need to rewrite IsValidURL() to handle other encodings
873						$this->warnings[] = 'Invalid URL in '.$frame_name.' ('.$source_data_array['data'].')';
874					} elseif ((($source_data_array['frameid'] == 'AENC') || ($source_data_array['frameid'] == 'APIC') || ($source_data_array['frameid'] == 'GEOB') || ($source_data_array['frameid'] == 'TXXX')) && ($source_data_array['additionaldata'] == '')) {
875						$this->errors[] = 'Content Descriptor must be specified as additional data for Frame Identifier of '.$source_data_array['frameid'].' in '.$frame_name;
876					} elseif (($source_data_array['frameid'] == 'USER') && (getid3_id3v2::LanguageLookup($source_data_array['additionaldata'], true) == '')) {
877						$this->errors[] = 'Language must be specified as additional data for Frame Identifier of '.$source_data_array['frameid'].' in '.$frame_name;
878					} elseif (($source_data_array['frameid'] == 'PRIV') && ($source_data_array['additionaldata'] == '')) {
879						$this->errors[] = 'Owner Identifier must be specified as additional data for Frame Identifier of '.$source_data_array['frameid'].' in '.$frame_name;
880					} elseif ((($source_data_array['frameid'] == 'COMM') || ($source_data_array['frameid'] == 'SYLT') || ($source_data_array['frameid'] == 'USLT')) && ((getid3_id3v2::LanguageLookup(substr($source_data_array['additionaldata'], 0, 3), true) == '') || (substr($source_data_array['additionaldata'], 3) == ''))) {
881						$this->errors[] = 'Language followed by Content Descriptor must be specified as additional data for Frame Identifier of '.$source_data_array['frameid'].' in '.$frame_name;
882					} else {
883						$framedata .= $source_data_array['frameid'];
884						$framedata .= str_replace("\x00", '', $source_data_array['data'])."\x00";
885						switch ($source_data_array['frameid']) {
886							case 'COMM':
887							case 'SYLT':
888							case 'USLT':
889							case 'PRIV':
890							case 'USER':
891							case 'AENC':
892							case 'APIC':
893							case 'GEOB':
894							case 'TXXX':
895								$framedata .= $source_data_array['additionaldata'];
896								break;
897							case 'ASPI':
898							case 'ETCO':
899							case 'EQU2':
900							case 'MCID':
901							case 'MLLT':
902							case 'OWNE':
903							case 'RVA2':
904							case 'RVRB':
905							case 'SYTC':
906							case 'IPLS':
907							case 'RVAD':
908							case 'EQUA':
909								// no additional data required
910								break;
911							case 'RBUF':
912								if ($this->majorversion == 3) {
913									// no additional data required
914								} else {
915									$this->errors[] = $source_data_array['frameid'].' is not a valid Frame Identifier in '.$frame_name.' (in ID3v2.'.$this->majorversion.')';
916								}
917
918							default:
919								if ((substr($source_data_array['frameid'], 0, 1) == 'T') || (substr($source_data_array['frameid'], 0, 1) == 'W')) {
920									// no additional data required
921								} else {
922									$this->errors[] = $source_data_array['frameid'].' is not a valid Frame Identifier in '.$frame_name.' (in ID3v2.'.$this->majorversion.')';
923								}
924								break;
925						}
926					}
927					break;
928
929				case 'POSS':
930					// 4.21  POSS Position synchronisation frame (ID3v2.3+ only)
931					// Time stamp format         $xx
932					// Position                  $xx (xx ...)
933					if (($source_data_array['timestampformat'] < 1) || ($source_data_array['timestampformat'] > 2)) {
934						$this->errors[] = 'Invalid Time Stamp Format in '.$frame_name.' ('.$source_data_array['timestampformat'].') (valid = 1 or 2)';
935					} elseif (!$this->IsWithinBitRange($source_data_array['position'], 32, false)) {
936						$this->errors[] = 'Invalid Position in '.$frame_name.' ('.$source_data_array['position'].') (range = 0 to 4294967295)';
937					} else {
938						$framedata .= chr($source_data_array['timestampformat']);
939						$framedata .= getid3_lib::BigEndian2String($source_data_array['position'], 4, false);
940					}
941					break;
942
943				case 'USER':
944					// 4.22  USER Terms of use (ID3v2.3+ only)
945					// Text encoding        $xx
946					// Language             $xx xx xx
947					// The actual text      <text string according to encoding>
948					$source_data_array['encodingid'] = (isset($source_data_array['encodingid']) ? $source_data_array['encodingid'] : $this->id3v2_default_encodingid);
949					if (!$this->ID3v2IsValidTextEncoding($source_data_array['encodingid'])) {
950						$this->errors[] = 'Invalid Text Encoding in '.$frame_name.' ('.$source_data_array['encodingid'].')';
951					} elseif (getid3_id3v2::LanguageLookup($source_data_array['language'], true) == '') {
952						$this->errors[] = 'Invalid Language in '.$frame_name.' ('.$source_data_array['language'].')';
953					} else {
954						$framedata .= chr($source_data_array['encodingid']);
955						$framedata .= strtolower($source_data_array['language']);
956						$framedata .= $source_data_array['data'];
957					}
958					break;
959
960				case 'OWNE':
961					// 4.23  OWNE Ownership frame (ID3v2.3+ only)
962					// Text encoding     $xx
963					// Price paid        <text string> $00
964					// Date of purch.    <text string>
965					// Seller            <text string according to encoding>
966					$source_data_array['encodingid'] = (isset($source_data_array['encodingid']) ? $source_data_array['encodingid'] : $this->id3v2_default_encodingid);
967					if (!$this->ID3v2IsValidTextEncoding($source_data_array['encodingid'])) {
968						$this->errors[] = 'Invalid Text Encoding in '.$frame_name.' ('.$source_data_array['encodingid'].')';
969					} elseif (!$this->IsANumber($source_data_array['pricepaid']['value'], false)) {
970						$this->errors[] = 'Invalid Price Paid in '.$frame_name.' ('.$source_data_array['pricepaid']['value'].')';
971					} elseif (!$this->IsValidDateStampString($source_data_array['purchasedate'])) {
972						$this->errors[] = 'Invalid Date Of Purchase in '.$frame_name.' ('.$source_data_array['purchasedate'].') (format = YYYYMMDD)';
973					} else {
974						$framedata .= chr($source_data_array['encodingid']);
975						$framedata .= str_replace("\x00", '', $source_data_array['pricepaid']['value'])."\x00";
976						$framedata .= $source_data_array['purchasedate'];
977						$framedata .= $source_data_array['seller'];
978					}
979					break;
980
981				case 'COMR':
982					// 4.24  COMR Commercial frame (ID3v2.3+ only)
983					// Text encoding      $xx
984					// Price string       <text string> $00
985					// Valid until        <text string>
986					// Contact URL        <text string> $00
987					// Received as        $xx
988					// Name of seller     <text string according to encoding> $00 (00)
989					// Description        <text string according to encoding> $00 (00)
990					// Picture MIME type  <string> $00
991					// Seller logo        <binary data>
992					$source_data_array['encodingid'] = (isset($source_data_array['encodingid']) ? $source_data_array['encodingid'] : $this->id3v2_default_encodingid);
993					if (!$this->ID3v2IsValidTextEncoding($source_data_array['encodingid'])) {
994						$this->errors[] = 'Invalid Text Encoding in '.$frame_name.' ('.$source_data_array['encodingid'].')';
995					} elseif (!$this->IsValidDateStampString($source_data_array['pricevaliduntil'])) {
996						$this->errors[] = 'Invalid Valid Until date in '.$frame_name.' ('.$source_data_array['pricevaliduntil'].') (format = YYYYMMDD)';
997					} elseif (!$this->IsValidURL($source_data_array['contacturl'], false, true)) {
998						$this->errors[] = 'Invalid Contact URL in '.$frame_name.' ('.$source_data_array['contacturl'].') (allowed schemes: http, https, ftp, mailto)';
999					} elseif (!$this->ID3v2IsValidCOMRreceivedAs($source_data_array['receivedasid'])) {
1000						$this->errors[] = 'Invalid Received As byte in '.$frame_name.' ('.$source_data_array['contacturl'].') (range = 0 to 8)';
1001					} elseif (!$this->IsValidMIMEstring($source_data_array['mime'])) {
1002						$this->errors[] = 'Invalid MIME Type in '.$frame_name.' ('.$source_data_array['mime'].')';
1003					} else {
1004						$framedata .= chr($source_data_array['encodingid']);
1005						unset($pricestring);
1006						foreach ($source_data_array['price'] as $key => $val) {
1007							if ($this->ID3v2IsValidPriceString($key.$val['value'])) {
1008								$pricestrings[] = $key.$val['value'];
1009							} else {
1010								$this->errors[] = 'Invalid Price String in '.$frame_name.' ('.$key.$val['value'].')';
1011							}
1012						}
1013						$framedata .= implode('/', $pricestrings);
1014						$framedata .= $source_data_array['pricevaliduntil'];
1015						$framedata .= str_replace("\x00", '', $source_data_array['contacturl'])."\x00";
1016						$framedata .= chr($source_data_array['receivedasid']);
1017						$framedata .= $source_data_array['sellername'].getid3_id3v2::TextEncodingTerminatorLookup($source_data_array['encodingid']);
1018						$framedata .= $source_data_array['description'].getid3_id3v2::TextEncodingTerminatorLookup($source_data_array['encodingid']);
1019						$framedata .= $source_data_array['mime']."\x00";
1020						$framedata .= $source_data_array['logo'];
1021					}
1022					break;
1023
1024				case 'ENCR':
1025					// 4.25  ENCR Encryption method registration (ID3v2.3+ only)
1026					// Owner identifier    <text string> $00
1027					// Method symbol       $xx
1028					// Encryption data     <binary data>
1029					if (!$this->IsWithinBitRange($source_data_array['methodsymbol'], 8, false)) {
1030						$this->errors[] = 'Invalid Group Symbol in '.$frame_name.' ('.$source_data_array['methodsymbol'].') (range = 0 to 255)';
1031					} else {
1032						$framedata .= str_replace("\x00", '', $source_data_array['ownerid'])."\x00";
1033						$framedata .= ord($source_data_array['methodsymbol']);
1034						$framedata .= $source_data_array['data'];
1035					}
1036					break;
1037
1038				case 'GRID':
1039					// 4.26  GRID Group identification registration (ID3v2.3+ only)
1040					// Owner identifier      <text string> $00
1041					// Group symbol          $xx
1042					// Group dependent data  <binary data>
1043					if (!$this->IsWithinBitRange($source_data_array['groupsymbol'], 8, false)) {
1044						$this->errors[] = 'Invalid Group Symbol in '.$frame_name.' ('.$source_data_array['groupsymbol'].') (range = 0 to 255)';
1045					} else {
1046						$framedata .= str_replace("\x00", '', $source_data_array['ownerid'])."\x00";
1047						$framedata .= ord($source_data_array['groupsymbol']);
1048						$framedata .= $source_data_array['data'];
1049					}
1050					break;
1051
1052				case 'PRIV':
1053					// 4.27  PRIV Private frame (ID3v2.3+ only)
1054					// Owner identifier      <text string> $00
1055					// The private data      <binary data>
1056					$framedata .= str_replace("\x00", '', $source_data_array['ownerid'])."\x00";
1057					$framedata .= $source_data_array['data'];
1058					break;
1059
1060				case 'SIGN':
1061					// 4.28  SIGN Signature frame (ID3v2.4+ only)
1062					// Group symbol      $xx
1063					// Signature         <binary data>
1064					if (!$this->IsWithinBitRange($source_data_array['groupsymbol'], 8, false)) {
1065						$this->errors[] = 'Invalid Group Symbol in '.$frame_name.' ('.$source_data_array['groupsymbol'].') (range = 0 to 255)';
1066					} else {
1067						$framedata .= ord($source_data_array['groupsymbol']);
1068						$framedata .= $source_data_array['data'];
1069					}
1070					break;
1071
1072				case 'SEEK':
1073					// 4.29  SEEK Seek frame (ID3v2.4+ only)
1074					// Minimum offset to next tag       $xx xx xx xx
1075					if (!$this->IsWithinBitRange($source_data_array['data'], 32, false)) {
1076						$this->errors[] = 'Invalid Minimum Offset in '.$frame_name.' ('.$source_data_array['data'].') (range = 0 to 4294967295)';
1077					} else {
1078						$framedata .= getid3_lib::BigEndian2String($source_data_array['data'], 4, false);
1079					}
1080					break;
1081
1082				case 'ASPI':
1083					// 4.30  ASPI Audio seek point index (ID3v2.4+ only)
1084					// Indexed data start (S)         $xx xx xx xx
1085					// Indexed data length (L)        $xx xx xx xx
1086					// Number of index points (N)     $xx xx
1087					// Bits per index point (b)       $xx
1088					//   Then for every index point the following data is included:
1089					// Fraction at index (Fi)          $xx (xx)
1090					if (!$this->IsWithinBitRange($source_data_array['datastart'], 32, false)) {
1091						$this->errors[] = 'Invalid Indexed Data Start in '.$frame_name.' ('.$source_data_array['datastart'].') (range = 0 to 4294967295)';
1092					} elseif (!$this->IsWithinBitRange($source_data_array['datalength'], 32, false)) {
1093						$this->errors[] = 'Invalid Indexed Data Length in '.$frame_name.' ('.$source_data_array['datalength'].') (range = 0 to 4294967295)';
1094					} elseif (!$this->IsWithinBitRange($source_data_array['indexpoints'], 16, false)) {
1095						$this->errors[] = 'Invalid Number Of Index Points in '.$frame_name.' ('.$source_data_array['indexpoints'].') (range = 0 to 65535)';
1096					} elseif (!$this->IsWithinBitRange($source_data_array['bitsperpoint'], 8, false)) {
1097						$this->errors[] = 'Invalid Bits Per Index Point in '.$frame_name.' ('.$source_data_array['bitsperpoint'].') (range = 0 to 255)';
1098					} elseif ($source_data_array['indexpoints'] != count($source_data_array['indexes'])) {
1099						$this->errors[] = 'Number Of Index Points does not match actual supplied data in '.$frame_name;
1100					} else {
1101						$framedata .= getid3_lib::BigEndian2String($source_data_array['datastart'], 4, false);
1102						$framedata .= getid3_lib::BigEndian2String($source_data_array['datalength'], 4, false);
1103						$framedata .= getid3_lib::BigEndian2String($source_data_array['indexpoints'], 2, false);
1104						$framedata .= getid3_lib::BigEndian2String($source_data_array['bitsperpoint'], 1, false);
1105						foreach ($source_data_array['indexes'] as $key => $val) {
1106							$framedata .= getid3_lib::BigEndian2String($val, ceil($source_data_array['bitsperpoint'] / 8), false);
1107						}
1108					}
1109					break;
1110
1111				case 'RGAD':
1112					//   RGAD Replay Gain Adjustment
1113					//   http://privatewww.essex.ac.uk/~djmrob/replaygain/
1114					// Peak Amplitude                     $xx $xx $xx $xx
1115					// Radio Replay Gain Adjustment        %aaabbbcd %dddddddd
1116					// Audiophile Replay Gain Adjustment   %aaabbbcd %dddddddd
1117					//   a - name code
1118					//   b - originator code
1119					//   c - sign bit
1120					//   d - replay gain adjustment
1121
1122					if (($source_data_array['track_adjustment'] > 51) || ($source_data_array['track_adjustment'] < -51)) {
1123						$this->errors[] = 'Invalid Track Adjustment in '.$frame_name.' ('.$source_data_array['track_adjustment'].') (range = -51.0 to +51.0)';
1124					} elseif (($source_data_array['album_adjustment'] > 51) || ($source_data_array['album_adjustment'] < -51)) {
1125						$this->errors[] = 'Invalid Album Adjustment in '.$frame_name.' ('.$source_data_array['album_adjustment'].') (range = -51.0 to +51.0)';
1126					} elseif (!$this->ID3v2IsValidRGADname($source_data_array['raw']['track_name'])) {
1127						$this->errors[] = 'Invalid Track Name Code in '.$frame_name.' ('.$source_data_array['raw']['track_name'].') (range = 0 to 2)';
1128					} elseif (!$this->ID3v2IsValidRGADname($source_data_array['raw']['album_name'])) {
1129						$this->errors[] = 'Invalid Album Name Code in '.$frame_name.' ('.$source_data_array['raw']['album_name'].') (range = 0 to 2)';
1130					} elseif (!$this->ID3v2IsValidRGADoriginator($source_data_array['raw']['track_originator'])) {
1131						$this->errors[] = 'Invalid Track Originator Code in '.$frame_name.' ('.$source_data_array['raw']['track_originator'].') (range = 0 to 3)';
1132					} elseif (!$this->ID3v2IsValidRGADoriginator($source_data_array['raw']['album_originator'])) {
1133						$this->errors[] = 'Invalid Album Originator Code in '.$frame_name.' ('.$source_data_array['raw']['album_originator'].') (range = 0 to 3)';
1134					} else {
1135						$framedata .= getid3_lib::Float2String($source_data_array['peakamplitude'], 32);
1136						$framedata .= getid3_lib::RGADgainString($source_data_array['raw']['track_name'], $source_data_array['raw']['track_originator'], $source_data_array['track_adjustment']);
1137						$framedata .= getid3_lib::RGADgainString($source_data_array['raw']['album_name'], $source_data_array['raw']['album_originator'], $source_data_array['album_adjustment']);
1138					}
1139					break;
1140
1141				default:
1142					if ((($this->majorversion == 2) && (strlen($frame_name) != 3)) || (($this->majorversion > 2) && (strlen($frame_name) != 4))) {
1143						$this->errors[] = 'Invalid frame name "'.$frame_name.'" for ID3v2.'.$this->majorversion;
1144					} elseif ($frame_name{0} == 'T') {
1145						// 4.2. T???  Text information frames
1146						// Text encoding                $xx
1147						// Information                  <text string(s) according to encoding>
1148						$source_data_array['encodingid'] = (isset($source_data_array['encodingid']) ? $source_data_array['encodingid'] : $this->id3v2_default_encodingid);
1149						if (!$this->ID3v2IsValidTextEncoding($source_data_array['encodingid'])) {
1150							$this->errors[] = 'Invalid Text Encoding in '.$frame_name.' ('.$source_data_array['encodingid'].') for ID3v2.'.$this->majorversion;
1151						} else {
1152							$framedata .= chr($source_data_array['encodingid']);
1153							$framedata .= $source_data_array['data'];
1154						}
1155					} elseif ($frame_name{0} == 'W') {
1156						// 4.3. W???  URL link frames
1157						// URL              <text string>
1158						if (!$this->IsValidURL($source_data_array['data'], false, false)) {
1159							//$this->errors[] = 'Invalid URL in '.$frame_name.' ('.$source_data_array['data'].')';
1160							// probably should be an error, need to rewrite IsValidURL() to handle other encodings
1161							$this->warnings[] = 'Invalid URL in '.$frame_name.' ('.$source_data_array['data'].')';
1162						} else {
1163							$framedata .= $source_data_array['data'];
1164						}
1165					} else {
1166						$this->errors[] = $frame_name.' not yet supported in $this->GenerateID3v2FrameData()';
1167					}
1168					break;
1169			}
1170		}
1171		if (!empty($this->errors)) {
1172			return false;
1173		}
1174		return $framedata;
1175	}
1176
1177	public function ID3v2FrameIsAllowed($frame_name, $source_data_array) {
1178		static $PreviousFrames = array();
1179
1180		if ($frame_name === null) {
1181			// if the writing functions are called multiple times, the static array needs to be
1182			// cleared - this can be done by calling $this->ID3v2FrameIsAllowed(null, '')
1183			$PreviousFrames = array();
1184			return true;
1185		}
1186		if ($this->majorversion == 4) {
1187			switch ($frame_name) {
1188				case 'UFID':
1189				case 'AENC':
1190				case 'ENCR':
1191				case 'GRID':
1192					if (!isset($source_data_array['ownerid'])) {
1193						$this->errors[] = '[ownerid] not specified for '.$frame_name;
1194					} elseif (in_array($frame_name.$source_data_array['ownerid'], $PreviousFrames)) {
1195						$this->errors[] = 'Only one '.$frame_name.' tag allowed with the same OwnerID ('.$source_data_array['ownerid'].')';
1196					} else {
1197						$PreviousFrames[] = $frame_name.$source_data_array['ownerid'];
1198					}
1199					break;
1200
1201				case 'TXXX':
1202				case 'WXXX':
1203				case 'RVA2':
1204				case 'EQU2':
1205				case 'APIC':
1206				case 'GEOB':
1207					if (!isset($source_data_array['description'])) {
1208						$this->errors[] = '[description] not specified for '.$frame_name;
1209					} elseif (in_array($frame_name.$source_data_array['description'], $PreviousFrames)) {
1210						$this->errors[] = 'Only one '.$frame_name.' tag allowed with the same Description ('.$source_data_array['description'].')';
1211					} else {
1212						$PreviousFrames[] = $frame_name.$source_data_array['description'];
1213					}
1214					break;
1215
1216				case 'USER':
1217					if (!isset($source_data_array['language'])) {
1218						$this->errors[] = '[language] not specified for '.$frame_name;
1219					} elseif (in_array($frame_name.$source_data_array['language'], $PreviousFrames)) {
1220						$this->errors[] = 'Only one '.$frame_name.' tag allowed with the same Language ('.$source_data_array['language'].')';
1221					} else {
1222						$PreviousFrames[] = $frame_name.$source_data_array['language'];
1223					}
1224					break;
1225
1226				case 'USLT':
1227				case 'SYLT':
1228				case 'COMM':
1229					if (!isset($source_data_array['language'])) {
1230						$this->errors[] = '[language] not specified for '.$frame_name;
1231					} elseif (!isset($source_data_array['description'])) {
1232						$this->errors[] = '[description] not specified for '.$frame_name;
1233					} elseif (in_array($frame_name.$source_data_array['language'].$source_data_array['description'], $PreviousFrames)) {
1234						$this->errors[] = 'Only one '.$frame_name.' tag allowed with the same Language + Description ('.$source_data_array['language'].' + '.$source_data_array['description'].')';
1235					} else {
1236						$PreviousFrames[] = $frame_name.$source_data_array['language'].$source_data_array['description'];
1237					}
1238					break;
1239
1240				case 'POPM':
1241					if (!isset($source_data_array['email'])) {
1242						$this->errors[] = '[email] not specified for '.$frame_name;
1243					} elseif (in_array($frame_name.$source_data_array['email'], $PreviousFrames)) {
1244						$this->errors[] = 'Only one '.$frame_name.' tag allowed with the same Email ('.$source_data_array['email'].')';
1245					} else {
1246						$PreviousFrames[] = $frame_name.$source_data_array['email'];
1247					}
1248					break;
1249
1250				case 'IPLS':
1251				case 'MCDI':
1252				case 'ETCO':
1253				case 'MLLT':
1254				case 'SYTC':
1255				case 'RVRB':
1256				case 'PCNT':
1257				case 'RBUF':
1258				case 'POSS':
1259				case 'OWNE':
1260				case 'SEEK':
1261				case 'ASPI':
1262				case 'RGAD':
1263					if (in_array($frame_name, $PreviousFrames)) {
1264						$this->errors[] = 'Only one '.$frame_name.' tag allowed';
1265					} else {
1266						$PreviousFrames[] = $frame_name;
1267					}
1268					break;
1269
1270				case 'LINK':
1271					// this isn't implemented quite right (yet) - it should check the target frame data for compliance
1272					// but right now it just allows one linked frame of each type, to be safe.
1273					if (!isset($source_data_array['frameid'])) {
1274						$this->errors[] = '[frameid] not specified for '.$frame_name;
1275					} elseif (in_array($frame_name.$source_data_array['frameid'], $PreviousFrames)) {
1276						$this->errors[] = 'Only one '.$frame_name.' tag allowed with the same FrameID ('.$source_data_array['frameid'].')';
1277					} elseif (in_array($source_data_array['frameid'], $PreviousFrames)) {
1278						// no links to singleton tags
1279						$this->errors[] = 'Cannot specify a '.$frame_name.' tag to a singleton tag that already exists ('.$source_data_array['frameid'].')';
1280					} else {
1281						$PreviousFrames[] = $frame_name.$source_data_array['frameid']; // only one linked tag of this type
1282						$PreviousFrames[] = $source_data_array['frameid'];             // no non-linked singleton tags of this type
1283					}
1284					break;
1285
1286				case 'COMR':
1287					//   There may be more than one 'commercial frame' in a tag, but no two may be identical
1288					// Checking isn't implemented at all (yet) - just assumes that it's OK.
1289					break;
1290
1291				case 'PRIV':
1292				case 'SIGN':
1293					if (!isset($source_data_array['ownerid'])) {
1294						$this->errors[] = '[ownerid] not specified for '.$frame_name;
1295					} elseif (!isset($source_data_array['data'])) {
1296						$this->errors[] = '[data] not specified for '.$frame_name;
1297					} elseif (in_array($frame_name.$source_data_array['ownerid'].$source_data_array['data'], $PreviousFrames)) {
1298						$this->errors[] = 'Only one '.$frame_name.' tag allowed with the same OwnerID + Data ('.$source_data_array['ownerid'].' + '.$source_data_array['data'].')';
1299					} else {
1300						$PreviousFrames[] = $frame_name.$source_data_array['ownerid'].$source_data_array['data'];
1301					}
1302					break;
1303
1304				default:
1305					if (($frame_name{0} != 'T') && ($frame_name{0} != 'W')) {
1306						$this->errors[] = 'Frame not allowed in ID3v2.'.$this->majorversion.': '.$frame_name;
1307					}
1308					break;
1309			}
1310
1311		} elseif ($this->majorversion == 3) {
1312
1313			switch ($frame_name) {
1314				case 'UFID':
1315				case 'AENC':
1316				case 'ENCR':
1317				case 'GRID':
1318					if (!isset($source_data_array['ownerid'])) {
1319						$this->errors[] = '[ownerid] not specified for '.$frame_name;
1320					} elseif (in_array($frame_name.$source_data_array['ownerid'], $PreviousFrames)) {
1321						$this->errors[] = 'Only one '.$frame_name.' tag allowed with the same OwnerID ('.$source_data_array['ownerid'].')';
1322					} else {
1323						$PreviousFrames[] = $frame_name.$source_data_array['ownerid'];
1324					}
1325					break;
1326
1327				case 'TXXX':
1328				case 'WXXX':
1329				case 'APIC':
1330				case 'GEOB':
1331					if (!isset($source_data_array['description'])) {
1332						$this->errors[] = '[description] not specified for '.$frame_name;
1333					} elseif (in_array($frame_name.$source_data_array['description'], $PreviousFrames)) {
1334						$this->errors[] = 'Only one '.$frame_name.' tag allowed with the same Description ('.$source_data_array['description'].')';
1335					} else {
1336						$PreviousFrames[] = $frame_name.$source_data_array['description'];
1337					}
1338					break;
1339
1340				case 'USER':
1341					if (!isset($source_data_array['language'])) {
1342						$this->errors[] = '[language] not specified for '.$frame_name;
1343					} elseif (in_array($frame_name.$source_data_array['language'], $PreviousFrames)) {
1344						$this->errors[] = 'Only one '.$frame_name.' tag allowed with the same Language ('.$source_data_array['language'].')';
1345					} else {
1346						$PreviousFrames[] = $frame_name.$source_data_array['language'];
1347					}
1348					break;
1349
1350				case 'USLT':
1351				case 'SYLT':
1352				case 'COMM':
1353					if (!isset($source_data_array['language'])) {
1354						$this->errors[] = '[language] not specified for '.$frame_name;
1355					} elseif (!isset($source_data_array['description'])) {
1356						$this->errors[] = '[description] not specified for '.$frame_name;
1357					} elseif (in_array($frame_name.$source_data_array['language'].$source_data_array['description'], $PreviousFrames)) {
1358						$this->errors[] = 'Only one '.$frame_name.' tag allowed with the same Language + Description ('.$source_data_array['language'].' + '.$source_data_array['description'].')';
1359					} else {
1360						$PreviousFrames[] = $frame_name.$source_data_array['language'].$source_data_array['description'];
1361					}
1362					break;
1363
1364				case 'POPM':
1365					if (!isset($source_data_array['email'])) {
1366						$this->errors[] = '[email] not specified for '.$frame_name;
1367					} elseif (in_array($frame_name.$source_data_array['email'], $PreviousFrames)) {
1368						$this->errors[] = 'Only one '.$frame_name.' tag allowed with the same Email ('.$source_data_array['email'].')';
1369					} else {
1370						$PreviousFrames[] = $frame_name.$source_data_array['email'];
1371					}
1372					break;
1373
1374				case 'IPLS':
1375				case 'MCDI':
1376				case 'ETCO':
1377				case 'MLLT':
1378				case 'SYTC':
1379				case 'RVAD':
1380				case 'EQUA':
1381				case 'RVRB':
1382				case 'PCNT':
1383				case 'RBUF':
1384				case 'POSS':
1385				case 'OWNE':
1386				case 'RGAD':
1387					if (in_array($frame_name, $PreviousFrames)) {
1388						$this->errors[] = 'Only one '.$frame_name.' tag allowed';
1389					} else {
1390						$PreviousFrames[] = $frame_name;
1391					}
1392					break;
1393
1394				case 'LINK':
1395					// this isn't implemented quite right (yet) - it should check the target frame data for compliance
1396					// but right now it just allows one linked frame of each type, to be safe.
1397					if (!isset($source_data_array['frameid'])) {
1398						$this->errors[] = '[frameid] not specified for '.$frame_name;
1399					} elseif (in_array($frame_name.$source_data_array['frameid'], $PreviousFrames)) {
1400						$this->errors[] = 'Only one '.$frame_name.' tag allowed with the same FrameID ('.$source_data_array['frameid'].')';
1401					} elseif (in_array($source_data_array['frameid'], $PreviousFrames)) {
1402						// no links to singleton tags
1403						$this->errors[] = 'Cannot specify a '.$frame_name.' tag to a singleton tag that already exists ('.$source_data_array['frameid'].')';
1404					} else {
1405						$PreviousFrames[] = $frame_name.$source_data_array['frameid']; // only one linked tag of this type
1406						$PreviousFrames[] = $source_data_array['frameid'];             // no non-linked singleton tags of this type
1407					}
1408					break;
1409
1410				case 'COMR':
1411					//   There may be more than one 'commercial frame' in a tag, but no two may be identical
1412					// Checking isn't implemented at all (yet) - just assumes that it's OK.
1413					break;
1414
1415				case 'PRIV':
1416					if (!isset($source_data_array['ownerid'])) {
1417						$this->errors[] = '[ownerid] not specified for '.$frame_name;
1418					} elseif (!isset($source_data_array['data'])) {
1419						$this->errors[] = '[data] not specified for '.$frame_name;
1420					} elseif (in_array($frame_name.$source_data_array['ownerid'].$source_data_array['data'], $PreviousFrames)) {
1421						$this->errors[] = 'Only one '.$frame_name.' tag allowed with the same OwnerID + Data ('.$source_data_array['ownerid'].' + '.$source_data_array['data'].')';
1422					} else {
1423						$PreviousFrames[] = $frame_name.$source_data_array['ownerid'].$source_data_array['data'];
1424					}
1425					break;
1426
1427				default:
1428					if (($frame_name{0} != 'T') && ($frame_name{0} != 'W')) {
1429						$this->errors[] = 'Frame not allowed in ID3v2.'.$this->majorversion.': '.$frame_name;
1430					}
1431					break;
1432			}
1433
1434		} elseif ($this->majorversion == 2) {
1435
1436			switch ($frame_name) {
1437				case 'UFI':
1438				case 'CRM':
1439				case 'CRA':
1440					if (!isset($source_data_array['ownerid'])) {
1441						$this->errors[] = '[ownerid] not specified for '.$frame_name;
1442					} elseif (in_array($frame_name.$source_data_array['ownerid'], $PreviousFrames)) {
1443						$this->errors[] = 'Only one '.$frame_name.' tag allowed with the same OwnerID ('.$source_data_array['ownerid'].')';
1444					} else {
1445						$PreviousFrames[] = $frame_name.$source_data_array['ownerid'];
1446					}
1447					break;
1448
1449				case 'TXX':
1450				case 'WXX':
1451				case 'PIC':
1452				case 'GEO':
1453					if (!isset($source_data_array['description'])) {
1454						$this->errors[] = '[description] not specified for '.$frame_name;
1455					} elseif (in_array($frame_name.$source_data_array['description'], $PreviousFrames)) {
1456						$this->errors[] = 'Only one '.$frame_name.' tag allowed with the same Description ('.$source_data_array['description'].')';
1457					} else {
1458						$PreviousFrames[] = $frame_name.$source_data_array['description'];
1459					}
1460					break;
1461
1462				case 'ULT':
1463				case 'SLT':
1464				case 'COM':
1465					if (!isset($source_data_array['language'])) {
1466						$this->errors[] = '[language] not specified for '.$frame_name;
1467					} elseif (!isset($source_data_array['description'])) {
1468						$this->errors[] = '[description] not specified for '.$frame_name;
1469					} elseif (in_array($frame_name.$source_data_array['language'].$source_data_array['description'], $PreviousFrames)) {
1470						$this->errors[] = 'Only one '.$frame_name.' tag allowed with the same Language + Description ('.$source_data_array['language'].' + '.$source_data_array['description'].')';
1471					} else {
1472						$PreviousFrames[] = $frame_name.$source_data_array['language'].$source_data_array['description'];
1473					}
1474					break;
1475
1476				case 'POP':
1477					if (!isset($source_data_array['email'])) {
1478						$this->errors[] = '[email] not specified for '.$frame_name;
1479					} elseif (in_array($frame_name.$source_data_array['email'], $PreviousFrames)) {
1480						$this->errors[] = 'Only one '.$frame_name.' tag allowed with the same Email ('.$source_data_array['email'].')';
1481					} else {
1482						$PreviousFrames[] = $frame_name.$source_data_array['email'];
1483					}
1484					break;
1485
1486				case 'IPL':
1487				case 'MCI':
1488				case 'ETC':
1489				case 'MLL':
1490				case 'STC':
1491				case 'RVA':
1492				case 'EQU':
1493				case 'REV':
1494				case 'CNT':
1495				case 'BUF':
1496					if (in_array($frame_name, $PreviousFrames)) {
1497						$this->errors[] = 'Only one '.$frame_name.' tag allowed';
1498					} else {
1499						$PreviousFrames[] = $frame_name;
1500					}
1501					break;
1502
1503				case 'LNK':
1504					// this isn't implemented quite right (yet) - it should check the target frame data for compliance
1505					// but right now it just allows one linked frame of each type, to be safe.
1506					if (!isset($source_data_array['frameid'])) {
1507						$this->errors[] = '[frameid] not specified for '.$frame_name;
1508					} elseif (in_array($frame_name.$source_data_array['frameid'], $PreviousFrames)) {
1509						$this->errors[] = 'Only one '.$frame_name.' tag allowed with the same FrameID ('.$source_data_array['frameid'].')';
1510					} elseif (in_array($source_data_array['frameid'], $PreviousFrames)) {
1511						// no links to singleton tags
1512						$this->errors[] = 'Cannot specify a '.$frame_name.' tag to a singleton tag that already exists ('.$source_data_array['frameid'].')';
1513					} else {
1514						$PreviousFrames[] = $frame_name.$source_data_array['frameid']; // only one linked tag of this type
1515						$PreviousFrames[] = $source_data_array['frameid'];             // no non-linked singleton tags of this type
1516					}
1517					break;
1518
1519				default:
1520					if (($frame_name{0} != 'T') && ($frame_name{0} != 'W')) {
1521						$this->errors[] = 'Frame not allowed in ID3v2.'.$this->majorversion.': '.$frame_name;
1522					}
1523					break;
1524			}
1525		}
1526
1527		if (!empty($this->errors)) {
1528			return false;
1529		}
1530		return true;
1531	}
1532
1533	public function GenerateID3v2Tag($noerrorsonly=true) {
1534		$this->ID3v2FrameIsAllowed(null, ''); // clear static array in case this isn't the first call to $this->GenerateID3v2Tag()
1535
1536		$tagstring = '';
1537		if (is_array($this->tag_data)) {
1538			foreach ($this->tag_data as $frame_name => $frame_rawinputdata) {
1539				foreach ($frame_rawinputdata as $irrelevantindex => $source_data_array) {
1540					if (getid3_id3v2::IsValidID3v2FrameName($frame_name, $this->majorversion)) {
1541						unset($frame_length);
1542						unset($frame_flags);
1543						$frame_data = false;
1544						if ($this->ID3v2FrameIsAllowed($frame_name, $source_data_array)) {
1545							if(array_key_exists('description', $source_data_array) && array_key_exists('encodingid', $source_data_array) && array_key_exists('encoding', $this->tag_data)) {
1546								$source_data_array['description'] = getid3_lib::iconv_fallback($this->tag_data['encoding'], $source_data_array['encoding'], $source_data_array['description']);
1547							}
1548							if ($frame_data = $this->GenerateID3v2FrameData($frame_name, $source_data_array)) {
1549								$FrameUnsynchronisation = false;
1550								if ($this->majorversion >= 4) {
1551									// frame-level unsynchronisation
1552									$unsynchdata = $frame_data;
1553									if ($this->id3v2_use_unsynchronisation) {
1554										$unsynchdata = $this->Unsynchronise($frame_data);
1555									}
1556									if (strlen($unsynchdata) != strlen($frame_data)) {
1557										// unsynchronisation needed
1558										$FrameUnsynchronisation = true;
1559										$frame_data = $unsynchdata;
1560										if (isset($TagUnsynchronisation) && $TagUnsynchronisation === false) {
1561											// only set to true if ALL frames are unsynchronised
1562										} else {
1563											$TagUnsynchronisation = true;
1564										}
1565									} else {
1566										if (isset($TagUnsynchronisation)) {
1567											$TagUnsynchronisation = false;
1568										}
1569									}
1570									unset($unsynchdata);
1571
1572									$frame_length = getid3_lib::BigEndian2String(strlen($frame_data), 4, true);
1573								} else {
1574									$frame_length = getid3_lib::BigEndian2String(strlen($frame_data), 4, false);
1575								}
1576								$frame_flags  = $this->GenerateID3v2FrameFlags($this->ID3v2FrameFlagsLookupTagAlter($frame_name), $this->ID3v2FrameFlagsLookupFileAlter($frame_name), false, false, false, false, $FrameUnsynchronisation, false);
1577							}
1578						} else {
1579							$this->errors[] = 'Frame "'.$frame_name.'" is NOT allowed';
1580						}
1581						if ($frame_data === false) {
1582							$this->errors[] = '$this->GenerateID3v2FrameData() failed for "'.$frame_name.'"';
1583							if ($noerrorsonly) {
1584								return false;
1585							} else {
1586								unset($frame_name);
1587							}
1588						}
1589					} else {
1590						// ignore any invalid frame names, including 'title', 'header', etc
1591						$this->warnings[] = 'Ignoring invalid ID3v2 frame type: "'.$frame_name.'"';
1592						unset($frame_name);
1593						unset($frame_length);
1594						unset($frame_flags);
1595						unset($frame_data);
1596					}
1597					if (isset($frame_name) && isset($frame_length) && isset($frame_flags) && isset($frame_data)) {
1598						$tagstring .= $frame_name.$frame_length.$frame_flags.$frame_data;
1599					}
1600				}
1601			}
1602
1603			if (!isset($TagUnsynchronisation)) {
1604				$TagUnsynchronisation = false;
1605			}
1606			if (($this->majorversion <= 3) && $this->id3v2_use_unsynchronisation) {
1607				// tag-level unsynchronisation
1608				$unsynchdata = $this->Unsynchronise($tagstring);
1609				if (strlen($unsynchdata) != strlen($tagstring)) {
1610					// unsynchronisation needed
1611					$TagUnsynchronisation = true;
1612					$tagstring = $unsynchdata;
1613				}
1614			}
1615
1616			while ($this->paddedlength < (strlen($tagstring) + getid3_id3v2::ID3v2HeaderLength($this->majorversion))) {
1617				$this->paddedlength += 1024;
1618			}
1619
1620			$footer = false; // ID3v2 footers not yet supported in getID3()
1621			if (!$footer && ($this->paddedlength > (strlen($tagstring) + getid3_id3v2::ID3v2HeaderLength($this->majorversion)))) {
1622				// pad up to $paddedlength bytes if unpadded tag is shorter than $paddedlength
1623				// "Furthermore it MUST NOT have any padding when a tag footer is added to the tag."
1624				if (($this->paddedlength - strlen($tagstring) - getid3_id3v2::ID3v2HeaderLength($this->majorversion)) > 0) {
1625					$tagstring .= str_repeat("\x00", $this->paddedlength - strlen($tagstring) - getid3_id3v2::ID3v2HeaderLength($this->majorversion));
1626				}
1627			}
1628			if ($this->id3v2_use_unsynchronisation && (substr($tagstring, strlen($tagstring) - 1, 1) == "\xFF")) {
1629				// special unsynchronisation case:
1630				// if last byte == $FF then appended a $00
1631				$TagUnsynchronisation = true;
1632				$tagstring .= "\x00";
1633			}
1634
1635			$tagheader  = 'ID3';
1636			$tagheader .= chr($this->majorversion);
1637			$tagheader .= chr($this->minorversion);
1638			$tagheader .= $this->GenerateID3v2TagFlags(array('unsynchronisation'=>$TagUnsynchronisation));
1639			$tagheader .= getid3_lib::BigEndian2String(strlen($tagstring), 4, true);
1640
1641			return $tagheader.$tagstring;
1642		}
1643		$this->errors[] = 'tag_data is not an array in GenerateID3v2Tag()';
1644		return false;
1645	}
1646
1647	public function ID3v2IsValidPriceString($pricestring) {
1648		if (getid3_id3v2::LanguageLookup(substr($pricestring, 0, 3), true) == '') {
1649			return false;
1650		} elseif (!$this->IsANumber(substr($pricestring, 3), true)) {
1651			return false;
1652		}
1653		return true;
1654	}
1655
1656	public function ID3v2FrameFlagsLookupTagAlter($framename) {
1657		// unfinished
1658		switch ($framename) {
1659			case 'RGAD':
1660				$allow = true;
1661			default:
1662				$allow = false;
1663				break;
1664		}
1665		return $allow;
1666	}
1667
1668	public function ID3v2FrameFlagsLookupFileAlter($framename) {
1669		// unfinished
1670		switch ($framename) {
1671			case 'RGAD':
1672				return false;
1673				break;
1674
1675			default:
1676				return false;
1677				break;
1678		}
1679	}
1680
1681	public function ID3v2IsValidETCOevent($eventid) {
1682		if (($eventid < 0) || ($eventid > 0xFF)) {
1683			// outside range of 1 byte
1684			return false;
1685		} elseif (($eventid >= 0xF0) && ($eventid <= 0xFC)) {
1686			// reserved for future use
1687			return false;
1688		} elseif (($eventid >= 0x17) && ($eventid <= 0xDF)) {
1689			// reserved for future use
1690			return false;
1691		} elseif (($eventid >= 0x0E) && ($eventid <= 0x16) && ($this->majorversion == 2)) {
1692			// not defined in ID3v2.2
1693			return false;
1694		} elseif (($eventid >= 0x15) && ($eventid <= 0x16) && ($this->majorversion == 3)) {
1695			// not defined in ID3v2.3
1696			return false;
1697		}
1698		return true;
1699	}
1700
1701	public function ID3v2IsValidSYLTtype($contenttype) {
1702		if (($contenttype >= 0) && ($contenttype <= 8) && ($this->majorversion == 4)) {
1703			return true;
1704		} elseif (($contenttype >= 0) && ($contenttype <= 6) && ($this->majorversion == 3)) {
1705			return true;
1706		}
1707		return false;
1708	}
1709
1710	public function ID3v2IsValidRVA2channeltype($channeltype) {
1711		if (($channeltype >= 0) && ($channeltype <= 8) && ($this->majorversion == 4)) {
1712			return true;
1713		}
1714		return false;
1715	}
1716
1717	public function ID3v2IsValidAPICpicturetype($picturetype) {
1718		if (($picturetype >= 0) && ($picturetype <= 0x14) && ($this->majorversion >= 2) && ($this->majorversion <= 4)) {
1719			return true;
1720		}
1721		return false;
1722	}
1723
1724	public function ID3v2IsValidAPICimageformat($imageformat) {
1725		if ($imageformat == '-->') {
1726			return true;
1727		} elseif ($this->majorversion == 2) {
1728			if ((strlen($imageformat) == 3) && ($imageformat == strtoupper($imageformat))) {
1729				return true;
1730			}
1731		} elseif (($this->majorversion == 3) || ($this->majorversion == 4)) {
1732			if ($this->IsValidMIMEstring($imageformat)) {
1733				return true;
1734			}
1735		}
1736		return false;
1737	}
1738
1739	public function ID3v2IsValidCOMRreceivedAs($receivedas) {
1740		if (($this->majorversion >= 3) && ($receivedas >= 0) && ($receivedas <= 8)) {
1741			return true;
1742		}
1743		return false;
1744	}
1745
1746	public static function ID3v2IsValidRGADname($RGADname) {
1747		if (($RGADname >= 0) && ($RGADname <= 2)) {
1748			return true;
1749		}
1750		return false;
1751	}
1752
1753	public static function ID3v2IsValidRGADoriginator($RGADoriginator) {
1754		if (($RGADoriginator >= 0) && ($RGADoriginator <= 3)) {
1755			return true;
1756		}
1757		return false;
1758	}
1759
1760	public function ID3v2IsValidTextEncoding($textencodingbyte) {
1761		// 0 = ISO-8859-1
1762		// 1 = UTF-16 with BOM
1763		// 2 = UTF-16BE without BOM
1764		// 3 = UTF-8
1765		static $ID3v2IsValidTextEncoding_cache = array(
1766			2 => array(true, true),              // ID3v2.2 - allow 0=ISO-8859-1, 1=UTF-16
1767			3 => array(true, true),              // ID3v2.3 - allow 0=ISO-8859-1, 1=UTF-16
1768			4 => array(true, true, true, true),  // ID3v2.4 - allow 0=ISO-8859-1, 1=UTF-16, 2=UTF-16BE, 3=UTF-8
1769		);
1770		return isset($ID3v2IsValidTextEncoding_cache[$this->majorversion][$textencodingbyte]);
1771	}
1772
1773	public static function Unsynchronise($data) {
1774		// Whenever a false synchronisation is found within the tag, one zeroed
1775		// byte is inserted after the first false synchronisation byte. The
1776		// format of a correct sync that should be altered by ID3 encoders is as
1777		// follows:
1778		//      %11111111 111xxxxx
1779		// And should be replaced with:
1780		//      %11111111 00000000 111xxxxx
1781		// This has the side effect that all $FF 00 combinations have to be
1782		// altered, so they won't be affected by the decoding process. Therefore
1783		// all the $FF 00 combinations have to be replaced with the $FF 00 00
1784		// combination during the unsynchronisation.
1785
1786		$data = str_replace("\xFF\x00", "\xFF\x00\x00", $data);
1787		$unsyncheddata = '';
1788		$datalength = strlen($data);
1789		for ($i = 0; $i < $datalength; $i++) {
1790			$thischar = $data{$i};
1791			$unsyncheddata .= $thischar;
1792			if ($thischar == "\xFF") {
1793				$nextchar = ord($data{$i + 1});
1794				if (($nextchar & 0xE0) == 0xE0) {
1795					// previous byte = 11111111, this byte = 111?????
1796					$unsyncheddata .= "\x00";
1797				}
1798			}
1799		}
1800		return $unsyncheddata;
1801	}
1802
1803	public function is_hash($var) {
1804		// written by dev-nullØchristophe*vg
1805		// taken from http://www.php.net/manual/en/function.array-merge-recursive.php
1806		if (is_array($var)) {
1807			$keys = array_keys($var);
1808			$all_num = true;
1809			for ($i = 0; $i < count($keys); $i++) {
1810				if (is_string($keys[$i])) {
1811					return true;
1812				}
1813			}
1814		}
1815		return false;
1816	}
1817
1818	public function array_join_merge($arr1, $arr2) {
1819		// written by dev-nullØchristophe*vg
1820		// taken from http://www.php.net/manual/en/function.array-merge-recursive.php
1821		if (is_array($arr1) && is_array($arr2)) {
1822			// the same -> merge
1823			$new_array = array();
1824
1825			if ($this->is_hash($arr1) && $this->is_hash($arr2)) {
1826				// hashes -> merge based on keys
1827				$keys = array_merge(array_keys($arr1), array_keys($arr2));
1828				foreach ($keys as $key) {
1829					$new_array[$key] = $this->array_join_merge((isset($arr1[$key]) ? $arr1[$key] : ''), (isset($arr2[$key]) ? $arr2[$key] : ''));
1830				}
1831			} else {
1832				// two real arrays -> merge
1833				$new_array = array_reverse(array_unique(array_reverse(array_merge($arr1, $arr2))));
1834			}
1835			return $new_array;
1836		} else {
1837			// not the same ... take new one if defined, else the old one stays
1838			return $arr2 ? $arr2 : $arr1;
1839		}
1840	}
1841
1842	public static function IsValidMIMEstring($mimestring) {
1843		return preg_match('#^.+/.+$#', $mimestring);
1844	}
1845
1846	public static function IsWithinBitRange($number, $maxbits, $signed=false) {
1847		if ($signed) {
1848			if (($number > (0 - pow(2, $maxbits - 1))) && ($number <= pow(2, $maxbits - 1))) {
1849				return true;
1850			}
1851		} else {
1852			if (($number >= 0) && ($number <= pow(2, $maxbits))) {
1853				return true;
1854			}
1855		}
1856		return false;
1857	}
1858
1859	public static function IsValidEmail($email) {
1860		if (function_exists('filter_var')) {
1861			return filter_var($email, FILTER_VALIDATE_EMAIL);
1862		}
1863		// VERY crude email validation
1864		return preg_match('#^[^ ]+@[a-z\\-\\.]+\\.[a-z]{2,}$#', $email);
1865	}
1866
1867	public static function IsValidURL($url, $allowUserPass=false) {
1868		if ($url == '') {
1869			return false;
1870		}
1871		if ($allowUserPass !== true) {
1872			if (strstr($url, '@')) {
1873				// in the format http://user:pass@example.com  or http://user@example.com
1874				// but could easily be somebody incorrectly entering an email address in place of a URL
1875				return false;
1876			}
1877		}
1878		// 2016-06-08: relax URL checking to avoid falsely rejecting valid URLs, leave URL validation to the user
1879		// http://www.getid3.org/phpBB3/viewtopic.php?t=1926
1880		return true;
1881		/*
1882		if ($parts = $this->safe_parse_url($url)) {
1883			if (($parts['scheme'] != 'http') && ($parts['scheme'] != 'https') && ($parts['scheme'] != 'ftp') && ($parts['scheme'] != 'gopher')) {
1884				return false;
1885			} elseif (!preg_match('#^[[:alnum:]]([-.]?[0-9a-z])*\\.[a-z]{2,3}$#i', $parts['host'], $regs) && !preg_match('#^[0-9]{1,3}(\\.[0-9]{1,3}){3}$#', $parts['host'])) {
1886				return false;
1887			} elseif (!preg_match('#^([[:alnum:]-]|[\\_])*$#i', $parts['user'], $regs)) {
1888				return false;
1889			} elseif (!preg_match('#^([[:alnum:]-]|[\\_])*$#i', $parts['pass'], $regs)) {
1890				return false;
1891			} elseif (!preg_match('#^[[:alnum:]/_\\.@~-]*$#i', $parts['path'], $regs)) {
1892				return false;
1893			} elseif (!empty($parts['query']) && !preg_match('#^[[:alnum:]?&=+:;_()%\\#/,\\.-]*$#i', $parts['query'], $regs)) {
1894				return false;
1895			} else {
1896				return true;
1897			}
1898		}
1899		return false;
1900		*/
1901	}
1902
1903	public static function safe_parse_url($url) {
1904		$parts = @parse_url($url);
1905		$parts['scheme'] = (isset($parts['scheme']) ? $parts['scheme'] : '');
1906		$parts['host']   = (isset($parts['host'])   ? $parts['host']   : '');
1907		$parts['user']   = (isset($parts['user'])   ? $parts['user']   : '');
1908		$parts['pass']   = (isset($parts['pass'])   ? $parts['pass']   : '');
1909		$parts['path']   = (isset($parts['path'])   ? $parts['path']   : '');
1910		$parts['query']  = (isset($parts['query'])  ? $parts['query']  : '');
1911		return $parts;
1912	}
1913
1914	public static function ID3v2ShortFrameNameLookup($majorversion, $long_description) {
1915		$long_description = str_replace(' ', '_', strtolower(trim($long_description)));
1916		static $ID3v2ShortFrameNameLookup = array();
1917		if (empty($ID3v2ShortFrameNameLookup)) {
1918
1919			// The following are unique to ID3v2.2
1920			$ID3v2ShortFrameNameLookup[2]['recommended_buffer_size']           = 'BUF';
1921			$ID3v2ShortFrameNameLookup[2]['comment']                           = 'COM';
1922			$ID3v2ShortFrameNameLookup[2]['audio_encryption']                  = 'CRA';
1923			$ID3v2ShortFrameNameLookup[2]['encrypted_meta_frame']              = 'CRM';
1924			$ID3v2ShortFrameNameLookup[2]['equalisation']                      = 'EQU';
1925			$ID3v2ShortFrameNameLookup[2]['event_timing_codes']                = 'ETC';
1926			$ID3v2ShortFrameNameLookup[2]['general_encapsulated_object']       = 'GEO';
1927			$ID3v2ShortFrameNameLookup[2]['involved_people_list']              = 'IPL';
1928			$ID3v2ShortFrameNameLookup[2]['linked_information']                = 'LNK';
1929			$ID3v2ShortFrameNameLookup[2]['music_cd_identifier']               = 'MCI';
1930			$ID3v2ShortFrameNameLookup[2]['mpeg_location_lookup_table']        = 'MLL';
1931			$ID3v2ShortFrameNameLookup[2]['attached_picture']                  = 'PIC';
1932			$ID3v2ShortFrameNameLookup[2]['popularimeter']                     = 'POP';
1933			$ID3v2ShortFrameNameLookup[2]['reverb']                            = 'REV';
1934			$ID3v2ShortFrameNameLookup[2]['relative_volume_adjustment']        = 'RVA';
1935			$ID3v2ShortFrameNameLookup[2]['synchronised_lyric']                = 'SLT';
1936			$ID3v2ShortFrameNameLookup[2]['synchronised_tempo_codes']          = 'STC';
1937			$ID3v2ShortFrameNameLookup[2]['album']                             = 'TAL';
1938			$ID3v2ShortFrameNameLookup[2]['beats_per_minute']                  = 'TBP';
1939			$ID3v2ShortFrameNameLookup[2]['bpm']                               = 'TBP';
1940			$ID3v2ShortFrameNameLookup[2]['composer']                          = 'TCM';
1941			$ID3v2ShortFrameNameLookup[2]['genre']                             = 'TCO';
1942			$ID3v2ShortFrameNameLookup[2]['part_of_a_compilation']             = 'TCP';
1943			$ID3v2ShortFrameNameLookup[2]['copyright_message']                 = 'TCR';
1944			$ID3v2ShortFrameNameLookup[2]['date']                              = 'TDA';
1945			$ID3v2ShortFrameNameLookup[2]['playlist_delay']                    = 'TDY';
1946			$ID3v2ShortFrameNameLookup[2]['encoded_by']                        = 'TEN';
1947			$ID3v2ShortFrameNameLookup[2]['file_type']                         = 'TFT';
1948			$ID3v2ShortFrameNameLookup[2]['time']                              = 'TIM';
1949			$ID3v2ShortFrameNameLookup[2]['initial_key']                       = 'TKE';
1950			$ID3v2ShortFrameNameLookup[2]['language']                          = 'TLA';
1951			$ID3v2ShortFrameNameLookup[2]['length']                            = 'TLE';
1952			$ID3v2ShortFrameNameLookup[2]['media_type']                        = 'TMT';
1953			$ID3v2ShortFrameNameLookup[2]['original_artist']                   = 'TOA';
1954			$ID3v2ShortFrameNameLookup[2]['original_filename']                 = 'TOF';
1955			$ID3v2ShortFrameNameLookup[2]['original_lyricist']                 = 'TOL';
1956			$ID3v2ShortFrameNameLookup[2]['original_year']                     = 'TOR';
1957			$ID3v2ShortFrameNameLookup[2]['original_album']                    = 'TOT';
1958			$ID3v2ShortFrameNameLookup[2]['artist']                            = 'TP1';
1959			$ID3v2ShortFrameNameLookup[2]['band']                              = 'TP2';
1960			$ID3v2ShortFrameNameLookup[2]['conductor']                         = 'TP3';
1961			$ID3v2ShortFrameNameLookup[2]['remixer']                           = 'TP4';
1962			$ID3v2ShortFrameNameLookup[2]['part_of_a_set']                     = 'TPA';
1963			$ID3v2ShortFrameNameLookup[2]['publisher']                         = 'TPB';
1964			$ID3v2ShortFrameNameLookup[2]['isrc']                              = 'TRC';
1965			$ID3v2ShortFrameNameLookup[2]['recording_dates']                   = 'TRD';
1966			$ID3v2ShortFrameNameLookup[2]['tracknumber']                       = 'TRK';
1967			$ID3v2ShortFrameNameLookup[2]['track_number']                      = 'TRK';
1968			$ID3v2ShortFrameNameLookup[2]['album_artist_sort_order']           = 'TS2';
1969			$ID3v2ShortFrameNameLookup[2]['album_sort_order']                  = 'TSA';
1970			$ID3v2ShortFrameNameLookup[2]['composer_sort_order']               = 'TSC';
1971			$ID3v2ShortFrameNameLookup[2]['size']                              = 'TSI';
1972			$ID3v2ShortFrameNameLookup[2]['performer_sort_order']              = 'TSP';
1973			$ID3v2ShortFrameNameLookup[2]['encoder_settings']                  = 'TSS';
1974			$ID3v2ShortFrameNameLookup[2]['title_sort_order']                  = 'TST';
1975			$ID3v2ShortFrameNameLookup[2]['content_group_description']         = 'TT1';
1976			$ID3v2ShortFrameNameLookup[2]['title']                             = 'TT2';
1977			$ID3v2ShortFrameNameLookup[2]['subtitle']                          = 'TT3';
1978			$ID3v2ShortFrameNameLookup[2]['lyricist']                          = 'TXT';
1979			$ID3v2ShortFrameNameLookup[2]['text']                              = 'TXX';
1980			$ID3v2ShortFrameNameLookup[2]['year']                              = 'TYE';
1981			$ID3v2ShortFrameNameLookup[2]['unique_file_identifier']            = 'UFI';
1982			$ID3v2ShortFrameNameLookup[2]['unsychronised_lyric']               = 'ULT';
1983			$ID3v2ShortFrameNameLookup[2]['url_file']                          = 'WAF';
1984			$ID3v2ShortFrameNameLookup[2]['url_artist']                        = 'WAR';
1985			$ID3v2ShortFrameNameLookup[2]['url_source']                        = 'WAS';
1986			$ID3v2ShortFrameNameLookup[2]['commercial_information']            = 'WCM';
1987			$ID3v2ShortFrameNameLookup[2]['copyright']                         = 'WCP';
1988			$ID3v2ShortFrameNameLookup[2]['url_publisher']                     = 'WPB';
1989			$ID3v2ShortFrameNameLookup[2]['url_user']                          = 'WXX';
1990
1991			// The following are common to ID3v2.3 and ID3v2.4
1992			$ID3v2ShortFrameNameLookup[3]['audio_encryption']                  = 'AENC';
1993			$ID3v2ShortFrameNameLookup[3]['attached_picture']                  = 'APIC';
1994			$ID3v2ShortFrameNameLookup[3]['picture']                           = 'APIC';
1995			$ID3v2ShortFrameNameLookup[3]['comment']                           = 'COMM';
1996			$ID3v2ShortFrameNameLookup[3]['commercial_frame']                  = 'COMR';
1997			$ID3v2ShortFrameNameLookup[3]['encryption_method_registration']    = 'ENCR';
1998			$ID3v2ShortFrameNameLookup[3]['event_timing_codes']                = 'ETCO';
1999			$ID3v2ShortFrameNameLookup[3]['general_encapsulated_object']       = 'GEOB';
2000			$ID3v2ShortFrameNameLookup[3]['group_identification_registration'] = 'GRID';
2001			$ID3v2ShortFrameNameLookup[3]['linked_information']                = 'LINK';
2002			$ID3v2ShortFrameNameLookup[3]['music_cd_identifier']               = 'MCDI';
2003			$ID3v2ShortFrameNameLookup[3]['mpeg_location_lookup_table']        = 'MLLT';
2004			$ID3v2ShortFrameNameLookup[3]['ownership_frame']                   = 'OWNE';
2005			$ID3v2ShortFrameNameLookup[3]['play_counter']                      = 'PCNT';
2006			$ID3v2ShortFrameNameLookup[3]['popularimeter']                     = 'POPM';
2007			$ID3v2ShortFrameNameLookup[3]['position_synchronisation_frame']    = 'POSS';
2008			$ID3v2ShortFrameNameLookup[3]['private_frame']                     = 'PRIV';
2009			$ID3v2ShortFrameNameLookup[3]['recommended_buffer_size']           = 'RBUF';
2010			$ID3v2ShortFrameNameLookup[3]['replay_gain_adjustment']            = 'RGAD';
2011			$ID3v2ShortFrameNameLookup[3]['reverb']                            = 'RVRB';
2012			$ID3v2ShortFrameNameLookup[3]['synchronised_lyric']                = 'SYLT';
2013			$ID3v2ShortFrameNameLookup[3]['synchronised_tempo_codes']          = 'SYTC';
2014			$ID3v2ShortFrameNameLookup[3]['album']                             = 'TALB';
2015			$ID3v2ShortFrameNameLookup[3]['beats_per_minute']                  = 'TBPM';
2016			$ID3v2ShortFrameNameLookup[3]['bpm']                               = 'TBPM';
2017			$ID3v2ShortFrameNameLookup[3]['part_of_a_compilation']             = 'TCMP';
2018			$ID3v2ShortFrameNameLookup[3]['composer']                          = 'TCOM';
2019			$ID3v2ShortFrameNameLookup[3]['genre']                             = 'TCON';
2020			$ID3v2ShortFrameNameLookup[3]['copyright_message']                 = 'TCOP';
2021			$ID3v2ShortFrameNameLookup[3]['playlist_delay']                    = 'TDLY';
2022			$ID3v2ShortFrameNameLookup[3]['encoded_by']                        = 'TENC';
2023			$ID3v2ShortFrameNameLookup[3]['lyricist']                          = 'TEXT';
2024			$ID3v2ShortFrameNameLookup[3]['file_type']                         = 'TFLT';
2025			$ID3v2ShortFrameNameLookup[3]['content_group_description']         = 'TIT1';
2026			$ID3v2ShortFrameNameLookup[3]['title']                             = 'TIT2';
2027			$ID3v2ShortFrameNameLookup[3]['subtitle']                          = 'TIT3';
2028			$ID3v2ShortFrameNameLookup[3]['initial_key']                       = 'TKEY';
2029			$ID3v2ShortFrameNameLookup[3]['language']                          = 'TLAN';
2030			$ID3v2ShortFrameNameLookup[3]['length']                            = 'TLEN';
2031			$ID3v2ShortFrameNameLookup[3]['media_type']                        = 'TMED';
2032			$ID3v2ShortFrameNameLookup[3]['original_album']                    = 'TOAL';
2033			$ID3v2ShortFrameNameLookup[3]['original_filename']                 = 'TOFN';
2034			$ID3v2ShortFrameNameLookup[3]['original_lyricist']                 = 'TOLY';
2035			$ID3v2ShortFrameNameLookup[3]['original_artist']                   = 'TOPE';
2036			$ID3v2ShortFrameNameLookup[3]['file_owner']                        = 'TOWN';
2037			$ID3v2ShortFrameNameLookup[3]['artist']                            = 'TPE1';
2038			$ID3v2ShortFrameNameLookup[3]['band']                              = 'TPE2';
2039			$ID3v2ShortFrameNameLookup[3]['conductor']                         = 'TPE3';
2040			$ID3v2ShortFrameNameLookup[3]['remixer']                           = 'TPE4';
2041			$ID3v2ShortFrameNameLookup[3]['part_of_a_set']                     = 'TPOS';
2042			$ID3v2ShortFrameNameLookup[3]['publisher']                         = 'TPUB';
2043			$ID3v2ShortFrameNameLookup[3]['tracknumber']                       = 'TRCK';
2044			$ID3v2ShortFrameNameLookup[3]['track_number']                      = 'TRCK';
2045			$ID3v2ShortFrameNameLookup[3]['internet_radio_station_name']       = 'TRSN';
2046			$ID3v2ShortFrameNameLookup[3]['internet_radio_station_owner']      = 'TRSO';
2047			$ID3v2ShortFrameNameLookup[3]['album_artist_sort_order']           = 'TSO2';
2048			$ID3v2ShortFrameNameLookup[3]['album_sort_order']                  = 'TSOA';
2049			$ID3v2ShortFrameNameLookup[3]['composer_sort_order']               = 'TSOC';
2050			$ID3v2ShortFrameNameLookup[3]['performer_sort_order']              = 'TSOP';
2051			$ID3v2ShortFrameNameLookup[3]['title_sort_order']                  = 'TSOT';
2052			$ID3v2ShortFrameNameLookup[3]['isrc']                              = 'TSRC';
2053			$ID3v2ShortFrameNameLookup[3]['encoder_settings']                  = 'TSSE';
2054			$ID3v2ShortFrameNameLookup[3]['text']                              = 'TXXX';
2055			$ID3v2ShortFrameNameLookup[3]['unique_file_identifier']            = 'UFID';
2056			$ID3v2ShortFrameNameLookup[3]['terms_of_use']                      = 'USER';
2057			$ID3v2ShortFrameNameLookup[3]['unsychronised_lyric']               = 'USLT';
2058			$ID3v2ShortFrameNameLookup[3]['commercial_information']            = 'WCOM';
2059			$ID3v2ShortFrameNameLookup[3]['copyright']                         = 'WCOP';
2060			$ID3v2ShortFrameNameLookup[3]['url_file']                          = 'WOAF';
2061			$ID3v2ShortFrameNameLookup[3]['url_artist']                        = 'WOAR';
2062			$ID3v2ShortFrameNameLookup[3]['url_source']                        = 'WOAS';
2063			$ID3v2ShortFrameNameLookup[3]['url_station']                       = 'WORS';
2064			$ID3v2ShortFrameNameLookup[3]['url_payment']                       = 'WPAY';
2065			$ID3v2ShortFrameNameLookup[3]['url_publisher']                     = 'WPUB';
2066			$ID3v2ShortFrameNameLookup[3]['url_user']                          = 'WXXX';
2067
2068			// The above are common to ID3v2.3 and ID3v2.4
2069			// so copy them to ID3v2.4 before adding specifics for 2.3 and 2.4
2070			$ID3v2ShortFrameNameLookup[4] = $ID3v2ShortFrameNameLookup[3];
2071
2072			// The following are unique to ID3v2.3
2073			$ID3v2ShortFrameNameLookup[3]['equalisation']                      = 'EQUA';
2074			$ID3v2ShortFrameNameLookup[3]['involved_people_list']              = 'IPLS';
2075			$ID3v2ShortFrameNameLookup[3]['relative_volume_adjustment']        = 'RVAD';
2076			$ID3v2ShortFrameNameLookup[3]['date']                              = 'TDAT';
2077			$ID3v2ShortFrameNameLookup[3]['time']                              = 'TIME';
2078			$ID3v2ShortFrameNameLookup[3]['original_year']                     = 'TORY';
2079			$ID3v2ShortFrameNameLookup[3]['recording_dates']                   = 'TRDA';
2080			$ID3v2ShortFrameNameLookup[3]['size']                              = 'TSIZ';
2081			$ID3v2ShortFrameNameLookup[3]['year']                              = 'TYER';
2082
2083
2084			// The following are unique to ID3v2.4
2085			$ID3v2ShortFrameNameLookup[4]['audio_seek_point_index']            = 'ASPI';
2086			$ID3v2ShortFrameNameLookup[4]['equalisation']                      = 'EQU2';
2087			$ID3v2ShortFrameNameLookup[4]['relative_volume_adjustment']        = 'RVA2';
2088			$ID3v2ShortFrameNameLookup[4]['seek_frame']                        = 'SEEK';
2089			$ID3v2ShortFrameNameLookup[4]['signature_frame']                   = 'SIGN';
2090			$ID3v2ShortFrameNameLookup[4]['encoding_time']                     = 'TDEN';
2091			$ID3v2ShortFrameNameLookup[4]['original_release_time']             = 'TDOR';
2092			$ID3v2ShortFrameNameLookup[4]['recording_time']                    = 'TDRC';
2093			$ID3v2ShortFrameNameLookup[4]['release_time']                      = 'TDRL';
2094			$ID3v2ShortFrameNameLookup[4]['tagging_time']                      = 'TDTG';
2095			$ID3v2ShortFrameNameLookup[4]['involved_people_list']              = 'TIPL';
2096			$ID3v2ShortFrameNameLookup[4]['musician_credits_list']             = 'TMCL';
2097			$ID3v2ShortFrameNameLookup[4]['mood']                              = 'TMOO';
2098			$ID3v2ShortFrameNameLookup[4]['produced_notice']                   = 'TPRO';
2099			$ID3v2ShortFrameNameLookup[4]['album_sort_order']                  = 'TSOA';
2100			$ID3v2ShortFrameNameLookup[4]['performer_sort_order']              = 'TSOP';
2101			$ID3v2ShortFrameNameLookup[4]['title_sort_order']                  = 'TSOT';
2102			$ID3v2ShortFrameNameLookup[4]['set_subtitle']                      = 'TSST';
2103		}
2104		return (isset($ID3v2ShortFrameNameLookup[$majorversion][strtolower($long_description)]) ? $ID3v2ShortFrameNameLookup[$majorversion][strtolower($long_description)] : '');
2105
2106	}
2107
2108}
2109
2110