Example #1
0
 /**
  * Saves the Form
  *
  * @param  \yii\db\ActiveRecord  $member
  * @return bool
  */
 public function save($member)
 {
     // Find language
     $language = Language::find()->where(['id' => $this->languageId])->limit(1)->one();
     if (!$language) {
         $this->addError('languageId', 'Could not find Language');
         return false;
     }
     $slug = Util::generateUrlSafeSlug($this->name);
     $iteration = 0;
     // Generate a unique slug
     do {
         $exists = Snippet::find()->where(['slug' => $slug])->count();
         if ($exists) {
             $iteration++;
             $slug = Util::generateUrlSafeSlug($this->name . '-' . $iteration);
         }
     } while ($exists);
     // TODO: strip <script tags from description
     $snippet = new Snippet();
     $snippet->memberId = $member->id;
     $snippet->languageId = $language->id;
     $snippet->slug = $slug;
     $snippet->name = $this->name;
     $snippet->description = $this->description;
     $snippet->code = $this->code;
     if ($snippet->save()) {
         return '/snippets/' . $language->slug . '/' . $snippet->slug;
     } else {
         $this->addError('code', 'There was an error saving the Snippet!');
         return false;
     }
 }
Example #2
0
 /**
  * @param  \yii\db\ActiveRecord  $member
  * @return array
  */
 public static function get($member)
 {
     $request =& Yii::$app->request;
     $offset = (int) $request->getQueryParam('o', 0);
     $query = Bookmark::find()->where(['memberId' => $member->id]);
     $count = $query->count();
     $bookmarks = $query->orderBy('createdTime DESC')->offset($offset)->limit(20)->all();
     return ['bookmarks' => $bookmarks, 'pagination' => Util::getPagination($offset, $count, 20, 'o')];
 }
 /**
  * @param  \yii\db\ActiveRecord  $member
  * @return array
  */
 public static function get($member)
 {
     $request =& Yii::$app->request;
     $offset = (int) $request->getQueryParam('o', 0);
     $query = Snippet::find()->where(['isHidden' => 0, 'memberId' => $member->id]);
     $count = $query->count();
     $snippets = $query->orderBy('createdTime DESC')->offset($offset)->limit(10)->all();
     return ['snippets' => $snippets, 'pagination' => Util::getPagination($offset, $count, 20, 'o')];
 }
Example #4
0
 /**
  * @param  string  $searchString
  * @return array
  */
 public static function get($searchString)
 {
     $request =& Yii::$app->request;
     $offset = (int) $request->getQueryParam('o', 0);
     $query = Snippet::find()->where(['isHidden' => 0]);
     $query->andFilterWhere(['like', 'name', $searchString]);
     $count = $query->count();
     $snippets = $query->orderBy('createdTime DESC')->offset($offset)->limit(20)->all();
     return ['snippets' => $snippets, 'pagination' => Util::getPagination($offset, $count, 20, 'o')];
 }
Example #5
0
 /**
  * @param  \yii\db\ActiveRecord  $language
  * @return array
  */
 public static function get($language = null)
 {
     $request =& Yii::$app->request;
     $offset = (int) $request->getQueryParam('o', 0);
     $where = ['isHidden' => 0];
     if ($language) {
         $where['languageId'] = $language->id;
     }
     $query = Snippet::find()->where($where);
     $count = $query->count();
     $snippets = $query->orderBy('views DESC')->offset($offset)->limit(20)->all();
     return ['snippets' => $snippets, 'pagination' => Util::getPagination($offset, $count, 20, 'o')];
 }
Example #6
0
 /**
  * Attempts to find the member and send them an email
  *
  * @return bool
  */
 public function sendEmail()
 {
     $member = Member::find()->where(['email' => ['like', 'email', $this->email]])->limit(1)->one();
     /* @var $member \yii\db\ActiveRecord */
     if ($member) {
         if ($member->isActive) {
             // Create a new Password Reset Key
             $member->passwordResetKey = Util::getRandomString(32);
             $member->save();
             $encrypted = JWT::encode(['i' => $member->id, 'k' => $member->passwordResetKey], Yii::$app->params['secret']);
             // Send email
             return Yii::$app->mailer->compose(['html' => 'password-reset/html', 'text' => 'password-reset/text'], ['encrypted' => $encrypted, 'member' => $member])->setFrom(Yii::$app->params['fromEmail'])->setTo($this->email)->setSubject('Password Reset - ' . Yii::$app->params['siteName'])->send();
         } else {
             $this->addError('email', 'You account is not active.');
         }
     } else {
         $this->addError('email', 'Could not find you!');
     }
     return false;
 }
