Generate / Update copyright headers

@return  bool

@since   1.0
439326
public function run()
	{
		$this->say("Updating / adding copyright headers");
		$text    = $this->replaceInText(trim($this->getJConfig()->header->text));
		$exclude = explode(",", trim($this->getJConfig()->header->exclude));

		$path      = realpath($this->getJConfig()->source);
		$fileTypes = explode(",", trim($this->getJConfig()->header->files));

		foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path)) as $filename)
		{
			if (substr($filename, 0, 1) == '.')
			{
				continue;
			}

			$file = new \SplFileInfo($filename);


			if (!in_array($file->getExtension(), $fileTypes))
			{
				continue;
			}

			// Skip directories in exclude list
			if (isset($exclude) && count($exclude))
			{
				$relative = str_replace(realpath($path), "", $file->getPath());

				// It is possible to have multiple exclude directories
				foreach ($exclude as $e)
				{
					if (stripos($relative, $e) !== false)
					{
						$this->say("Excluding " . $filename);
						continue 2;
					}
				}
			}

			// Remove previous / any doctype headers at the beginning of the file
			// Todo: needs check for class headers (as long as namespace / use / defined _jexec is there, this is no issue)
			$this->removeHeader($file);
			$this->addHeader($file, $text);
		}

		$this->say("Finished updating copyright headers");
	}
388749
private function setLicense() {
		if ( ! $this->getApiKey() ) {
			$license = 'Missing Connect Key';
		} else if ( ! ( $license = $this->getTransient() ) || ! $this->isVersionValid( $license ) ) {
			delete_site_transient( $this->getKey() );
			$license = $this->getRemoteLicense();
		}

		return $this->license = $license;
	}
450596
private function _saveHeaders()
    {
        fwrite($this->SHPFile, pack('N', $this->recordNumber));
        fwrite($this->SHPFile, pack('N', $this->getContentLength()));
        fwrite($this->SHPFile, pack('V', $this->shapeType));
    }
1021996
public function compileHeaders()
    {
        if (count($this->attachement) > 0) {
            $this->headers[] = "Content-type: multipart/mixed; boundary=\"{$this->boundary}\"" . self::END;

            foreach ($this->attachement as $file) {
                $filename = basename($file);
                $this->headers[] = "--" . $this->boundary;
                $this->headers[] = "Content-Type: application/octet-stream; name=\"{$filename}\"";
                $this->headers[] = "Content-Transfer-Encoding: base64";
                $this->headers[] = "Content-Disposition: attachment" . self::END;
                $this->headers[] = chunk_split(base64_encode(file_get_contents($file)));
            }

            $this->headers[] = "--" . $this->boundary;
        }

        return implode(self::END, $this->headers).self::END;
    }
149331
public function _updateContentType()
    {
        unset($this->_headers['Content-Type']);
        $suffix = '';
        if ($this->isMultipart()) {
            $suffix = '; boundary=' . $this->boundary();
        } elseif ($this->_charset) {
            $suffix = '; charset=' . $this->_charset . $suffix;
        }
        if ($this->_mime) {
            $this->_headers['Content-Type'] = $this->_mime . $suffix;
        }
    }
