/** * Removes an item */ function delete() { // Check for request forgeries Session::checkToken() or exit(Lang::txt('JINVALID_TOKEN')); // Initialise variables. $ids = Request::getVar('cid', array(), '', 'array'); // Access checks. foreach ($ids as $i => $id) { if (!User::authorise('core.delete', 'com_content.article.' . (int) $id)) { // Prune items that you can't delete. unset($ids[$i]); Notify::warning(Lang::txt('JERROR_CORE_DELETE_NOT_PERMITTED')); } } if (empty($ids)) { Notify::error(Lang::txt('JERROR_NO_ITEMS_SELECTED')); } else { // Get the model. $model = $this->getModel(); // Remove the items. if (!$model->featured($ids, 0)) { throw new Exception($model->getError(), 500); } } $this->setRedirect('index.php?option=com_content&view=featured'); }
/** * Method to toggle the featured setting of a list of articles. * * @return void * @since 1.6 */ function featured() { // Check for request forgeries Session::checkToken() or exit(Lang::txt('JINVALID_TOKEN')); // Initialise variables. $ids = Request::getVar('cid', array(), '', 'array'); $values = array('featured' => 1, 'unfeatured' => 0); $task = $this->getTask(); $value = \Hubzero\Utility\Arr::getValue($values, $task, 0, 'int'); // Access checks. foreach ($ids as $i => $id) { if (!$user->authorise('core.edit.state', 'com_content.article.' . (int) $id)) { // Prune items that you can't change. unset($ids[$i]); Notify::warning(Lang::txt('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED')); } } if (empty($ids)) { Notify::error(Lang::txt('JERROR_NO_ITEMS_SELECTED')); } else { // Get the model. $model = $this->getModel(); // Publish the items. if (!$model->featured($ids, $value)) { throw new Exception($model->getError(), 500); } } $this->setRedirect('index.php?option=com_content&view=articles'); }
/** * Create a new member * * @return void */ public function addTask() { Request::setVar('hidemainmenu', 1); // Set any errors foreach ($this->getErrors() as $error) { \Notify::error($error); } // Output the HTML $this->view->setLayout('add')->display(); }
/** * Method to clone an existing module. * @since 1.6 */ public function duplicate() { // Check for request forgeries Session::checkToken() or exit(Lang::txt('JINVALID_TOKEN')); // Initialise variables. $pks = Request::getVar('cid', array(), 'post', 'array'); \Hubzero\Utility\Arr::toInteger($pks); try { if (empty($pks)) { throw new Exception(Lang::txt('COM_MODULES_ERROR_NO_MODULES_SELECTED')); } $model = $this->getModel(); $model->duplicate($pks); $this->setMessage(Lang::txts('COM_MODULES_N_MODULES_DUPLICATED', count($pks))); } catch (Exception $e) { Notify::error($e->getMessage()); } $this->setRedirect(Route::url('index.php?option=com_modules&view=modules', false)); }
/** * Removes an item */ public function delete() { // Check for request forgeries Session::checkToken() or exit(Lang::txt('JINVALID_TOKEN')); // Get items to remove from the request. $cid = Request::getVar('cid', array(), '', 'array'); if (!is_array($cid) || count($cid) < 1) { Notify::error(Lang::txt('COM_MENUS_NO_MENUS_SELECTED')); } else { // Get the model. $model = $this->getModel(); // Make sure the item ids are integers \Hubzero\Utility\Arr::toInteger($cid); // Remove the items. if (!$model->delete($cid)) { $this->setMessage($model->getError()); } else { $this->setMessage(Lang::txts('COM_MENUS_N_MENUS_DELETED', count($cid))); } } $this->setRedirect('index.php?option=com_menus&view=menus'); }
/** * Generate default template files for special groups * * @param object $group \Hubzero\User\Group * @return void */ private function _handleSuperGroup($group) { //get the upload path for groups $uploadPath = PATH_APP . DS . trim($this->config->get('uploadpath', '/site/groups'), DS) . DS . $group->get('gidNumber'); // get the source path $srcTplPath = null; $db = \App::get('db'); $query = $db->getQuery(true); $query->select('s.id, s.home, s.template, s.params, e.protected'); $query->from('#__template_styles as s'); $query->where('s.client_id = 0'); $query->where('e.enabled = 1'); $query->where('s.home = 1'); $query->leftJoin('#__extensions as e ON e.element=s.template AND e.type=' . $db->quote('template') . ' AND e.client_id=s.client_id'); $db->setQuery($query); $template = $db->loadObject(); if ($template) { foreach (array(PATH_APP, PATH_CORE) as $path) { if (is_dir($path . DS . 'templates' . DS . $template->template . DS . 'super')) { $srcTplPath = $path . DS . 'templates' . DS . $template->template . DS . 'super'; break; } } } $srcPath = dirname(dirname(__DIR__)) . DS . 'super' . DS . 'default' . DS . '.'; // create group folder if one doesnt exist if (!is_dir($uploadPath)) { if (!Filesystem::makeDirectory($uploadPath)) { Notify::error(Lang::txt('COM_GROUPS_SUPER_UNABLE_TO_CREATE')); } } // make sure folder is writable if (!is_writable($uploadPath)) { Notify::error(Lang::txt('COM_GROUPS_SUPER_FOLDER_NOT_WRITABLE', $uploadpath)); return; } // We need to handle templates a little differently if ($srcTplPath) { $uploadTplPath = $uploadPath . DS . 'template'; shell_exec("cp -rf {$srcTplPath} {$uploadTplPath} 2>&1"); } // copy over default template recursively // must have /. at the end of source path to get all items in that directory // also doesnt overwrite already existing files/folders shell_exec("cp -rn {$srcPath} {$uploadPath} 2>&1"); // make sure files are group read and writable // make sure files are all group owned properly shell_exec("chmod -R 2770 {$uploadPath} 2>&1"); shell_exec("chgrp -R " . escapeshellcmd($this->config->get('super_group_file_owner', 'access-content')) . " " . $uploadPath . " 2>&1"); // get all current users granted permissionss $this->database->setQuery("SHOW GRANTS FOR CURRENT_USER();"); $grants = $this->database->loadColumn(); // look at all current users granted permissions $canCreateSuperGroupDB = false; if (count($grants) > 0) { foreach ($grants as $grant) { if (preg_match('/sg\\\\_%/', $grant)) { $canCreateSuperGroupDB = true; } } //end foreach } //end if // create super group DB if doesnt already exist if ($canCreateSuperGroupDB) { $this->database->setQuery("CREATE DATABASE IF NOT EXISTS `sg_{$group->get('cn')}`;"); if (!$this->database->query()) { Notify::error(Lang::txt('COM_GROUPS_SUPER_UNABLE_TO_CREATE_DB')); } } else { Notify::error(Lang::txt('COM_GROUPS_SUPER_UNABLE_TO_CREATE_DB')); } // check to see if we have a super group db config $supergroupDbConfigFile = DS . 'etc' . DS . 'supergroup.conf'; if (!file_exists($supergroupDbConfigFile)) { Notify::error(Lang::txt('COM_GROUPS_SUPER_UNABLE_TO_LOAD_CONFIG')); } else { // get hub super group database config file $supergroupDbConfig = (include $supergroupDbConfigFile); // define username, password, and database to be written in config $username = isset($supergroupDbConfig['username']) ? $supergroupDbConfig['username'] : ''; $password = isset($supergroupDbConfig['password']) ? $supergroupDbConfig['password'] : ''; $database = 'sg_' . $group->get('cn'); //write db config in super group $dbConfigFile = $uploadPath . DS . 'config' . DS . 'db.php'; $dbConfigContents = "<?php\n\treturn array(\n\t\t'host' => 'localhost',\n\t\t'port' => '',\n\t\t'user' => '{$username}',\n\t\t'password' => '{$password}',\n\t\t'database' => '{$database}',\n\t\t'prefix' => ''\n\t);"; // write db config file if (!file_exists($dbConfigFile)) { if (!file_put_contents($dbConfigFile, $dbConfigContents)) { Notify::error(Lang::txt('COM_GROUPS_SUPER_UNABLE_TO_WRITE_CONFIG')); } } } // log super group change Log::log(array('gidNumber' => $group->get('gidNumber'), 'action' => 'super_group_created', 'comments' => '')); }
/** * Edit a category * * @return void */ public function editTask($row = null) { Request::setVar('hidemainmenu', 1); $this->view->wishlist = Request::getInt('wishlist', 0); if (!is_object($row)) { // Incoming $id = Request::getVar('id', array(0)); if (is_array($id) && !empty($id)) { $id = $id[0]; } // Load category $row = new Wish($this->database); $row->load($id); } $this->view->row = $row; if (!$this->view->row->id) { $this->view->row->wishlist = $this->view->wishlist; } else { if (!$this->view->wishlist) { $this->view->wishlist = $this->view->row->wishlist; } } /* $m = new Models\AdminWish(); $this->view->form = $m->getForm(); */ $obj = new Wishlist($this->database); $filters = array(); $filters['sort'] = 'title'; $filters['sort_Dir'] = 'ASC'; $this->view->lists = $obj->getRecords($filters); // who are list owners? $this->admingroup = $this->config->get('group', 'hubadmin'); $objOwner = new Owner($this->database); $objG = new OwnerGroup($this->database); $this->view->ownerassignees = array(); $this->view->ownerassignees[-1] = array(); $none = new stdClass(); $none->id = '-1'; $none->name = Lang::txt('COM_WISHLIST_SELECT'); $this->view->ownerassignees[-1][] = $none; $this->view->assignees = null; if ($this->view->lists) { foreach ($this->view->lists as $k => $list) { if ($list->category == 'resource') { include_once PATH_CORE . DS . 'components' . DS . 'com_resources' . DS . 'tables' . DS . 'resource.php'; $list->resource = new \Components\Resources\Tables\Resource($this->database); $list->resource->load($list->referenceid); } $this->view->ownerassignees[$list->id] = array(); $none = new stdClass(); $none->id = '0'; $none->name = Lang::txt('COM_WISHLIST_NONE'); $this->view->ownerassignees[$list->id][] = $none; $owners = $objOwner->get_owners($list->id, $this->admingroup, $list); if (count($owners['individuals']) > 0) { $query = "SELECT a.id, a.name FROM `#__users` AS a WHERE a.block = '0' AND a.id IN (" . implode(',', $owners['individuals']) . ") ORDER BY a.name"; $this->database->setQuery($query); $users = $this->database->loadObjectList(); foreach ($users as $row2) { $this->view->ownerassignees[$list->id][] = $row2; } if ($list->id == $this->view->row->wishlist) { $this->view->assignees = $this->view->ownerassignees[$list->id]; } } } } // Get the plan for this wish $objPlan = new Plan($this->database); $plan = $objPlan->getPlan($this->view->row->id); $this->view->plan = $plan ? $plan[0] : $objPlan; // Get tags on this wish include_once dirname(dirname(__DIR__)) . DS . 'models' . DS . 'tags.php'; $tagging = new Tags($this->view->row->id); $this->view->tags = $tagging->render('string'); // Set any errors foreach ($this->getErrors() as $error) { \Notify::error($error); } // Output the HTML $this->view->setLayout('edit')->display(); }
/** * Remove one or more entries * * @return void */ public function removeTask() { // Check for request forgeries Request::checkToken(); $ids = Request::getVar('id', array()); $ids = !is_array($ids) ? array($ids) : $ids; // Make sure we have an ID if (empty($ids)) { Notify::warning(Lang::txt('COM_GROUPS_ERROR_NO_ITEMS_SELECTED')); return $this->cancelTask(); } $i = 0; foreach ($ids as $id) { // Remove the entry $model = Role::oneOrFail(intval($id)); if (!$model->destroy()) { Notify::error($model->getError()); continue; } $i++; } if ($i) { Notify::success(Lang::txt('COM_GROUPS_ROLE_REMOVED')); } $this->cancelTask(); }
/** * Edit a course page * * @return void */ public function editTask($model = null) { Request::setVar('hidemainmenu', 1); if (!is_object($model)) { // Incoming $id = Request::getVar('id', array(0)); // Get the single ID we're working with if (is_array($id)) { $id = !empty($id) ? $id[0] : 0; } $model = new \Components\Courses\Models\Page($id); } $this->view->row = $model; if (!$this->view->row->get('course_id')) { $this->view->row->set('course_id', Request::getInt('course', 0)); } if (!$this->view->row->get('offering_id')) { $this->view->row->set('offering_id', Request::getInt('offering', 0)); } if (!$this->view->row->exists()) { $this->view->row->set('active', 1); } $this->view->course = \Components\Courses\Models\Course::getInstance($this->view->row->get('course_id')); $this->view->offering = \Components\Courses\Models\Offering::getInstance($this->view->row->get('offering_id')); // Set any errors foreach ($this->getErrors() as $error) { \Notify::error($error); } // Output the HTML $this->view->setLayout('edit')->display(); }
/** * Mark an entry as deleted * * @return void */ public function deleteTask() { if (User::isGuest()) { $rtrn = Request::getVar('REQUEST_URI', Route::url('index.php?option=' . $this->_option, false, true), 'server'); App::redirect(Route::url('index.php?option=com_users&view=login&return=' . base64_encode($rtrn)), Lang::txt('COM_BLOG_LOGIN_NOTICE'), 'warning'); return; } if (!$this->config->get('access-delete-entry') && !$this->config->get('access-manage-entry')) { App::abort(403, Lang::txt('COM_BLOG_NOT_AUTH')); } // Incoming $id = Request::getInt('entry', 0); if (!$id) { return $this->displayTask(); } $process = Request::getVar('process', ''); $confirmdel = Request::getVar('confirmdel', ''); // Initiate a blog entry object $entry = Entry::oneOrFail($id); // Did they confirm delete? if (!$process || !$confirmdel) { if ($process && !$confirmdel) { $this->setError(Lang::txt('COM_BLOG_ERROR_CONFIRM_DELETION')); } foreach ($this->getErrors() as $error) { $this->view->setError($error); } $this->view->set('archive', $this->model)->set('config', $this->config)->set('entry', $entry)->display(); return; } // Check for request forgeries Request::checkToken(); // Delete the entry itself $entry->set('state', 2); if (!$entry->save()) { Notify::error($entry->getError()); } // Log the activity Event::trigger('system.logActivity', ['activity' => ['action' => 'deleted', 'scope' => 'blog.entry', 'scope_id' => $id, 'description' => Lang::txt('COM_BLOG_ACTIVITY_ENTRY_DELETED', '<a href="' . Route::url($entry->link()) . '">' . $entry->get('title') . '</a>'), 'details' => array('title' => $entry->get('title'), 'url' => Route::url($entry->link()))], 'recipients' => [$entry->get('created_by')]]); // Return the entries lsit App::redirect(Route::url('index.php?option=' . $this->_option)); }
Notify::error($errors); return Response::redirect('admin/categories/add'); } if (empty($input['slug'])) { $input['slug'] = $input['title']; } $input['slug'] = slug($input['slug']); $category = Category::create($input); Extend::process('category', $category->id); Notify::success(__('categories.created')); return Response::redirect('admin/categories'); }); /* Delete Category */ Route::get('admin/categories/delete/(:num)', function ($id) { $total = Category::count(); if ($total == 1) { Notify::error(__('categories.delete_error')); return Response::redirect('admin/categories/edit/' . $id); } // move posts $category = Category::where('id', '<>', $id)->fetch(); // delete selected Category::find($id)->delete(); // update posts Post::where('category', '=', $id)->update(array('category' => $category->id)); Notify::success(__('categories.deleted')); return Response::redirect('admin/categories'); }); });
/** * Method to save the configuration data. * * @param array An array containing all global config data. * @return bool True on success, false on failure. * @since 1.6 */ public function save($data) { // Save the rules if (isset($data['rules'])) { $rules = new JAccessRules($data['rules']); // Check that we aren't removing our Super User permission // Need to get groups from database, since they might have changed $myGroups = JAccess::getGroupsByUser(\User::get('id')); $myRules = $rules->getData(); $hasSuperAdmin = $myRules['core.admin']->allow($myGroups); if (!$hasSuperAdmin) { $this->setError(Lang::txt('COM_CONFIG_ERROR_REMOVING_SUPER_ADMIN')); return false; } $asset = JTable::getInstance('asset'); if ($asset->loadByName('root.1')) { $asset->rules = (string) $rules; if (!$asset->check() || !$asset->store()) { Notify::error('SOME_ERROR_CODE', $asset->getError()); } } else { $this->setError(Lang::txt('COM_CONFIG_ERROR_ROOT_ASSET_NOT_FOUND')); return false; } unset($data['rules']); } // Save the text filters if (isset($data['filters'])) { $registry = new Registry(array('filters' => $data['filters'])); $extension = JTable::getInstance('extension'); // Get extension_id $extension_id = $extension->find(array('name' => 'com_config')); if ($extension->load((int) $extension_id)) { $extension->params = (string) $registry; if (!$extension->check() || !$extension->store()) { Notify::error('SOME_ERROR_CODE', $extension->getError()); } } else { $this->setError(Lang::txt('COM_CONFIG_ERROR_CONFIG_EXTENSION_NOT_FOUND')); return false; } unset($data['filters']); } // Get the previous configuration. $config = new \Hubzero\Config\Repository('site'); $prev = $config->toArray(); /*$extras = array(); foreach ($prev as $key => $val) { $found = false; foreach ($data as $group => $values) { if (in_array($key, $values)) { $found = true; } } if (!$found) { $extras[$key] = $val; } } // Merge the new data in. We do this to preserve values that were not in the form. $data['app'] = array_merge($data['app'], $extras);*/ // Perform miscellaneous options based on configuration settings/changes. // Escape the offline message if present. if (isset($data['offline']['offline_message'])) { $data['offline']['offline_message'] = \Hubzero\Utility\String::ampReplace($data['offline']['offline_message']); } // Purge the database session table if we are changing to the database handler. if ($prev['session']['session_handler'] != 'database' && $data['session']['session_handler'] == 'database') { $table = JTable::getInstance('session'); $table->purge(-1); } if (empty($data['cache']['cache_handler'])) { $data['cache']['caching'] = 0; } // Clean the cache if disabled but previously enabled. if (!$data['cache']['caching'] && $prev['cache']['caching']) { \Cache::clean(); } foreach ($data as $group => $values) { foreach ($values as $key => $value) { if (!isset($prev[$group])) { $prev[$group] = array(); } $prev[$group][$key] = $value; } } // Create the new configuration object. //$config = new Registry($data); // Overwrite the old FTP credentials with the new ones. if (isset($data['ftp'])) { $temp = \Config::getRoot(); $temp->set('ftp.ftp_enable', $data['ftp']['ftp_enable']); $temp->set('ftp.ftp_host', $data['ftp']['ftp_host']); $temp->set('ftp.ftp_port', $data['ftp']['ftp_port']); $temp->set('ftp.ftp_user', $data['ftp']['ftp_user']); $temp->set('ftp.ftp_pass', $data['ftp']['ftp_pass']); $temp->set('ftp.ftp_root', $data['ftp']['ftp_root']); } // Clear cache of com_config component. $this->cleanCache('_system'); // Write the configuration file. return $this->writeConfigFile($prev); }
/** * Set the state of an entry * * @param integer $state State to set * @return void */ public function stateTask($state = 0) { $ids = Request::getVar('id', array()); $ids = !is_array($ids) ? array($ids) : $ids; //print_r($ids); die; // Check for an ID if (count($ids) < 1) { App::redirect(Route::url('index.php?option=' . $this->_option . '&controller=' . $this->_controller, false), $state == 1 ? Lang::txt('COM_STOREFRONT_SELECT_PUBLISH') : Lang::txt('COM_STOREFRONT_SELECT_UNPUBLISH'), 'error'); return; } // Update record(s) $obj = new Archive(); foreach ($ids as $ogId) { // Save category try { $obj->updateOptionGroup($ogId, array('state' => $state)); } catch (\Exception $e) { \Notify::error($e->getMessage()); return; } } // Set message switch ($state) { case '-1': $message = Lang::txt('COM_STOREFRONT_ARCHIVED', count($ids)); break; case '1': $message = Lang::txt('COM_STOREFRONT_PUBLISHED', count($ids)); break; case '0': $message = Lang::txt('COM_STOREFRONT_UNPUBLISHED', count($ids)); break; } // Redirect App::redirect(Route::url('index.php?option=' . $this->_option . '&controller=' . $this->_controller, false), $message); }
/** * Mark an entry as deleted * * @return void */ public function deleteTask() { if (User::isGuest()) { $rtrn = Request::getVar('REQUEST_URI', Route::url('index.php?option=' . $this->_option, false, true), 'server'); App::redirect(Route::url('index.php?option=com_users&view=login&return=' . base64_encode($rtrn)), Lang::txt('COM_BLOG_LOGIN_NOTICE'), 'warning'); return; } if (!$this->config->get('access-delete-entry')) { App::redirect(Route::url('index.php?option=' . $this->_option), Lang::txt('COM_BLOG_NOT_AUTHORIZED'), 'error'); return; } // Incoming $id = Request::getInt('entry', 0); if (!$id) { return $this->displayTask(); } $process = Request::getVar('process', ''); $confirmdel = Request::getVar('confirmdel', ''); // Initiate a blog entry object $entry = Entry::oneOrFail($id); // Did they confirm delete? if (!$process || !$confirmdel) { if ($process && !$confirmdel) { $this->setError(Lang::txt('COM_BLOG_ERROR_CONFIRM_DELETION')); } foreach ($this->getErrors() as $error) { $this->view->setError($error); } $this->view->set('archive', $this->model)->set('config', $this->config)->set('entry', $entry)->display(); return; } // Check for request forgeries Request::checkToken(); // Delete the entry itself $entry->set('state', 2); if (!$entry->save()) { Notify::error($entry->getError()); } // Return the topics list App::redirect(Route::url('index.php?option=' . $this->_option)); return; }
public function update_permissions() { //return Input::all(); // // create the validation rules ------------------------ $rules = array('group_name' => 'required', 'permissions' => 'required'); $messages = array('required' => 'The :attribute required.', 'permissions.required' => 'permissions.required'); // do the validation ---------------------------------- // validate against the inputs from our form $validator = Validator::make(Input::all(), $rules, $messages); // check if the validator failed ----------------------- if ($validator->fails()) { // get the error messages from the validator $messages = $validator->messages(); // redirect our user back to the form with the errors from the validator return Redirect::to('settings/user-management/user-groups')->withErrors($validator)->withInput(); } else { // validation successful --------------------------- $permissionArray = array(); // Creating permission array foreach (Input::get('permissions') as $permission) { $permissionArray[$permission] = 1; } $is_group_exists = DB::table('groups')->where('name', '=', urldecode(Input::get('group_name')))->get(); if ($is_group_exists) { $sucsess = DB::table('groups')->where('name', '=', urldecode(Input::get('group_name')))->update(array('permissions' => json_encode($permissionArray))); if ($sucsess == 1) { Notify::success('Permissions Successfully Updated'); return Redirect::to('settings/user-management/user-groups'); } } else { try { // Create the group $group = Sentry::createGroup(array('name' => Input::get('group_name'), 'permissions' => $permissionArray)); } catch (Cartalyst\Sentry\Groups\NameRequiredException $e) { echo 'Name field is required'; } catch (Cartalyst\Sentry\Groups\GroupExistsException $e) { //echo 'Group already exists'; Notify::error('Group already exists'); return Redirect::to('settings/user-management/user-groups')->withErrors('Group already exists'); } } // redirect ---------------------------------------- return Redirect::to('settings/user-management/user-groups'); } }
/** * Load the editor * * @param array $config Associative array of editor config paramaters * @return mixed */ protected function load($config = array()) { // Check whether editor is already loaded if (!is_null($this->editor)) { return; } // Build the path to the needed editor plugin $name = (string) preg_replace('/[^A-Z0-9_\\.-]/i', '', $this->name); $name = ltrim($name, '.'); $path = PATH_CORE . '/plugins/editors/' . $name . '/' . $name . '.php'; if (!is_file($path)) { \Notify::error(Lang::txt('JLIB_HTML_EDITOR_CANNOT_LOAD')); return false; } // Require plugin file require_once $path; // Get the plugin $plugin = Plugin::byType('editors', $this->name); $params = new Registry($plugin->params); $params->merge($config); $plugin->params = $params; // Build editor plugin classname $name = 'plgEditor' . $this->name; if ($this->editor = new $name($this, (array) $plugin)) { // Load plugin parameters $this->initialise(); Plugin::import('editors-xtd'); } }
$info_path[] = $_path; File::open($_path)->delete(); } $P = array('data' => array('files' => $info_path)); Notify::success(Config::speak('notify_' . $is_folder_or_file . '_deleted', '<code>' . implode('</code>, <code>', $deletes) . '</code>')); Weapon::fire('on_asset_update', array($P, $P)); Weapon::fire('on_asset_destruct', array($P, $P)); Guardian::kick($config->manager->slug . '/asset/1' . $p); } else { Notify::warning(count($deletes) === 1 ? Config::speak('notify_confirm_delete_', '<code>' . File::path($name) . '</code>') : $speak->notify_confirm_delete); } Shield::lot('segment', 'asset')->attach('manager', false); }); /** * Multiple Asset Killer * --------------------- */ Route::accept($config->manager->slug . '/asset/kill', function ($path = "") use($config, $speak) { if ($request = Request::post()) { Guardian::checkToken($request['token']); if (!isset($request['selected'])) { Notify::error($speak->notify_error_no_files_selected); Guardian::kick($config->manager->slug . '/asset/1'); } $files = array(); foreach ($request['selected'] as $file) { $files[] = str_replace('%2F', '/', Text::parse($file, '->encoded_url')); } Guardian::kick($config->manager->slug . '/asset/kill/files:' . implode(';', $files)); } });
/** * Display an offering asset * * @return void */ public function enrollTask() { // Check if they're logged in if (User::isGuest()) { $this->loginTask(Lang::txt('COM_COURSES_ENROLLMENT_REQUIRES_LOGIN')); return; } $offering = $this->course->offering(); // Is the user a manager or student? if ($offering->isManager() || $offering->isStudent()) { // Yes! Already enrolled // Redirect back to the course page App::redirect(Route::url($offering->link()), Lang::txt('COM_COURSES_ALREADY_ENROLLED')); return; } $this->view->course = $this->course; // Build the title $this->_buildTitle(); // Build pathway $this->_buildPathway(); // Can the user enroll? if (!$offering->section()->canEnroll()) { $this->view->setLayout('enroll_closed'); $this->view->display(); return; } $enrolled = false; // If enrollment is open OR a coupon code was posted if (!$offering->section()->get('enrollment') || ($code = Request::getVar('code', ''))) { $section_id = $offering->section()->get('id'); // If a coupon code was posted if (isset($code)) { // Get the coupon $coupon = $offering->section()->code($code); // Is it a valid code? if (!$coupon->exists()) { $this->setError(Lang::txt('COM_COURSES_ERROR_CODE_INVALID', $code)); } // Has it already been redeemed? if ($coupon->isRedeemed()) { $this->setError(Lang::txt('COM_COURSES_ERROR_CODE_ALREADY_REDEEMED', $code)); } else { // Has it expired? if ($coupon->isExpired()) { $this->setError(Lang::txt('COM_COURSES_ERROR_CODE_EXPIRED', $code)); } } if (!$this->getError()) { // Is this a coupon for a different section? if ($offering->section()->get('id') != $coupon->get('section_id')) { $section = \Components\Courses\Models\Section::getInstance($coupon->get('section_id')); if ($section->exists() && $section->get('offering_id') != $offering->get('id')) { $offering = \Components\Courses\Models\Offering::getInstance($section->get('offering_id')); if ($offering->exists() && $offering->get('course_id') != $this->course->get('id')) { $this->course = \Components\Courses\Models\Course::getInstance($offering->get('course_id')); } } App::redirect(Route::url($offering->link() . '&task=enroll&code=' . $code)); return; } // Redeem the code $coupon->redeem(User::get('id')); // set('redeemed_by', User::get('id')); //$coupon->store(); } } // If no errors if (!$this->getError()) { // Add the user to the course $model = new \Components\Courses\Models\Member(0); //::getInstance(User::get('id'), $offering->get('id')); $model->set('user_id', User::get('id')); $model->set('course_id', $this->course->get('id')); $model->set('offering_id', $offering->get('id')); $model->set('section_id', $offering->section()->get('id')); if ($roles = $offering->roles()) { foreach ($roles as $role) { if ($role->alias == 'student') { $model->set('role_id', $role->id); break; } } } $model->set('student', 1); if ($model->store(true)) { $enrolled = true; } else { $this->setError($model->getError()); } } } if ($enrolled) { $link = $offering->link(); $data = Event::trigger('courses.onCourseEnrolled', array($this->course, $offering, $offering->section())); if ($data && count($data) > 0) { $link = implode('', $data); } App::redirect(Route::url($link)); return; } // If enrollment is srestricted and the user isn't enrolled yet if ($offering->section()->get('enrollment') == 1 && !$enrolled) { // Show a form for entering a coupon code $this->view->setLayout('enroll_restricted'); } if ($this->getError()) { \Notify::error($this->getError(), 'courses'); } $this->view->notifications = \Notify::messages('courses'); $this->view->display(); }
/** * Edit a type * * @param object $row * @return void */ public function editTask($row = null) { Request::setVar('hidemainmenu', 1); if (!is_object($row)) { // Incoming (expecting an array) $id = Request::getVar('id', array(0)); $id = is_array($id) ? $id[0] : $id; // Load the object $row = new \Components\Publications\Tables\License($this->database); $row->loadLicense($id); } $this->view->row = $row; // Set any errors if ($this->getError()) { \Notify::error($this->getError()); } // Output the HTML $this->view->setLayout('edit')->display(); }
/** * Process import selections * * @return void */ private function processAction() { // Check if they're logged in if (User::isGuest()) { return $this->loginAction(); } if (!$this->params->get('access-manage')) { throw new Exception(Lang::txt('PLG_MEMBERS_CITATIONS_NOT_AUTHORIZED'), 403); } Request::checkToken(); $cites_require_attention = $this->importer->readRequiresAttention(); $cites_require_no_attention = $this->importer->readRequiresNoAttention(); // action for citations needing attention $citations_action_attention = Request::getVar('citation_action_attention', array()); // action for citations needing no attention $citations_action_no_attention = Request::getVar('citation_action_no_attention', array()); // check to make sure we have citations if (!$cites_require_attention && !$cites_require_no_attention) { App::redirect(Route::url($this->member->getLink() . '&active=' . $this->_name . '&action=import'), Lang::txt('PLG_MEMBERS_CITATIONS_IMPORT_MISSING_FILE_CONTINUE'), 'error'); return; } // vars $allow_tags = "yes"; $allow_badges = "yes"; $this->importer->set('user', User::get('id')); $this->importer->setTags($allow_tags == 'yes'); $this->importer->setBadges($allow_badges == 'yes'); $this->importer->set('scope_id', $this->member->get('uidNumber')); $this->importer->set('scope', 'member'); // Process $results = $this->importer->process($citations_action_attention, $citations_action_no_attention); // success message a redirect Notify::success(Lang::txt('PLG_MEMBERS_CITATIONS_IMPORT_RESULTS_SAVED', count($results['saved'])), 'plg_citations'); // if we have citations not getting saved if (count($results['not_saved']) > 0) { Notify::warning(Lang::txt('PLG_MEMBERS_CITATIONS_IMPORT_RESULTS_NOT_SAVED', count($results['not_saved'])), 'plg_citations'); } if (count($results['error']) > 0) { Notify::error(Lang::txt('PLG_MEMBERS_CITATIONS_IMPORT_RESULTS_SAVE_ERROR', count($results['error'])), 'plg_citations'); } //get the session object $session = App::get('session'); //ids of sessions saved and not saved $session->set('citations_saved', $results['saved']); $session->set('citations_not_saved', $results['not_saved']); $session->set('citations_error', $results['error']); //delete the temp files that hold citation data $this->importer->cleanup(true); //redirect App::redirect(Route::url($this->member->getLink() . '&active=' . $this->_name . '&action=saved')); }
<?php /** * Created by PhpStorm. * User: kkeiper * Date: 9/4/14 * Time: 9:14 AM */ Route::filter("sentry.auth", function () { if (!Sentry::check()) { if (Request::ajax()) { return Response::make('Unauthorized', 401); } else { return Redirect::guest('sentry/login'); } } }); Route::filter('sentry.guest', function () { if (Sentry::check()) { return Redirect::to('/'); } }); Route::filter("sentry.is", function ($route, $request) { $filterArgs = array_slice(func_get_args(), 2); if (!Sentry::getUser()->hasAccess($filterArgs)) { Notify::error("You Do Not Have Permission To Access This Area."); return Redirect::to("/"); } });
/** * Vote on a comment * * @return void */ protected function _vote() { // Ensure the user is logged in if (User::isGuest()) { return $this->_login(); } $no_html = Request::getInt('no_html', 0); // Record the vote if ($item_id = Request::getInt('voteup', 0)) { $how = 1; } else { if ($item_id = Request::getInt('votedown', 0)) { $how = -1; } } $item = \Plugins\Hubzero\Comments\Models\Comment::oneOrFail($item_id); if (!$item->vote($how)) { $this->setError($item->getError()); } if (!$no_html) { if ($this->getError()) { Notify::error($this->getError()); } else { Notify::success(Lang::txt('PLG_HUBZERO_COMMENTS_VOTE_SAVED')); } App::redirect($this->url); } $item->set('vote', $how); $this->view->setLayout('vote'); $this->view->set('item', $item); $this->view->setErrors($this->getErrors()); // Ugly brute force method of cleaning output ob_clean(); echo $this->view->loadTemplate(); exit; }
try { Installer::run(); } catch (Exception $e) { Input::flash(); Notify::error($e->getMessage()); return Response::redirect('account'); } return Response::redirect('complete'); })); /* Complete */ Route::get('complete', function () { // check we have a database if (!Session::get('install')) { Notify::error('Please select your language'); return Response::redirect('start'); } $settings = Session::get('install'); $vars['site_uri'] = $settings['metadata']['site_path']; $vars['admin_uri'] = rtrim($settings['metadata']['site_path'], '/') . '/index.php/admin/login'; $vars['htaccess'] = Session::get('htaccess'); // scrub session now we are done Session::erase('install'); file_put_contents(APP . 'install.lock', time()); return Layout::create('complete', $vars); }); /* 404 catch all */ Route::any(':all', function () {
function do_comment_construct() { $config = Config::get(); $speak = Config::speak(); if ($config->page_type === 'article') { $comment_id = 'comment-%d'; // Your comment ID $comment_form_id = 'comment-form'; // Your comment form ID $article = isset($config->article->path) ? $config->article : false; $G = array('data' => array('article' => Mecha::A($article), 'comment_id' => $comment_id, 'comment_form_id' => $comment_form_id)); if ($article !== false && ($request = Request::post())) { if ($task = File::exist(SHIELD . DS . $config->shield . DS . 'workers' . DS . 'task.comment.php')) { require $task; // Custom comment constructor } else { // Check token Guardian::checkToken($request['token'], $article->url . '#' . $comment_form_id); $extension = $config->comments->moderation && !Guardian::happy() ? '.hold' : '.txt'; // Check name if (trim($request['name']) === "") { Notify::error(Config::speak('notify_error_empty_field', $speak->name)); } // Check email if (trim($request['email']) !== "") { if (!Guardian::check($request['email'], '->email')) { Notify::error($speak->notify_invalid_email); } else { // Disallow passenger(s) from entering your email address in the comment email field if (!Guardian::happy() && $request['email'] === $config->author->email) { Notify::warning(Config::speak('notify_warning_forbidden_input', array('<em>' . $request['email'] . '</em>', strtolower($speak->email)))); } } } else { Notify::error(Config::speak('notify_error_empty_field', $speak->email)); } // Check URL if (trim($request['url']) !== "" && !Guardian::check($request['url'], '->url')) { Notify::error($speak->notify_invalid_url); } // Check message if (trim($request['message']) === "") { Notify::error(Config::speak('notify_error_empty_field', $speak->message)); } // Check challenge if (!Guardian::checkMath($request['math'])) { Notify::error($speak->notify_invalid_math_answer); } // Check name length if (Guardian::check($request['name'], '->too_long', 100)) { Notify::error(Config::speak('notify_error_too_long', $speak->name)); } // Check email length if (Guardian::check($request['email'], '->too_long', 100)) { Notify::error(Config::speak('notify_error_too_long', $speak->email)); } // Check URL length if (Guardian::check($request['url'], '->too_long', 100)) { Notify::error(Config::speak('notify_error_too_long', $speak->url)); } // Check message length if (Guardian::check($request['message'], '->too_long', 1700)) { Notify::error(Config::speak('notify_error_too_long', $speak->message)); } // Check for spam keyword(s) in comment $fucking_words = explode(',', $config->keywords_spam); foreach ($fucking_words as $spam) { if ($f**k = trim($spam)) { if ($request['email'] === $f**k || strpos(strtolower($request['message']), strtolower($f**k)) !== false) { Notify::warning($speak->notify_warning_intruder_detected . ' <strong class="text-error pull-right">' . $f**k . '</strong>'); break; } } } if (!Notify::errors()) { $post = Date::slug($article->time); $id = (int) time(); $parent = Request::post('parent'); $P = array('data' => $request); $P['data']['id'] = $id; $name = strip_tags($request['name']); $email = Text::parse($request['email'], '->broken_entity'); $url = isset($request['url']) && trim($request['url']) !== "" ? $request['url'] : false; $parser = strip_tags(Request::post('content_type', $config->html_parser->active)); $message = Text::parse($request['message'], '->text', WISE_CELL . '<img>', false); $field = Request::post('fields', array()); include File::D(__DIR__, 2) . DS . 'task.fields.php'; // Temporarily disallow image(s) in comment to prevent XSS $message = preg_replace('#<img(\\s[^<>]*?)>#i', '<img$1>', $message); Page::header(array('Name' => $name, 'Email' => $email, 'URL' => $url, 'Status' => Guardian::happy() ? 1 : 2, 'Content Type' => $parser, 'Fields' => !empty($field) ? Text::parse($field, '->encoded_json') : false))->content($message)->saveTo(COMMENT . DS . $post . '_' . Date::slug($id) . '_' . ($parent ? Date::slug($parent) : '0000-00-00-00-00-00') . $extension); Notify::success(Config::speak('notify_success_submitted', $speak->comment)); if ($extension === '.hold') { Notify::info($speak->notify_info_comment_moderation); } Weapon::fire(array('on_comment_update', 'on_comment_construct'), array($G, $P)); Guardian::kick($config->url_current . $config->ur_query . (!Guardian::happy() && $config->comments->moderation ? '#' . $comment_form_id : '#' . sprintf($comment_id, Date::format($id, 'U')))); } else { Guardian::kick($config->url_current . $config->url_query . '#' . $comment_form_id); } } } } }
if ($request = Request::post()) { Guardian::checkToken($request['token']); $name = File::path($request['name']); if (!Request::post('name')) { Notify::error(Config::speak('notify_error_empty_field', $speak->name)); } else { if ($path !== $name && File::exist(SHIELD . DS . $folder . DS . $name)) { Notify::error(Config::speak('notify_file_exist', '<code>' . $name . '</code>')); } if (($extension = File::E($name)) !== "") { if (strpos(',' . SCRIPT_EXT . ',', ',' . $extension . ',') === false) { Notify::error(Config::speak('notify_error_file_extension', $extension)); } } else { // Missing file extension Notify::error($speak->notify_error_file_extension_missing); } } $P = array('data' => $request); if (!Notify::errors()) { File::open($file)->write($request['content'])->save(); if ($path !== $name) { File::open($file)->moveTo(SHIELD . DS . $folder . DS . $name); } Notify::success(Config::speak('notify_file_updated', '<code>' . File::B($path) . '</code>')); Weapon::fire('on_shield_update', array($G, $P)); Weapon::fire('on_shield_repair', array($G, $P)); Guardian::kick($config->manager->slug . '/shield/' . $folder . '/repair/file:' . File::url($name)); } } Shield::lot(array('segment' => 'shield', 'the_shield' => $folder, 'the_name' => $path, 'the_content' => $content))->attach('manager', false);
if (trim($request['name']) === "") { $request['name'] = $id . '.txt'; // empty file name } $_path = Text::parse(sprintf($request['name'], $id), '->safe_path_name'); $e = File::E($_path, false); if ($e !== 'txt' && $e !== 'php') { $e = 'txt'; $_path .= '.txt'; } $_path_ = File::path($_path); $file = ASSET . DS . '__snippet' . DS . $e . DS . $_path; if (File::exist($file)) { // file already exists Notify::error(Config::speak('notify_file_exist', '<code>' . $_path_ . '</code>')); } if (trim($request['content']) === "") { // empty file content Notify::error($speak->notify_error_content_empty); } if (!Notify::errors()) { $recent = array_slice(File::open(CACHE . DS . 'plugin.snippet.cache')->unserialize(), 0, $config->per_page); File::serialize(array_merge(array($_path), $recent))->saveTo(CACHE . DS . 'plugin.snippet.cache', 0600); $url = $config->manager->slug . '/asset/repair/file:__snippet/' . $e . '/' . File::url($_path) . '?path=' . urlencode(rtrim('__snippet/' . $e . '/' . File::D(File::url($_path)), '/')); File::write($request['content'])->saveTo($file, 0600); Notify::success(Config::speak('notify_file_created', '<code>' . $_path_ . '</code>' . (!isset($request['redirect']) ? ' <a class="pull-right" href="' . $config->url . '/' . $url . '" target="_blank">' . Jot::icon('pencil') . ' ' . $speak->edit . '</a>' : ""))); Notify::info('<strong>' . $speak->shortcode . ':</strong> <code>{{' . ($e === 'php' ? 'include' : 'print') . ':' . str_replace('.' . $e . X, "", File::url($_path) . X) . '}}</code>'); Guardian::kick(isset($request['redirect']) ? $url : File::D($config->url_current)); } Guardian::kick(File::D($config->url_current)); });
}); Route::post('admin/users/add', function () { $input = Input::get(array('username', 'email', 'real_name', 'password', 'bio', 'status', 'role')); $validator = new Validator($input); $validator->check('username')->is_max(3, __('users.username_missing', 2)); $validator->check('email')->is_email(__('users.email_missing')); $validator->check('password')->is_max(6, __('users.password_too_short', 6)); if ($errors = $validator->errors()) { Input::flash(); Notify::error($errors); return Response::redirect('admin/users/add'); } $input['password'] = Hash::make($input['password']); User::create($input); Notify::success(__('users.created')); return Response::redirect('admin/users'); }); /* Delete user */ Route::get('admin/users/delete/(:num)', function ($id) { $self = Auth::user(); if ($self->id == $id) { Notify::error(__('users.delete_error')); return Response::redirect('admin/users/edit/' . $id); } User::where('id', '=', $id)->delete(); Notify::success(__('users.deleted')); return Response::redirect('admin/users'); }); });
if (empty($input['key'])) { $input['key'] = $input['label']; } $input['key'] = slug($input['key'], '_'); array_walk_recursive($input, function (&$value) { $value = eq($value); }); $validator = new Validator($input); $validator->add('valid_key', function ($str) use($id, $input) { return Extend::where('key', '=', $str)->where('type', '=', $input['type'])->where('id', '<>', $id)->count() == 0; }); $validator->check('key')->is_max(1, __('extend.key_missing'))->is_valid_key(__('extend.key_exists')); $validator->check('label')->is_max(1, __('extend.label_missing')); if ($errors = $validator->errors()) { Input::flash(); Notify::error($errors); return Response::redirect('admin/extend/fields/edit/' . $id); } if ($input['field'] == 'image') { $attributes = Json::encode($input['attributes']); } elseif ($input['field'] == 'file') { $attributes = Json::encode(array('attributes' => array('type' => $input['attributes']['type']))); } else { $attributes = ''; } Extend::update($id, array('type' => $input['type'], 'pagetype' => $input['pagetype'], 'field' => $input['field'], 'key' => $input['key'], 'label' => $input['label'], 'attributes' => $attributes)); Notify::success(__('extend.field_updated')); return Response::redirect('admin/extend/fields/edit/' . $id); }); /* Delete Field
/** * Save Subscription * * @return void */ public function saveTask() { // Check for request forgeries Request::checkToken(); $id = Request::getInt('id', 0); $subscription = new Subscription($this->database); if (!$subscription->load($id)) { App::redirect(Route::url('index.php?option=' . $this->_option . '&controller=' . $this->_controller, false), Lang::txt('COM_SERVICES_SUBSCRIPTION_NOT_FOUND'), 'error'); return; } // get service $service = new Service($this->database); if (!$service->loadService('', $subscription->serviceid)) { App::redirect(Route::url('index.php?option=' . $this->_option . '&controller=' . $this->_controller, false), Lang::txt('COM_SERVICES_SERVICE_NOT_FOUND') . ' ' . $subscription->serviceid, 'error'); return; } $author = User::getInstance($subscription->uid); $subscription->notes = rtrim(stripslashes(Request::getVar('notes', ''))); $action = Request::getVar('action', ''); $message = Request::getVar('message', ''); $statusmsg = ''; $email = 0; switch ($action) { case 'refund': $received_refund = Request::getInt('received_refund', 0); $newunits = Request::getInt('newunits', 0); $pending = $subscription->pendingpayment - $received_refund; $pendingunits = $subscription->pendingunits - $newunits; $subscription->pendingpayment = $pending <= 0 ? 0 : $pending; $subscription->pendingunits = $pendingunits <= 0 ? 0 : $pendingunits; $email = 0; $statusmsg .= Lang::txt('Refund has been processed.'); break; case 'activate': $received_payment = Request::getInt('received_payment', 0); $newunits = Request::getInt('newunits', 0); $pending = $subscription->pendingpayment - $received_payment; $pendingunits = $subscription->pendingunits - $newunits; $subscription->pendingpayment = $pending <= 0 ? 0 : $pending; $subscription->pendingunits = $pendingunits <= 0 ? 0 : $pendingunits; $subscription->totalpaid = $subscription->totalpaid + $received_payment; $oldunits = $subscription->units; $months = $newunits * $service->unitsize; $newexpire = $oldunits > 0 && intval($subscription->expires) != 0 ? Date::of(strtotime($subscription->expires . "+" . $months . "months"))->format("Y-m-d") : Date::of(strtotime("+" . $months . "months"))->format("Y-m-d"); $subscription->expires = $newunits ? $newexpire : $subscription->expires; $subscription->status = 1; $subscription->units = $subscription->units + $newunits; $email = ($received_payment > 0 or $newunits > 0) ? 1 : 0; $statusmsg .= Lang::txt('COM_SERVICES_SUBSCRIPTION_ACTIVATED'); if ($newunits > 0) { $statusmsg .= ' ' . Lang::txt('for') . ' ' . $newunits . ' '; $statusmsg .= $oldunits > 0 ? Lang::txt('additional') . ' ' : ''; $statusmsg .= Lang::txt('month(s)'); } break; case 'message': $statusmsg .= Lang::txt('Your message has been sent.'); break; case 'cancelsub': $refund = 0; $unitsleft = $subscription->getRemaining('unit', $subscription, $service->maxunits, $service->unitsize); // get cost per unit (to compute required refund) $refund = $subscription->totalpaid > 0 && $unitsleft > 0 && $subscription->totalpaid - $unitsleft * $unitcost > 0 ? $unitsleft * $prevunitcost : 0; $subscription->status = 2; $subscription->pendingpayment = $refund; $subscription->pendingunits = $refund > 0 ? $unitsleft : 0; $email = 1; $statusmsg .= Lang::txt('COM_SERVICES_SUBSCRIPTION_CANCELLED'); break; } if ($action && $action != 'message' || $message) { $subscription->notes .= '------------------------------' . "\r\n"; $subscription->notes .= Lang::txt('COM_SERVICES_SUBSCRIPTION_STATUS_UPDATED') . ', ' . Date::toSql() . "\r\n"; $subscription->notes .= $statusmsg ? $statusmsg . "\r\n" : ''; $subscription->notes .= $message ? $message . "\r\n" : ''; $subscription->notes .= '------------------------------' . "\r\n"; } if (!$subscription->check()) { $this->setError($subscription->getError()); $this->editTask($subscription); return; } if (!$subscription->store()) { $this->setError($subscription->getError()); $this->editTask($subscription); return; } if ($email || $message) { // E-mail "from" info $from = array('email' => Config::get('mailfrom'), 'name' => Config::get('sitename') . ' ' . Lang::txt('COM_SERVICES_SUBSCRIPTIONS')); // start email message $subject = Lang::txt('COM_SERVICES_EMAIL_SUBJECT', $subscription->code); $emailbody = $subject . ':' . "\r\n"; $emailbody .= Lang::txt('COM_SERVICES_SUBSCRIPTION_SERVICE') . ' - ' . $service->title . "\r\n"; $emailbody .= '----------------------------------------------------------' . "\r\n"; $emailbody .= $action != 'message' && $statusmsg ? $statusmsg : ''; if ($message) { $emailbody .= "\r\n"; $emailbody .= $message; } if (!Event::trigger('xmessage.onSendMessage', array('subscriptions_message', $subject, $emailbody, $from, array($subscription->uid), $this->_option))) { \Notify::error(Lang::txt('COM_SERVICES_ERROR_FAILED_TO_MESSAGE')); } } App::redirect(Route::url('index.php?option=' . $this->_option . '&controller=' . $this->_controller, false), Lang::txt('COM_SERVICES_SUBSCRIPTION_SAVED') . ($statusmsg ? ' ' . $statusmsg : '')); }
public static function upload($file, $destination = ROOT, $callback = null) { $config = Config::get(); $speak = Config::speak(); $destination = self::path($destination); $errors = Mecha::A($speak->notify_file); // Create a safe file name $file['name'] = Text::parse($file['name'], '->safe_file_name'); $extension = self::E($file['name']); // Something goes wrong if ($file['error'] > 0 && isset($errors[$file['error']])) { Notify::error($errors[$file['error']]); } else { // Destination not found if (!file_exists($destination)) { self::pocket($destination); } // Unknown file type if (!isset($file['type']) || empty($file['type'])) { Notify::error($speak->notify_error_file_type_unknown); } // Bad file extension $extension_allow = ',' . implode(',', self::$config['file_extension_allow']) . ','; if (strpos($extension_allow, ',' . $extension . ',') === false) { Notify::error(Config::speak('notify_error_file_extension', $extension)); } // Too small if ($file['size'] < self::$config['file_size_min_allow']) { Notify::error(Config::speak('notify_error_file_size_min', self::size(self::$config['file_size_min_allow'], 'KB'))); } // Too large if ($file['size'] > self::$config['file_size_max_allow']) { Notify::error(Config::speak('notify_error_file_size_max', self::size(self::$config['file_size_max_allow'], 'KB'))); } } if (!Notify::errors()) { // Move the uploaded file to the destination folder if (!file_exists($destination . DS . $file['name'])) { move_uploaded_file($file['tmp_name'], $destination . DS . $file['name']); } else { Notify::error(Config::speak('notify_file_exist', '<code>' . $file['name'] . '</code>')); } if (!Notify::errors()) { // Create public asset link to show on file uploaded $link = self::url($destination) . '/' . $file['name']; Notify::success(Config::speak('notify_file_uploaded', '<code>' . $file['name'] . '</code>')); self::$open = $destination . DS . $file['name']; if (is_callable($callback)) { call_user_func($callback, $file['name'], $file['type'], $file['size'], $link); } } return new static(); } return false; }