<?php

// +----------------------------------------------------------------------
// | date: 2015-09-12
// +----------------------------------------------------------------------
// | Upload.php: 七牛上传实现
// +----------------------------------------------------------------------
// | Author: yangyifan <yangyifanphp@gmail.com>
// +----------------------------------------------------------------------

namespace Ikodota\Upload\Qiniu;

use League\Flysystem\Adapter\AbstractAdapter;
use League\Flysystem\Config;
use Qiniu\Storage\ResumeUploader;
use Qiniu\Storage\UploadManager;
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Config AS QiniuConfig;
use Symfony\Component\Finder\SplFileInfo;
use InvalidArgumentException;
use Yangyifan\Upload\Functions\FileFunction;

class QiniuAdapter extends AbstractAdapter
{
    /**
     * Auth
     *
     * @var Auth
     */
    protected $auth;

    /**
     * token
     *
     * @var string
     */
    protected $token;

    /**
     * bucket
     *
     * @var
     */
    protected $bucket;

    /**
     * 七牛空间管理对象
     *
     * @var
     */
    protected $bucketManager;

    /**
     * 上传对象
     *
     * @var
     */
    protected $uploadManager;

    /**
     * 二进制流上传对象
     *
     * @var
     */
    protected $resumeUploader;

    /**
     * 配置信息
     *
     * @var array
     */
    protected $config;

    /**
     * 构造方法
     *
     * @param array $config 配置信息
     * @author yangyifan <yangyifanphp@gmail.com>
     */
    public function __construct($config)
    {
        $this->config   = $config;
        $this->bucket   = $this->config['bucket'];
        $this->auth     = new Auth($this->config['access_key'], $this->config['secret_key']);
        $this->token    = $this->auth->uploadToken($this->bucket);

        //设置路径前缀
        $this->setPathPrefix($this->config['transport'] . '://' . $this->config['domain']);
    }

    /**
     * 获得七牛空间管理对象
     *
     * @return BucketManager
     * @author yangyifan <yangyifanphp@gmail.com>
     */
    protected function getBucketManager()
    {
        if (!$this->bucketManager) {
            $this->bucketManager = new BucketManager($this->auth);
        }
        return $this->bucketManager;
    }

    /**
     * 获得七牛上传对象
     *
     * @return UploadManager
     * @author yangyifan <yangyifanphp@gmail.com>
     */
    protected function getUploadManager()
    {
        if (!$this->uploadManager) {
            $this->uploadManager = new UploadManager();
        }
        return $this->uploadManager;
    }

    /**
     * 获得二进制流上传对象
     *
     * @param $key          上传文件名
     * @param $inputStream  上传二进制流
     * @param $config       配置信息
     * @param $params       自定义变量
     * @return ResumeUploader
     * @author yangyifan <yangyifanphp@gmail.com>
     */
    protected function getResumeUpload($key, $inputStream, Config $config, $params = null)
    {
        if (!$this->resumeUploader) {
            if (!$config->has('file_path')) {
                throw new InvalidArgumentException("请配置 file_path 选项，此选项表示需要上传的文件的路径");
            }

            $file_path = $config->get('file_path');

            if ( $file_path ) {
                $file_info = new \SplFileInfo($file_path);

                if ($file_info->isFile() == true) {
                    $this->resumeUploader = new ResumeUploader( $this->token, $key, $inputStream, $file_info->getSize(), $params, FileFunction::getFileMimeType($file_path), (new QiniuConfig()) );
                }
            }

            throw new InvalidArgumentException("{$file_path} 不是一个文件");
        }
        return $this->resumeUploader;
    }

    /**
     * 判断文件是否存在
     *
     * @param string $path
     * @return bool
     * @author yangyifan <yangyifanphp@gmail.com>
     */
    public function has($path)
    {
        $file_stat = $this->getMetadata($path);
        return !empty($file_stat) ? true : false;
    }

    /**
     * 读取文件
     *
     * @param $file_name
     * @author yangyifan <yangyifanphp@gmail.com>
     */
    public function read($path)
    {
        return ['contents' => file_get_contents($this->applyPathPrefix($path)) ];
    }

    /**
     * 获得文件流
     *
     * @param string $path
     * @return array
     * @author yangyifan <yangyifanphp@gmail.com>
     */
    public function readStream($path)
    {
        return ['stream' => fopen($this->applyPathPrefix($path), 'r')];
    }

    /**
     * 写入文件
     *
     * @param $file_name
     * @param $contents
     * @author yangyifan <yangyifanphp@gmail.com>
     */
    public function write($path, $contents, Config $config)
    {
        list(, $error) = $this->getUploadManager()->put($this->token, $path, $contents);

        if ($error) {
            return false;
        }
        return true;
    }

    /**
     * 写入文件流
     *
     * @param string $path
     * @param resource $resource
     * @param array $config
     */
    public function writeStream($path, $resource, Config $config)
    {
        list(, $error) = $this->getResumeUpload($path, $resource, $config)->upload();

        return $error ? false : true;
    }

    /**
     * 更新文件
     *
     * @param string $path
     * @param string $contents
     * @param array $config
     */
    public function update($path, $contents, Config $config)
    {
        return $this->write($path, $contents, $config);
    }

    /**
     * 更新文件流
     *
     * @param string $path
     * @param resource $resource
     * @param array $config
     */
    public function updateStream($path, $resource, Config $config)
    {
        return $this->writeStream($path, $resource, $config);
    }

    /**
     * 列出目录文件
     *
     * @param string $directory
     * @param bool|false $recursive
     * @return array
     * @author yangyifan <yangyifanphp@gmail.com>
     */
    public function listContents($directory = '', $recursive = false)
    {
        list($file_list, $marker, $error) = $this->getBucketManager()->listFiles($this->bucket, $directory);

        if (!$error) {
            foreach ($file_list as &$file) {
                $file['path']   = $file['key'];
                $file['marker'] = $marker;//用于下次请求的标识符
            }
            return $file_list;
        }
        return false;
    }

    /**
     * 获取资源的元信息，但不返回文件内容
     *
     * @param $path
     * @return array
     * @author yangyifan <yangyifanphp@gmail.com>
     */
    public function getMetadata($path)
    {
        list($info, $error) = $this->getBucketManager()->stat($this->bucket, $path);

        if ($error) {
            return false;
        }
        return $info;
    }

    /**
     * 获得文件大小
     *
     * @param string $path
     * @return int
     * @author yangyifan <yangyifanphp@gmail.com>
     */
    public function getSize($path)
    {
        list($fsize, , , ) = array_values($this->getMetadata($path));
        return $fsize > 0 ? [ 'size' => $fsize ] : false;
    }

    /**
     * 获得文件Mime类型
     *
     * @param string $path
     * @return mixed string|null
     * @author yangyifan <yangyifanphp@gmail.com>
     */
    public function getMimetype($path)
    {
        list(, , $mimeType,) = array_values($this->getMetadata($path));
        return !empty($mimeType) ? ['mimetype' => $mimeType ] : false;
    }

    /**
     * 获得文件最后修改时间
     *
     * @param string $path
     * @return int 时间戳
     * @author yangyifan <yangyifanphp@gmail.com>
     */
    public function getTimestamp($path)
    {
        list(, , , $timestamp) = array_values($this->getMetadata($path));
        return !empty($timestamp) ? ['timestamp' => $timestamp ] : false;
    }

    /**
     * 获得文件模式 (未实现)
     *
     * @param string $path
     * @author yangyifan <yangyifanphp@gmail.com>
     */
    public function getVisibility($path)
    {
        return self::VISIBILITY_PUBLIC;
    }

    /**
     * 重命名文件
     *
     * @param $oldname
     * @param $newname
     * @return boolean
     * @author yangyifan <yangyifanphp@gmail.com>
     */
    public function rename($path, $newpath)
    {
        return $this->getBucketManager()->rename($this->bucket, $path, $newpath) == null ? true : false;
    }

    /**
     * 复制文件
     *
     * @param $path
     * @param $newpath
     * @return boolean
     * @author yangyifan <yangyifanphp@gmail.com>
     */
    public function copy($path, $newpath)
    {
        return $this->getBucketManager()->copy($this->bucket, $path, $this->bucket, $newpath) == null ? true : false;
    }

    /**
     * 删除文件或者文件夹
     *
     * @param $path
     * @author yangyifan <yangyifanphp@gmail.com>
     */
    public function delete($path)
    {
        return $this->getBucketManager()->delete($this->bucket, $path);
    }

    /**
     * 删除文件夹
     *
     * @param string $path
     * @return mixed
     * @author yangyifan <yangyifanphp@gmail.com>
     */
    public function deleteDir($path)
    {
        list($file_list, , $error) = $this->getBucketManager()->listFiles($this->bucket, $path);

        if (!$error) {
            foreach ( $file_list as $file) {
                $this->delete($file['key']);
            }
        }
        return true;
    }

    /**
     * 创建文件夹(因为七牛没有文件夹的概念，所以此方法没有实现)
     *
     * @param string $dirname
     * @param array $config
     * @author yangyifan <yangyifanphp@gmail.com>
     */
    public function createDir($dirname, Config $config)
    {
        return true;
    }

    /**
     * 设置文件模式 (未实现)
     *
     * @param string $path
     * @param string $visibility
     * @return bool
     * @author yangyifan <yangyifanphp@gmail.com>
     */
    public function setVisibility($path, $visibility)
    {
        return true;
    }
}


<?php
namespace Potter\Theme;

abstract class Options
{
    protected $page_title          = 'Theme Options';
    protected $menu_title          = 'Theme Options';
    protected $settings_id         = 'theme_options';
    protected $header_logo         = null;
    protected $header_version_text = null;
    protected $header_logo_link    = null;
    protected $show_new_layout     = false;
    protected $show_docs           = false;
    protected $show_pages          = false;
    protected $options_capability  = 'edit_theme_options';

    protected $contextual_help = array(
        'content' => array(),
        'sidebar' => ''
    );
    protected $sections        = array();
    protected $settings        = array();

    protected $current_section = null;

    public function __construct()
    {
        add_filter('ot_settings_id', array($this, 'getSettingsId'));
        add_filter('ot_show_new_layout', array($this, 'getShowNewLayout'));
        add_filter('ot_show_docs', array($this, 'getShowDocs'));
        add_filter('ot_show_pages', array($this, 'getShowPages'));
        add_filter('ot_theme_options_page_title', array($this, 'getPageTitle'));
        add_filter('ot_theme_options_menu_title', array($this, 'getMenuTitle'));
        add_filter('ot_header_logo_link', array($this, 'getHeaderLogoLink'));
        add_filter('ot_header_version_text', array($this, 'getHeaderVersionText'));
        add_filter('ot_theme_options_capability', array($this, 'getOptionsCapability'));

        add_action('admin_init', array($this, 'admin_init'));

        $this->doRegister();
    }

    /**
     * @return boolean
     */
    public function getShowPages()
    {
        return $this->show_pages;
    }