Example #7
0
 /**
  * Attempts to find the member and send them an email
  *
  * @return bool
  */
 public function register()
 {
     $member = Member::find()->where(['email' => ['like', 'email', $this->email]])->limit(1)->one();
     if (!$member) {
         // Create a new member
         $member = new Member();
         $member->email = $this->email;
         $member->name = $this->name;
         $member->isActive = 0;
         $member->passwordResetKey = Util::getRandomString(32);
         $member->setRawPassword($this->password);
         $member->save();
         $encrypted = JWT::encode(['i' => $member->id, 'k' => $member->passwordResetKey], Yii::$app->params['secret']);
         // Send email
         return Yii::$app->mailer->compose(['html' => 'register/html', 'text' => 'register/text'], ['encrypted' => $encrypted, 'member' => $member])->setFrom(Yii::$app->params['fromEmail'])->setTo($this->email)->setSubject('Registration Confirmation - ' . Yii::$app->params['siteName'])->send();
     } else {
         $this->addError('email', 'An account already exists for ' . $this->email);
     }
     return false;
 }
Example #8
0
 /**
  * Return the listing of a directory
  *
  * @access public
  * @param  string  $directory
  * @param  string  $type
  * @param  string  $order
  * @param  string  $direction
  * @param  bool    $limit
  * @param  array   $fileExtensions
  * @return array
  * @throws \Exception
  */
 public function getListing($directory, $type = self::TYPE_BOTH, $order = self::KEY_NAME, $direction = self::ASC, $limit = false, $fileExtensions = array())
 {
     // Get the contents of the dir
     $listing = array();
     $directory = rtrim($directory, '/');
     // Check Dir
     if (!is_dir($directory)) {
         throw new \Exception('Directory does not exist: ' . $directory);
     }
     // Get Raw Listing
     $directoryHandle = opendir($directory);
     while (false !== ($file = readdir($directoryHandle))) {
         if (substr($file, 0, 1) != '.') {
             // skip anything that starts with a '.' i.e.:('.', '..', or any hidden file)
             // Directories
             if (is_dir($directory . '/' . $file) && ($type == self::TYPE_BOTH || $type == self::TYPE_DIR)) {
                 $listing[] = array(self::KEY_TYPE => self::TYPE_DIR, self::KEY_NAME => $file, self::KEY_DATE => filemtime($directory . '/' . $file), self::KEY_SIZE => filesize($directory . '/' . $file), self::KEY_EXT => '');
                 // Files
             } elseif (is_file($directory . '/' . $file) && ($type == self::TYPE_BOTH || $type == self::TYPE_FILE)) {
                 if (!count($fileExtensions) || in_array(Util::getExtension($file), $fileExtensions)) {
                     $listing[] = array(self::KEY_TYPE => self::TYPE_FILE, self::KEY_NAME => $file, self::KEY_DATE => filemtime($directory . '/' . $file), self::KEY_SIZE => filesize($directory . '/' . $file), self::KEY_EXT => Util::getExtension($file));
                 }
             }
         }
         // Impose Limit, if specified
         if ($limit && count($listing) >= $limit) {
             break;
         }
     }
     closedir($directoryHandle);
     // Sorting
     $listing = $this->sort($listing, $type, $order, $direction);
     // Callbacks
     if ($this->filterCallback) {
         $listing = call_user_func($this->filterCallback, $listing);
     }
     // Total Size
     $totalSize = 0;
     foreach ($listing as $item) {
         $totalSize += $item[self::KEY_SIZE];
     }
     $this->lastSize = $totalSize;
     // Item Count
     $this->lastItemCount = count($listing);
     // Done
     return $listing;
 }
