示例#1
0
 public static function create(string $service) : AbstractProvider
 {
     // persistent storage to save the token
     $storage = new SessionStorage();
     // Setup the credentials for the requests
     $credentials = new Credentials(DI::config()->get('socials/' . $service . '/key'), DI::config()->get('socials/' . $service . '/secret'), self::uri('oauth/end', ['service' => $service])->get(false));
     // Oauth Service
     $serviceFactory = new ServiceFactory();
     $serviceFactory->setHttpClient(new HttpClient());
     $class = 'Cawa\\Oauth\\Providers\\' . ucfirst($service);
     /** @var AbstractProvider $provider */
     $provider = new $class();
     $provider->type = $service;
     // scope
     $scopes = DI::config()->getIfExists('socials/' . $service . '/scopes');
     if (!$scopes && defined($class . '::DEFAULT_SCOPES')) {
         $scopes = constant($class . '::DEFAULT_SCOPES');
     }
     if (!$scopes) {
         $scopes = [];
     }
     // version
     $version = null;
     if (defined($class . '::API_VERSION')) {
         $version = constant($class . '::API_VERSION');
     }
     $service = $serviceFactory->createService($service, $credentials, $storage, $scopes, null, $version);
     $provider->service = $service;
     return $provider;
 }
示例#2
0
 /**
  * @param string $url
  * @param array $queries
  *
  * @throws InvalidRequest
  * @throws OverQueryLimit
  * @throws RequestDenied
  * @throws Unknown
  *
  * @return array
  */
 protected static function query(string $url, array $queries = []) : array
 {
     if (!self::$client) {
         self::$client = new HttpClient();
         $base = new Uri('https://maps.googleapis.com/maps/api');
         self::$client->setBaseUri($base);
     }
     if (!isset($queries['key'])) {
         $queries['key'] = DI::config()->get('googleMaps/apikey');
     }
     $uri = new Uri($url);
     $uri->addQueries($queries);
     $response = self::$client->get($uri->get());
     $data = json_decode($response->getBody(), true);
     if (!($data['status'] == 'OK' || $data['status'] == 'ZERO_RESULTS')) {
         switch ($data['status']) {
             case 'OVER_QUERY_LIMIT':
                 throw new OverQueryLimit($data['error_message'] ?? $data['status']);
             case 'REQUEST_DENIED':
                 throw new RequestDenied($data['error_message'] ?? $data['status']);
             case 'INVALID_REQUEST':
                 throw new InvalidRequest($data['error_message'] ?? $data['status']);
             default:
                 throw new Unknown($data['error_message'] ?? $data['status']);
         }
     }
     return $data;
 }
示例#3
0
 /**
  * @return Session
  */
 private static function session() : Session
 {
     if ($return = DI::get(__METHOD__)) {
         return $return;
     }
     $item = new Session();
     return DI::set(__METHOD__, null, $item);
 }
示例#4
0
 /**
  * @return Router
  */
 protected static function router() : Router
 {
     if ($return = DI::get(__METHOD__)) {
         return $return;
     }
     $item = new Router();
     return DI::set(__METHOD__, null, $item);
 }
示例#5
0
 /**
  * {@inheritdoc}
  */
 public function __construct(array $casters = null)
 {
     parent::__construct($casters);
     $this->addCasters(['DateInterval' => 'Cawa\\VarDumper\\Caster\\DateInterval::cast', 'Cawa\\Orm\\Collection' => 'Cawa\\VarDumper\\Caster\\Collection::cast']);
     if ($casters = DI::config()->getIfExists('varDumper/casters')) {
         $this->addCasters($casters);
     }
 }
示例#6
0
 /**
  * @param string $name
  * @param string|null $label
  */
 public function __construct(string $name, string $label = null)
 {
     parent::__construct();
     $this->main = new Text($name . '[text]', $label);
     $this->hidden = new Hidden($name . '[data]');
     $this->add($this->main)->add($this->hidden);
     $this->main->getField()->addClass('cawa-fields-googleplace')->addAttribute('data-key', DI::config()->get('googleMaps/apikey'));
 }