    /**
     * @return string
     */
    public function getMenuTitle()
    {
        return $this->menu_title;
    }

    /**
     * @return string
     */
    public function getHeaderLogo()
    {
        return $this->header_logo;
    }

    /**
     * @return string
     */
    public function getHeaderLogoLink()
    {
        return $this->header_logo_link;
    }

    /**
     * @return string
     */
    public function getHeaderVersionText()
    {
        return $this->header_version_text;
    }

    /**
     * @return string
     */
    public function getPageTitle()
    {
        return $this->page_title;
    }

    /**
     * @return string
     */
    public function getSettingsId()
    {
        return $this->settings_id;
    }

    /**
     * @return boolean
     */
    public function getShowDocs()
    {
        return $this->show_docs;
    }

    /**
     * @return string
     */
    public function getOptionsCapability()
    {
        return $this->options_capability;
    }

    /**
     * @return boolean
     */
    public function getShowNewLayout()
    {
        return $this->show_new_layout;
    }

    public function  admin_init()
    {
        /**
         * Get a copy of the saved settings array.
         */
        $saved_settings = get_option(ot_settings_id(), array());

        /**
         * Custom settings array that will eventually be
         * passes to the OptionTree Settings API Class.
         */
        $custom_settings = array(
            'contextual_help' => $this->contextual_help,
            'sections'        => $this->sections,
            'settings'        => $this->settings
        );

        /* allow settings to be filtered before saving */
        $custom_settings = apply_filters(ot_settings_id() . '_args', $custom_settings);

        /* settings are not the same update the DB */
        if ($saved_settings !== $custom_settings) {
            update_option(ot_settings_id(), $custom_settings);
        }
    }

    /**
     * @param $id
     * @param $title
     *
     * @return $this
     */
    public function addSection($id, $title)
    {
        $this->sections[] = array(
            'id'    => $id,
            'title' => $title,
        );

        $this->current_section = $id;

        return $this;
    }

    /**
     * @return array
     */
    public function getSettings()
    {
        return $this->settings;
    }

    /**
     * @param array $choices
     *
     * @return array
     */
    protected function filterChoices(array $choices)
    {
        $return = array();

        foreach ($choices as $key => $choice):
            if (!isset($choice['value']) or empty($choice['value'])):
                $choice['value'] = $key;
            endif;

            if (!isset($choice['label']) or empty($choice['label'])):
                $choice['label'] = $choice['value'];
            endif;
            $return[] = $choice;
        endforeach;

        return $return;
    }

    /**
     * @param array $args
     *
     * @return $this
     */
    public function addOption(array $args)
    {
        $default = array(
            'id'           => '',
            'label'        => '',
            'desc'         => '',
            'std'          => '',
            'type'         => 'text',
            'section'      => '',
            'rows'         => '',
            'taxonomy'     => '',
            'min_max_step' => '',
            'class'        => '',
            'condition'    => '',
            'operator'     => 'and'
        );

        if (empty($args['section'])):
            $args['section'] = $this->current_section;
        endif;

        $args = wp_parse_args($args, $default);

        $this->settings[] = $args;

        return $this;
    }

    /**
     * @param string $id
     * @param string $label
     * @param string $desc
     * @param string $std
     * @param string $section
     * @param array  $extra
     *
     * @return $this
     */
    public function addText($id, $label, $desc = null, $std = null, $section = null, array $extra = array())
    {
        $args = array(
            'id'      => $id,
            'label'   => $label,
            'std'     => $std,
            'desc'    => $desc,
            'type'    => 'text',
            'section' => $section
        );

        $args = array_merge($args, $extra);

        return $this->addOption($args);

    }

    /**
     * @param string $id
     * @param string $label
     * @param string $desc
     * @param string $std
     * @param string $section
     * @param array  $extra
     *
     * @return $this
     */
    public function addTextarea($id, $label, $desc = null, $std = null, $section = null, array $extra = array())
    {
        $args = array(
            'id'      => $id,
            'label'   => $label,
            'std'     => $std,
            'desc'    => $desc,
            'type'    => 'textarea-simple',
            'rows'    => '7',
            'section' => $section,
        );

        $args = array_merge($args, $extra);

        return $this->addOption($args);

    }

    /**
     * @param string $id
     * @param string $label
     * @param string $desc
     * @param string $std
     * @param string $section
     * @param array  $extra
     *
     * @return $this
     */
    public function addWYSIWYG($id, $label, $desc = null, $std = null, $section = null, array $extra = array())
    {
        $args = array(
            'id'      => $id,
            'label'   => $label,
            'std'     => $std,
            'desc'    => $desc,
            'type'    => 'textarea',
            'section' => $section
        );

        $args = array_merge($args, $extra);

        return $this->addOption($args);

    }

    /**
     * @param string $id
     * @param string $label
     * @param string $desc
     * @param string $std
     * @param string $section
     * @param array  $extra
     *
     * @return $this
     */
    public function addUpload($id, $label, $desc = null, $std = null, $section = null, array $extra = array())
    {
        $args = array(
            'id'      => $id,
            'label'   => $label,
            'std'     => $std,
            'desc'    => $desc,
            'type'    => 'upload',
            'section' => $section,
        );

        $args = array_merge($args, $extra);

        return $this->addOption($args);

    }

    /**
     * @param string $id
     * @param string $label
     * @param null   $desc
     * @param null   $section
     * @param array  $extra
     *
     * @return Options
     */
    public function addTextblock($id, $label, $desc = null, $section = null, array $extra = array())
    {
        $args = array(
            'id'      => $id,
            'label'   => $label,
            'desc'    => $desc,
            'type'    => 'textblock',
            'section' => $section,
        );

        $args = array_merge($args, $extra);

        return $this->addOption($args);
    }

    /**
     * @param string $id
     * @param string $label
     * @param null   $desc
     * @param null   $section
     * @param array  $extra
     *
     * @return Options
     */
    public function addTextblockTitled($id, $label, $desc = null, $section = null, array $extra = array())
    {
        $args = array(
            'id'      => $id,
            'label'   => $label,
            'desc'    => $desc,
            'type'    => 'textblock-titled',
            'section' => $section,
        );

        $args = array_merge($args, $extra);

        return $this->addOption($args);

    }

    /**
     * @param string $id
     * @param string $label
     * @param string $desc
     * @param string $postType
     * @param string $std
     * @param string $section
     * @param array  $extra
     *
     * @return $this
     */
    public function addCustomPostTypeSelect(
        $id,
        $label,
        $desc = null,
        $postType = 'post',
        $std = null,
        $section = null,
        array $extra = array()
    ) {
        $args = array(
            'id'        => $id,
            'label'     => $label,
            'std'       => $std,
            'desc'      => $desc,
            'type'      => 'custom-post-type-select',
            'post_type' => $postType,
            'section'   => $section,
        );

        $args = array_merge($args, $extra);

        return $this->addOption($args);
    }

    /**
     * @param string $id
     * @param string $label
     * @param string $desc
     * @param string $postType
     * @param string $std
     * @param string $section
     * @param array  $extra
     *
     * @return $this
     */
    public function addCustomPostTypeCheckbox(
        $id,
        $label,
        $desc = null,
        $postType = 'post',
        $std = null,
        $section = null,
        array $extra = array()
    ) {
        $args = array(
            'id'        => $id,
            'label'     => $label,
            'std'       => $std,
            'desc'      => $desc,
            'type'      => 'custom-post-type-checkbox',
            'post_type' => $postType,
            'section'   => $section,
        );

        $args = array_merge($args, $extra);

        return $this->addOption($args);
    }

    /**
     * @param string $id
     * @param string $label
     * @param string $desc
     * @param string $std
     * @param string $section
     * @param array  $extra
     *
     * @return $this
     */
    public function addPageCheckbox($id, $label, $desc = null, $std = null, $section = null, array $extra = array())
    {
        return $this->addCustomPostTypeCheckbox($id, $label, $desc, 'page', $std, $section, $extra);
    }

    /**
     * @param string $id
     * @param string $label
     * @param string $desc
     * @param string $std
     * @param string $section
     * @param array  $extra
     *
     * @return $this
     */
    public function addPageSelect($id, $label, $desc = null, $std = null, $section = null, array $extra = array())
    {
        return $this->addCustomPostTypeSelect($id, $label, $desc, 'page', $std, $section, $extra);
    }

    /**
     * @param string $id
     * @param string $label
     * @param string $desc
     * @param string $std
     * @param string $section
     * @param array  $extra
     *
     * @return $this
     */
    public function addPostCheckbox($id, $label, $desc = null, $std = null, $section = null, array $extra = array())
    {
        return $this->addCustomPostTypeCheckbox($id, $label, $desc, 'post', $std, $section, $extra);
    }

    /**
     * @param string $id
     * @param string $label
     * @param string $desc
     * @param string $std
     * @param string $section
     * @param array  $extra
     *
     * @return $this
     */
    public function addPostSelect($id, $label, $desc = null, $std = null, $section = null, array $extra = array())
    {
        return $this->addCustomPostTypeSelect($id, $label, $desc, 'post', $std, $section, $extra);
    }

    /**
     * @param string $id
     * @param string $label
     * @param string $desc
     * @param string $taxonomy
     * @param string $std
     * @param string $section
     * @param array  $extra
     *
     * @return $this
     */
    public function addTaxonomySelect(
        $id,
        $label,
        $desc = null,
        $taxonomy = 'category',
        $std = null,
        $section = null,
        array $extra = array()
    ) {
        $args = array(
            'id'       => $id,
            'label'    => $label,
            'std'      => $std,
            'desc'     => $desc,
            'type'     => 'taxonomy-select',
            'taxonomy' => $taxonomy,
            'section'  => $section,
        );

        $args = array_merge($args, $extra);

        return $this->addOption($args);
    }

    /**
     * @param string $id
     * @param string $label
     * @param string $desc
     * @param string $taxonomy
     * @param string $std
     * @param string $section
     * @param array  $extra
     *
     * @return $this
     */
    public function addTaxonomyCheckbox(
        $id,
        $label,
        $desc = null,
        $taxonomy = 'category',
        $std = null,
        $section = null,
        array $extra = array()
    ) {
        $args = array(
            'id'       => $id,
            'label'    => $label,
            'std'      => $std,
            'desc'     => $desc,
            'type'     => 'taxonomy-checkbox',
            'taxonomy' => $taxonomy,
            'section'  => $section,
        );

        $args = array_merge($args, $extra);

        return $this->addOption($args);
    }

    /**
     * @param string $id
     * @param string $label
     * @param string $desc
     * @param string $std
     * @param string $section
     * @param array  $extra
     *
     * @return $this
     */
    public function addCategorySelect($id, $label, $desc = null, $std = null, $section = null, array $extra = array())
    {
        return $this->addTaxonomySelect($id, $label, $desc, 'category', $std, $section, $extra);
    }

