예제 #1
0
 protected function log($message)
 {
     if (!class_exists('\\rock\\log\\Log')) {
         return;
     }
     $message = BaseException::convertExceptionToString(new ValidateException($message));
     Log::warn($message);
 }
예제 #2
0
 /**
  * @param Mail $mail
  * @param Users $users
  * @param SignupForm $model
  */
 public function sendMail(Mail $mail, Users $users, SignupForm $model)
 {
     $subject = i18n::t('subjectRegistration', ['site_name' => i18n::t('siteName')]);
     $body = $this->prepareBody($model, $users);
     try {
         $mail->address($users->email)->subject($subject)->body($body)->send();
     } catch (\Exception $e) {
         $model->addError('alerts', i18n::t('failSendEmail'));
         Log::warn(BaseException::convertExceptionToString($e));
     }
 }
예제 #3
0
 /**
  * Opens the connection to a server in the pool.
  *
  * This method implements the load balancing among the given list of the servers.
  *
  * @param array $pool the list of connection configurations in the server pool
  * @param array $sharedConfig the configuration common to those given in `$pool`.
  * @return Connection the opened DB connection, or null if no server is available
  * @throws DbException if a configuration does not specify "dsn"
  */
 protected function openFromPool(array $pool, array $sharedConfig)
 {
     if (empty($pool)) {
         return null;
     }
     if (!isset($sharedConfig['class'])) {
         $sharedConfig['class'] = get_class($this);
     }
     $cache = Instance::ensure($this->serverStatusCache, null, [], false);
     shuffle($pool);
     foreach ($pool as $config) {
         $config = array_merge($sharedConfig, $config);
         if (empty($config['dsn'])) {
             throw new DbException('The "dsn" option must be specified.');
         }
         $key = [__METHOD__, $config['dsn']];
         if ($cache instanceof CacheInterface && $cache->get($key)) {
             // should not try this dead server now
             continue;
         }
         /* @var $connection Connection */
         $connection = Instance::ensure($config);
         try {
             $connection->open();
             return $connection;
         } catch (\Exception $e) {
             if (class_exists('\\rock\\log\\Log')) {
                 Log::warn(BaseException::convertExceptionToString($e));
             }
             if ($cache instanceof CacheInterface) {
                 // mark this server as dead and only retry it after the specified interval
                 $cache->set($key, 1, $this->serverRetryInterval);
             }
         }
     }
     return null;
 }