示例#7
0
文件: Map.php 项目: cawaphp/widget
 /**
  * {@inheritdoc}
  */
 public function __construct()
 {
     parent::__construct('<div>');
     $this->addClass('cawa-google-map');
     $this->add(new HtmlElement('<div>'));
     $this->widgetOptions = new WidgetOption(['key' => DI::config()->get('googleMaps/apikey')]);
     $this->setZoom(15);
 }
示例#8
0
 /**
  * @return Translator
  */
 protected static function translator() : Translator
 {
     if ($return = DI::get(__METHOD__)) {
         return $return;
     }
     $item = new Translator();
     return DI::set(__METHOD__, null, $item);
 }
示例#9
0
 /**
  * @return ServerResponse
  */
 protected static function response() : ServerResponse
 {
     if ($return = DI::get(__METHOD__)) {
         return $return;
     }
     $item = new ServerResponse();
     return DI::set(__METHOD__, null, $item);
 }
示例#10
0
 /**
  * @return Dispatcher
  */
 private static function dispatcher() : Dispatcher
 {
     if ($return = DI::get(__METHOD__)) {
         return $return;
     }
     $item = new Dispatcher();
     return DI::set(__METHOD__, null, $item);
 }
示例#11
0
 /**
  * @return Logger
  */
 private static function logger() : Logger
 {
     if ($return = DI::get(__METHOD__)) {
         return $return;
     }
     $item = new Logger();
     return DI::set(__METHOD__, null, $item);
 }
示例#12
0
 /**
  * @return Dispatcher
  */
 public function instanceDispatcher() : Dispatcher
 {
     if ($return = DI::get(get_class($this), spl_object_hash($this))) {
         return $return;
     }
     $item = new Dispatcher();
     return DI::set(get_class($this), spl_object_hash($this), $item);
 }
示例#13
0
 /**
  * @param string $name
  *
  * @return Cache
  */
 private static function cache(string $name = null) : Cache
 {
     if ($return = DI::get(__METHOD__, $name)) {
         return $return;
     }
     $config = DI::config()->get('cache/' . ($name ?: 'default'));
     $item = new Cache($config);
     return DI::set(__METHOD__, $name, $item);
 }
示例#14
0
 /**
  * @return StorageInterface
  */
 public static function getStorage()
 {
     $config = DI::config()->getIfExists('clockwork');
     $class = 'Cawa\\Clockwork\\Storage\\' . ($config ? $config['type'] : 'Session');
     if ($config) {
         return new $class(...$config['config']);
     } else {
         return new $class();
     }
 }
示例#15
0
文件: Ip.php 项目: cawaphp/cawa
 /**
  * @return bool
  */
 public static function isAdmin() : bool
 {
     $ips = DI::config()->getIfExists('ip/admin');
     if (!$ips) {
         return false;
     }
     $ip = Ip::get();
     foreach ($ips as $currentIp) {
         if ($currentIp === $ip) {
             return true;
         }
     }
     return false;
 }
示例#16
0
 /**
  * @param string $name
  *
  * @return Cache
  */
 private static function httpClient(string $name = null) : Cache
 {
     if ($return = DI::get(__METHOD__, $name)) {
         return $return;
     }
     $config = DI::config()->get('httpclient/' . $name);
     if (is_callable($config)) {
         $item = $config();
     } else {
         $item = new HttpClient();
         $item->setBaseUri($config);
     }
     return DI::set(__METHOD__, $name, $item);
 }