    /**
     * @param string $id
     * @param string $label
     * @param string $desc
     * @param string $std
     * @param string $section
     * @param array  $extra
     *
     * @return $this
     */
    public function addCategoryCheckbox($id, $label, $desc = null, $std = null, $section = null, array $extra = array())
    {
        return $this->addTaxonomyCheckbox($id, $label, $desc, 'category', $std, $section, $extra);
    }

    /**
     * @param string $id
     * @param string $label
     * @param string $desc
     * @param string $std
     * @param string $section
     * @param array  $extra
     *
     * @return $this
     */
    public function addTagSelect($id, $label, $desc = null, $std = null, $section = null, array $extra = array())
    {
        return $this->addTaxonomySelect($id, $label, $desc, 'post_tag', $std, $section, $extra);
    }

    /**
     * @param string $id
     * @param string $label
     * @param string $desc
     * @param string $std
     * @param string $section
     * @param array  $extra
     *
     * @return $this
     */
    public function addTagCheckbox($id, $label, $desc = null, $std = null, $section = null, array $extra = array())
    {
        return $this->addTaxonomyCheckbox($id, $label, $desc, 'post_tag', $std, $section, $extra);
    }

    /**
     * @param string $id
     * @param string $label
     * @param string $desc
     * @param string $std
     * @param string $section
     * @param array  $extra
     *
     * @return $this
     */
    public function addTypography($id, $label, $desc = null, $std = null, $section = null, array $extra = array())
    {
        $args = array(
            'id'      => $id,
            'label'   => $label,
            'std'     => $std,
            'desc'    => $desc,
            'type'    => 'typography',
            'section' => $section
        );

        $args = array_merge($args, $extra);

        return $this->addOption($args);

    }

    /**
     * @param string $id
     * @param string $label
     * @param array  $choices
     * @param string $desc
     * @param string $std
     * @param string $section
     * @param array  $extra
     *
     * @return $this
     */
    public function addRadio(
        $id,
        $label,
        array $choices,
        $desc = null,
        $std = null,
        $section = null,
        array $extra = array()
    ) {
        $choices = $this->filterChoices($choices);

        $args = array(
            'id'      => $id,
            'label'   => $label,
            'desc'    => $desc,
            'std'     => $std,
            'type'    => 'radio',
            'section' => $section,
            'choices' => $choices
        );

        $args = array_merge($args, $extra);

        return $this->addOption($args);
    }

    /**
     * @param string $id
     * @param string $label
     * @param array  $choices
     * @param string $desc
     * @param string $std
     * @param string $section
     * @param array  $extra
     *
     * @return $this
     */
    public function addSelect(
        $id,
        $label,
        array $choices,
        $desc = null,
        $std = null,
        $section = null,
        array $extra = array()
    ) {
        $choices = $this->filterChoices($choices);

        $args = array(
            'id'      => $id,
            'label'   => $label,
            'desc'    => $desc,
            'std'     => $std,
            'type'    => 'select',
            'section' => $section,
            'choices' => $choices
        );

        $args = array_merge($args, $extra);

        return $this->addOption($args);
    }

    /**
     * @param string $id
     * @param string $label
     * @param array  $choices
     * @param string $desc
     * @param string $std
     * @param string $section
     * @param array  $extra
     *
     * @return $this
     */
    public function addCheckbox(
        $id,
        $label,
        array $choices,
        $desc = null,
        $std = null,
        $section = null,
        array $extra = array()
    ) {
        $choices = $this->filterChoices($choices);

        $args = array(
            'id'      => $id,
            'label'   => $label,
            'desc'    => $desc,
            'std'     => $std,
            'type'    => 'checkbox',
            'section' => $section,
            'choices' => $choices
        );

        $args = array_merge($args, $extra);

        return $this->addOption($args);
    }

    /**
     * @param string $id
     * @param string $label
     * @param string $desc
     * @param string $std
     * @param string $section
     * @param array  $extra
     *
     * @return $this
     */
    public function addOnOff($id, $label, $desc = null, $std = null, $section = null, array $extra = array())
    {
        $args = array(
            'id'      => $id,
            'label'   => $label,
            'std'     => $std,
            'desc'    => $desc,
            'type'    => 'on-off',
            'section' => $section
        );

        $args = array_merge($args, $extra);

        return $this->addOption($args);

    }

    abstract function doRegister();
}


<?php
/*
 * This file is part of the Invite Wsapi Bundle
 *
 * The bundle provides a mapping to Cisco's IOS UC Gateway Api.
 *
 * (c) Invite Networks Inc. <info@invitenetworks.com>
 *
 * For the full copyright and license information,
 * please view the LICENSE file that was distributed
 * with this source code.
 */
namespace Invite\Component\Cisco\Wsapi\Request;

use Invite\Component\Cisco\Wsapi\Request\WsapiRequestInterface;

/**
 * INVITE WsApi Request Abstract class.
 *
 * @category   API
 * @author     Josh Whiting <josh@invitenetworks.com>
 * @version    Release: @package_version@
 * @since      Class available since Release 1.1.0
 */
abstract class WsapiRequest implements WsapiRequestInterface
{

    protected $msgHeader;
    protected $registrationID;
    protected $transactionID;
    protected $applicationData;
    protected $applicationUrl;
    protected $providerData;
    protected $providerUrl;
    protected $schema;
    protected $sequence;
    protected $interval;
    protected $failureCount;
    protected $registered = false;
    protected $providerStatus;
    protected $options = array();
    protected $valid = true;

    /**
     * Xcdr Soap Handler construct.
     *
     * @param array additonal options
     */
    public function __construct(array$options = array())
    {
        $this->options = $options;
    }

    /**
     * Respond to wsapi keepalive probing response.
     */
    protected function probing($msgHeader, $sequence, $interval, $failureCount, $registered, $providerStatus)
    {
        $this->msgHeader = $msgHeader;
        $this->registrationID = $msgHeader->registrationID;
        $this->transactionID = $msgHeader->transactionID;
        $this->sequence = $sequence;
        $this->interval = $interval;
        $this->failureCount = $failureCount;
        $this->registered = $registered;
        $this->providerStatus = $providerStatus;

        $soapObjXML =
                '<msgHeader>
                    <registrationID>' . $this->registrationID . '</registrationID>
                    <transactionID>' . $this->transactionID . '</transactionID>
                </msgHeader>
                <sequence>' . $this->sequence . '</sequence>'
        ;

        $soapXML = new \SoapVar($soapObjXML, XSD_ANYXML, null, null, null, $this->schema);

        return $soapXML;
    }

    /**
     * Respond to wsapi xcdr unregister response.
     */
    protected function unregister($msgHeader)
    {
        $this->msgHeader = $msgHeader;
        $this->registrationID = $msgHeader->registrationID;
        $this->transactionID = $msgHeader->transactionID;

        $soapObjXML =
                '<msgHeader>
                    <registrationID>' . $this->registrationID . '</registrationID>
                    <transactionID>' . $this->transactionID . '</transactionID>
                </msgHeader>'
        ;

        $soapXML = new \SoapVar($soapObjXML, XSD_ANYXML, null, null, null, $this->schema);

        return $soapXML;
    }

    /**
     * Respond to wsapi xcdr status change message.
     */
    protected function status($msgHeader, $applicationData, $providerData, $providerStatus)
    {
        $this->msgHeader = $msgHeader;
        $this->transactionID = $msgHeader->transactionID;
        $this->applicationData = $applicationData;
        $this->applicationUrl = $applicationData->url;
        $this->providerData = $providerData;
        $this->providerUrl = $providerData->url;
        $this->providerStatus = $providerStatus;

        return;
    }

    /**
     * @return std Object
     */
    public function getMsgHeader()
    {
        return $this->msgHeader;
    }

    /**
     * @return string
     */
    public function getRegistrationID()
    {
        return $this->registrationID;
    }

    /**
     * @return string
     */
    public function getTransactionID()
    {
        return $this->transactionID;
    }

    /**
     * @return string
     */
    public function getApplicationData()
    {
        return $this->applicationData;
    }

    /**
     * @return string
     */
    public function getApplicationUrl()
    {
        return $this->applicationUrl;
    }

    /**
     * @return string
     */
    public function getProviderData()
    {
        return $this->providerData;
    }

    /**
     * @return string
     */
    public function getProviderUrl()
    {
        return $this->providerUrl;
    }

    /**
     * @return string
     */
    public function getProviderStatus()
    {
        return $this->providerStatus;
    }

    /**
     * @return string
     */
    public function setProviderStatus($status)
    {
        $this->providerStatus = $status;
        return $this;
    }

    /**
     * @return string
     */
    public function getSchema()
    {
        return $this->schema;
    }

    /**
     * @return string
     */
    public function isInService()
    {
        return $this->providerStatus === 'IN_SERVICE' ? true : false;
    }

    /**
     * @return string
     */
    public function isShutdown()
    {
        return $this->providerStatus === 'SHUTDOWN' ? true : false;
    }

    /**
     * @return string
     */
    public function getSequence()
    {
        return $this->sequence;
    }

    /**
     * @return string
     */
    public function getInterval()
    {
        return $this->interval;
    }

    /**
     * @return string
     */
    public function getFailureCount()
    {
        return $this->failureCount;
    }

    /**
     * @return string
     */
    public function isRegistered()
    {
        return $this->registered;
    }

    /**
     * @return string
     */
    public function SetRegistered($registered)
    {
        $this->registered = $registered;
        return $this;
    }

    /**
     * @return string
     */
    public function isValid()
    {
        return $this->valid;
    }

    /**
     * @return string
     */
    public function setValid($valid)
    {
        $this->valid = $valid;
        return $this;
    }

    /**
     * @return string
     */
    public function getOptions()
    {
        return $this->options;
    }

    /**
     * @return string
     */
    public function setOptions(array$options)
    {
        $this->options = $options;
    }

    /**
     * @return string
     */
    public function setOption($key, $option)
    {
        $this->options[$key] = $option;
    }

    /**
     * @return string
     */
    public function hasOption($option)
    {
        return array_key_exists($option, $this->options) ? true : false;
    }

}


<?php
/**
 * Base provider class.
 *
 * @package metis
 */

namespace Metis;

use Pimple\Container;
use Pimple\ServiceProviderInterface;

/**
 * Defines the base provider abstract class.
 */
abstract class Base_Provider implements ServiceProviderInterface {
	/**
	 * Cached proxy objects.
	 *
	 * @var Proxy[]
	 */
	protected $proxies = array();

	/**
	 * Get a proxy object for a given container entry.
	 *
	 * @param  Container $container Container instance.
	 * @param  string    $key       Container key.
	 *
	 * @return Proxy
	 */
	public function proxy( Container $container, $key ) {
		if ( isset( $this->proxies[ $key ] ) ) {
			return $this->proxies[ $key ];
		}

		$this->proxies[ $key ] = new Proxy( $container, $key );

		return $this->proxies[ $key ];
	}
}


<?php
namespace AdobeConnect;

/**
 * Provides a connection with an Adobe Connect's Host, log in the admin user, and provides the method to call actions.
 *
 * @author Nassajis <nassaji.s@gmail.com>
 */