예제 #4
0
 /**
  * @inheritdoc
  */
 protected function generate($generate = false)
 {
     if (!empty($this->data) && $generate === false) {
         return $this->data;
     }
     $fonts = [];
     $fontsdir_absolute = dirname(__FILE__) . DIRECTORY_SEPARATOR . $this->fontsDir;
     if ($handle = opendir($fontsdir_absolute)) {
         while (false !== ($file = readdir($handle))) {
             if (preg_match('/\\.png$/i', $file)) {
                 $fonts[] = $fontsdir_absolute . DIRECTORY_SEPARATOR . $file;
             }
         }
         closedir($handle);
     }
     $alphabet = self::ALPHABET_FONT;
     $alphabet_length = strlen($alphabet);
     // generating random keystring
     do {
         while (true) {
             $this->code = null;
             for ($i = 0; $i < $this->length; ++$i) {
                 $this->code .= $this->alphabet[mt_rand(0, strlen($this->alphabet) - 1)];
             }
             if (!preg_match('/cp|cb|ck|c6|c9|rn|rm|mm|co|do|cl|db|qp|qb|dp|ww/', $this->code)) {
                 break;
             }
         }
         $font_file = $fonts[mt_rand(0, count($fonts) - 1)];
         $font = imagecreatefrompng($font_file);
         imagealphablending($font, true);
         $fontfile_width = imagesx($font);
         $fontfile_height = imagesy($font) - 1;
         $font_metrics = [];
         $symbol = 0;
         $reading_symbol = false;
         // loading font
         for ($i = 0; $i < $fontfile_width && $symbol < $alphabet_length; ++$i) {
             $transparent = imagecolorat($font, $i, 0) >> 24 == 127;
             if (empty($reading_symbol) && empty($transparent)) {
                 $font_metrics[$alphabet[$symbol]] = ['start' => $i];
                 $reading_symbol = true;
                 continue;
             } elseif (!empty($reading_symbol) && !empty($transparent)) {
                 $font_metrics[$alphabet[$symbol]]['end'] = $i;
                 $reading_symbol = false;
                 ++$symbol;
                 continue;
             }
         }
         $img = imagecreatetruecolor($this->width, $this->height);
         imagealphablending($img, true);
         $white = imagecolorallocate($img, 255, 255, 255);
         $black = imagecolorallocate($img, 0, 0, 0);
         imagefilledrectangle($img, 0, 0, $this->width - 1, $this->height - 1, $white);
         // draw text
         $x = 1;
         $odd = mt_rand(0, 1);
         if ($odd == 0) {
             $odd = -1;
         }
         for ($i = 0; $i < $this->length; ++$i) {
             $m = $font_metrics[$this->code[$i]];
             $y = ($i % 2 * $this->fluctuationAmplitude - $this->fluctuationAmplitude / 2) * $odd + mt_rand(-round($this->fluctuationAmplitude / 3), round($this->fluctuationAmplitude / 3)) + ($this->height - $fontfile_height) / 2;
             if ($this->noSpaces === true) {
                 $shift = 0;
                 if ($i > 0) {
                     $shift = 10000;
                     for ($sy = 3; $sy < $fontfile_height - 10; $sy += 1) {
                         for ($sx = $m['start'] - 1; $sx < $m['end']; $sx += 1) {
                             $rgb = imagecolorat($font, $sx, $sy);
                             $opacity = $rgb >> 24;
                             if ($opacity < 127) {
                                 $left = $sx - $m['start'] + $x;
                                 $py = $sy + $y;
                                 if ($py > $this->height) {
                                     break;
                                 }
                                 for ($px = min($left, $this->width - 1); $px > $left - 200 && $px >= 0; $px -= 1) {
                                     $color = imagecolorat($img, $px, $py) & 0xff;
                                     if ($color + $opacity < 170) {
                                         // 170 - threshold
                                         if ($shift > $left - $px) {
                                             $shift = $left - $px;
                                         }
                                         break;
                                     }
                                 }
                                 break;
                             }
                         }
                     }
                     if ($shift == 10000) {
                         $shift = mt_rand(4, 6);
                     }
                 }
             } else {
                 $shift = 1;
             }
             imagecopy($img, $font, $x - $shift, $y, $m['start'], 1, $m['end'] - $m['start'], $fontfile_height);
             $x += $m['end'] - $m['start'] - $shift;
         }
     } while ($x >= $this->width - 10);
     // while not fit in canvas
     // noise
     $white = imagecolorallocate($font, 255, 255, 255);
     $black = imagecolorallocate($font, 0, 0, 0);
     for ($i = 0; $i < ($this->height - 30) * $x * $this->whiteNoiseDensity; ++$i) {
         imagesetpixel($img, mt_rand(0, $x - 1), mt_rand(10, $this->height - 15), $white);
     }
     for ($i = 0; $i < ($this->height - 30) * $x * $this->blackNoiseDensity; ++$i) {
         imagesetpixel($img, mt_rand(0, $x - 1), mt_rand(10, $this->height - 15), $black);
     }
     $center = $x / 2;
     // credits. To remove, see configuration file
     $img2 = imagecreatetruecolor($this->width, $this->height + ($this->showCredits === true ? 12 : 0));
     $foreground = imagecolorallocate($img2, $this->foregroundColor[0], $this->foregroundColor[1], $this->foregroundColor[2]);
     $background = imagecolorallocate($img2, $this->backgroundColor[0], $this->backgroundColor[1], $this->backgroundColor[2]);
     imagefilledrectangle($img2, 0, 0, $this->width - 1, $this->height - 1, $background);
     imagefilledrectangle($img2, 0, $this->height, $this->width - 1, $this->height + 12, $foreground);
     $credits = empty($credits) ? $_SERVER['HTTP_HOST'] : $credits;
     imagestring($img2, 2, $this->width / 2 - imagefontwidth(2) * strlen($credits) / 2, $this->height - 2, $credits, $background);
     // periods
     $rand1 = mt_rand(750000, 1200000) / 10000000;
     $rand2 = mt_rand(750000, 1200000) / 10000000;
     $rand3 = mt_rand(750000, 1200000) / 10000000;
     $rand4 = mt_rand(750000, 1200000) / 10000000;
     // phases
     $rand5 = mt_rand(0, 31415926) / 10000000;
     $rand6 = mt_rand(0, 31415926) / 10000000;
     $rand7 = mt_rand(0, 31415926) / 10000000;
     $rand8 = mt_rand(0, 31415926) / 10000000;
     // amplitudes
     $rand9 = mt_rand(330, 420) / 110;
     $rand10 = mt_rand(330, 450) / 100;
     // wave distortion
     for ($x = 0; $x < $this->width; ++$x) {
         for ($y = 0; $y < $this->height; ++$y) {
             $sx = $x + (sin($x * $rand1 + $rand5) + sin($y * $rand3 + $rand6)) * $rand9 - $this->width / 2 + $center + 1;
             $sy = $y + (sin($x * $rand2 + $rand7) + sin($y * $rand4 + $rand8)) * $rand10;
             if ($sx < 0 || $sy < 0 || $sx >= $this->width - 1 || $sy >= $this->height - 1) {
                 continue;
             } else {
                 $color = imagecolorat($img, $sx, $sy) & 0xff;
                 $color_x = imagecolorat($img, $sx + 1, $sy) & 0xff;
                 $color_y = imagecolorat($img, $sx, $sy + 1) & 0xff;
                 $color_xy = imagecolorat($img, $sx + 1, $sy + 1) & 0xff;
             }
             if ($color == 255 && $color_x == 255 && $color_y == 255 && $color_xy == 255) {
                 continue;
             } elseif ($color === 0 && $color_x === 0 && $color_y === 0 && $color_xy === 0) {
                 $newred = $this->foregroundColor[0];
                 $newgreen = $this->foregroundColor[1];
                 $newblue = $this->foregroundColor[2];
             } else {
                 $frsx = $sx - floor($sx);
                 $frsy = $sy - floor($sy);
                 $frsx1 = 1 - $frsx;
                 $frsy1 = 1 - $frsy;
                 $newcolor = $color * $frsx1 * $frsy1 + $color_x * $frsx * $frsy1 + $color_y * $frsx1 * $frsy + $color_xy * $frsx * $frsy;
                 if ($newcolor > 255) {
                     $newcolor = 255;
                 }
                 $newcolor = $newcolor / 255;
                 $newcolor0 = 1 - $newcolor;
                 $newred = $newcolor0 * $this->foregroundColor[0] + $newcolor * $this->backgroundColor[0];
                 $newgreen = $newcolor0 * $this->foregroundColor[1] + $newcolor * $this->backgroundColor[1];
                 $newblue = $newcolor0 * $this->foregroundColor[2] + $newcolor * $this->backgroundColor[2];
             }
             imagesetpixel($img2, $x, $y, imagecolorallocate($img2, $newred, $newgreen, $newblue));
         }
     }
     ob_start();
     if (function_exists('imagejpeg')) {
         $result['mimeType'] = 'image/jpeg';
         imagejpeg($img2, null, $this->quality);
     } elseif (function_exists('imagegif')) {
         $result['mimeType'] = 'image/gif';
         imagegif($img2);
     } elseif (function_exists('imagepng')) {
         $result['mimeType'] = 'image/x-png';
         imagepng($img2);
     }
     $result['image'] = ob_get_clean();
     if (empty($result['image'])) {
         if (class_exists('\\rock\\log\\Log')) {
             $message = BaseException::convertExceptionToString(new CaptchaException(CaptchaException::UNKNOWN_VAR, ['name' => '$return[\'image\']']));
             Log::warn($message);
         }
         return [];
     }
     return $this->data = $result;
 }
