Beispiel #1
0
 /**
  * Find all bootatble instances and set it to object map
  */
 public function compileBootableClasses()
 {
     // list app root's
     foreach ($this->appRoots as $app) {
         $app .= '/Apps/Controller/' . env_name;
         $files = File::listFiles($app, ['.php'], true);
         foreach ($files as $file) {
             // define full class name with namespace
             $class = 'Apps\\Controller\\' . env_name . '\\' . Str::cleanExtension($file);
             // check if class exists (must be loaded over autoloader), boot method exist and this is controller instanceof
             if (class_exists($class) && method_exists($class, 'boot') && is_a($class, 'Ffcms\\Core\\Arch\\Controller', true)) {
                 $this->objects[] = $class;
             }
         }
     }
     // list widget root's
     foreach ($this->widgetRoots as $widget) {
         $widget .= '/Widgets/' . env_name;
         // widgets are packed in directory, classname should be the same with root directory name
         $dirs = Directory::scan($widget, GLOB_ONLYDIR, true);
         if (!Obj::isArray($dirs)) {
             continue;
         }
         foreach ($dirs as $instance) {
             $class = 'Widgets\\' . env_name . '\\' . $instance . '\\' . $instance;
             if (class_exists($class) && method_exists($class, 'boot') && is_a($class, 'Ffcms\\Core\\Arch\\Widget', true)) {
                 $this->objects[] = $class;
             }
         }
     }
 }
Beispiel #2
0
 /**
  * Build variables and display output html
  */
 public function buildOutput()
 {
     $this->after();
     // if layout is not required and this is just standalone app
     if ($this->layout === null) {
         $content = $this->output;
     } else {
         $layoutPath = App::$Alias->currentViewPath . '/layout/' . $this->layout . '.php';
         if (!File::exist($layoutPath)) {
             throw new NativeException('Layout not founded: ' . $layoutPath);
         }
         $body = $this->output;
         // pass global data to config viewer
         if (App::$Debug !== null) {
             App::$Debug->bar->getCollector('config')->setData(['Global Vars' => Variables::instance()->getGlobalsArray()]);
         }
         // cleanup buffer from random shits after exception throw'd
         ob_clean();
         // start buffering to render layout
         ob_start();
         include $layoutPath;
         $content = ob_get_clean();
         // read buffer content & stop buffering
         // set custom css library's not included on static call
         $cssIncludeCode = App::$View->showCodeLink('css');
         if (!Str::likeEmpty($cssIncludeCode)) {
             $content = Str::replace('</head>', $cssIncludeCode . '</head>', $content);
         }
         // add debug bar
         if (App::$Debug !== null) {
             $content = Str::replace(['</body>', '</head>'], [App::$Debug->renderOut() . '</body>', App::$Debug->renderHead() . '</head>'], $content);
         }
     }
     return $content;
 }
Beispiel #3
0
 /**
  * Import all tables to database
  * @param string $connectName
  * @return string
  */
 public function actionImportAll($connectName = 'default')
 {
     $importFile = root . '/Private/Database/install.php';
     if (!File::exist($importFile)) {
         return 'Import file is not exist: ' . $importFile;
     }
     @(include $importFile);
     return 'All database tables was imported!';
 }
Beispiel #4
0
 /**
  * Build sitemap index files information - location, last modify time
  */
 public function make()
 {
     if (!Obj::isArray($this->files)) {
         return;
     }
     // build file information data
     foreach ($this->files as $file) {
         $this->info[] = ['loc' => App::$Alias->scriptUrl . $file, 'lastmod' => Date::convertToDatetime(File::mTime($file), 'c')];
     }
 }
Beispiel #5
0
 public function before()
 {
     parent::before();
     // define application root diskpath and tpl native directory
     $this->appRoot = realpath(__DIR__ . '/../../../');
     $this->tplDir = realpath($this->appRoot . '/Apps/View/Front/default/demoapp/');
     // load internalization package for current lang
     $langFile = $this->appRoot . '/I18n/Front/' . App::$Request->getLanguage() . '/Demoapp.php';
     if (App::$Request->getLanguage() !== 'en' && File::exist($langFile)) {
         App::$Translate->append($langFile);
     }
 }