class Connection
{
    /** @var    Config      Connection Configuration */
    protected $config;

    /** @var    string      The value of the session cookie at AdobeConnect */
    protected $cookie;

    /** @var    bool        Is the connection established? */
    protected $connected = false;

    /** @var    bool        Is the user logged in? */
    protected $loggedIn = false;

    /**
     * @param   Config $config
     */
    public function __construct(Config $config)
    {
        $this->config = $config;
    }

    /**
     * @param string $action
     * @param array  $params
     *
     * @return \SimpleXMLElement
     *
     * @see doRequest
     */
    public function callAction($action, $params = array())
    {
        return $this->doRequest($action, $params)->getXmlResponse();
    }

    /**
     * Establish a connection to AdobeConnect's server
     */
    public function connect()
    {
        if (! $this->getCookie()) {
            $response = $this->doRequest('common-info');

            $this->setCookie($response->getXmlResponse()->common->cookie);
        }

        $this->connected = true;
    }

    public function login()
    {
        $this->checkIfIsConnected();

        $this->doRequest('login', array(
            'login' => $this->config->getUsername(),
            'password' => $this->config->getPassword(),
        ));

        $this->loggedIn = true;
    }

    /** @return Config */
    public function getConfig()
    {
        return $this->config;
    }

    /**
     * @return bool     true if is already connected
     *
     * @throws  \Exception      If is not connected yet
     */
    protected function checkIfIsConnected()
    {
        if (! $this->connected) {
            throw new \Exception(sprintf('First you have to establish a connection.'));
        }

        return true;
    }

    /**
     * @return bool     true if is already logged in
     *
     * @throws  \Exception      If is not logged in yet
     */
    protected function checkIfIsLoggedIn()
    {
        if (! $this->loggedIn) {
            throw new \Exception(sprintf('First you have to log in a admin user.'));
        }

        return true;
    }

    /**
     * Call to an action from AdobeConnect's Server
     *
     * @param string $action
     * @param array  $params
     *
     * @return Response
     */
    protected function doRequest($action, $params = array())
    {
        if ('common-info' != $action && 'login' != $action) {
            $this->checkIfIsConnected();
            $this->checkIfIsLoggedIn();
        }

        if ($this->cookie && ! isset($params['session'])) {
            $params['session'] = $this->getCookie();
        }

        return new Response(new Request($this->config->getHost(), $action, $params));
    }

    /**
     * @param string $cookie
     *
     * @return Connection
     */
    protected function setCookie($cookie)
    {
		ini_set('error_reporting', E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);
        $this->cookie = trim(base64_encode(mcrypt_encrypt(
            MCRYPT_RIJNDAEL_256, '7e2d20j23a21db9f', $cookie, MCRYPT_MODE_ECB, $this->config->getSecret()
        )));

        setcookie($this->config->getCookieName(), $this->cookie, (time() + 60 * 5), null, null, null, true);

        return $this;
    }

    /**
     * @return string|null
     */
    protected function getCookie()
    {
		ini_set('error_reporting', E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);
        if (! $this->cookie && isset($_COOKIE[$this->config->getCookieName()])) {
            $this->cookie = $_COOKIE[$this->config->getCookieName()];
        }
        if ($this->cookie) {
            return trim(utf8_encode(mcrypt_decrypt(
                MCRYPT_RIJNDAEL_256,
                '7e2d20j23a21db9f',
                base64_decode($this->cookie),
                MCRYPT_MODE_ECB,
                $this->config->getSecret()
            )));
        }

        return null;
    }
}


<?php namespace Impleri\Toolbox;

use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\ServiceProvider;

class ToolboxServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     * @var bool
     */
    protected $defer = false;

    /**
     * Bootstrap the application events.
     */
    public function boot()
    {
        $this->package('impleri/toolbox', null, realpath(__DIR__));
    }

    /**
     * Register the service provider.
     */
    public function register()
    {
        App::bind(
            'toolbox.commands.controllers',
            function () {
                return new \Impleri\Toolbox\Commands\ControllersCommand();
            }
        );

        App::bind(
            'toolbox.commands.models',
            function () {
                return new \Impleri\Toolbox\Commands\ModelsCommand();
            }
        );

        App::bind(
            'toolbox.commands.routes',
            function () {
                return new \Impleri\Toolbox\Commands\RoutesCommand();
            }
        );

        App::bind(
            'toolbox.commands.schema',
            function () {
                return new \Impleri\Toolbox\Commands\SchemaCommand();
            }
        );

        App::bind(
            'toolbox.commands.views',
            function () {
                return new \Impleri\Toolbox\Commands\ViewsCommand();
            }
        );

        App::bind(
            'toolbox.commands.build',
            function () {
                return new \Impleri\Toolbox\Commands\BuildCommand();
            }
        );

        $this->commands($this->provides());

        // Subscribe our own commands to toolbox.compile
        Event::listen('toolbox.build', function ($app) {
            $app->call('toolbox:routes');
            $app->call('toolbox:controllers');
            $app->call('toolbox:models');
            $app->call('toolbox:schema');
            $app->call('toolbox:views');
        });
    }

    /**
     * Get the services provided by the provider.
     * @return array
     */
    public function provides()
    {
        return [
            'toolbox.commands.controllers',
            'toolbox.commands.models',
            'toolbox.commands.routes',
            'toolbox.commands.schema',
            'toolbox.commands.views',
            'toolbox.commands.build'
        ];
    }
}


<?php namespace Impleri\Toolbox\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Event;

abstract class BaseCommand extends Command
{
    /**
     * Execute the console command.
     */
    protected function trump($event, $label)
    {
        $this->line('');

        $message = 'This will generate ' . $label . ' for all of the packages that'
            . ' subscribe to the `' . $event . '` event.';
        $this->comment($message);
        $this->line('');

        if ($this->confirm('Proceed with rebuilding ' . $label . '? [Yes|no]')) {
            $this->line('');

            // Trigger generation
            $this->info('Generating ' . $label . '...');
            $counts = Event::fire($event);
            $total = array_sum($counts);

            // Done!
            $this->line('');
            $this->info('Process completed!');
            if ($total) {
                $this->info($total . ' ' . $label . ' saved.');
            }
            $this->line('');
        }
    }
}


<?php
/**
 * Class Log
 *
 * @filesource   Log.php
 * @created      04.01.2018
 * @package      chillerlan\Logger
 * @author       Smiley <smiley@chillerlan.net>
 * @copyright    2018 Smiley
 * @license      MIT
 */

namespace chillerlan\Logger;

use chillerlan\Logger\Output\LogOutputInterface;
use Psr\Log\{LoggerInterface, LoggerTrait};

class Log implements LoggerInterface{
	use LoggerTrait;

	/**
	 * @var \chillerlan\Logger\Output\LogOutputInterface[]
	 */
	protected $logOutputInterfaces = [];

	/**
	 * @return void
	 */
	public function __destruct(){
		$this->close();
	}

	/**
	 * closes all remaining logger instances
	 *
	 * @return \chillerlan\Logger\Log
	 */
	public function close():Log{

		if(!empty($this->logOutputInterfaces)){
			foreach($this->logOutputInterfaces as $instanceName => $instance){
				unset($this->logOutputInterfaces[$instanceName]);
			}
		}

		return $this;
	}

	/**
	 * @param \chillerlan\Logger\Output\LogOutputInterface $logger
	 * @param string                                       $instanceName
	 *
	 * @return \chillerlan\Logger\Log
	 */
	public function addInstance(LogOutputInterface $logger, string $instanceName = null):Log{
		$this->logOutputInterfaces[$instanceName ?? 'default'] = $logger;

		return $this;
	}

	/**
	 * @param string $instanceName
	 *
	 * @return \chillerlan\Logger\Output\LogOutputInterface
	 * @throws \chillerlan\Logger\LogException
	 */
	public function getInstance(string $instanceName):LogOutputInterface{

		if(!array_key_exists($instanceName, $this->logOutputInterfaces)){
			throw new LogException('invalid logger instance: '.$instanceName);
		}

		return $this->logOutputInterfaces[$instanceName];
	}

	/**
	 * @param string $instanceName
	 *
	 * @return \chillerlan\Logger\Log
	 * @throws \chillerlan\Logger\LogException
	 */
	public function removeInstance(string $instanceName):Log{

		if(!array_key_exists($instanceName, $this->logOutputInterfaces)){
			throw new LogException('invalid logger instance: '.$instanceName);
		}

		unset($this->logOutputInterfaces[$instanceName]);

		return $this;
	}

	/**
	 * Logs with an arbitrary level.
	 *
	 * @param mixed       $level
	 * @param string      $message
	 * @param array       $context
	 *
	 * @param string|null $instance
	 *
	 * @return void
	 */
	public function log($level, $message, array $context = [], string $instance = null):void{

		foreach($this->logOutputInterfaces as $logger){
			$logger->log($level, $message, $context);
		}

	}

}


<?php

namespace Potter;

use Illuminate\Support\Collection;
use Potter\Theme\OptionsEmpty;
use Super_CPT_Loader;

class PotterCore
{
    /**
     * @var array
     */
    protected $autoloadFolders = array('app/models', 'app/taxonomies');
    /**
     * @var string
     */
    protected $widgetsFolder = 'app/widgets';
    /**
     * @var array
     */
    protected $autolaodFiles = array();
    /**
     * @var string
     */
    protected $themeDIR;
    /**
     * @var string
     */
    protected $themeURL;
    /**
     * @var \Illuminate\Support\Collection
     */
    protected $models;
    /**
     * @var \Illuminate\Support\Collection
     */
    protected $widgets;

    /**
     * @var \Potter\Theme\Options
     */
    protected $optionsInstance;

    public function __construct()
    {
        $this->themeDIR = THEME_DIR;
        $this->themeURL = THEME_URL;

        $this->models = new Collection();
        $this->widgets = new Collection();
    }

    /**
     * Load files
     * @return void
     */
    public function autoload()
    {
        $folders = apply_filters('potter_autoload_folders', $this->autoloadFolders);
        $files = apply_filters('potter_autoload_files', $this->autolaodFiles);

        // Files
        foreach ($files as $file) {
            $file = cleanURI($this->themeDIR . $file);
            $this->loadFile($file);
        }

        // Folders
        foreach ($folders as $folder):
            $pattern = $this->themeDIR . $folder . "/*.php";
            foreach (glob($pattern) as $file):
                $this->loadFile($file);
            endforeach;
        endforeach;

        $this->loadWidgets();
        $this->loadThemeOptions();
    }

    /**
     * @param $file
     *
     * @return mixed
     */
    public function  loadFile($file)
    {
        $file = cleanURI($file);
        if (!file_exists($file)) return false;;
        // Include
        require_once($file);

        $name = basename($file, '.php');

        // File class
        if (class_exists($name)):
            $class = new $name;
            //Model Class
            if (is_subclass_of($name, 'Potter\Post\Type')):
                $this->registerModel($class);
            endif;

            return $class;
        endif;

        return true;
    }