예제 #5
0
 /**
  * Session write handler.
  * Do not call this method directly.
  * @param string $id session ID
  * @param string $data session data
  * @return boolean whether session write is successful
  */
 public function writeSession($id, $data)
 {
     // exception must be caught in session write handler
     // http://us.php.net/manual/en/function.session-set-save-handler.php
     try {
         $this->connection->getCollection($this->sessionCollection)->update(['id' => $id], ['id' => $id, 'data' => $data, 'expire' => new \MongoDate(time() + $this->getTimeout())], ['upsert' => true]);
     } catch (\Exception $e) {
         if (class_exists('\\rock\\log\\Log')) {
             Log::warn(BaseException::convertExceptionToString($e));
         }
         return false;
     }
     return true;
 }
예제 #6
0
 protected function prepareImage($path)
 {
     $metadata = $this->adapter->getMetadata($path);
     $path = implode(DIRECTORY_SEPARATOR, [trim($metadata['dirname'], DIRECTORY_SEPARATOR), "{$this->width}x{$this->height}", $metadata['basename']]);
     $this->src = $this->srcCache . '/' . ltrim($path, '/');
     if ($this->adapterCache->has($path)) {
         return;
     }
     if ($this->handler instanceof \Closure) {
         call_user_func($this->handler, $path, $this);
         return;
     }
     $string = Image::thumbnail($this->image, $this->width, $this->height)->get('jpg');
     if (!$this->adapterCache->write($path, $string)) {
         if (class_exists('\\rock\\log\\Log')) {
             $message = BaseException::convertExceptionToString(new ImageException(ImageException::NOT_CREATE_FILE, ['path' => $path]));
             Log::warn($message);
         }
     }
 }