Beispiel #6
0
 /**
  * Get user avatar full url for current object
  * @param string $type
  * @return string
  */
 public function getAvatarUrl($type = 'small')
 {
     $default = '/upload/user/avatar/' . $type . '/default.jpg';
     if (!Arr::in($type, ['small', 'big', 'medium'])) {
         return MainApp::$Alias->scriptUrl . $default;
     }
     $route = '/upload/user/avatar/' . $type . '/' . $this->user_id . '.jpg';
     if (File::exist($route)) {
         return MainApp::$Alias->scriptUrl . $route . '?mtime=' . File::mTime($route);
     }
     return MainApp::$Alias->scriptUrl . $default;
 }
Beispiel #7
0
 /**
  * Display installation form and process install
  * @throws ForbiddenException
  * @throws \Ffcms\Core\Exception\SyntaxException
  * @throws \Ffcms\Core\Exception\NativeException
  */
 public function actionInstall()
 {
     if (File::exist('/Private/Install/install.lock')) {
         throw new ForbiddenException(__('installer is blocked! If you want to continue delete file /Private/Installer/install.lock'));
     }
     $model = new FormInstall();
     if ($model->send() && $model->validate()) {
         $model->make();
         $this->response->redirect('main/success');
     }
     return $this->view->render('install', ['model' => $model]);
 }
Beispiel #8
0
 /**
  * Build xml output and save it into sitemap folder
  * @param string $uniqueName
  * @return bool
  * @throws \Ffcms\Core\Exception\NativeException
  * @throws \Ffcms\Core\Exception\SyntaxException
  */
 public function save($uniqueName)
 {
     // check if data exists
     if ($this->data === null || !Obj::isArray($this->data)) {
         return false;
     }
     // list data each every language, render xml output and write into file
     foreach ($this->data as $lang => $items) {
         $xml = App::$View->render('native/sitemap_urlset', ['items' => $items]);
         File::write(EntityIndexList::INDEX_PATH . '/' . $uniqueName . '.' . $lang . '.xml', $xml);
     }
     return true;
 }
Beispiel #9
0
 /**
  * Find update files with sql queries
  */
 public function findUpdateFiles()
 {
     // find all file with update sql queries between $dbVersion<->scriptVersion (dbVer <= x <= scriptVer)
     $all = File::listFiles('/Private/Database/Updates/', ['.php'], true);
     foreach ($all as $file) {
         $file = Str::cleanExtension(basename($file));
         // $file="3.0.0-3.0.1" become to $start = 3.0.0,$end=3.0.1
         list($start, $end) = explode('-', $file);
         // true: start <= db & script >= $end
         if (version_compare($this->dbVersion, $start) !== 1 && version_compare($this->scriptVersion, $end) !== -1) {
             $this->updateQueries[] = $file;
         }
     }
     sort($this->updateQueries);
 }
Beispiel #10
0
 /**
  * Download archive and extract to root directory
  * @return bool
  */
 public function make()
 {
     $archive = $this->name . '.zip';
     // download archive
     File::saveFromUrl($this->url, '/' . $archive);
     // extract archive
     $zip = new \ZipArchive();
     if ($zip->open(root . '/' . $archive) === true) {
         $zip->extractTo(root);
         $zip->close();
         // cleanup cache
         App::$Cache->clean();
         return true;
     }
     return false;
 }
Beispiel #11
0
 /**
  * Show scan results
  * @return string
  */
 public function actionAntivirusresults()
 {
     $response = null;
     if (!File::exist('/Private/Antivirus/Infected.json')) {
         $response = ['status' => 0];
     } else {
         $data = json_decode(File::read('/Private/Antivirus/Infected.json'));
         $compile = [];
         foreach ($data as $file => $sign) {
             $file = Str::replace('\\', '/', Str::sub($file, strlen(root)));
             $compile[$file][] = $sign;
         }
         $response = ['status' => 1, 'data' => $compile];
     }
     $this->setJsonHeader();
     return json_encode($response);
 }
Beispiel #12
0
 /**
  * Browse files from ckeditor
  * @param string $type
  * @throws NativeException
  * @throws \Ffcms\Core\Exception\SyntaxException
  */
 public function actionBrowse($type)
 {
     $files = null;
     $relative = null;
     // check if request type is defined
     if ($this->allowedExt[$type] === null || !Obj::isArray($this->allowedExt[$type])) {
         throw new NativeException('Hack attempt');
     }
     // list files in directory
     $files = File::listFiles('/upload/' . $type, $this->allowedExt[$type]);
     // absolute path to relative URI
     foreach ($files as $file) {
         $newName = Str::sub($file, Str::length(root) + 1);
         $relative[] = trim(Str::replace(DIRECTORY_SEPARATOR, '/', $newName), '/');
     }
     // generate response
     return App::$View->render('editor/browse', ['callbackName' => App::$Security->strip_tags(App::$Request->query->get('CKEditor')), 'callbackId' => (int) App::$Request->query->get('CKEditorFuncNum'), 'files' => $relative, 'type' => $type], __DIR__);
 }