    /**
     * Load and register widgets
     */
    protected function loadWidgets()
    {
        $widgets_folder = apply_filters('potter_widgets_folder', $this->widgetsFolder);

        $pattern = $this->themeDIR . $widgets_folder . "/*.php";

        foreach (glob($pattern) as $file): // Load File
            require_once($file);

            $widget = basename($file, '.php');

            // Register
            if (class_exists($widget)):
                $this->widgets->push($widget);
            endif;
        endforeach;
    }

    /**
     * Load end register theme options
     */
    private function loadThemeOptions()
    {
        $file = cleanURI($this->themeDIR . 'app/ThemeOptions.php');
        $file = apply_filters('potter_autoload_themeoptions', $file);

        $class = $this->loadFile($file);

        if (!$class):
            $class = new OptionsEmpty();
            add_action('admin_menu', array($this, 'remove_ot_theme_options_page'), 999);
        endif;

        $this->optionsInstance = $class;
    }

    public function remove_ot_theme_options_page()
    {
        remove_submenu_page('themes.php', 'ot-theme-options');
    }

    /**
     * @return Collection
     */
    public function getModels()
    {
        return $this->models;
    }

    /**
     * @return Collection
     */
    public function getWidgets()
    {
        return $this->widgets;
    }

    /**
     * @return Theme\Options
     */
    public function getOptionsInstance()
    {
        return $this->optionsInstance;
    }

    /**
     * @param Post\Type $postType
     */
    private function registerModel(Post\Type $postType)
    {
        $type = $postType->getPostType();

        $this->models->put($type, $postType);
    }
}


<?php namespace Gears;
////////////////////////////////////////////////////////////////////////////////
// __________ __             ________                   __________
// \______   \  |__ ______  /  _____/  ____ _____ ______\______   \ _______  ___
//  |     ___/  |  \\____ \/   \  ____/ __ \\__  \\_  __ \    |  _//  _ \  \/  /
//  |    |   |   Y  \  |_> >    \_\  \  ___/ / __ \|  | \/    |   (  <_> >    <
//  |____|   |___|  /   __/ \______  /\___  >____  /__|  |______  /\____/__/\_ \
//                \/|__|           \/     \/     \/             \/            \/
// -----------------------------------------------------------------------------
//          Designed and Developed by Brad Jones <brad @="bjc.id.au" />
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////

use \Gears\Arrays\Fluent;
use \Gears\Arrays\Exceptions\InvalidMethod;
use \Illuminate\Support\Arr as LaravelArray;

class Arrays extends LaravelArray
{
	/**
	 * Method: a
	 * =========================================================================
	 * This is the static factory method allowing a syntax like this:
	 *
	 * ```php
	 * Arr::a([1,2,3])->add(4)->each(function($v){ echo $v; });
	 * ```
	 *
	 * Parameters:
	 * -------------------------------------------------------------------------
	 * $array - A PHP array to turn into a Gears\Arrays\Fluent object
	 *
	 * Returns:
	 * -------------------------------------------------------------------------
	 * A new instance of Gears\Arrays\Fluent object
	 */
	public static function a(array $array = array())
	{
		return Fluent::make($array);
	}

	/**
	 * Method: add
	 * =========================================================================
	 * We are overloading the parent add method so that we can accept
	 * either an array of keys or "dot" separated keys. This should stay
	 * compatiable with the upstream method.
	 *
	 * For example the following 2 calls are the same:
	 *
	 * ```php
	 * Arr::add([], 'a.b.c', 'd');
	 * Arr::add([], ['a','b','c'], 'd');
	 * ```
	 *
	 * Parameters:
	 * -------------------------------------------------------------------------
	 * $array - A PHP array to add items to.
	 * $key - Can be a single key, "dot" separated keys or an array of keys.
	 * $value - The value to set.
	 *
	 * Returns:
	 * -------------------------------------------------------------------------
	 * array
	 */
	public static function add($array, $key, $value)
	{
		// this allows the key to be an array of keys
		if (\Gears\Arrays\isArrayLike($key)) $key = implode('.', $key);

		return parent::add($array, $key, $value);
	}

	/**
	 * Method: get
	 * =========================================================================
	 * We are overloading the parent get method so that we can accept
	 * either an array of keys or "dot" separated keys. This should stay
	 * compatiable with the upstream method.
	 *
	 * For example the following 2 calls are the same:
	 *
	 * ```php
	 * Arr::get(['a' => ['b' => ['c' => 'd']]], 'a.b.c');
	 * Arr::get(['a' => ['b' => ['c' => 'd']]], ['a','b','c']);
	 * ```
	 *
	 * Parameters:
	 * -------------------------------------------------------------------------
	 * $array - A PHP array to get items from.
	 * $key - Can be a single key, "dot" separated keys or an array of keys.
	 * $default - A value to return upon failure.
	 *
	 * Returns:
	 * -------------------------------------------------------------------------
	 * mixed
	 */
	public static function get($array, $key, $default = null)
	{
		// this allows the key to be an array of keys
		if (\Gears\Arrays\isArrayLike($key)) $key = implode('.', $key);

		return parent::get($array, $key, $default);
	}

	/**
	 * Method: set
	 * =========================================================================
	 * We are overloading the parent set method so that we can accept
	 * either an array of keys or "dot" separated keys. This should stay
	 * compatiable with the upstream method.
	 *
	 * For example the following 2 calls are the same:
	 *
	 * ```php
	 * Arr::set([], 'a.b.c', 'd');
	 * Arr::set([], ['a','b','c'], 'd');
	 * ```
	 *
	 * Parameters:
	 * -------------------------------------------------------------------------
	 * $array - A refrence to the PHP array to set items in.
	 * $key - Can be a single key, "dot" separated keys or an array of keys.
	 * $value - The value to set.
	 *
	 * Returns:
	 * -------------------------------------------------------------------------
	 * array
	 */
	public static function set(&$array, $key, $value)
	{
		// this allows the key to be an array of keys
		if (\Gears\Arrays\isArrayLike($key)) $key = implode('.', $key);

		return parent::set($array, $key, $value);
	}

	/**
	 * Method: forget
	 * =========================================================================
	 * We are overloading the parent forget method so that we can accept
	 * either an array of keys or "dot" separated keys. This should stay
	 * compatiable with the upstream method.
	 *
	 * For example the following 2 calls are the same:
	 *
	 * ```php
	 * Arr::forget(['a' => ['b' => ['c' => 'd']]], 'a.b.c');
	 * Arr::forget(['a' => ['b' => ['c' => 'd']]], ['a','b','c']);
	 * ```
	 *
	 * Parameters:
	 * -------------------------------------------------------------------------
	 * $array - A refrence to the PHP array to remove items from.
	 * $keys - Can be a single key, "dot" separated keys or an array of keys.
	 *
	 * Returns:
	 * -------------------------------------------------------------------------
	 * void
	 */
	public static function forget(&$array, $keys)
	{
		// this allows the key to be an array of keys
		if (\Gears\Arrays\isArrayLike($keys))
		{
			$new_keys = [];

			foreach ($keys as $key)
			{
				if (\Gears\Arrays\isArrayLike($key))
				{
					$new_keys[] = implode('.', $key);
				}
				else
				{
					$new_keys[] = $key;
				}
			}

			$keys = $new_keys;
		}

		return parent::forget($array, $keys);
	}

	/**
	 * Method: fetch
	 * =========================================================================
	 * We are overloading the parent fetch method so that we can accept
	 * either an array of keys or "dot" separated keys. This should stay
	 * compatiable with the upstream method.
	 *
	 * For example the following 2 calls are the same:
	 *
	 * ```php
	 * Arr::fetch(['a' => ['b' => ['c' => 'd']]], 'a.b.c');
	 * Arr::fetch(['a' => ['b' => ['c' => 'd']]], ['a','b','c']);
	 * ```
	 *
	 * Parameters:
	 * -------------------------------------------------------------------------
	 * $array - A refrence to the PHP array to remove items from.
	 * $keys - Can be a single key, "dot" separated keys or an array of keys.
	 *
	 * Returns:
	 * -------------------------------------------------------------------------
	 * void
	 */
	public static function fetch($array, $key)
	{
		// this allows the key to be an array of keys
		if (\Gears\Arrays\isArrayLike($key)) $key = implode('.', $key);

		return parent::fetch($array, $key);
	}

	/**
	 * Method: __callStatic
	 * =========================================================================
	 * The existing methods in the ```Illuminate\Support\Arr``` class
	 * are awesome. But there are some extra methods we would like to have
	 * access to.
	 *
	 * This will first look for a function under our \Gears\Arrays
	 * namespace. If one is found we call that function for you, as if it
	 * were a static method of this class.
	 *
	 * If we can't find a function there we then check for any macros.
	 * If a macro exists we hand control to our parent.
	 *
	 * On failure of all that we finally throw an InvalidMethod Exception.
	 *
	 * NOTE: Any functions which require a reference to be passed through will
	 * not work via __callStatic. As the magic method does not accept
	 * references. These functions need to be defined in this class as stubs.
	 *
	 * Parameters:
	 * -------------------------------------------------------------------------
	 * $name - The name of the \Gears\Arrays\"FUNCTION" to call.
	 * $arguments - The arguments to pass to the function.
	 *
	 * Returns:
	 * -------------------------------------------------------------------------
	 * mixed
	 */
	public static function __callStatic($name, $arguments)
	{
		// Create the function name
		$func_name = '\Gears\Arrays\\'.$name;

		// Does the function exist
		if (!function_exists($func_name))
		{
			// Try a macro
			if (self::hasMacro($name))
			{
				return parent::__callStatic($name, $arguments);
			}

			// Bail out, we don't have a function to run
			throw new InvalidMethod($name);
		}

		// Call the function
		return call_user_func_array($func_name, $arguments);
	}
}


<?php
/**
 * @version     $Revision: $:
 * @author      $Author: $:
 * @date        $Date: $:
 */
namespace ManiaLivePlugins\NadeoLive\AutoTweet;

use ManiaLive\DedicatedApi\Callback\Event as ServerEvent;

class Plugin extends \ManiaLive\PluginHandler\Plugin
{
	/**
	 * @var Config
	 */
	protected $config;

	protected $twitter;

	public function onInit()
	{
		$this->config = Config::getInstance();

		$this->setVersion('0.0.1');

		$this->addDependency(new \ManiaLive\PluginHandler\Dependency('NadeoLive\XmlRpcScript'));

		$this->twitter = new TwitterAPIExchange(array(
			'oauth_access_token' => $this->config->twitterOauthAccessToken,
			'oauth_access_token_secret' => $this->config->twitterOauthAccessTokenSecret,
			'consumer_key' => $this->config->twitterConsumerKey,
			'consumer_secret' => $this->config->twitterConsumerSecret
		));
	}

