/** * Bootstrap the module * * @param Application $application * @return void */ public static function bootstrap(Application $application) { $path = BASE_PATH . APP_URI; if ($path == '') { $path = '/'; } $cookie = Cookie::getInstance(['path' => $path]); if (isset($cookie->phire)) { $phire = (array) $cookie->phire; if (!isset($phire['fields_media_library'])) { $phire['fields_media_library'] = $application->module('phire-fields')->config()['media_library']; } $cookie->set('phire', $phire); } $modules = $application->modules(); $roles = \Phire\Table\Roles::findAll(); foreach ($roles->rows() as $role) { if (isset($modules['phire-fields']) && isset($modules['phire-fields']->config()['models']) && isset($modules['phire-fields']->config()['models']['Phire\\Model\\User']) && isset($modules['phire-fields']->config()['models']['Phire\\Model\\Role'])) { $models = $modules['phire-fields']->config()['models']; $models['Phire\\Model\\User'][] = ['type_field' => 'role_id', 'type_value' => $role->id, 'type_name' => $role->name]; $models['Phire\\Model\\Role'][] = ['type_field' => 'id', 'type_value' => $role->id, 'type_name' => $role->name]; $application->module('phire-fields')->mergeConfig(['models' => $models]); } } foreach ($modules as $module => $config) { if ($module != 'phire-fields' && isset($config['models'])) { $application->module('phire-fields')->mergeConfig(['models' => $config['models']]); } } }
/** * Bootstrap the module * * @param Application $application * @return void */ public static function bootstrap(Application $application) { $resources = $application->config()['resources']; $params = $application->services()->getParams('nav.phire'); $config = $application->module('phire-media'); $models = isset($config['models']) ? $config['models'] : null; $libraries = Table\MediaLibraries::findAll(['order' => 'order ASC']); foreach ($libraries->rows() as $library) { if (null !== $models) { if (!isset($models['Phire\\Media\\Model\\Media'])) { $models['Phire\\Media\\Model\\Media'] = []; } $models['Phire\\Media\\Model\\Media'][] = ['type_field' => 'library_id', 'type_value' => $library->id, 'type_name' => $library->name]; } $resources['media-library-' . $library->id . '|media-library-' . str_replace(' ', '-', strtolower($library->name))] = ['index', 'add', 'edit', 'remove']; if (!isset($params['tree']['media']['children'])) { $params['tree']['media']['children'] = []; } $params['tree']['media']['children']['media-library-' . $library->id] = ['name' => $library->name, 'href' => '/media/' . $library->id, 'acl' => ['resource' => 'media-library-' . $library->id, 'permission' => 'index']]; } $application->mergeConfig(['resources' => $resources]); $application->services()->setParams('nav.phire', $params); if (null !== $models) { $application->module('phire-media')->mergeConfig(['models' => $models]); } }
/** * Bootstrap the module * * @param Application $application * @return void */ public static function bootstrap(Application $application) { $config = $application->module('phire-forms'); $models = isset($config['models']) ? $config['models'] : null; $forms = Table\Forms::findAll(); foreach ($forms->rows() as $form) { if (null !== $models) { if (!isset($models['Phire\\Forms\\Model\\Form'])) { $models['Phire\\Forms\\Model\\Form'] = []; } $models['Phire\\Forms\\Model\\Form'][] = ['type_field' => 'id', 'type_value' => $form->id, 'type_name' => $form->name]; } } if (null !== $models) { $application->module('phire-forms')->mergeConfig(['models' => $models]); } }
/** * Add CAPTCHA image to form with a CAPTCHA field * * @param AbstractController $controller * @param Application $application * @return void */ public static function addCaptcha(AbstractController $controller, Application $application) { if ($controller->hasView() && null !== $controller->view()->form && $controller->view()->form !== false && $controller->view()->form instanceof \Pop\Form\Form && null !== $controller->view()->form->getElement('captcha')) { $captcha = new \Phire\Captcha\Model\Captcha($application->module('phire-captcha')['config']); $captcha->createToken(); $controller->view()->form->getElement('captcha')->setToken($captcha->token, 'Enter Code'); } }
/** * Parse calendar * * @param AbstractController $controller * @param Application $application * @return void */ public static function parse(AbstractController $controller, Application $application) { if (!$_POST && $controller->hasView() && $controller instanceof \Phire\Content\Controller\IndexController) { $body = $controller->response()->getBody(); // Parse any calendar placeholders $calendars = []; $calendarIds = []; preg_match_all('/\\[\\{calendar.*\\}\\]/', $body, $calendars); if (isset($calendars[0]) && isset($calendars[0][0])) { foreach ($calendars[0] as $calendar) { $id = substr($calendar, strpos($calendar, '[{calendar_') + 11); if (strpos($id, '_') !== false) { $id = substr($id, 0, strpos($id, '_')); $replace = '[{calendar_' . $id . '_time}]'; $time = true; } else { $id = substr($id, 0, strpos($id, '}]')); $replace = '[{calendar_' . $id . '}]'; $time = false; } $calendarIds[] = ['id' => $id, 'replace' => $replace, 'time' => $time]; } } if (count($calendarIds) > 0) { $sess = $application->services()->get('session'); $roleId = isset($sess->user) ? $sess->user->role_id : null; foreach ($calendarIds as $cal) { $calendar = new Model\Calendar(['user_role_id' => $roleId, 'weekdays' => $application->module('phire-calendar')['weekdays'], 'range' => $application->module('phire-calendar')['range'], 'range_format' => $application->module('phire-calendar')['range_format'], 'day_format' => $application->module('phire-calendar')['day_format'], 'force_list' => $application->module('phire-calendar')['force_list'], 'force_list_mobile' => $application->module('phire-calendar')['force_list_mobile'], 'show_all' => $application->module('phire-calendar')['show_all'], 'date' => $controller->request()->getQuery('date')]); $rendered = $calendar->getById($cal['id'], $cal['time']); $body = str_replace($cal['replace'], $rendered, $body); } $controller->response()->setBody($body); } } }
/** * Bootstrap the module * * @param Application $application * @return void */ public static function bootstrap(Application $application) { if ($application->isRegistered('phire-content')) { $theme = Table\Themes::findBy(['active' => 1]); if (isset($theme->id)) { $dir = new Dir($_SERVER['DOCUMENT_ROOT'] . BASE_PATH . CONTENT_PATH . '/themes/' . $theme->folder, ['filesOnly' => true]); $parentDir = null; if (null !== $theme->parent_id) { $parentTheme = Table\Themes::findById($theme->parent_id); if (isset($parentTheme->id)) { $parentDir = new Dir($_SERVER['DOCUMENT_ROOT'] . BASE_PATH . CONTENT_PATH . '/themes/' . $parentTheme->folder, ['filesOnly' => true]); } } $forms = $application->config()['forms']; if (null !== $parentDir) { $dirFiles = $dir->getFiles(); foreach ($dirFiles as $file) { if (strpos($file, '.ph') !== false && !in_array($file, $application->module('phire-themes')['invisible'])) { $forms['Phire\\Content\\Form\\Content'][0]['content_template']['value'][$file] = $file; } } foreach ($parentDir->getFiles() as $file) { if (!in_array($file, $dirFiles) && strpos($file, '.ph') !== false && !in_array($file, $application->module('phire-themes')['invisible'])) { $forms['Phire\\Content\\Form\\Content'][0]['content_template']['value'][$file] = $file . ' (parent)'; } } } else { foreach ($dir->getFiles() as $file) { if (strpos($file, '.ph') !== false && !in_array($file, $application->module('phire-themes')['invisible'])) { $forms['Phire\\Content\\Form\\Content'][0]['content_template']['value'][$file] = $file; } } } $application->mergeConfig(['forms' => $forms], true); } } }
/** * Prepare view * * @param string $template * @return void */ protected function prepareView($template) { // Check for any override templates $headerTemplate = file_exists(CONTENT_ABS_PATH . '/phire/view/phire/header.phtml') ? CONTENT_ABS_PATH . '/phire/view/phire/header.phtml' : __DIR__ . '/../../view/phire/header.phtml'; $footerTemplate = file_exists(CONTENT_ABS_PATH . '/phire/view/phire/footer.phtml') ? CONTENT_ABS_PATH . '/phire/view/phire/footer.phtml' : __DIR__ . '/../../view/phire/footer.phtml'; $viewTemplate = file_exists(CONTENT_ABS_PATH . '/phire/view/' . $template) ? CONTENT_ABS_PATH . '/phire/view/' . $template : $this->viewPath . '/' . $template; $this->view = new View($viewTemplate); $this->view->phire = new \ArrayObject([], \ArrayObject::ARRAY_AS_PROPS); $this->view->assets = $this->application->module('phire')->getAssets(); $this->view->systemTitle = $this->application->config()['system_title']; $this->view->phireHeader = $headerTemplate; $this->view->phireFooter = $footerTemplate; $this->view->phireUri = BASE_PATH . APP_URI; $this->view->basePath = BASE_PATH; $this->view->base_path = BASE_PATH; $this->view->contentPath = CONTENT_PATH; $this->view->content_path = CONTENT_PATH; if (isset($this->sess->installed)) { $this->view->installed = true; } if (isset($this->sess->saved)) { $this->view->saved = true; } if (isset($this->sess->removed)) { $this->view->removed = true; } if (isset($this->sess->user)) { $this->services['nav.phire']->setRole($this->services['acl']->getRole($this->sess->user->role)); $this->services['nav.phire']->returnFalse(true); $this->view->phireNav = $this->services['nav.phire']; $this->view->phirePath = BASE_PATH . APP_PATH; $this->view->docRoot = $_SERVER['DOCUMENT_ROOT']; $this->view->user = $this->sess->user; $this->view->acl = $this->services['acl']; $this->view->config = $this->config; $this->view->headers = $this->application->config()['headers']; $this->view->dashboard = $this->application->config()['dashboard']; $this->view->dashboardSide = $this->application->config()['dashboard_side']; $this->view->footers = $this->application->config()['footers']; } else { $this->view->phireNav = null; } }
/** * Check if the user session is allowed with the ACL service * * @param Application $application * @return void */ public static function check(Application $application) { $application->module('app')->initAcl(); $sess = $application->getService('session'); $acl = $application->getService('acl'); if (isset($sess->user) && isset($sess->user->role) && $acl->hasRole($sess->user->role)) { // Get routes with slash options $route = $application->router()->getRouteMatch()->getRoute(); $routes = $application->router()->getRouteMatch()->getRoutes(); if (isset($routes[$route]) && isset($routes[$route]['acl']) && isset($routes[$route]['acl']['resource'])) { $resource = $routes[$route]['acl']['resource']; $permission = isset($routes[$route]['acl']['permission']) ? $routes[$route]['acl']['permission'] : null; if (!$acl->isAllowed($sess->user->role, $resource, $permission)) { Response::redirect('/'); exit; } } } }
/** * Save content to cache * * @param Application $application * @return void */ public static function save(Application $application) { if ($application->router()->getController() instanceof \Phire\Content\Controller\IndexController && $application->router()->getController()->response()->getCode() == 200 && empty($_SERVER['QUERY_STRING']) && !$_POST) { $sess = $application->services()->get('session'); $uri = $application->router()->getController()->request()->getRequestUri(); $cache = (new Model\Cache())->getCacheAdapter(); $exclude = $application->module('phire-cache')['exclude']; if (null !== $cache && !isset($sess->user) && !in_array($uri, $exclude)) { $contentType = $application->router()->getController()->response()->getHeader('Content-Type'); $body = $application->router()->getController()->response()->getBody(); if ($contentType == 'text/html') { $body .= PHP_EOL . PHP_EOL . '<!-- Generated by the phire-cache module on ' . date('M j, Y H:i:s') . '. //-->' . PHP_EOL . PHP_EOL; } else { if (stripos($contentType, 'xml') !== false) { $body .= PHP_EOL . PHP_EOL . '<!-- Generated by the phire-cache module on ' . date('M j, Y H:i:s') . '. -->' . PHP_EOL . PHP_EOL; } } $cache->save($uri, ['content-type' => $contentType, 'body' => $body]); } } }
/** * Delete dynamic field files * * @param int $fieldId * @param int $modelId * @param string $model * @param boolean $encrypt * @param Application $app * @param string $uploadFolder * @param string $mediaLibrary * @return void */ protected static function saveFiles($fieldId, $modelId, $model, $encrypt, $app, $uploadFolder, $mediaLibrary = null) { $field = T\Fields::findById($fieldId); if (isset($field->id)) { $time = time(); $newValues = []; $oldValues = new Record(); $oldValues->setPrefix(DB_PREFIX)->setPrimaryKeys(['id'])->setTable('field_' . $field->name); $oldValues->findRecordsBy(['model_id' => $modelId, 'model' => $model], ['order' => 'id ASC']); $old = $oldValues->rows(false); foreach ($_FILES as $key => $file) { $id = substr_count($key, '_') == 2 ? substr($key, strrpos($key, '_') + 1) : 0; if (!empty($_FILES[$key]['tmp_name']) && !empty($_FILES[$key]['name'])) { if (null !== $mediaLibrary) { $library = new \Phire\Media\Model\MediaLibrary(); $library->getByFolder($mediaLibrary); if (isset($library->id)) { $settings = $library->getSettings(); $mediaUpload = new Upload($_SERVER['DOCUMENT_ROOT'] . BASE_PATH . CONTENT_PATH . '/' . $library->folder, $settings['max_filesize'], $settings['disallowed_types'], $settings['allowed_types']); if ($mediaUpload->test($_FILES[$key])) { $media = new \Phire\Media\Model\Media(); $media->save($_FILES[$key], ['library_id' => $library->id]); $value = $media->file; if ($encrypt) { $value = (new Mcrypt())->create($value); } if (isset($old[$id])) { $replaceValue = new Record(); $replaceValue->setPrefix(DB_PREFIX)->setPrimaryKeys(['id'])->setTable('field_' . $field->name); $replaceValue->findRecordById($old[$id]['id']); if (isset($replaceValue->id)) { $replaceValue->value = $value; $replaceValue->save(); if (file_exists($_SERVER['DOCUMENT_ROOT'] . $uploadFolder . '/' . $old[$id]['value'])) { unlink($_SERVER['DOCUMENT_ROOT'] . $uploadFolder . '/' . $old[$id]['value']); } if (file_exists($_SERVER['DOCUMENT_ROOT'] . BASE_PATH . CONTENT_PATH . '/' . $library->folder . '/' . $old[$id]['value'])) { $media = new \Phire\Media\Model\Media(); $media->getByFile($old[$id]['value']); if (isset($media->id)) { $media->remove(['rm_media' => [$media->id]]); } } } } else { $newValues[] = $value; } copy($_SERVER['DOCUMENT_ROOT'] . BASE_PATH . CONTENT_PATH . '/' . $library->folder . '/' . $media->file, $_SERVER['DOCUMENT_ROOT'] . $uploadFolder . '/' . $media->file); } } } else { $upload = new Upload($_SERVER['DOCUMENT_ROOT'] . $uploadFolder . '/', $app->module('phire-fields')->config()['max_size'], $app->module('phire-fields')->config()['disallowed_types'], $app->module('phire-fields')->config()['allowed_types']); $value = $upload->upload($_FILES[$key]); if ($encrypt) { $value = (new Mcrypt())->create($value); } if (isset($old[$id])) { $replaceValue = new Record(); $replaceValue->setPrefix(DB_PREFIX)->setPrimaryKeys(['id'])->setTable('field_' . $field->name); $replaceValue->findRecordById($old[$id]['id']); if (isset($replaceValue->id)) { $replaceValue->value = $value; $replaceValue->save(); if (file_exists($_SERVER['DOCUMENT_ROOT'] . $uploadFolder . '/' . $old[$id]['value'])) { unlink($_SERVER['DOCUMENT_ROOT'] . $uploadFolder . '/' . $old[$id]['value']); } } } else { $newValues[] = $value; } } } } foreach ($newValues as $v) { if (!empty($v)) { $fv = new Record(['model_id' => $modelId, 'model' => $model, 'timestamp' => $time, 'revision' => 0, 'value' => $v]); $fv->setPrefix(DB_PREFIX)->setPrimaryKeys(['id'])->setTable('field_' . $field->name); $fv->save(); $fvs = new Record(); $fvs->setPrefix(DB_PREFIX)->setPrimaryKeys(['id'])->setTable('field_' . $field->name); $sql = $fvs->getSql(); $sql->update(['timestamp' => ':timestamp'])->where('model_id = :model_id')->where('model = :model'); $fvs->execute($sql, ['timestamp' => $time, 'model_id' => $modelId, 'model' => $model]); } } } }
/** * Get all category values for the form object * * @param AbstractController $controller * @param Application $application * @return void */ public static function parseCategories(AbstractController $controller, Application $application) { if ($controller->hasView() && ($controller instanceof \Phire\Categories\Controller\IndexController || $controller instanceof \Phire\Content\Controller\IndexController)) { $body = $controller->response()->getBody(); $category = new Model\Category(); $category->show_total = $application->module('phire-categories')['show_total']; $category->filters = $application->module('phire-categories')['filters']; $category->datetime_formats = $application->module('phire-categories')['datetime_formats']; $catIds = self::parseCategoryIds($body); $catParentIds = self::parseParentCategoryIds($body); if (count($catIds) > 0) { foreach ($catIds as $key => $value) { $category->getById($value['id']); $categoryName = 'category_' . $value['id']; if (isset($value['limit']) && $value['limit'] > 0 && $category->hasPages($value['limit'])) { $limit = $value['limit']; $pages = null; } else { if ($category->pagination > 0 && $category->hasPages($category->pagination)) { $limit = $category->pagination; $pages = new \Pop\Paginator\Paginator($category->getCount(), $limit); $pages->useInput(true); } else { $limit = null; $pages = null; } } if (null !== $pages) { $controller->view()->pages = $pages; } $controller->view()->{$categoryName} = $category->getItems($limit, $controller->request()->getQuery('page')); } } if (count($catParentIds) > 0) { foreach ($catParentIds as $key => $value) { if (isset($value['limit']) && $value['limit'] > 0) { $limit = $value['limit']; $categoryName = 'categories_' . $value['id'] . '_' . $limit; } else { $limit = null; $categoryName = 'categories_' . $value['id']; } $controller->view()->{$categoryName} = $category->getCategoryChildren($value['id'], $limit); } } $controller->view()->setTemplate($body); $body = $controller->view()->render(); $controller->response()->setBody($body); } }
/** * Save dynamic field values to the EAV table * * @param Application $application * @param Table\Fields $field * @param mixed $value * @param string $model * @param int $modelId * @param string $uploadFolder * @param string $mediaLibrary * @return void */ public static function save(Application $application, $field, $value, $model, $modelId, $uploadFolder = null, $mediaLibrary = null) { $dynamicFieldIds = []; $fieldId = $field->id; $key = 'field_' . $fieldId; if ($field->dynamic) { $dynamicFieldIds[] = $field->id; } $fv = Table\FieldValues::findById([$fieldId, $modelId, $model]); if ($field->type == 'file' && isset($_FILES[$key]) && !empty($_FILES[$key]['tmp_name']) && !empty($_FILES[$key]['name'])) { if (isset($fv->field_id)) { $oldFile = json_decode($fv->value); if (file_exists($_SERVER['DOCUMENT_ROOT'] . $uploadFolder . '/' . $oldFile)) { unlink($_SERVER['DOCUMENT_ROOT'] . $uploadFolder . '/' . $oldFile); } } if (null !== $mediaLibrary && $application->isRegistered('phire-media')) { $library = new \Phire\Media\Model\MediaLibrary(); $library->getByFolder($mediaLibrary); if (isset($library->id)) { $settings = $library->getSettings(); $mediaUpload = new Upload($_SERVER['DOCUMENT_ROOT'] . BASE_PATH . CONTENT_PATH . '/' . $library->folder, $settings['max_filesize'], $settings['disallowed_types'], $settings['allowed_types']); if ($mediaUpload->test($_FILES[$key])) { $media = new \Phire\Media\Model\Media(); $media->save($_FILES[$key], ['library_id' => $library->id]); $value = $media->file; copy($_SERVER['DOCUMENT_ROOT'] . BASE_PATH . CONTENT_PATH . '/' . $library->folder . '/' . $media->file, $_SERVER['DOCUMENT_ROOT'] . $uploadFolder . '/' . $media->file); } } } else { $upload = new Upload($_SERVER['DOCUMENT_ROOT'] . $uploadFolder . '/', $application->module('phire-fields')->config()['max_size'], $application->module('phire-fields')->config()['disallowed_types'], $application->module('phire-fields')->config()['allowed_types']); $value = $upload->upload($_FILES[$key]); } } if (!empty($value) && $value != ' ') { if ($field->encrypt && !is_array($value)) { $value = (new Mcrypt())->create($value); } } if (isset($fv->field_id)) { $oldValue = json_decode($fv->value, true); if (!empty($value) && $value != ' ') { if (strpos($field->type, '-history') !== false) { if ($value != $oldValue) { $ts = null !== $fv->timestamp ? $fv->timestamp : time() - 180; if (null !== $fv->history) { $history = json_decode($fv->history, true); $history[$ts] = $oldValue; if (count($history) > $application->module('phire-fields')->config()['history']) { $history = array_slice($history, 1, $application->module('phire-fields')->config()['history'], true); } $fv->history = json_encode($history); } else { $fv->history = json_encode([$ts => $oldValue]); } } } if ($field->dynamic && is_array($oldValue) && isset($oldValue[0])) { $oldValue[0] = $value; $newValue = json_encode($oldValue); } else { $newValue = json_encode($value); } $fv->value = $newValue; $fv->timestamp = time(); $fv->save(); } else { if (!$field->dynamic && $field->type != 'file') { $fv->delete(); } else { if ($field->dynamic && $field->type != 'file' && is_array($oldValue) && isset($oldValue[0])) { $oldValue[0] = ''; $newValue = json_encode($oldValue); $fv->value = $newValue; $fv->timestamp = time(); $fv->save(); } } } } else { if (!empty($value) && $value != ' ') { $fv = new Table\FieldValues(['field_id' => $fieldId, 'model_id' => $modelId, 'model' => $model, 'value' => $field->dynamic ? json_encode([$value]) : json_encode($value), 'timestamp' => time()]); $fv->save(); } } foreach ($dynamicFieldIds as $fieldId) { $i = 1; $offset = 0; $fv = Table\FieldValues::findById([$fieldId, $modelId, $model]); $checkValue = json_decode($fv->value, true); if (is_array($checkValue) && isset($checkValue[0]) && is_array($checkValue[0])) { foreach ($checkValue as $k => $v) { $fieldToCheck = $k > 0 ? 'field_' . $fieldId . '_' . $k : 'field_' . $fieldId; if (!isset($_POST[$fieldToCheck])) { unset($checkValue[$k]); } } $checkValue = array_values($checkValue); $fv->value = json_encode($checkValue); $fv->timestamp = time(); $fv->save(); } while (isset($_POST['field_' . $fieldId . '_' . $i])) { if (!empty($_POST['field_' . $fieldId . '_' . $i]) && $_POST['field_' . $fieldId . '_' . $i] != ' ') { $postValue = $_POST['field_' . $fieldId . '_' . $i]; if (isset($fv->field_id)) { $value = json_decode($fv->value, true); if (isset($value[$i - $offset])) { $value[$i - $offset] = $postValue; } else { $value[] = $postValue; } $fv->value = json_encode($value); $fv->timestamp = time(); $fv->save(); } else { $fv = new Table\FieldValues(['field_id' => $fieldId, 'model_id' => $modelId, 'model' => $model, 'value' => json_encode([$postValue]), 'timestamp' => time()]); $fv->save(); } } else { if (isset($fv->field_id)) { $value = json_decode($fv->value, true); if (isset($value[$i])) { unset($value[$i]); $value = array_values($value); $offset++; } $fv->value = json_encode($value); $fv->timestamp = time(); $fv->save(); } } $i++; } } foreach ($dynamicFieldIds as $fieldId) { $i = 1; $offset = 0; $fv = Table\FieldValues::findById([$fieldId, $modelId, $model]); while (isset($_FILES['field_' . $fieldId . '_' . $i])) { if (!empty($_FILES['field_' . $fieldId . '_' . $i]['tmp_name'])) { if (null !== $mediaLibrary && $application->isRegistered('phire-media')) { $library = new \Phire\Media\Model\MediaLibrary(); $library->getByFolder($mediaLibrary); if (isset($library->id)) { $settings = $library->getSettings(); $mediaUpload = new Upload($_SERVER['DOCUMENT_ROOT'] . BASE_PATH . CONTENT_PATH . '/' . $library->folder, $settings['max_filesize'], $settings['disallowed_types'], $settings['allowed_types']); if ($mediaUpload->test($_FILES['field_' . $fieldId . '_' . $i])) { $media = new \Phire\Media\Model\Media(); $media->save($_FILES['field_' . $fieldId . '_' . $i], ['library_id' => $library->id]); $postValue = $media->file; copy($_SERVER['DOCUMENT_ROOT'] . BASE_PATH . CONTENT_PATH . '/' . $library->folder . '/' . $media->file, $_SERVER['DOCUMENT_ROOT'] . $uploadFolder . '/' . $media->file); } } } else { $upload = new Upload($_SERVER['DOCUMENT_ROOT'] . $uploadFolder . '/', $application->module('phire-fields')->config()['max_size'], $application->module('phire-fields')->config()['allowed_types']); $postValue = $upload->upload($_FILES['field_' . $fieldId . '_' . $i]); } if (isset($fv->field_id)) { $value = json_decode($fv->value, true); if (isset($value[$i - $offset])) { $value[$i - $offset] = $postValue; } else { $value[] = $postValue; } $fv->value = json_encode($value); $fv->timestamp = time(); $fv->save(); } else { $fv = new Table\FieldValues(['field_id' => $fieldId, 'model_id' => $modelId, 'model' => $model, 'value' => json_encode([$postValue]), 'timestamp' => time()]); $fv->save(); } } $i++; } } foreach ($dynamicFieldIds as $fieldId) { $fv = Table\FieldValues::findById([$fieldId, $modelId, $model]); if (isset($fv->field_id)) { $value = json_decode($fv->value, true); if (is_array($value) && isset($value[0]) && is_array($value[0])) { foreach ($value as $key => $val) { if (is_array($val) && isset($val[0]) && (empty($val[0]) || $val[0] == ' ')) { unset($val[0]); $value[$key] = array_values($val); if (count($value[$key]) == 0) { unset($value[$key]); } } } $value = array_values($value); } else { if (is_array($value) && isset($value[0]) && (empty($value[0]) || $value[0] == ' ')) { unset($value[0]); $value = array_values($value); } } if (count($value) == 0) { $fv->delete(); } else { $fv->value = json_encode($value); $fv->save(); } } } }
/** * Init data values * * @param AbstractController $controller * @param Application $application * @return void */ public static function initDateValues(AbstractController $controller, Application $application) { if ($controller instanceof \Phire\Content\Controller\IndexController && $controller->hasView()) { $publish = $controller->view()->publish; $expire = $controller->view()->expire; $pubDate = substr($publish, 0, strpos($publish, ' ')); $pubTime = substr($publish, strpos($publish, ' ') + 1); $expDate = substr($expire, 0, strpos($expire, ' ')); $expTime = substr($expire, strpos($expire, ' ') + 1); $pubMonth = date($application->module('phire-content')['month_format'], strtotime($pubDate)); $pubDay = date($application->module('phire-content')['day_format'], strtotime($pubDate)); $pubYear = date($application->module('phire-content')['year_format'], strtotime($pubDate)); $pubHour = date($application->module('phire-content')['hour_format'], strtotime($pubTime)); $pubMin = date($application->module('phire-content')['minute_format'], strtotime($pubTime)); $pubPeriod = date($application->module('phire-content')['period_format'], strtotime($pubTime)); $expMonth = date($application->module('phire-content')['month_format'], strtotime($expDate)); $expDay = date($application->module('phire-content')['day_format'], strtotime($expDate)); $expYear = date($application->module('phire-content')['year_format'], strtotime($expDate)); $expHour = date($application->module('phire-content')['hour_format'], strtotime($expTime)); $expMin = date($application->module('phire-content')['minute_format'], strtotime($expTime)); $expPeriod = date($application->module('phire-content')['period_format'], strtotime($expTime)); $pubDate = date($application->module('phire-content')['date_format'], strtotime($pubDate)); $pubTime = date($application->module('phire-content')['time_format'], strtotime($pubTime)); $expDate = date($application->module('phire-content')['date_format'], strtotime($expDate)); $expTime = date($application->module('phire-content')['time_format'], strtotime($expTime)); $controller->view()->set('publish_date', $pubDate); $controller->view()->set('publish_time', $pubTime); $controller->view()->set('publish_month', $pubMonth); $controller->view()->set('publish_day', $pubDay); $controller->view()->set('publish_year', $pubYear); $controller->view()->set('publish_hour', $pubHour); $controller->view()->set('publish_minute', $pubMin); $controller->view()->set('publish_period', $pubPeriod); $controller->view()->set('expire_date', $expDate); $controller->view()->set('expire_time', $expTime); $controller->view()->set('expire_month', $expMonth); $controller->view()->set('expire_day', $expDay); $controller->view()->set('expire_year', $expYear); $controller->view()->set('expire_hour', $expHour); $controller->view()->set('expire_minute', $expMin); $controller->view()->set('expire_period', $expPeriod); } }
/** * Init tag model and tag cloud * * @param AbstractController $controller * @param Application $application * @return void */ public static function init(AbstractController $controller, Application $application) { if (!$_POST && $controller->hasView() && $controller instanceof \Phire\Content\Controller\IndexController) { $sql = Table\TagItems::sql(); $sql->select([0 => 'tag_id', 1 => 'id', 2 => 'title', 3 => 'slug', 'count' => 'COUNT(1)'])->join(DB_PREFIX . 'tags', [DB_PREFIX . 'tags.id' => DB_PREFIX . 'tag_items.tag_id']); $sql->select()->groupBy('tag_id')->orderBy('count', 'DESC'); $tags = Table\TagItems::query($sql); $cloud = null; $max = 0; if ($tags->hasRows()) { foreach ($tags->rows() as $i => $tag) { if ($i == 0) { $max = $tag->count; } $weight = round($tag->count / $max * 100); if ($weight < 10) { $weight = 1; } else { $weight = $weight - $weight % 10; } $cloud .= '<a class="tag-link tag-weight-' . $weight . '" href="' . BASE_PATH . '/tag/' . $tag->slug . '">' . $tag->title . '</a>' . PHP_EOL; } } $tag = new Model\Tag(); $tag->filters = $application->module('phire-tags')['filters']; $controller->view()->tag_cloud = $cloud; $controller->view()->phire->tag = $tag; } }
/** * Delete dynamic field values * * @param AbstractController $controller * @param Application $application * * @return void */ public static function delete(AbstractController $controller, Application $application) { if ($_POST) { $uploadFolder = BASE_PATH . CONTENT_PATH . '/files'; $mediaLibrary = $application->module('phire-fields')->config()['media_library']; foreach ($_POST as $key => $value) { if (substr($key, 0, 3) == 'rm_' && is_array($value)) { $fields = Table\Fields::findBy(); $fieldIds = []; $fieldTypes = []; $fieldStorage = []; foreach ($fields->rows() as $field) { $fieldIds[$field->id] = $field->name; $fieldTypes[$field->id] = $field->type; $fieldStorage[$field->id] = $field->storage; } foreach ($value as $id) { foreach ($fieldIds as $fieldId => $fieldName) { if ($fieldStorage[$fieldId] == 'eav') { $fv = Table\FieldValues::findBy(['model_id' => (int) $id]); if ($fv->hasRows()) { foreach ($fv->rows() as $f) { $fValue = json_decode($f->value, true); if (!is_array($fValue)) { $fValue = [$fValue]; } foreach ($fValue as $f) { if (file_exists($_SERVER['DOCUMENT_ROOT'] . $uploadFolder . '/' . $f)) { unlink($_SERVER['DOCUMENT_ROOT'] . $uploadFolder . '/' . $f); } if (null !== $mediaLibrary && $application->isRegistered('phire-media')) { $library = new \Phire\Media\Model\MediaLibrary(); $library->getByFolder($mediaLibrary); if (file_exists($_SERVER['DOCUMENT_ROOT'] . BASE_PATH . CONTENT_PATH . '/' . $library->folder . '/' . $f)) { $media = new \Phire\Media\Model\Media(); $media->getByFile($f); if (isset($media->id)) { $media->remove(['rm_media' => [$media->id]]); } } } } } } $fv = new Table\FieldValues(); $fv->delete(['model_id' => (int) $id]); } else { $fv = new Record(); $fv->setPrefix(DB_PREFIX)->setPrimaryKeys(['id'])->setTable('field_' . $fieldName); $fv->findRecordsBy(['model_id' => (int) $id]); if ($fieldTypes[$fieldId] == 'file' && $fv->hasRows()) { foreach ($fv->rows() as $f) { if (file_exists($_SERVER['DOCUMENT_ROOT'] . $uploadFolder . '/' . $f->value)) { unlink($_SERVER['DOCUMENT_ROOT'] . $uploadFolder . '/' . $f->value); } if (null !== $mediaLibrary && $application->isRegistered('phire-media')) { $library = new \Phire\Media\Model\MediaLibrary(); $library->getByFolder($mediaLibrary); if (file_exists($_SERVER['DOCUMENT_ROOT'] . BASE_PATH . CONTENT_PATH . '/' . $library->folder . '/' . $f->value)) { $media = new \Phire\Media\Model\Media(); $media->getByFile($f->value); if (isset($media->id)) { $media->remove(['rm_media' => [$media->id]]); } } } } } $fv->delete(['model_id' => (int) $id]); } } } } } } }
/** * Login and track session * * @param AbstractController $controller * @param Application $application * @return void */ public static function login(AbstractController $controller, Application $application) { $sess = $application->getService('session'); $userUri = APP_URI; $key = 'user'; if (isset($sess->member) && $application->isRegistered('phire-members')) { $key = 'member'; $memberAdmin = new \Phire\Members\Model\MembersAdmin(); $memberAdmin->getByRoleId($sess->member->role_id); if (isset($memberAdmin->uri)) { $userUri = $memberAdmin->uri; } } $path = BASE_PATH . $userUri; if ($path == '') { $path = '/'; } $cookie = Cookie::getInstance(['path' => $path]); $cookie->delete('phire_session_timeout'); $cookie->delete('phire_session_path'); // If login, validate and start new session if ($controller->request()->isPost() && substr($controller->request()->getRequestUri(), -6) == '/login') { // If the user successfully logged in if (isset($sess[$key])) { $config = Table\UserSessionConfig::findById($sess[$key]->role_id); $data = Table\UserSessionData::findById($sess[$key]->id); if (isset($config->role_id)) { if (!self::validate($config, $sess[$key], $data)) { if (isset($data->user_id)) { $data->failed_attempts++; $data->save(); } else { $data = new Table\UserSessionData(['user_id' => $sess[$key]->id, 'logins' => null, 'failed_attempts' => 1]); $data->save(); } if (isset($config->role_id) && (int) $config->log_type > 0 && null !== $config->log_emails) { self::log($config, $sess[$key], false); } $sess->kill(); Response::redirect(BASE_PATH . $userUri . '/login?failed=' . $data->failed_attempts); exit; } else { if (isset($data->user_id)) { $limit = (int) $application->module('phire-sessions')['login_limit']; $logins = unserialize($data->logins); if ($limit > 0 && count($logins) >= $limit) { reset($logins); unset($logins[key($logins)]); } $logins[time()] = ['ua' => $_SERVER['HTTP_USER_AGENT'], 'ip' => $_SERVER['REMOTE_ADDR']]; $data->total_logins++; $data->failed_attempts = 0; $data->logins = serialize($logins); $data->save(); } else { $data = new Table\UserSessionData(['user_id' => $sess[$key]->id, 'logins' => serialize([time() => ['ua' => $_SERVER['HTTP_USER_AGENT'], 'ip' => $_SERVER['REMOTE_ADDR']]]), 'total_logins' => 1, 'failed_attempts' => 0]); $data->save(); } } $expire = (int) $config->session_expiration > 0 ? (int) $config->session_expiration : null; $timeout = (int) $config->timeout_warning; } else { $expire = null; $timeout = false; } $lastLogin = null; $lastIp = null; // Check for the last login $data = Table\UserSessionData::findById($sess[$key]->id); if (isset($data->user_id)) { $logins = null !== $data->logins ? unserialize($data->logins) : []; if (count($logins) > 1) { $keys = array_keys($logins); $timestamp = isset($keys[count($keys) - 2]) ? $keys[count($keys) - 2] : null; if (null !== $timestamp && isset($logins[$timestamp])) { $lastLogin = $timestamp; $lastIp = $logins[$timestamp]['ip']; } } } // Clear old sessions $clear = (int) $application->module('phire-sessions')['clear_sessions']; if ($clear > 0) { $clear = time() - $clear; $sql = Table\UserSessions::sql(); $sql->delete()->where(['start <= :start']); Table\UserSessions::execute((string) $sql, ['start' => $clear]); } $session = new Table\UserSessions(['user_id' => $sess[$key]->id, 'ip' => $_SERVER['REMOTE_ADDR'], 'ua' => $_SERVER['HTTP_USER_AGENT'], 'start' => time()]); $session->save(); $sess[$key]->session = new \ArrayObject(['id' => $session->id, 'start' => $session->start, 'last' => $session->start, 'expire' => $expire, 'timeout' => $timeout, 'last_login' => $lastLogin, 'last_ip' => $lastIp], \ArrayObject::ARRAY_AS_PROPS); if (isset($config->role_id) && (int) $config->log_type > 0 && null !== $config->log_emails) { self::log($config, $sess[$key], true); } // Else, if the user login failed } else { if (null !== $controller->view()->form && $controller->view()->form !== false && null !== $controller->view()->form->username) { $user = \Phire\Table\Users::findBy(['username' => $controller->view()->form->username]); $config = Table\UserSessionConfig::findById($user->role_id); if (isset($user->id)) { $data = Table\UserSessionData::findById($user->id); if (isset($data->user_id)) { $data->failed_attempts++; $data->save(); } else { $data = new Table\UserSessionData(['user_id' => $user->id, 'logins' => null, 'failed_attempts' => 1]); $data->save(); } if (isset($config->role_id) && (int) $config->log_type > 0 && null !== $config->log_emails) { self::log($config, $user, false); } } } } // Check existing session } else { if (isset($sess[$key]) && isset($sess[$key]->session)) { if (!isset(Table\UserSessions::findById((int) $sess[$key]->session->id)->id) || null !== $sess[$key]->session->expire && time() - $sess[$key]->session->last >= $sess[$key]->session->expire) { $session = Table\UserSessions::findById((int) $sess[$key]->session->id); if (isset($session->id)) { $session->delete(); } $sess->kill(); Response::redirect(BASE_PATH . $userUri . '/login?expired=1'); exit; } else { if ($sess[$key]->session->timeout && null !== $sess[$key]->session->expire) { $cookie->set('phire_session_timeout', $sess[$key]->session->expire - 30); $cookie->set('phire_session_path', BASE_PATH . $userUri); } $sess[$key]->session->last = time(); } } } }