Beispiel #13
0
 /**
  * Get default server information and prepare chmod info
  */
 public function before()
 {
     $this->phpVersion = phpversion();
     $this->pdo = extension_loaded('pdo');
     $this->gd = extension_loaded('gd') && function_exists('gd_info');
     // autoload is disabled, lets get chmod file & dirs from console app data
     File::inc('/Apps/Controller/Console/Main.php');
     $this->_chmodDirs = Main::$installDirs;
     // for each file or directory in list - check permissions
     foreach ($this->_chmodDirs as $object) {
         if (Str::endsWith('.php', $object)) {
             // sounds like a file
             $this->chmodCheck[$object] = File::exist($object) && File::writable($object);
         } else {
             $this->chmodCheck[$object] = Directory::exist($object) && Directory::writable($object);
         }
     }
 }
Beispiel #14
0
 /**
  * Delete user from database
  * @throws \Exception
  */
 public function delete()
 {
     foreach ($this->users as $user) {
         /** @var iUser $user */
         $uid = $user->getParam('id');
         // delete wall records
         WallPost::where('target_id', '=', $uid)->orWhere('sender_id', '=', $uid)->delete();
         // delete avatars
         File::remove('/upload/user/avatar/big/' . $uid . '.jpg');
         File::remove('/upload/user/avatar/medium/' . $uid . '.jpg');
         File::remove('/upload/user/avatar/small/' . $uid . '.jpg');
         File::remove('/upload/user/avatar/original/' . $uid . '.jpg');
         // delete user profile and auth data
         $user->getProfile()->delete();
         // delete user provider data
         $user->getProviders()->delete();
         // delete user object
         $user->delete();
     }
 }
Beispiel #15
0
 /**
  * Find latest release in github API and get required info
  */
 private function findLatestVersion()
 {
     // get remote api with json response
     $gitJson = File::getFromUrl(static::API_LATEST_RELEASE);
     if ($gitJson === null || $gitJson === false) {
         return;
     }
     // parse api response to model attributes
     $git = json_decode($gitJson, true);
     $this->lastVersion = $git['tag_name'];
     // get download url to full compiled distributive (uploaded to each release as .zip archive, placed in release.assets)
     $download = null;
     if (Obj::isArray($git['assets'])) {
         foreach ($git['assets'] as $asset) {
             if ($asset['content_type'] === 'application/zip' && $asset['state'] === 'uploaded') {
                 $download = $asset['browser_download_url'];
             }
         }
     }
     $this->lastInfo = ['name' => $git['name'], 'created_at' => Date::convertToDatetime($git['published_at'], Date::FORMAT_TO_HOUR), 'download_url' => $download];
 }
Beispiel #16
0
 /**
  * Download remote content in binary string
  * @param string $url
  * @return null|string
  * @deprecated
  */
 public static function download($url)
 {
     return File::getFromUrl($url);
 }