	protected function postTwitterMessage($message)
	{
		 $this->twitter->buildOauth('https://api.twitter.com/1.1/statuses/update.json', 'POST')
             ->setPostfields(array('status' => $message))
             ->performRequest();
	}

	public function onLoad()
	{
		$this->enableDedicatedEvents();

		\ManiaLive\Event\Dispatcher::register(\ManiaLivePlugins\NadeoLive\XmlRpcScript\Event::getClass(), $this);

		$this->connection->setModeScriptSettings(array('S_UseScriptCallbacks' => true));

		$this->postTwitterMessage(sprintf('Now following %s', $this->storage->server->name));
	}

	public function onTick()
	{
	}

	function onUnload()
	{
	}

	function onBeginMap($map, $warmUp, $matchContinuation)
	{
		$map = \DedicatedApi\Structures\Map::fromArray($map);
		$this->postTwitterMessage(sprintf("Map change for %s", $this->formatForTwitter($map->name)));
	}

	function onPlayerConnect($login, $isSpectator)
	{
	}

	function onPlayerDisconnect($login, $disconnectionReason)
	{
	}

	function onPlayerChangeSide($player, $oldSide)
	{

	}

	//Xml RPC events
	function onXmlRpcEliteBeginTurn($content)
	{
		$this->postTwitterMessage(sprintf("Turn #%d: %s attack", $content->TurnNumber, $this->formatForTwitter($content->AttackingPlayer->Name)));
	}

	function onXmlRpcEliteEndTurn($content)
	{
		$this->postTwitterMessage(sprintf("Turn #%d end", $content->TurnNumber));
	}

	function onXmlRpcEliteArmorEmpty($content)
	{
		$message = sprintf("%s has eliminated %s",
			$this->formatForTwitter($content->Event->Shooter->Name),
			$this->formatForTwitter($content->Event->Victim->Name));
		$this->postTwitterMessage($message);
	}

	function onXmlRpcEliteShoot($content)
	{
	}

	function onXmlRpcEliteHit($content)
	{
		if ($content->Event->Victim->IsTouchingGround == false)
		{
			$message = "AIRSHOT: ";
		}
		else
		{
			$message = "";
		}
		$message .= sprintf("%s has hit %s with %s",
				$this->formatForTwitter($content->Event->Shooter->Name),
				$this->formatForTwitter($content->Event->Victim->Name),
				$this->getWeaponName($content->Event->WeaponNum));

		if ($content->Event->HitDist > 50)
		{
			$message .= sprintf(" from %sm", $content->Event->HitDist);
		}

		$this->postTwitterMessage($message);
	}

	function onXmlRpcEliteMatchStart($content)
	{
		$this->postTwitterMessage("Match Started!");
		$this->postTwitterMessage(sprintf("Current map: %s", $this->formatForTwitter($this->storage->currentMap->name)));
	}

	function onXmlRpcEliteCapture($content)
	{
		$message = sprintf("%s has secured the pole",
				$this->formatForTwitter($content->Event->Player->Name));

		$this->postTwitterMessage($message);
	}

	function onXmlRpcEliteNearMiss($content)
	{
		$message = sprintf("%s missed %s by %01.2f cm",
				$this->formatForTwitter($content->Event->Shooter->Name),
				$this->formatForTwitter($content->Event->Victim->Name),
				$this->formatForTwitter($content->Event->MissDist));

		$this->postTwitterMessage($message);
	}

	protected function getWeaponName($num)
	{
		switch ($num)
		{
			case 1:
				return 'laser';
			case 2:
				return 'rocket';
			case 3:
				return 'nucleus';
			case 5:
				return 'arrow';
			default:
				return '';
		}
	}

	protected function formatForTwitter($text)
	{
		return \ManiaLib\Utils\Formatting::stripStyles($text);
	}
}


<?php

namespace Encore\Wx\Element;

use wxIcon;
use Encore\Giml\ElementTrait;
use Encore\Wx\Element\Traits\Wx;
use Encore\Wx\Element\Raw\TaskBarIcon as RawTaskBarIcon;
use Encore\Giml\ElementInterface;

class TaskBarIcon implements ElementInterface
{
    use ElementTrait;
    use Wx;

    /**
     * Initialise the object
     *
     * @return void
     */
    public function init()
    {
        $this->element = new RawTaskBarIcon;

        $resourcesPath = $this->collection->getContainer()->resourcesPath();

        $icon = new wxIcon($resourcesPath.'/'.$this->icon, wxBITMAP_TYPE_ANY);

        $this->element->SetIcon($icon, $this->tip);
    }

    /**
     * Add a child element
     *
     * @param ElementInterface $child
     */
    public function addChild(ElementInterface $child)
    {
        if ($child instanceof Menu) {
            $this->element->setMenu($child);
        }

        $this->children[] = $child;
    }
}


<?php

namespace L5Starter\PermissionManager\Http\Controllers\Admin;

use L5Starter\PermissionManager\Http\Requests\CreatePermissionRequest;
use L5Starter\PermissionManager\Http\Requests\UpdatePermissionRequest;
use L5Starter\PermissionManager\Repositories\PermissionRepository;
use App\Http\Controllers\Controller;
use Flash;
use L5Starter\PermissionManager\Repositories\RoleRepository;
use Response;

class PermissionController extends Controller
{
    private $permissionRepository;
    private $roleRepository;

    public function __construct(PermissionRepository $permissionRepository, RoleRepository $roleRepository)
    {
        $this->permissionRepository = $permissionRepository;
        $this->roleRepository = $roleRepository;
    }

    /**
     * Display a listing of the Permission.
     *
     * @return Response
     */
    public function index()
    {
        $permissions = $this->permissionRepository->paginate(config('settings.resultsPerPage'));

        return view('permissions::index')->with('permissions', $permissions);
    }

    /**
     * Show the form for creating a new Permission.
     *
     * @return Response
     */
    public function create()
    {
        return view('permissions::create')->with([
            'roles' => $this->roleRepository->all(),
        ]);
    }

    /**
     * Store a newly created Permission in storage.
     *
     * @param CreatePermissionRequest $request
     *
     * @return Response
     */
    public function store(CreatePermissionRequest $request)
    {
        $input = $request->all();

        $permission = $this->permissionRepository->create([
            'name' => $input['name'],
        ]);

        foreach ($input['roles'] as $role) {
            $permission->roles()->attach($role);
        }

        Flash::success(trans('l5starter::messages.create.success'));

        return redirect(route('admin.permissions.index'));
    }

    /**
     * Show the form for editing the specified Permission.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        $permission = $this->permissionRepository->findWithoutFail($id);

        if (empty($permission)) {
            Flash::error(trans('l5starter::messages.404_not_found'));

            return redirect(route('admin.permissions.index'));
        }

        return view('permissions::edit')->with([
            'roles' => $this->roleRepository->all(),
            'permission' => $permission,
        ]);
    }

    /**
     * Update the specified Permission in storage.
     *
     * @param  int $id
     * @param UpdatePermissionRequest $request
     *
     * @return Response
     */
    public function update($id, UpdatePermissionRequest $request)
    {
        $permission = $this->permissionRepository->findWithoutFail($id);

        if (empty($permission)) {
            Flash::error(trans('l5starter::messages.404_not_found'));

            return redirect(route('admin.permissions.index'));
        }

        $input = $request->all();

        $permission = $this->permissionRepository->update([
            'name' => $input['name'],
        ], $id);

        $roles = [];

        if (!empty($input['roles'])) {
            foreach ($input['roles'] as $role) {
                $roles[$role] = $role;
            }
        }

        $permission->roles()->sync($roles);

        Flash::success(trans('l5starter::messages.update.success'));

        return redirect(route('admin.permissions.index'));
    }

    /**
     * Remove the specified Permission from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        $permission = $this->permissionRepository->findWithoutFail($id);

        if (empty($permission)) {
            Flash::error(trans('l5starter::messages.404_not_found'));

            return redirect(route('admin.permissions.index'));
        }

        $this->permissionRepository->delete($id);

        Flash::success(trans('l5starter::messages.delete.success'));

        return redirect(route('admin.permissions.index'));
    }
}


<?php

/*
 * admin42
 *
 * @package admin42
 * @link https://github.com/kiwi-suite/admin42
 * @copyright Copyright (c) 2010 - 2017 kiwi suite (https://www.kiwi-suite.com)
 * @license MIT License
 * @author kiwi suite <tech@kiwi-suite.com>
 */

namespace Admin42\FormElements;

use Zend\Filter\StringTrim;
use Zend\Form\Element;
use Zend\InputFilter\InputProviderInterface;
use Zend\Validator\StringLength;

class Text extends Element implements InputProviderInterface, AngularAwareInterface
{
    use ElementTrait;

    /**
     * @var int
     */
    protected $minLength = 0;

    /**
     * @var int
     */
    protected $maxLength = 524288;

    /**
     * @param array|\Traversable $options
     * @return $this
     */
    public function setOptions($options)
    {
        if (!empty($options['minLength'])) {
            $this->setMinLength(\max((int) $options['minLength'], 0));
        }

        if (!empty($options['maxLength'])) {
            $this->setMaxLength(\min((int) $options['maxLength'], 524288));
        }

        return $this;
    }

    /**
     * @return int
     */
    public function getMinLength()
    {
        return $this->minLength;
    }

    /**
     * @param int $minLength
     * @return Text
     */
    public function setMinLength($minLength)
    {
        $this->minLength = $minLength;

        return $this;
    }

    /**
     * @return int
     */
    public function getMaxLength()
    {
        return $this->maxLength;
    }

    /**
     * @param int $maxLength
     * @return Text
     */
    public function setMaxLength($maxLength)
    {
        $this->maxLength = $maxLength;

        return $this;
    }