示例#17
0
 /**
  * @param bool $relative
  *
  * @return string
  */
 public function generateUrl(bool $relative = false) : string
 {
     if (!$this->hmacAdded && !$relative && ($sign = DI::config()->getIfExists('googleMaps/secret'))) {
         $binarySign = base64_decode(str_replace(['-', '_'], ['+', '/'], $sign));
         $hmac = hash_hmac('sha1', $this->generateUrl(true), $binarySign, true);
         $this->queries['signature'] = str_replace(['+', '/'], ['-', '_'], base64_encode($hmac));
         $this->hmacAdded = true;
     }
     $uri = new Uri('https://maps.googleapis.com/maps/api/staticmap');
     $uri->addQueries($this->queries);
     $url = $uri->get($relative);
     // google maps expect markers=...&markers=...
     $url = preg_replace('/%5B(?:[0-9]|[1-9][0-9]+)%5D=/', '=', $url);
     $url = str_replace('%2C', ',', $url);
     return $url;
 }
示例#18
0
 /**
  * @param string $path
  *
  * @return array
  */
 protected function getAssetData(string $path) : array
 {
     $return = [null, DI::config()->exists('assets/hashes')];
     // file hash
     $hashes = DI::config()->getIfExists('assets/hashes');
     if ($hashes) {
         if (isset($hashes[$path])) {
             $path = $hashes[$path];
         }
     }
     // relative path like "vendor.js", add assets/url
     if (substr($path, 0, 4) != 'http' && substr($path, 0, 1) != '/' && ($assetsPath = DI::config()->get('assets/url'))) {
         $path = rtrim($assetsPath, '/') . '/' . $path;
     }
     $return[0] = $path;
     return $return;
 }
示例#19
0
 /**
  * @param string $name
  *
  * @return \Swift_Mailer
  */
 private static function mailer(string $name = null) : \Swift_Mailer
 {
     if ($return = DI::get(__METHOD__)) {
         return $return;
     }
     $config = DI::config()->getIfExists('email/' . ($name ?: 'default'));
     if (!$config) {
         $transport = \Swift_MailTransport::newInstance();
         $return = \Swift_Mailer::newInstance($transport);
     } elseif (is_callable($config)) {
         $return = $config();
     } else {
         $uri = new Uri($config);
         switch ($uri->getScheme()) {
             case 'smtp':
                 $transport = \Swift_SmtpTransport::newInstance($uri->getHost(), $uri->getPort());
                 if ($uri->getUser()) {
                     $transport->setUsername($uri->getUser());
                 }
                 if ($uri->getPassword()) {
                     $transport->setPassword($uri->getPassword());
                 }
                 if ($uri->getQuery('auth')) {
                     $transport->setAuthMode($uri->getQuery('auth'));
                 }
                 if ($uri->getQuery('encryption')) {
                     $transport->setEncryption($uri->getQuery('encryption'));
                 }
                 break;
             case 'echo':
                 $transport = EchoTransport::newInstance();
                 break;
             default:
                 throw new \InvalidArgumentException(sprintf("Undefined email mailer type '%s'", $uri->getScheme()));
                 break;
         }
         $return = \Swift_Mailer::newInstance($transport);
         if ($uri->getQuery('plugins')) {
             foreach ($uri->getQuery('plugins') as $plugin) {
                 $return->registerPlugin(new $plugin());
             }
         }
     }
     return DI::set(__METHOD__, $name, $return);
 }