Beispiel #17
0
 /**
  * Console installation
  * @return string
  * @throws NativeException
  */
 public function actionInstall()
 {
     if (File::exist('/Private/Install/install.lock')) {
         throw new NativeException('Installation is locked! Please delete /Private/Install/install.lock');
     }
     echo Console::$Output->writeHeader('License start');
     echo File::read('/LICENSE') . PHP_EOL;
     echo Console::$Output->writeHeader('License end');
     $config = Console::$Properties->get('database');
     $newConfig = [];
     // creating default directory's
     foreach (self::$installDirs as $obj) {
         // looks like a directory
         if (!Str::contains('.', $obj)) {
             Directory::create($obj, 0777);
         }
     }
     echo Console::$Output->write('Upload and private directories are successful created!');
     // set chmods
     echo $this->actionChmod();
     // database config from input
     echo Console::$Output->writeHeader('Database connection configuration');
     echo 'Driver(default:' . $config['driver'] . '):';
     $dbDriver = Console::$Input->read();
     if (Arr::in($dbDriver, ['mysql', 'pgsql', 'sqlite'])) {
         $newConfig['driver'] = $dbDriver;
     }
     // for sqlite its would be a path
     echo 'Host(default:' . $config['host'] . '):';
     $dbHost = Console::$Input->read();
     if (!Str::likeEmpty($dbHost)) {
         $newConfig['host'] = $dbHost;
     }
     echo 'Database name(default:' . $config['database'] . '):';
     $dbName = Console::$Input->read();
     if (!Str::likeEmpty($dbName)) {
         $newConfig['database'] = $dbName;
     }
     echo 'User(default:' . $config['username'] . '):';
     $dbUser = Console::$Input->read();
     if (!Str::likeEmpty($dbUser)) {
         $newConfig['username'] = $dbUser;
     }
     echo 'Password(default:' . $config['password'] . '):';
     $dbPwd = Console::$Input->read();
     if (!Str::likeEmpty($dbPwd)) {
         $newConfig['password'] = $dbPwd;
     }
     echo 'Table prefix(default:' . $config['prefix'] . '):';
     $dbPrefix = Console::$Input->read();
     if (!Str::likeEmpty($dbPrefix)) {
         $newConfig['prefix'] = $dbPrefix;
     }
     // merge configs and add new connection to db pull
     $dbConfigs = Arr::merge($config, $newConfig);
     Console::$Database->addConnection($dbConfigs, 'install');
     try {
         Console::$Database->connection('install')->getDatabaseName();
     } catch (\Exception $e) {
         return 'Testing database connection is failed! Run installer again and pass tested connection data! Log: ' . $e->getMessage();
     }
     // autoload isn't work here
     include root . '/Apps/Controller/Console/Db.php';
     // import db data
     $dbController = new DbController();
     echo $dbController->actionImportAll('install');
     // add system info about current install version
     $system = new System();
     $system->setConnection('install');
     $system->var = 'version';
     $system->data = Version::VERSION;
     $system->save();
     // set website send from email from input
     $emailConfig = Console::$Properties->get('adminEmail');
     echo 'Website sendFrom email(default: ' . $emailConfig . '):';
     $email = Console::$Input->read();
     if (!Str::isEmail($email)) {
         $email = $emailConfig;
     }
     // set base domain
     echo 'Website base domain name(ex. ffcms.org):';
     $baseDomain = Console::$Input->read();
     if (Str::likeEmpty($baseDomain)) {
         $baseDomain = Console::$Properties->get('baseDomain');
     }
     // generate other configuration data and security salt, key's and other
     echo Console::$Output->writeHeader('Writing configurations');
     /** @var array $allCfg */
     $allCfg = Console::$Properties->getAll('default');
     $allCfg['database'] = $dbConfigs;
     $allCfg['adminEmail'] = $email;
     $allCfg['baseDomain'] = $baseDomain;
     echo Console::$Output->write('Generate password salt for BLOWFISH crypt');
     $allCfg['passwordSalt'] = '$2a$07$' . Str::randomLatinNumeric(mt_rand(21, 30)) . '$';
     echo Console::$Output->write('Generate security cookies for debug panel');
     $allCfg['debug']['cookie']['key'] = 'fdebug_' . Str::randomLatinNumeric(mt_rand(8, 32));
     $allCfg['debug']['cookie']['value'] = Str::randomLatinNumeric(mt_rand(32, 128));
     // write config data
     $writeCfg = Console::$Properties->writeConfig('default', $allCfg);
     if ($writeCfg !== true) {
         return 'File /Private/Config/Default.php is unavailable to write data!';
     }
     File::write('/Private/Install/install.lock', 'Install is locked');
     return 'Configuration done! FFCMS 3 is successful installed! Visit your website. You can add administrator using command php console.php db/adduser';
 }