    /**
     * Should return an array specification compatible with
     * {@link Zend\InputFilter\Factory::createInput()}.
     *
     * @return array
     */
    public function getInputSpecification()
    {
        return [
            'name' => $this->getName(),
            'required' => $this->isRequired(),
            'filters' => [
                ['name' => StringTrim::class],
            ],
            'validators' => [
                [
                    'name' => StringLength::class,
                    'options' => ['max' => $this->getMaxLength(), 'min' => $this->getMinLength()],
                ],
            ],
        ];
    }
}


<?php

namespace Fossar\GuzzleTranscoder;

class Utils {
    /**
     * HTTP Headers Util 0.1.
     *
     * @author: Keyvan Minoukadeh - hide@address.com - http://www.keyvan.net
     *
     * @license GNU General Public License, version 2
     *
     * @see (source) http://www.phpkode.com/source/s/http-headers-utility/http-headers-utility/HTTP_Headers_Util.php
     *
     * This method is based on:
     * <http://search.cpan.org/author/GAAS/libwww-perl-5.65/lib/HTTP/Headers/Util.pm>
     * by Gisle Aas.
     * The text here is copied from the documentation of the above, obviously
     * slightly modified as this is PHP not Perl.
     *
     * split_header_words
     *
     * This function will parse the header values given as argument into a
     * array containing key/value pairs.  The function
     * knows how to deal with ",", ";" and "=" as well as quoted values after
     * "=".  A list of space separated tokens are parsed as if they were
     * separated by ";".
     *
     * If the $headerValues passed as argument contains multiple values,
     * then they are treated as if they were a single value separated by
     * comma ",".
     *
     * This means that this function is useful for parsing header fields that
     * follow this syntax (BNF as from the HTTP/1.1 specification, but we relax
     * the requirement for tokens).
     *
     *   headers           = #header
     *   header            = (token | parameter) *( [";"] (token | parameter))
     *
     *   token             = 1*<any CHAR except CTLs or separators>
     *   separators        = "(" | ")" | "<" | ">" | "@"
     *                     | "," | ";" | ":" | "\" | <">
     *                     | "/" | "[" | "]" | "?" | "="
     *                     | "{" | "}" | SP | HT
     *
     *   quoted-string     = ( <"> *(qdtext | quoted-pair ) <"> )
     *   qdtext            = <any TEXT except <">>
     *   quoted-pair       = "\" CHAR
     *
     *   parameter         = attribute "=" value
     *   attribute         = token
     *   value             = token | quoted-string
     *
     * Each header is represented by an anonymous array of key/value
     * pairs.  The value for a simple token (not part of a parameter) is null.
     * Syntactically incorrect headers will not necessary be parsed as you
     * would want.
     *
     * This is easier to describe with some examples:
     *
     *    split_header_words('foo="bar"; port="80,81"; discard, bar=baz');
     *    split_header_words('text/html; charset="iso-8859-1");
     *    split_header_words('Basic realm="\"foo\\bar\""');
     *    split_header_words("</TheBook/chapter,2>;         rel=\"pre,vious\"; title*=UTF-8'de'letztes%20Kapitel, </TheBook/chapter4>;rel=\"next\"; title*=UTF-8'de'n%c3%a4chstes%20Kapitel");
     *
     * will return
     *
     *    [foo=>'bar', port=>'80,81', discard=>null], [bar=>'baz']
     *    ['text/html'=>null, charset=>'iso-8859-1']
     *    [Basic=>null, realm=>'"foo\bar"']
     *    ["</TheBook/chapter,2>" => null, "rel" => "pre,vious", "title*" => "UTF-8'de'letztes%20Kapitel" ], ["</TheBook/chapter4>" => null, "rel" => "next", "title*" => "UTF-8'de'n%c3%a4chstes%20Kapitel" ]
     *
     * @param array|string $headerValues
     *
     * @throws \Exception
     *
     * @return array
     */
    public static function splitHttpHeaderWords($headerValues) {
        if (!\is_array($headerValues)) {
            $headerValues = [$headerValues];
        }

        $result = [];
        foreach ($headerValues as $header) {
            $cur = [];
            while ($header) {
                $key = '';
                $val = null;
                // Parse <link> header correctly http://tools.ietf.org/html/rfc5988#section-5
                if (preg_match('/^\s*(<[^>]*>)(.*)/', $header, $match)) {
                    $key = $match[1];
                    $header = $match[2];
                    $cur[$key] = null;
                } elseif (preg_match('/^\s*(=*[^\s=;,]+)(.*)/', $header, $match)) {
                    // 'token' or parameter 'attribute'
                    $key = $match[1];
                    $header = $match[2];
                    // a quoted value
                    if (preg_match('/^\s*=\s*"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"(.*)/', $header, $match)) {
                        $val = $match[1];
                        $header = $match[2];
                        // remove backslash character escape
                        $val = preg_replace('/\\\\(.)/', '$1', $val);
                    // some unquoted value
                    } elseif (preg_match('/^\s*=\s*([^;,\s]*)(.*)/', $header, $match)) {
                        $val = trim($match[1]);
                        $header = $match[2];
                    }
                    // add details
                    $cur[$key] = $val;
                // reached the end, a new 'token' or 'attribute' about to start
                } elseif (preg_match('/^\s*,(.*)/', $header, $match)) {
                    $header = $match[1];
                    if (\count($cur)) {
                        $result[] = $cur;
                    }
                    $cur = [];
                // continue
                } elseif (preg_match('/^\s*;(.*)/', $header, $match)) {
                    $header = $match[1];
                } elseif (preg_match('/^\s+(.*)/', $header, $match)) {
                    $header = $match[1];
                } else {
                    throw new \Exception('This should not happen: "' . $header . '"');
                }
            }
            if (\count($cur)) {
                $result[] = $cur;
            }
        }

        return $result;
    }

    /**
     * HTTP Headers Util 0.1.
     *
     * @author: Keyvan Minoukadeh – hide@address.com – http://www.keyvan.net
     *
     * @license GNU General Public License, version 2
     *
     * @see (source)http://www.phpkode.com/source/s/http-headers-utility/http-headers-utility/HTTP_Headers_Util.php
     *
     * join_header_words
     *
     * This will do the opposite of the conversion done by split_header_words().
     * It takes a list of anonymous arrays as arguments (or a list of
     * key/value pairs) and produces a single header value.  Attribute values
     * are quoted if needed.
     *
     * Example:
     *
     *    join_header_words(array(array("text/plain" => null, "charset" => "iso-8859/1")));
     *    join_header_words(array("text/plain" => null, "charset" => "iso-8859/1"));
     *
     * will both return the string:
     *
     *    text/plain; charset="iso-8859/1"
     *
     * @param array $headerValues
     *
     * @return string
     *
     * @see http://tools.ietf.org/html/rfc5988#section-5
     */
    public static function joinHttpHeaderWords(array $headerValues) {
        if (\count($headerValues) === 0) {
            return '';
        }
        // evaluate if its a multidimensional array
        $first = reset($headerValues);
        if (!\is_array($first)) {
            $headerValues = [$headerValues];
        }

        $spaces = '\\s';
        $ctls = '\\x00-\\x1F\\x7F'; //@see http://stackoverflow.com/a/1497928/413531
        $tspecials = '()<>@,;:<>/[\\]?.="\\\\';
        $tokenPattern = "#^[^{$spaces}{$ctls}{$tspecials}]+$#";
        $result = [];
        foreach ($headerValues as $header) {
            $attr = [];
            foreach ($header as $key => $val) {
                if (isset($val)) {
                    if (preg_match($tokenPattern, $val)) {
                        $key .= "=$val";
                    } else {
                        $val = preg_replace('/(["\\\\])/', '\\\\$1', $val);
                        $key .= "=\"$val\"";
                    }
                }
                $attr[] = $key;
            }
            if (\count($attr)) {
                $result[] = implode('; ', $attr);
            }
        }

        return implode(', ', $result);
    }
}


<?php namespace Gears\Arrays\Conversions\To;
////////////////////////////////////////////////////////////////////////////////
// __________ __             ________                   __________
// \______   \  |__ ______  /  _____/  ____ _____ ______\______   \ _______  ___
//  |     ___/  |  \\____ \/   \  ____/ __ \\__  \\_  __ \    |  _//  _ \  \/  /
//  |    |   |   Y  \  |_> >    \_\  \  ___/ / __ \|  | \/    |   (  <_> >    <
//  |____|   |___|  /   __/ \______  /\___  >____  /__|  |______  /\____/__/\_ \
//                \/|__|           \/     \/     \/             \/            \/
// -----------------------------------------------------------------------------
//          Designed and Developed by Brad Jones <brad @="bjc.id.au" />
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////

use \tidy;
use \Gears\Arrays\Conversions\Template;

class Table extends Template
{
	/**
	 * Property: headings
	 * =========================================================================
	 * Do we take into account column headings when creating the table.
	 */
	protected $headings = true;

	/**
	 * Property: indent
	 * =========================================================================
	 * Do we want to have the HTML formated so it is readable.
	 */
	protected $indent = false;

	/**
	 * Method: Convert
	 * =========================================================================
	 * This will do the actual converting
	 *
	 * Parameters:
	 * -------------------------------------------------------------------------
	 * $data - An array to convert to a HTML Table
	 *
	 * Returns:
	 * -------------------------------------------------------------------------
	 * html
	 */
	public function Convert($data)
	{
		// Open the table
		$html_table = '
';

		// Loop through each row
		foreach ($data as $row)
		{
			// Open the row
			$html_table .= '
';

			// Are we creating the first row of headings
			if ($this->headings)
			{
				foreach ($row as $heading => $cell)
				{
					// Open Cell
					$html_table .= '';

					// Add cell contents
					$html_table .= $heading;

					// Close Cell
					$html_table .= '	';
				}

				$html_table .= '

';
				$this->headings = false;
			}

			// Create the body of the table
			foreach ($row as $cell)
			{
				// Open Cell
				$html_table .= '';

				// Add cell contents
				$html_table .= $cell;

				// Close Cell
				$html_table .= '	';
			}

			// Close the row
			$html_table .= '
';
		}

		// Close the table
		$html_table .= '
';

		// Make the table human readable
		if (!empty($this->indent)) $html_table = $this->AddIndents($html_table);

		return $html_table;
	}

	/**
	 * Method: AddIndents
	 * =========================================================================
	 * This will use HTML Tidy to pretify the HTML.
	 *
	 * Parameters:
	 * -------------------------------------------------------------------------
	 * $html - The html to be formatted
	 *
	 * Returns:
	 * -------------------------------------------------------------------------
	 * html
	 */
	private function AddIndents($html)
	{
		$tidy = new tidy();
		$tidy->parseString
		(
			$html,
			[
				'indent'		=> true,
				'indent-spaces'	=> 4,
				'output-html'	=> true,
				'input-xml'		=> true
			],
			'utf8'
		);
		$tidy->cleanRepair();
		return tidy_get_output($tidy);
	}
}


<?php

/**
 * @file
 * TeamSpeak 3 PHP Framework
 *
 * $Id: Abstract.php 9/26/2011 7:06:29 scp@orilla $
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 * @package   TeamSpeak3
 * @version   1.1.8-beta
 * @author    Sven 'ScP' Paulsen
 * @copyright Copyright (c) 2010 by Planet TeamSpeak. All rights reserved.
 */

namespace ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Transport;

/**
 * @class TeamSpeak3_Transport_Abstract
 * @brief Abstract class for connecting to a TeamSpeak 3 Server through different ways of transport.
 */
abstract class AbstractTransport
{
  /**
   * Stores user-provided configuration settings.
   *
   * @var array
   */
  protected $config = null;

  /**
   * Stores the stream resource of the connection.
   *
   * @var resource
   */
  protected $stream = null;

  /**
   * Stores the \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Adapter\AbstractAdapter object using this transport.
   *
   * @var \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Adapter\AbstractAdapter
   */
  protected $adapter = null;