예제 #7
0
 /**
  * Session write handler.
  *
  * Do not call this method directly.
  * @param string $id session ID
  * @param string $data session data
  * @return boolean whether session write is successful
  */
 public function writeSession($id, $data)
 {
     // exception must be caught in session write handler
     // http://us.php.net/manual/en/function.session-set-save-handler.php
     try {
         $expire = time() + $this->getTimeout();
         $exists = (new Query())->select(['id'])->from($this->sessionTable)->where(['id' => $id])->createCommand($this->connection)->queryScalar();
         if ($exists === null) {
             $this->connection->createCommand()->insert($this->sessionTable, ['id' => $id, 'data' => $data, 'expire' => $expire])->execute();
         } else {
             $this->connection->createCommand()->update($this->sessionTable, ['data' => $data, 'expire' => $expire], ['id' => $id])->execute();
         }
     } catch (\Exception $e) {
         if (class_exists('\\rock\\log\\Log')) {
             Log::warn(BaseException::convertExceptionToString($e));
         }
         return false;
     }
     return true;
 }
예제 #8
0
 /**
  * Copies a whole directory as another one.
  *
  * The files and sub-directories will also be copied over.
  *
  * @param string $src the source directory
  * @param string $dst the destination directory
  * @param array $options options for directory copy. Valid options are:
  *
  * - dirMode: integer, the permission to be set for newly copied directories. Defaults to `0775`.
  * - fileMode:  integer, the permission to be set for newly copied files. Defaults to the current environment setting.
  * - filter: callback, a PHP callback that is called for each directory or file.
  *   The signature of the callback should be: `function ($path)`, where `$path` refers the full path to be filtered.
  *   The callback can return one of the following values:
  *
  *   * true: the directory or file will be copied (the "only" and "except" options will be ignored)
  *   * false: the directory or file will NOT be copied (the "only" and "except" options will be ignored)
  *   * null: the "only" and "except" options will determine whether the directory or file should be copied
  *
  * - recursive: bool, whether the files under the subdirectories should also be copied. Defaults to true.
  * - beforeCopy: callback, a PHP callback that is called before copying each sub-directory or file.
  *   If the callback returns false, the copy operation for the sub-directory or file will be cancelled.
  *   The signature of the callback should be: `function ($from, $to)`, where `$from` is the sub-directory or
  *   file to be copied from, while `$to` is the copy target.
  * - afterCopy: callback, a PHP callback that is called after each sub-directory or file is successfully copied.
  *   The signature of the callback should be: `function ($from, $to)`, where `$from` is the sub-directory or
  *   file copied from, while `$to` is the copy target.
  * @return bool
  */
 public static function copyDirectory($src, $dst, $options = [])
 {
     if (!is_dir($dst)) {
         static::createDirectory($dst, isset($options['dirMode']) ? $options['dirMode'] : 0775, true);
     }
     $handle = opendir($src);
     if ($handle === false) {
         if (class_exists('\\rock\\log\\Log')) {
             $message = FileHelperException::convertExceptionToString(new FileHelperException('Unable to open directory: ' . $src));
             Log::warn($message);
         }
         return false;
     }
     if (!isset($options['basePath'])) {
         // this should be done only once
         $options['basePath'] = realpath($src);
         $options = self::normalizeOptions($options);
     }
     while (($file = readdir($handle)) !== false) {
         if ($file === '.' || $file === '..') {
             continue;
         }
         $from = $src . DIRECTORY_SEPARATOR . $file;
         $to = $dst . DIRECTORY_SEPARATOR . $file;
         if (static::filterPath($from, $options)) {
             if (isset($options['beforeCopy']) && !call_user_func($options['beforeCopy'], $from, $to)) {
                 continue;
             }
             if (is_file($from)) {
                 copy($from, $to);
                 if (isset($options['fileMode'])) {
                     @chmod($to, $options['fileMode']);
                 }
             } else {
                 static::copyDirectory($from, $to, $options);
             }
             if (isset($options['afterCopy'])) {
                 call_user_func($options['afterCopy'], $from, $to);
             }
         }
     }
     closedir($handle);
     return true;
 }