1090516
public function maybeUpdateStylesheets() {
		// If this is ajax/cron/404, don't update right now
		if ( wp_doing_ajax() || wp_doing_cron() || is_404() ) {
			return false;
		}

		// Compare current and previous Buckram versions
		$current_buckram_version = $this->getBuckramVersion();
		$last_buckram_version = get_option( 'pressbooks_buckram_version' );
		$buckram_updated = version_compare( $current_buckram_version, $last_buckram_version ) > 0;

		// Compare current and previous theme versions
		$theme = wp_get_theme();
		$current_theme_version = $theme->get( 'Version' );
		$last_theme_version = get_option( 'pressbooks_theme_version' );
		$theme_updated = version_compare( $current_theme_version, $last_theme_version ) > 0;

		// If either Buckram or the theme were updated, rebuild the web and editor stylesheets.
		if ( $buckram_updated || $theme_updated ) {
			// Try to stop a Cache Stampede, Dog-Pile, Cascading Failure...
			if ( ! get_transient( 'pressbooks_updating_stylesheet' ) ) {
				set_transient( 'pressbooks_updating_stylesheet', 1, 5 * MINUTE_IN_SECONDS );
				( new Modules\ThemeOptions\Admin() )->clearCache();
				$this->updateWebBookStyleSheet();
				update_editor_style();
				if ( $buckram_updated ) {
					update_option( 'pressbooks_buckram_version', $current_buckram_version );
				}
				if ( $theme_updated ) {
					update_option( 'pressbooks_theme_version', $current_theme_version );
				}
				delete_transient( 'pressbooks_updating_stylesheet' );
				return true;
			}
		}

		return false;
	}
733516
protected function uploadedDirIsWriteable()
    {
        $result = $this->Checkup->Webroot->isWriteable();

        return $result && array_key_exists(UPLOADED, $result) ? $result[UPLOADED] : false;
    }
1190335
public function getHeaderText()
    {
        $rule = $this->registry->registry('current_ddg_rule');

        if ($rule->getId()) {
            return __('Edit Rule %1', $this->escapeHtml($rule->getName()));
        } else {
            return __('New Rule');
        }
    }
294407
public function makeHeader()
    {
        // reset and recalculate
        $this->setAudioFormat();                                    // implicit setAudioSubFormat(), setFactChunkSize(), setFmtExtendedSize(), setFmtChunkSize(), setSize(), setActualSize(), setDataOffset()
        $this->setNumBlocks();

        // RIFF header
        $header = pack('N', 0x52494646);                            // ChunkID - "RIFF"
        $header .= pack('V', $this->getChunkSize());                // ChunkSize
        $header .= pack('N', 0x57415645);                           // Format - "WAVE"

        // "fmt " subchunk
        $header .= pack('N', 0x666d7420);                           // SubchunkID - "fmt "
        $header .= pack('V', $this->getFmtChunkSize());             // SubchunkSize
        $header .= pack('v', $this->getAudioFormat());              // AudioFormat
        $header .= pack('v', $this->getNumChannels());              // NumChannels
        $header .= pack('V', $this->getSampleRate());               // SampleRate
        $header .= pack('V', $this->getByteRate());                 // ByteRate
        $header .= pack('v', $this->getBlockAlign());               // BlockAlign
        $header .= pack('v', $this->getBitsPerSample());            // BitsPerSample
        if($this->getFmtExtendedSize() == 24) {
            $header .= pack('v', 22);                               // extension size = 24 bytes, cbSize: 24 - 2 = 22 bytes
            $header .= pack('v', $this->getValidBitsPerSample());   // ValidBitsPerSample
            $header .= pack('V', $this->getChannelMask());          // ChannelMask
            $header .= pack('H32', $this->getAudioSubFormat());     // SubFormat
        } elseif ($this->getFmtExtendedSize() == 2) {
            $header .= pack('v', 0);                                // extension size = 2 bytes, cbSize: 2 - 2 = 0 bytes
        }

        // "fact" subchunk
        if ($this->getFactChunkSize() == 4) {
            $header .= pack('N', 0x66616374);                       // SubchunkID - "fact"
            $header .= pack('V', 4);                                // SubchunkSize
            $header .= pack('V', $this->getNumBlocks());            // SampleLength (per channel)
        }

        return $header;
    }