Example #9
0
 /**
  * Обновление книги.
  *
  * @param string $id
  *
  * @return mixed
  * @throws \Exception
  * @throws \yii\base\Exception
  * @throws \yii\web\NotFoundHttpException
  */
 public function actionUpdate($id)
 {
     $model = $this->findModel($id);
     $oldImagePath = $model->preview;
     if ($model->load(Yii::$app->request->post()) && $model->save()) {
         if (null !== ($image = UploadedFile::getInstance($model, 'preview'))) {
             $model->preview = $image;
             if (!$model->validate(['preview'])) {
                 Yii::$app->getSession()->setFlash('error', Html::errorSummary($model, ['header' => 'Пожалуйста, исправьте следующие ошибки:', 'encode' => false]));
                 // возвращаем путь к изображению, если валидация провалилась
                 $model->preview = $oldImagePath;
                 $model->update(false, ['preview']);
                 return $this->render('update', ['model' => $model]);
             }
             // удаляем предыдущее изображение
             $oldImageFile = Yii::$app->params['booksUploadsDir'] . $oldImagePath;
             if (is_file($oldImageFile)) {
                 unlink($oldImageFile);
             }
             // работаем с новым загруженным изображением
             $uploadsDir = realpath(Yii::$app->params['booksUploadsDir']);
             $uploadsTmpDir = realpath(Yii::$app->params['frontendUploadsTmpDir']);
             // сохраняем изображение во временную директорию
             $tmpFilename = $uploadsTmpDir . DIRECTORY_SEPARATOR . 'book_preview_' . uniqid() . '.' . $image->getExtension();
             if (false === $image->saveAs($tmpFilename)) {
                 throw new Exception('Невозможно сохранить загруженное изображение для превью книги в файл: ' . $tmpFilename);
             } else {
                 // создаем вложенные директории
                 $path = Util::createNestedFolders($uploadsDir, $model->id);
                 $filename = $path . DIRECTORY_SEPARATOR . dechex($model->id) . '.' . $image->getExtension();
                 $previewFilename = $path . DIRECTORY_SEPARATOR . dechex($model->id) . '_thumb.' . $image->getExtension();
                 $imagine = Image::getImagine();
                 /** @var $i \Imagine\Gd\Image */
                 $i = $imagine->open($tmpFilename);
                 // если размеры изображения превышают лимиты, оно ресайзится
                 if ($i->getSize()->getWidth() > Yii::$app->params['maxImageWidth'] || $i->getSize()->getHeight() > Yii::$app->params['maxImageHeight']) {
                     $i->thumbnail(new Box(Yii::$app->params['maxImageWidth'], Yii::$app->params['maxImageHeight']), ImageInterface::THUMBNAIL_INSET)->save($filename, ['quality' => 100]);
                 } else {
                     $i->save($filename);
                 }
                 // создаем превьюшку из исходника
                 $i = $imagine->open($tmpFilename);
                 if ($i->getSize()->getWidth() > Yii::$app->params['thumbnailDefaultWidth'] || $i->getSize()->getHeight() > Yii::$app->params['thumbnailDefaultHeight']) {
                     $i->thumbnail(new Box(Yii::$app->params['thumbnailDefaultWidth'], Yii::$app->params['thumbnailDefaultHeight']), ImageInterface::THUMBNAIL_INSET)->save($previewFilename, ['quality' => 100]);
                 }
                 // удаляем временный файл
                 unlink($tmpFilename);
                 $filename = str_replace('\\', '/', $filename);
                 $filename = preg_replace('=^(.*?)(/uploads/books/.*)$=iu', '\\2', $filename);
                 $model->preview = $filename;
             }
         } else {
             $model->preview = $oldImagePath;
         }
         $model->update(false, ['preview']);
         Yii::$app->getSession()->setFlash('success', 'Данные книги &laquo;' . $model->name . '&raquo; успешно обновлены.');
         if (null === ($referer = Yii::$app->request->post('referer'))) {
             return $this->redirect(['index', 'id' => $model->id]);
         } else {
             return $this->redirect($referer);
         }
     } else {
         return $this->render('update', ['model' => $model]);
     }
 }