예제 #9
0
파일: Url.php 프로젝트: romeoz/rock-url
 /**
  * Modify URL.
  *
  * @param string|null $url URL for formatting. If URL as `NULL`, then use current (self) URL.
  * @param array $config
  * @throws UrlException
  * @throws \Exception
  * @throws \rock\helpers\InstanceException
  */
 public function __construct($url = null, $config = [])
 {
     $this->parentConstruct($config);
     $this->request = Instance::ensure($this->request, '\\rock\\request\\Request');
     $this->csrfInstance = Instance::ensure($this->csrfInstance, '\\rock\\csrf\\CSRF', [], false);
     if (empty($url)) {
         $url = $this->currentInternal();
     } else {
         $url = Alias::getAlias($url);
     }
     if (($url = parse_url(trim($url))) === false) {
         $exception = new UrlException('Wrong format URL.');
         if ($this->throwException) {
             throw $exception;
         } else {
             if (class_exists('\\rock\\log\\Log')) {
                 \rock\log\Log::warn(BaseException::convertExceptionToString($exception));
             }
             $url = parse_url(trim($this->currentInternal()));
             $url['fragment'] = '#';
         }
     }
     $this->data = array_merge($url, $this->data);
     if (isset($this->data['query'])) {
         $this->data['query'] = $this->_queryToArray($this->data['query']);
     }
 }