407199
protected function _writeHeader()
    {
        $output = "# LANGUAGE translation of CakePHP Application\n";
        $output .= "# Copyright YEAR NAME <EMAIL@ADDRESS>\n";
        $output .= "#\n";
        $output .= "#, fuzzy\n";
        $output .= "msgid \"\"\n";
        $output .= "msgstr \"\"\n";
        $output .= "\"Project-Id-Version: PROJECT VERSION\\n\"\n";
        $output .= '"POT-Creation-Date: ' . date('Y-m-d H:iO') . "\\n\"\n";
        $output .= "\"PO-Revision-Date: YYYY-mm-DD HH:MM+ZZZZ\\n\"\n";
        $output .= "\"Last-Translator: NAME <EMAIL@ADDRESS>\\n\"\n";
        $output .= "\"Language-Team: LANGUAGE <EMAIL@ADDRESS>\\n\"\n";
        $output .= "\"MIME-Version: 1.0\\n\"\n";
        $output .= "\"Content-Type: text/plain; charset=utf-8\\n\"\n";
        $output .= "\"Content-Transfer-Encoding: 8bit\\n\"\n";
        $output .= "\"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\\n\"\n\n";

        return $output;
    }
724094
public function generateHeaders()
    {
        // Workaround for encoded email addresses.
        // When encoded, email addresses (at least the name param) have more characters
        // By default, line length is set to 76 characters, after what a new line is created with $lineBreak.
        // This operation is done during encoding via iconv (see ezcMailTools::composeEmailAddress()).
        // Problem is that this operation is done a 2nd time in ezcMailPart::generateHeaders().
        // Following code ensures that there is no double $lineBreak introduced
        // by this process because it potentially breaks headers
        $lineBreak = ezcMailTools::lineBreak();
        $headers = str_replace( "$lineBreak$lineBreak", $lineBreak, parent::generateHeaders() );
        return $headers;
    }
160274
public function buildHeaders()
    {
        if ($this->use_cors) {
            if (strlen($this->cors_allow_origin) > 0) {
                header("Access-Control-Allow-Origin: $this->cors_allow_origin");
            }
            if ($this->cors_with_credentials) {
                header('Access-Control-Allow-Credentials: true');
            } else {
                header('Access-Control-Allow-Credentials: false');
            }
        }

        // Cache Control RFC: https://tools.ietf.org/html/rfc7234
        if ($this->nb_request instanceof CNabuHTTPRequest &&
            ($nb_site_target = $this->nb_request->getSiteTarget()) instanceof CNabuSiteTarget
        ) {
            if (($max_age = $nb_site_target->getDynamicCacheEffectiveMaxAge()) !== false) {
                $expire_date = gmdate("D, d M Y H:i:s", time() + $max_age);
                $this->setHeader('Expires', $expire_date . 'GMT');
                $this->setHeader('Cache-Control', "max-age=$max_age");
                $this->setHeader('User-Cache-Control', "max-age=$max_age");
                $this->setHeader('Pragma', 'cache');
            } else {
                $this->setHeader('Expires', 'Thu, 1 Jan 1981 00:00:00 GMT');
                $this->setheader('Cache-Control', 'no-store, no-cache, must-revalidate');
                $this->setHeader('Pragma', 'no-cache');
            }
            if ($nb_site_target->getAttachment() === 'T') {
                if (is_string($this->attachment_filename) && strlen($this->attachment_filename) > 0) {
                    $this->setHeader('Content-Disposition', 'attachment; filename=' . $this->attachment_filename);
                } else {
                    $this->setHeader('Content-Disposition', 'attachment');
                }
            }
        }

        if (($frame_options = $this->calculateFrameOptions()) !== null) {
            $this->setHeader('X-Frame-Options', $frame_options);
        }

        if (count($this->header_list) > 0) {
            foreach ($this->header_list as $name => $value) {
                header("$name: $value");
            }
        }
    }
204212
public function composerUpdateHash()
    {
        $paths = $this->getPaths();
        $this->stopOnFail(true);
        $this->info('Updating Composer lock file');
        $command = $this->taskExec('composer')->dir($paths['root']);
        $command
            ->arg('update')
            ->option('lock')
            ->printOutput(true)
            ->run();
        $this->info('Composer lock file updated');
    }