  /**
   * The TeamSpeak3_Transport_Abstract constructor.
   *
   * @param  array $config
   * @throws Exception
   * @return AbstractTransport
   */
  public function __construct(array $config)
  {
    if(!array_key_exists("host", $config))
    {
      throw new Exception("config must have a key for 'host' which specifies the server host name");
    }

    if(!array_key_exists("port", $config))
    {
      throw new Exception("config must have a key for 'port' which specifies the server port number");
    }

    if(!array_key_exists("timeout", $config))
    {
      $config["timeout"] = 10;
    }

    if(!array_key_exists("blocking", $config))
    {
      $config["blocking"] = 1;
    }

    $this->config = $config;
  }

  /**
   * Commit pending data.
   *
   * @return array
   */
  public function __sleep()
  {
    return array("config");
  }

  /**
   * Reconnects to the remote server.
   *
   * @return void
   */
  public function __wakeup()
  {
    $this->connect();
  }

  /**
   * The TeamSpeak3_Transport_Abstract destructor.
   *
   * @return void
   */
  public function __destruct()
  {
    if($this->adapter instanceof \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Adapter\AbstractAdapter)
    {
      $this->adapter->__destruct();
    }

    $this->disconnect();
  }

  /**
   * Connects to a remote server.
   *
   * @throws Exception
   * @return void
   */
  abstract public function connect();

  /**
   * Disconnects from a remote server.
   *
   * @return void
   */
  abstract public function disconnect();

  /**
   * Reads data from the stream.
   *
   * @param  integer $length
   * @throws Exception
   * @return \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\String
   */
  abstract public function read($length = 4096);

  /**
   * Writes data to the stream.
   *
   * @param  string $data
   * @return void
   */
  abstract public function send($data);

  /**
   * Returns the underlying stream resource.
   *
   * @return resource
   */
  public function getStream()
  {
    return $this->stream;
  }

  /**
   * Returns the configuration variables in this adapter.
   *
   * @param  string $key
   * @param  mixed  $default
   * @return array
   */
  public function getConfig($key = null, $default = null)
  {
    if($key !== null)
    {
      return array_key_exists($key, $this->config) ? $this->config[$key] : $default;
    }

    return $this->config;
  }

  /**
   * Sets the \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Adapter\AbstractAdapter object using this transport.
   *
   * @param  \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Adapter\AbstractAdapter $adapter
   * @return void
   */
  public function setAdapter(\ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Adapter\AbstractAdapter $adapter)
  {
    $this->adapter = $adapter;
  }

  /**
   * Returns the \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Adapter\AbstractAdapter object using this transport.
   *
   * @return \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Adapter\AbstractAdapter
   */
  public function getAdapter()
  {
    return $this->adapter;
  }

  /**
   * Returns the adapter type.
   *
   * @return string
   */
  public function getAdapterType()
  {
    if($this->adapter instanceof \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Adapter\AbstractAdapter)
    {
      $string = \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\String::factory(get_class($this->adapter));

      return $string->substr($string->findLast("\\"))->replace(array("\\", " "), "")->toString();
    }

    return "Unknown";
  }

  /**
   * Returns header/meta data from stream pointer.
   *
   * @throws Exception
   * @return array
   */
  public function getMetaData()
  {
    if($this->stream === null)
    {
      throw new Exception("unable to retrieve header/meta data from stream pointer");
    }

    return stream_get_meta_data($this->stream);
  }

  /**
   * Returns TRUE if the transport is connected.
   *
   * @return boolean
   */
  public function isConnected()
  {
    return (is_resource($this->stream)) ? TRUE : FALSE;
  }

  /**
   * Blocks a stream until data is available for reading if the stream is connected
   * in non-blocking mode.
   *
   * @param  integer $time
   * @return void
   */
  protected function waitForReadyRead($time = 0)
  {
    if(!$this->isConnected() || $this->config["blocking"]) return;

    do {
      $read = array($this->stream);
      $null = null;

      if($time)
      {
        \ManiaLivePlugins\Standard\TeamSpeak\TeamSpeak3\Helper\Signal::getInstance()->emit(strtolower($this->getAdapterType()) . "WaitTimeout", $time, $this->getAdapter());
      }

      $time = $time+$this->config["timeout"];
    } while(@stream_select($read, $null, $null, $this->config["timeout"]) == 0);
  }

  public function isReadyRead()
  {
	if(!$this->isConnected())
		return false;

    $read = array($this->stream);
    $null = null;

	return @stream_select($read, $null, $null, 0, 1000) == 1;
  }
}


<?php

namespace Shoko\TwitchApiBundle\Repository;

use Shoko\TwitchApiBundle\Factory\ChannelFactory;
use Shoko\TwitchApiBundle\Factory\GameFactory;
use Shoko\TwitchApiBundle\Factory\StreamFactory;

/**
 * Class SearchRepository.
 */
class SearchRepository extends AbstractRepository
{
    const ENDPOINT = 'search/';

    /**
     * Search channels.
     *
     * @param array $params
     *
     * @return ChannelList
     */
    public function getChannels($params = array())
    {
        $params = 0 < count($params) ? '?'.http_build_query($params) : '';
        $response = $this->getClient()->get(self::ENDPOINT.'channels'.$params);
        $data = $this->jsonResponse($response);

        return $this->setFactory((new ChannelFactory()))->getFactory()->createList($data);
    }

    /**
     * Search games.
     *
     * @param array $params
     *
     * @return GameList
     */
    public function getGames($params = array())
    {
        $params = 0 < count($params) ? '?'.http_build_query($params) : '';
        $response = $this->getClient()->get(self::ENDPOINT.'games'.$params);
        $data = $this->jsonResponse($response);

        return $this->setFactory((new GameFactory()))->getFactory()->createList($data);
    }

    /**
     * Search streams.
     *
     * @param array $params
     *
     * @return StreamList
     */
    public function getStreams($params = array())
    {
        $params = 0 < count($params) ? '?'.http_build_query($params) : '';
        $response = $this->getClient()->get(self::ENDPOINT.'streams'.$params);
        $data = $this->jsonResponse($response);

        return $this->setFactory((new StreamFactory()))->getFactory()->createList($data);
    }
}


<?php

namespace Rougin\Describe\Driver;

use Rougin\Describe\Column;
use Rougin\Describe\Table;

/**
 * SQLite Driver
 *
 * A database driver extension for SQLite.
 * NOTE: Should be renamed to "SqliteDriver" in v2.0.0.
 *
 * @package Describe
 * @author  Rougin Gutib <rougingutib@gmail.com>
 */
class SQLiteDriver extends MySQLDriver
{
    /**
     * @var \PDO
     */
    protected $pdo;

    /**
     * Initializes the driver instance.
     *
     * @param \PDO $pdo
     */
    public function __construct(\PDO $pdo)
    {
        $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

        $this->pdo = $pdo;
    }

    /**
     * Returns an array of Column instances from a table.
     *
     * @param  string $table
     * @return \Rougin\Describe\Column[]
     */
    public function columns($table)
    {
        return $this->query($table, 'PRAGMA table_info("' . $table . '");');
    }

    /**
     * Returns an array of Column instances from a table.
     * NOTE: To be removed in v2.0.0. Use columns() instead.
     *
     * @param  string $table
     * @return \Rougin\Describe\Column[]
     */
    public function getColumns($table)
    {
        return $this->columns($table);
    }

    /**
     * Returns an array of Column instances from a table.
     * NOTE: To be removed in v2.0.0. Use getColumns() instead.
     *
     * @param  string $table
     * @return \Rougin\Describe\Column[]
     */
    public function getTable($table)
    {
        return $this->getColumns($table);
    }

    /**
     * Returns an array of table names.
     * NOTE: To be removed in v2.0.0. Use tables() instead.
     *
     * @return array
     */
    public function getTableNames()
    {
        return $this->items(false);
    }

    /**
     * Returns an array of table names.
     * NOTE: To be removed in v2.0.0. Use getTableNames() instead.
     *
     * @return array
     */
    public function showTables()
    {
        return $this->getTableNames();
    }

    /**
     * Returns an array of Table instances.
     *
     * @return \Rougin\Describe\Table[]
     */
    public function tables()
    {
        return $this->items(true);
    }

    /**
     * Prepares the defined columns.
     *
     * @param  \Rougin\Describe\Column $column
     * @param  string                  $table
     * @param  mixed                   $row
     * @return \Rougin\Describe\Column
     */
    protected function column(Column $column, $table, $row)
    {
        $column->setDefaultValue($row->dflt_value);

        $column->setField($row->name);

        $column->setDataType(strtolower($row->type));

        $column = $this->reference($table, $column);

        $column->setNull(! $row->notnull);

        $row->pk && $column->setAutoIncrement(true);

        $row->pk && $column->setPrimary(true);

        return $column;
    }

    /**
     * Returns an array of table names or Table instances.
     * NOTE: To be removed in v2.0.0. Move to tables() instead.
     *
     * @param  boolean $instance
     * @param  array   $tables
     * @return array|\Rougin\Describe\Table[]
     */
    protected function items($instance = false, $tables = array())
    {
        $query = 'SELECT name FROM sqlite_master WHERE type = "table";';

        $result = $this->pdo->prepare($query);

        $result->execute();

        $result->setFetchMode(\PDO::FETCH_OBJ);

        while ($row = $result->fetch()) {
            if ($row->name !== 'sqlite_sequence') {
                $name = $row->name;

                $tables[] = new Table($name, $this);
            }
        }

        return $tables;
    }

    /**
     * Sets the properties of a column if it does exists.
     *
     * @param  string                  $table
     * @param  \Rougin\Describe\Column $column
     * @return \Rougin\Describe\Column
     */
    protected function reference($table, Column $column)
    {
        $query = 'PRAGMA foreign_key_list("' . $table . '");';

        $result = $this->pdo->prepare($query);

        $result->execute();

        $result->setFetchMode(\PDO::FETCH_OBJ);

        while ($row = $result->fetch()) {
            if ($column->getField() === $row->from) {
                $column->setReferencedTable($row->table);

                $column->setForeign(true);

                $column->setReferencedField($row->to);
            }
        }

        return $column;
    }
}


<?php

namespace Flobbos\LaravelSimpleHelper;

use Illuminate\Support\ServiceProvider;

class LaravelSimpleHelperServiceProvider extends ServiceProvider{

    public function boot(){
        $this->publishes([
            __DIR__.'/../config/simplehelper.php' => config_path('simplehelper.php'),
        ]);
    }

    /**
     * Register the service provider.
     */
    public function register(){
        $this->mergeConfigFrom(
            __DIR__.'/../config/simplehelper.php', 'simplehelper'
        );

        //load custom helpers with config
        if (count(config('simplehelper.custom_helpers'))) {
            foreach (config('simplehelper.custom_helpers') as $customHelper) {
                $file = app_path() . '/' . $this->getHelpersDirectory() . '/' . $customHelper . '.php';
                if(file_exists($file)) {
                    require_once($file);
                }
            }
        }
        //just load all of them
        else {
            foreach (glob(app_path() . '/' . $this->getHelpersDirectory() . '/*.php') as $file) {
                require_once($file);
            }
        }
    }

    public function getHelpersDirectory(){
        return config('simplehelper.directory', 'Helpers');
    }
}