示例#20
0
 /**
  * {@inheritdoc}
  */
 public function __construct($output = null, $charset = null)
 {
     $this->styles['default'] = str_replace('font:12px Menlo', "font:11px 'Source Code Pro', Menlo", $this->styles['default']);
     $this->styles['ctrl'] = 'color:#999';
     $this->dumpPrefix .= '<a class="sf-close sf-dump-index">×</a>';
     $header = $this->getDumpHeader();
     // max depth function
     $header = str_replace('function toggle(a, recursive) {', "function getLevel(elt) {\n" . "    var exit = false, level = 0, element = elt;\n" . "\n" . "    if (element.parentNode.className == 'sf-dump') {\n" . "        return 0;\n" . "    }\n" . "\n" . "    while(exit == false) {\n" . "        element = element.parentNode;\n" . "        level++;\n" . "        exit = !element.parentNode || element.parentNode.className == 'sf-dump';\n" . "    }\n" . "    return level;\n" . "}\n" . "\n" . 'function toggle(a, recursive) {', $header);
     // close button function
     $header = str_replace("var container = root;\n" . "addEventListener(root, 'mouseover', function (e) {", "addEventListener(container.querySelectorAll('.sf-close')[0], 'click', function(e) {\n" . "    e.target.parentNode.parentNode.removeChild(e.target.parentNode);\n" . "});\n" . "\n" . "addEventListener(document, 'selectionchange', function(e) {\n" . "    if (\n" . "        window.getSelection &&\n" . "        window.getSelection().toString() &&\n" . "        window.getSelection().anchorNode.parentNode.className.indexOf('sf-dump') >= 0\n" . "    ) {\n" . "        var ctrl = container.querySelectorAll('.sf-dump-ctrl');\n" . "        ctrl.forEach(function(node)\n" . "        {\n" . "           node.style.display = 'none';\n" . "        });\n" . "    }\n" . "}, false);\n" . "\n" . "addEventListener(root, 'mouseover', function (e) {", $header);
     // close button style
     $header = str_replace('pre.sf-dump span {', "pre.sf-dump a.sf-close {\n" . "    font-size:22px;\n" . "    position:absolute;\n" . "    right: 10px;\n" . "};\n" . "\n" . 'pre.sf-dump span {', $header);
     $expandLevel = DI::config()->getIfExists('varDumper/expandLevel');
     if (is_null($expandLevel)) {
         $expandLevel = 4;
     }
     $header = preg_replace("/if \\('sf-dump' != elt.parentNode.className\\) \\{.*\\}/mU", $expandLevel == false ? '' : 'if (getLevel(elt) > ' . $expandLevel . ') {toggle(a);}', $header, -1, $count);
     $this->setDumpHeader($header);
     $this->originalDumpPrefix = $this->dumpPrefix;
     parent::__construct($output, $charset);
 }
示例#21
0
 /**
  * @return bool
  */
 public function save() : bool
 {
     if (!self::$init) {
         return true;
     }
     $this->accessTime = time();
     if (!$this->startTime) {
         $this->startTime = $this->accessTime;
     }
     $ttl = DI::config()->getIfExists('session/refreshTtl') ?? 60;
     if (!$this->changed && $this->accessTime + $ttl < time()) {
         $event = new TimerEvent('session.touch');
         $return = $this->storage->touch($this->id, $this->data, $this->startTime, $this->accessTime);
     } else {
         $event = new TimerEvent('session.write');
         $return = $this->storage->write($this->id, $this->data, $this->startTime, $this->accessTime);
     }
     $event->setData(['length' => $return]);
     self::emit($event);
     return $return === false ? false : true;
 }
示例#22
0
 /**
  * @param int $maxWidth
  * @param int $maxHeight
  *
  * @return Uri
  */
 public function getUrl(int $maxWidth = null, int $maxHeight = null) : Uri
 {
     if ($maxWidth && $maxHeight) {
         throw new \InvalidArgumentException("You can't specify maxWidth AND maxHeight");
     }
     $queries = ['photoreference' => $this->reference, 'key' => DI::config()->get('googleMaps/apikey')];
     if ($maxWidth) {
         $queries['maxwidth'] = (string) $maxWidth;
     }
     if ($maxHeight) {
         $queries['maxheight'] = (string) $maxHeight;
     }
     $uri = new Uri('https://maps.googleapis.com/maps/api/place/photo');
     $uri->addQueries($queries);
     return $uri;
 }
示例#23
0
 /**
  *
  */
 private function addConfigListeners()
 {
     foreach (DI::config()->getIfExists('listeners/byClass') ?? [] as $class => $listeners) {
         foreach ($listeners as $listener) {
             self::dispatcher()->addListenerByClass($class, $listener);
         }
     }
     foreach (DI::config()->getIfExists('listeners/byName') ?? [] as $name => $listeners) {
         foreach ($listeners as $listener) {
             self::dispatcher()->addListener($name, $listener);
         }
     }
 }