Beispiel #18
0
 /**
  * Save changes in database
  */
 public function save()
 {
     $this->_content->title = $this->title;
     $this->_content->text = $this->text;
     $this->_content->path = $this->path;
     $this->_content->category_id = $this->categoryId;
     $this->_content->author_id = $this->authorId;
     $this->_content->display = $this->display;
     $this->_content->meta_title = $this->metaTitle;
     $this->_content->meta_keywords = $this->metaKeywords;
     $this->_content->meta_description = $this->metaDescription;
     $this->_content->source = $this->source;
     // check if rating is changed
     if ((int) $this->addRating !== 0) {
         $this->_content->rating += (int) $this->addRating;
     }
     // check if special comment hash is exist
     if ($this->_new || Str::length($this->_content->comment_hash) < 32) {
         $this->_content->comment_hash = $this->generateCommentHash();
     }
     // check if date is updated
     if (!Str::likeEmpty($this->createdAt) && !Str::startsWith('0000', Date::convertToDatetime($this->createdAt, Date::FORMAT_SQL_TIMESTAMP))) {
         $this->_content->created_at = Date::convertToDatetime($this->createdAt, Date::FORMAT_SQL_TIMESTAMP);
     }
     // save poster data
     $posterPath = '/upload/gallery/' . $this->galleryFreeId . '/orig/' . $this->poster;
     if (File::exist($posterPath)) {
         $this->_content->poster = $this->poster;
     }
     // get temporary gallery id
     $tmpGalleryId = $this->galleryFreeId;
     // save row
     $this->_content->save();
     // update tags data in special table (relation: content->content_tags = oneToMany)
     ContentTag::where('content_id', '=', $this->_content->id)->delete();
     $insertData = [];
     foreach ($this->metaKeywords as $lang => $keys) {
         // split keywords to tag array
         $tags = explode(',', $keys);
         foreach ($tags as $tag) {
             // cleanup tag from white spaces
             $tag = trim($tag);
             // prepare data to insert
             if (Str::length($tag) > 0) {
                 $insertData[] = ['content_id' => $this->_content->id, 'lang' => $lang, 'tag' => $tag];
             }
         }
     }
     // insert tags
     ContentTag::insert($insertData);
     // move files
     if ($tmpGalleryId !== $this->_content->id) {
         Directory::rename('/upload/gallery/' . $tmpGalleryId, $this->_content->id);
     }
 }
Beispiel #19
0
 /**
  * Try to download and parse remote avatar
  * @param string $url
  * @param int $userId
  */
 protected function parseAvatar($url, $userId)
 {
     // check if user is defined
     if ((int) $userId < 1) {
         return;
     }
     // check remote image extension
     $imageExtension = Str::lastIn($url, '.', true);
     if (!Arr::in($imageExtension, ['png', 'gif', 'jpg', 'jpeg'])) {
         return;
     }
     // try to get image binary data
     $imageContent = Url::download($url);
     if ($imageContent === null || Str::likeEmpty($imageContent)) {
         return;
     }
     // write image to filesystem
     $imagePath = '/upload/user/avatar/original/' . $userId . '.' . $imageExtension;
     $write = File::write($imagePath, $imageContent);
     if ($write === false) {
         return;
     }
     // try to write and resize file
     try {
         $fileObject = new FileObject(root . $imagePath);
         $avatarUpload = new FormAvatarUpload();
         $avatarUpload->resizeAndSave($fileObject, $userId, 'small');
         $avatarUpload->resizeAndSave($fileObject, $userId, 'medium');
         $avatarUpload->resizeAndSave($fileObject, $userId, 'big');
     } catch (\Exception $e) {
         if (App::$Debug) {
             App::$Debug->addException($e);
         }
     }
 }
Beispiel #20
0
 /**
  * Render view in sandbox function
  * @param string $path
  * @param array|null $params
  * @return string
  */
 protected function renderSandbox($path, $params = null)
 {
     if ($path === null || !File::exist($path)) {
         return null;
     }
     // render defaults params as variables
     if (Obj::isArray($params) && count($params) > 0) {
         foreach ($params as $key => $value) {
             ${$key} = $value;
         }
     }
     $global = $this->buildGlobal();
     $self = $this;
     // turn on output buffer
     ob_start();
     // try get buffered content and catch native exception to exit from app
     try {
         include $path;
         $response = ob_get_clean();
         // get buffer data and stop buffering
     } catch (NativeException $e) {
         // cleanup response
         $response = null;
         // cleanup buffer
         ob_end_clean();
         // prepare output message
         $msg = $e->getMessage();
         if (!Str::likeEmpty($msg)) {
             $msg .= '. ';
         }
         $msg .= __('Native exception catched in view: %path% in line %line%', ['path' => $path, 'line' => $e->getLine()]);
         exit($e->display($msg));
     }
     // cleanup init params
     $this->path = null;
     $this->params = null;
     $this->sourcePath = null;
     // return response
     return $response;
 }