63361
private function generateFilename()
    {
        if ($this->filename) {
            return $this->filename;
        }

        if ($this->hash_filename) {
            return $this->generateHash();
        }

        return $this->sanitizeFileName($this->source->filename());
    }
515055
protected function canonicalizeHeaders()
    {
        $canonical = array();
        $headers = array();
        if (isset($this->config['headers'])) {
            $headers = array_map('strtolower', array_keys($this->config['headers']));
            if (count($this->config['headers']) > 0) {
                $headers = array_combine(
                    $headers,
                    array_values($this->config['headers'])
                );
            }
        }

        foreach ($this->headers_to_sign as $key) {
            $key = strtolower($key);
            if (isset($headers[$key])) {
                if (is_array($headers[$key]) && count($headers[$key]) >= 1) {
                    $value = trim($headers[$key][0]);
                } elseif (is_array($headers[$key]) && count($headers[$key]) === 0) {
                    continue;
                } else {
                    $value = trim($headers[$key]);
                }

                if (!empty($value)) {
                    $canonical[$key] = preg_replace('/\s+/', ' ', $value);
                }
            }
        }

        ksort($canonical);
        $serialized_header = '';
        foreach ($canonical as $key => $value) {
            $serialized_header .= $key . ':' . $value . "\t";
        }

        return rtrim($serialized_header);
    }
1310364
private function generateHead()
	{
		$out  = '<?xml version="1.0" encoding="utf-8"?>' . "\n";

		if ($this->version == self::RSS2)
		{
			$out .= '<rss version="2.0"
					xmlns:content="http://purl.org/rss/1.0/modules/content/"
					xmlns:wfw="http://wellformedweb.org/CommentAPI/"
				  >' . PHP_EOL;
		}
		elseif ($this->version == self::RSS1)
		{
			$out .= '<rdf:RDF
					 xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
					 xmlns="http://purl.org/rss/1.0/"
					 xmlns:dc="http://purl.org/dc/elements/1.1/"
					>' . PHP_EOL;
		}
		elseif ($this->version == self::ATOM)
		{
			$out .= '<feed xmlns="http://www.w3.org/2005/Atom">' . PHP_EOL;
		}
		return $out;
	}
553925
public function buildDefaultHeader(): void
    {
        $this->set(PoTokens::MESSAGE, "");
        $this->set(PoTokens::TRANSLATOR_COMMENTS, 'SOME DESCRIPTIVE TITLE');
        $this->add(PoTokens::TRANSLATOR_COMMENTS, 'Copyright (C) YEAR HOLDER');
        $this->add(PoTokens::TRANSLATOR_COMMENTS, 'LICENSE');
        $this->add(PoTokens::TRANSLATOR_COMMENTS, 'FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.');
        $this->add(PoTokens::TRANSLATOR_COMMENTS, '');
        $this->set(PoTokens::FLAG, 'fuzzy');
        $this->setHeader('Project-Id-Version', 'PACKAGE VERSION');
        $this->setHeader('Report-Msgid-Bugs-To', 'FULL NAME <EMAIL@ADDRESS>');
        $this->setCreateDate();
        $this->setHeader('PO-Revision-Date', 'YEAR-MO-DA HO:MI+ZONE');
        $this->setHeader('Last-Translator', 'FULL NAME <EMAIL@ADDRESS>');
        $this->setHeader('Language-Team', 'LANGUAGE <EMAIL@ADDRESS>');
        $this->setHeader('MIME-Version', '1.0');
        $this->setHeader('Content-Type', 'text/plain; charset=UTF-8');
        $this->setHeader('Content-Transfer-Encoding', '8bit');
        $this->setHeader('Plural-Forms', 'nplurals=INTEGER; plural=EXPRESSION;');
        $this->setHeader('X-Generator', 'geekwright/po');
    }