示例#24
0
 /**
  * @param \swoole_http_request $request
  * @param \swoole_http_response $response
  */
 public function setHttp(\swoole_http_request $request, \swoole_http_response $response)
 {
     DI::set('Cawa\\App\\HttpFactory::response', null, new ServerResponse($response));
 }
示例#25
0
 /**
  * @param array $params
  *
  * @return PlaceDetail
  */
 public static function detail(array $params = [])
 {
     $data = self::query('/place/details/json', array_merge($params, ['key' => DI::config()->get('googleApi/server')]));
     if ($data) {
         return PlaceDetail::parse($data['result']);
     }
     return null;
 }
示例#26
0
 /**
  * @param string $file
  * @param string $extension
  * @param string $extensionFrom
  * @param int $width
  * @param int $height
  * @param string $position
  * @param string $effect
  *
  * @return string
  */
 public function resize(string $file, string $extension, string $extensionFrom = null, int $width = null, int $height = null, string $position = null, string $effect = null) : string
 {
     $options = class_exists('Imagick') ? ['driver' => 'imagick'] : [];
     $manager = new ImageManager($options);
     $path = $_SERVER['DOCUMENT_ROOT'] . $file . '.' . ($extensionFrom ? $extensionFrom : $extension);
     $timerEvent = new TimerEvent('image.make', ['path' => $path]);
     if (!file_exists($path)) {
         self::response()->setStatus(404);
         $img = $manager->make(dirname(__DIR__) . '/assets/404.png');
     } else {
         $img = $manager->make($path);
     }
     $timerEvent->addData(['width' => $img->width(), 'heigth' => $img->height(), 'size' => $img->filesize()]);
     self::emit($timerEvent);
     if (!$height) {
         $height = round($width * $img->height() / $img->width());
     }
     if (!$width) {
         $width = round($height * $img->width() / $img->height());
     }
     $timerEvent = new TimerEvent('image.resize');
     $interlace = DI::config()->getIfExists('image/interlace');
     $interlace = is_null($interlace) ? true : $interlace;
     $sharpen = DI::config()->getIfExists('image/sharpen');
     $sharpen = is_null($sharpen) ? 5 : $sharpen;
     $quality = DI::config()->getIfExists('image/quality');
     $timerEvent->addData(['width' => $width, 'heigth' => $height]);
     $positions = [];
     if ($position) {
         foreach (str_split($position) as $letter) {
             if ($letter == 't') {
                 $positions[] = 'top';
             } elseif ($letter == 'b') {
                 $positions[] = 'bottom';
             } elseif ($letter == 'l') {
                 $positions[] = 'left';
             } elseif ($letter == 'r') {
                 $positions[] = 'right';
             }
         }
     }
     $encoded = $img->fit($width, $height, null, sizeof($positions) > 0 ? implode('-', $positions) : null);
     self::emit($timerEvent);
     if ($interlace) {
         $timerEvent = new TimerEvent('image.effect', ['type' => 'interlace']);
         $encoded->interlace();
         self::emit($timerEvent);
     }
     if ($sharpen) {
         $timerEvent = new TimerEvent('image.effect', ['type' => 'sharpen']);
         $encoded->sharpen($sharpen);
         self::emit($timerEvent);
     }
     if ($effect) {
         /* @var \Cawa\ImageModule\Module $module */
         $module = AbstractApp::instance()->getModule('Cawa\\ImageModule\\Module');
         foreach (explode('-', $effect) as $currentEffect) {
             $timerEvent = new TimerEvent('image.effect', ['type' => $currentEffect]);
             $filter = $module->getEffect($currentEffect);
             $encoded->filter($filter);
             self::emit($timerEvent);
         }
     }
     $encoded = $encoded->encode($extension, $quality);
     self::response()->addHeader('Content-Type', $encoded->mime());
     self::response()->addHeader('Content-Length', (string) strlen($encoded->getEncoded()));
     return $encoded->getEncoded();
 }
示例#27
0
 /**
  * @return mixed
  */
 public function getDefaultLocale()
 {
     return DI::config()->get('locale/default');
 }