Beispiel #21
0
        try {
            $capsule->addConnection(App::$Properties->get('database'));
        } catch (\Exception $e) {
            exit('Database connection error!');
        }
    }
    $capsule->setAsGlobal();
    // available from any places
    $capsule->bootEloquent();
    // allow active record model's
    if (\App::$Debug !== null) {
        // enable query collector
        $capsule->connection()->enableQueryLog();
    }
    // if this is not installer interface and cms is not installed - try to redirect to install interface
    if (env_name !== 'Install' && !File::exist('/Private/Install/install.lock')) {
        try {
            $capsule->connection()->getPdo();
        } catch (\Exception $e) {
            $instUri = \App::$Alias->scriptUrl . '/install';
            \App::$Response->redirect($instUri, true);
        }
    }
    return $capsule;
}, 'Session' => function () {
    $handler = null;
    try {
        $pdo = \App::$Database->connection()->getPdo();
        $handler = new PdoSessionHandler($pdo, ['db_table' => App::$Properties->get('database')['prefix'] . 'sessions']);
    } catch (Exception $e) {
        $handler = new NativeFileSessionHandler(root . '/Private/Sessions');
Beispiel #22
0
 /**
  * Append translation data from exist full path
  * @param string $path
  * @return bool
  */
 public function append($path)
 {
     $path = Normalize::diskFullPath($path);
     // check if file exist
     if (!File::exist($path)) {
         return false;
     }
     // load file translations
     $addTranslation = (require $path);
     if (!Obj::isArray($addTranslation)) {
         return false;
     }
     // merge data
     $this->cached = Arr::merge($this->cached, $addTranslation);
     return true;
 }
Beispiel #23
0
 /**
  * Get poster thumbnail uri
  * @return null|string
  */
 public function getPosterThumbUri()
 {
     $pName = $this->poster;
     if ($pName === null || Str::likeEmpty($pName)) {
         return null;
     }
     // remove extension, thumbs always in jpeg ;D
     $pName = Str::cleanExtension($pName);
     $path = '/upload/gallery/' . $this->id . '/thumb/' . $pName . '.jpg';
     if (!File::exist($path)) {
         return null;
     }
     return $path;
 }
Beispiel #24
0
 /**
  * Build content data to model properties
  * @param $records
  * @throws ForbiddenException
  * @throws NotFoundException
  */
 private function buildContent($records)
 {
     $nullItems = 0;
     foreach ($records as $row) {
         /** @var Content $row */
         // check title length on current language locale
         $localeTitle = $row->getLocaled('title');
         if (Str::likeEmpty($localeTitle)) {
             ++$nullItems;
             continue;
         }
         // get snippet from full text for current locale
         $text = Text::snippet($row->getLocaled('text'));
         $itemPath = $this->categories[$row->category_id]->path;
         if (!Str::likeEmpty($itemPath)) {
             $itemPath .= '/';
         }
         $itemPath .= $row->path;
         // prepare tags data
         $tags = $row->getLocaled('meta_keywords');
         if (!Str::likeEmpty($tags)) {
             $tags = explode(',', $tags);
         } else {
             $tags = null;
         }
         $owner = App::$User->identity($row->author_id);
         // make a fake if user is not exist over id
         if ($owner === null) {
             $owner = new User();
         }
         // check if current user can rate item
         $ignoredRate = App::$Session->get('content.rate.ignore');
         $canRate = true;
         if (Obj::isArray($ignoredRate) && Arr::in((string) $row->id, $ignoredRate)) {
             $canRate = false;
         }
         if (!App::$User->isAuth()) {
             $canRate = false;
         } elseif ($owner->getId() === App::$User->identity()->getId()) {
             // own item
             $canRate = false;
         }
         // build result array
         $this->items[] = ['id' => $row->id, 'title' => $localeTitle, 'text' => $text, 'date' => Date::humanize($row->created_at), 'updated' => $row->updated_at, 'author' => $owner, 'poster' => $row->getPosterUri(), 'thumb' => $row->getPosterThumbUri(), 'thumbSize' => File::size($row->getPosterThumbUri()), 'views' => (int) $row->views, 'rating' => (int) $row->rating, 'canRate' => $canRate, 'category' => $this->categories[$row->category_id], 'uri' => '/content/read/' . $itemPath, 'tags' => $tags];
     }
     if ($nullItems === $this->_contentCount) {
         throw new NotFoundException(__('Content is not founded'));
     }
 }
Beispiel #25
0
 /**
  * Prepare model attributes from passed objects
  * @throws ForbiddenException
  */
 public function before()
 {
     $this->id = $this->_content->id;
     $this->title = $this->_content->getLocaled('title');
     $this->text = $this->_content->getLocaled('text');
     // check if title and text are exists
     if (Str::length($this->title) < 1 || Str::length($this->text) < 1) {
         throw new ForbiddenException();
     }
     // get meta data
     $this->metaTitle = $this->_content->getLocaled('meta_title');
     if (Str::likeEmpty($this->metaTitle)) {
         $this->metaTitle = $this->title;
     }
     $this->metaDescription = $this->_content->getLocaled('meta_description');
     $tmpKeywords = $this->_content->getLocaled('meta_keywords');
     $this->metaKeywords = explode(',', $tmpKeywords);
     // set content date, category data
     $this->createDate = Date::humanize($this->_content->created_at);
     $this->catName = $this->_category->getLocaled('title');
     $this->catPath = $this->_category->path;
     // set user data
     if (App::$User->isExist($this->_content->author_id)) {
         $this->authorId = $this->_content->author_id;
         $profile = App::$User->identity($this->authorId)->getProfile();
         $this->authorName = $profile->getNickname();
     }
     $this->source = $this->_content->source;
     $this->views = $this->_content->views + 1;
     // check for dependence, add '' for general cat, ex: general/depend1/depend2/.../depend-n
     $catNestingArray = Arr::merge([0 => ''], explode('/', $this->catPath));
     if ($catNestingArray > 1) {
         // latest element its a current nesting level, lets cleanup it
         array_pop($catNestingArray);
         $catNestingPath = null;
         foreach ($catNestingArray as $cPath) {
             $catNestingPath .= $cPath;
             // try to find category by path in db
             $record = ContentCategory::getByPath($catNestingPath);
             if ($record !== null && $record->count() > 0) {
                 // if founded - add to nesting data
                 $this->catNesting[] = ['name' => $record->getLocaled('title'), 'path' => $record->path];
             }
             if (!Str::likeEmpty($catNestingPath)) {
                 $catNestingPath .= '/';
             }
         }
     }
     // build array of category nesting level
     $this->catNesting[] = ['name' => $this->catName, 'path' => $this->catPath];
     // get gallery images and poster data
     $galleryPath = '/upload/gallery/' . $this->_content->id;
     // check if gallery folder is exist
     if (Directory::exist($galleryPath)) {
         $originImages = File::listFiles($galleryPath . '/orig/', ['.jpg', '.png', '.gif', '.jpeg', '.bmp', '.webp'], true);
         // generate poster data
         if (Arr::in($this->_content->poster, $originImages)) {
             // original poster
             $posterName = $this->_content->poster;
             $this->posterFull = $galleryPath . '/orig/' . $posterName;
             if (!File::exist($this->posterFull)) {
                 $this->posterFull = null;
             }
             // thumb poster
             $posterSplit = explode('.', $posterName);
             array_pop($posterSplit);
             $posterCleanName = implode('.', $posterSplit);
             $this->posterThumb = $galleryPath . '/thumb/' . $posterCleanName . '.jpg';
             if (!File::exist($this->posterThumb)) {
                 $this->posterThumb = null;
             }
         }
         // generate full gallery
         foreach ($originImages as $image) {
             $imageSplit = explode('.', $image);
             array_pop($imageSplit);
             $imageClearName = implode('.', $imageSplit);
             // skip image used in poster
             if (Str::startsWith($imageClearName, $this->_content->poster)) {
                 continue;
             }
             $thumbPath = $galleryPath . '/thumb/' . $imageClearName . '.jpg';
             if (File::exist($thumbPath)) {
                 $this->galleryItems[$thumbPath] = $galleryPath . '/orig/' . $image;
             }
         }
     }
     // set rating data
     $this->rating = $this->_content->rating;
     $ignoredRate = App::$Session->get('content.rate.ignore');
     $this->canRate = true;
     if (Obj::isArray($ignoredRate) && Arr::in((string) $this->id, $ignoredRate)) {
         $this->canRate = false;
     }
     if (!App::$User->isAuth()) {
         $this->canRate = false;
     } elseif ($this->authorId === App::$User->identity()->getId()) {
         $this->canRate = false;
     }
     // update views count
     $this->_content->views += 1;
     $this->_content->save();
 }
Beispiel #26
0
 /**
  * Prepare scan list on first run. Scan directory's and save as JSON
  */
 private function prepareScanlist()
 {
     $files = (object) File::listFiles(root, $this->affectedExt);
     File::write('/Private/Antivirus/ScanFiles.json', json_encode($files));
 }
Beispiel #27
0
 /**
  * Finish current form.
  * @param bool $validate
  * @return string
  */
 public function finish($validate = true)
 {
     // pre-validate form fields based on model rules and jquery.validation
     if ($validate) {
         App::$Alias->addPlainCode('js', '$().ready(function() { $("#' . $this->name . '").validate(); });');
         App::$Alias->setCustomLibrary('js', '/vendor/bower/jquery-validation/dist/jquery.validate.min.js');
         if (App::$Request->getLanguage() !== 'en') {
             $localeFile = '/vendor/bower/jquery-validation/src/localization/messages_' . App::$Request->getLanguage() . '.js';
             if (File::exist($localeFile)) {
                 App::$Alias->setCustomLibrary('js', $localeFile);
             }
         }
         // if model is not empty - add js error color notification
         if ($this->model !== null) {
             $badAttr = $this->model->getBadAttribute();
             $formName = $this->model->getFormName();
             if (Obj::isArray($badAttr) && count($badAttr) > 0) {
                 foreach ($badAttr as $attr) {
                     $itemId = $formName . '-' . $attr;
                     $render = App::$View->render(static::$structLayer['jsnotify'], ['itemId' => $itemId]);
                     App::$Alias->addPlainCode('js', $render);
                 }
             }
         }
     }
     return '</form>';
 }
Beispiel #28
0
 public function createObject($name, $type)
 {
     $singleName = false;
     if (!Str::contains('/', $name)) {
         if ($type === 'ActiveRecord') {
             $singleName = true;
         } else {
             $this->message = 'Command dosn\'t contains valid name. Example: Front/SomeForm, Admin/SomePkg/SomeInput';
             return false;
         }
     }
     $objectDirPath = null;
     $objectNamespace = null;
     $objectName = null;
     $objectTemplate = null;
     if ($singleName) {
         $objectDirPath = root . '/Apps/' . $type . '/';
         $objectNamespace = 'Apps\\' . $type;
         $objectName = ucfirst($name);
     } else {
         $split = explode('/', $name);
         $workground = ucfirst(strtolower(array_shift($split)));
         $objectName = ucfirst(array_pop($split));
         $subName = false;
         if (count($split) > 0) {
             // some sub-namespace / folder path
             foreach ($split as $part) {
                 if (Str::length($part) > 0) {
                     $subName[] = ucfirst(strtolower($part));
                 }
             }
         }
         if ($type === 'Widget') {
             $objectDirPath = root . '/Widgets/' . $workground;
             $objectNamespace = 'Widgets\\' . $workground;
         } else {
             $objectDirPath = root . '/Apps/' . $type . '/' . $workground;
             $objectNamespace = 'Apps\\' . $type . '\\' . $workground;
         }
         if (false !== $subName) {
             $objectDirPath .= '/' . implode('/', $subName);
             $objectNamespace .= '\\' . implode('\\', $subName);
         }
         // try to find workground-based controller
         if (File::exist('/Private/Carcase/' . $workground . '/' . $type . '.tphp')) {
             $objectTemplate = File::read('/Private/Carcase/' . $workground . '/' . $type . '.tphp');
         }
     }
     if (!Directory::exist($objectDirPath) && !Directory::create($objectDirPath)) {
         $this->message = 'Directory could not be created: ' . $objectDirPath;
         return false;
     }
     if ($objectTemplate === null) {
         $objectTemplate = File::read('/Private/Carcase/' . $type . '.tphp');
         if (false === $objectTemplate) {
             $this->message = 'Php template file is not founded: /Private/Carcase/' . $type . '.tphp';
             return false;
         }
     }
     $objectContent = Str::replace(['%namespace%', '%name%'], [$objectNamespace, $objectName], $objectTemplate);
     $objectFullPath = $objectDirPath . '/' . $objectName . '.php';
     if (File::exist($objectFullPath)) {
         $this->message = $type . ' is always exist: ' . $objectFullPath;
         return false;
     }
     File::write($objectFullPath, $objectContent);
     $this->message = $type . ' template was created: [' . $objectName . '] in path: ' . Str::replace(root, '', $objectDirPath);
     return true;
 }
Beispiel #29
0
 /**
  * Write configurations data from array to cfg file
  * @param string $configFile
  * @param array $data
  * @return bool
  */
 public function writeConfig($configFile, array $data)
 {
     $path = '/Private/Config/' . ucfirst(Str::lowerCase($configFile)) . '.php';
     if (!File::exist($path) || !File::writable($path)) {
         return false;
     }
     $saveData = '<?php return ' . Arr::exportVar($data) . ';';
     File::write($path, $saveData);
     return true;
 }
Beispiel #30
0
 /**
  * Save model properties as configurations
  * @return bool
  */
 public function makeSave()
 {
     $toSave = App::$Security->strip_php_tags($this->getAllProperties());
     $stringSave = '<?php return ' . Arr::exportVar($toSave, null, true) . ';';
     $cfgPath = '/Private/Config/Default.php';
     if (File::exist($cfgPath) && File::writable($cfgPath)) {
         File::write($cfgPath, $stringSave);
         return true;
     }
     return false;
 }