Example #1
0
 /**
  * Remove recursively the directory named by dirname.
  *
  * @param string $dirname       Path to the directory
  * @param boolean $followLinks  Removes symbolic links if set to true
  * @return boolean              True if success otherwise false
  * @throws Exception            When the directory does not exist or permission denied
  */
 public static function rmdir($dirname, $followLinks = false)
 {
     if (!is_dir($dirname) && !is_link($dirname)) {
         throw new Exception(sprintf('Directory %s does not exist', $dirname));
     }
     if (!is_writable($dirname)) {
         throw new Exception('You do not have renaming permissions');
     }
     $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dirname), RecursiveIteratorIterator::CHILD_FIRST);
     while ($iterator->valid()) {
         if (!$iterator->isDot()) {
             if (!$iterator->isWritable()) {
                 throw new Exception(sprintf('Permission denied for %s', $iterator->getPathName()));
             }
             if ($iterator->isLink() && false === (bool) $followLinks) {
                 $iterator->next();
                 continue;
             }
             if ($iterator->isFile()) {
                 unlink($iterator->getPathName());
             } else {
                 if ($iterator->isDir()) {
                     rmdir($iterator->getPathName());
                 }
             }
         }
         $iterator->next();
     }
     unset($iterator);
     return rmdir($dirname);
 }
 private function recursive_rmdir($dirname, $followLinks = false)
 {
     if (is_dir($dirname) && !is_link($dirname)) {
         if (!is_writable($dirname)) {
             throw new Exception('You do not have renaming permissions!');
         }
         $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dirname), RecursiveIteratorIterator::CHILD_FIRST);
         while ($iterator->valid()) {
             if (!$iterator->isDot()) {
                 if (!$iterator->isWritable()) {
                     throw new Exception(sprintf('Permission Denied: %s.', $iterator->getPathName()));
                 }
                 if ($iterator->isLink() && false === (bool) $followLinks) {
                     $iterator->next();
                 }
                 if ($iterator->isFile()) {
                     unlink($iterator->getPathName());
                 } else {
                     if ($iterator->isDir()) {
                         rmdir($iterator->getPathName());
                     }
                 }
             }
             $iterator->next();
         }
         unset($iterator);
         // Fix for Windows.
         return rmdir($dirname);
     } else {
         throw new Exception(sprintf('Directory %s does not exist!', $dirname));
     }
 }
 /**
  * Do the job.
  * Throw exceptions on errors (the job will be retried).
  */
 public function execute()
 {
     global $CFG;
     $tmpdir = $CFG->tempdir;
     // Default to last weeks time.
     $time = strtotime('-1 week');
     $dir = new \RecursiveDirectoryIterator($tmpdir);
     // Show all child nodes prior to their parent.
     $iter = new \RecursiveIteratorIterator($dir, \RecursiveIteratorIterator::CHILD_FIRST);
     for ($iter->rewind(); $iter->valid(); $iter->next()) {
         $node = $iter->getRealPath();
         if (!is_readable($node)) {
             continue;
         }
         // Check if file or directory is older than the given time.
         if ($iter->getMTime() < $time) {
             if ($iter->isDir() && !$iter->isDot()) {
                 // Don't attempt to delete the directory if it isn't empty.
                 if (!glob($node . DIRECTORY_SEPARATOR . '*')) {
                     if (@rmdir($node) === false) {
                         mtrace("Failed removing directory '{$node}'.");
                     }
                 }
             }
             if ($iter->isFile()) {
                 if (@unlink($node) === false) {
                     mtrace("Failed removing file '{$node}'.");
                 }
             }
         }
     }
 }
Example #4
0
 public function buildArray()
 {
     $directory = new \RecursiveDirectoryIterator('assets');
     $iterator = new \RecursiveIteratorIterator($directory, \RecursiveIteratorIterator::CHILD_FIRST);
     $tree = [];
     foreach ($iterator as $info) {
         //if (in_array($info->getFilename(), ['.', '..'])) continue;
         if ($iterator->getDepth() >= 2 || !$iterator->isDir() || $iterator->isDot()) {
             continue;
         }
         if ($iterator->getDepth() == 1) {
             $path = $info->isDir() ? [$iterator->getDepth() - 1 => $info->getFilename()] : [$info->getFilename()];
         } else {
             $path = $info->isDir() ? [$info->getFilename() => []] : [$info->getFilename()];
         }
         for ($depth = $iterator->getDepth() - 1; $depth >= 0; $depth--) {
             $path = [$iterator->getSubIterator($depth)->current()->getFilename() => $path];
         }
         $tree = array_merge_recursive($tree, $path);
     }
     $data = array();
     foreach ($tree as $category => $children) {
         foreach ($children as $index => $value) {
             $data[$category][] = $value;
         }
     }
     foreach ($data as $category => $children) {
         $parentId = $this->addEntry($category, '0');
         foreach ($children as $index => $value) {
             $this->addEntry($value, $parentId);
         }
     }
     return $data;
 }
Example #5
0
 public static function findDirectories($rootDir, $multiMap = true)
 {
     if (!is_dir($rootDir)) {
         throw new \LogicException($rootDir . ' is not a directory');
     }
     $elements = array();
     $d = @dir($rootDir);
     if (!$d) {
         throw new \LogicException('Directory is not readable');
     }
     $dirs = array();
     $it = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($rootDir, \FilesystemIterator::KEY_AS_PATHNAME | \FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::CHILD_FIRST);
     while ($it->valid()) {
         if (!$it->isDir()) {
             $it->next();
         } else {
             $cur = $it->current();
             if ($cur->isDir()) {
                 if ($multiMap) {
                     $dirs[$cur->getPath()][] = $cur->getFilename();
                 } else {
                     $dirs[] = $cur->getPath();
                 }
             }
             $it->next();
         }
     }
     return $dirs;
 }
Example #6
0
 protected function countThemePages($path)
 {
     $result = 0;
     $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
     $it->setMaxDepth(1);
     while ($it->valid()) {
         if (!$it->isDot() && !$it->isDir() && $it->getExtension() == 'htm') {
             $result++;
         }
         $it->next();
     }
     return $result;
 }
 /**
  * Do the job.
  * Throw exceptions on errors (the job will be retried).
  */
 public function execute()
 {
     global $CFG;
     $tmpdir = $CFG->tempdir;
     // Default to last weeks time.
     $time = time() - $CFG->tempdatafoldercleanup * 3600;
     $dir = new \RecursiveDirectoryIterator($tmpdir);
     // Show all child nodes prior to their parent.
     $iter = new \RecursiveIteratorIterator($dir, \RecursiveIteratorIterator::CHILD_FIRST);
     // An array of the full path (key) and date last modified.
     $modifieddateobject = array();
     // Get the time modified for each directory node. Nodes will be updated
     // once a file is deleted, so we need a list of the original values.
     for ($iter->rewind(); $iter->valid(); $iter->next()) {
         $node = $iter->getRealPath();
         if (!is_readable($node)) {
             continue;
         }
         $modifieddateobject[$node] = $iter->getMTime();
     }
     // Now loop through again and remove old files and directories.
     for ($iter->rewind(); $iter->valid(); $iter->next()) {
         $node = $iter->getRealPath();
         if (!is_readable($node)) {
             continue;
         }
         // Check if file or directory is older than the given time.
         if ($modifieddateobject[$node] < $time) {
             if ($iter->isDir() && !$iter->isDot()) {
                 // Don't attempt to delete the directory if it isn't empty.
                 if (!glob($node . DIRECTORY_SEPARATOR . '*')) {
                     if (@rmdir($node) === false) {
                         mtrace("Failed removing directory '{$node}'.");
                     }
                 }
             }
             if ($iter->isFile()) {
                 if (@unlink($node) === false) {
                     mtrace("Failed removing file '{$node}'.");
                 }
             }
         } else {
             // Return the time modified to the original date only for real files.
             if ($iter->isDir() && !$iter->isDot()) {
                 touch($node, $modifieddateobject[$node]);
             }
         }
     }
 }
 public function delete()
 {
     if (!$this->loadData()) {
         $this->dataError();
         sendBack();
     }
     $moduleobject = $this->_uses[$this->modeltype];
     $db = DB::Instance();
     $db->StartTrans();
     if ($moduleobject->isLoaded()) {
         $modulename = $moduleobject->name;
         $modulelocation = FILE_ROOT . $moduleobject->location;
         if ($moduleobject->enabled && !$moduleobject->disable()) {
             $errors[] = 'Failed to disable module';
         }
         if ($moduleobject->registered && !$moduleobject->unregister()) {
             $errors[] = 'Failed to unregister module';
         }
         if (!$moduleobject->delete()) {
             $errors[] = 'Failed to delete module';
         } else {
             $dir = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($modulelocation), RecursiveIteratorIterator::CHILD_FIRST);
             for ($dir->rewind(); $dir->valid(); $dir->next()) {
                 if ($dir->isDir()) {
                     rmdir($dir->getPathname());
                 } else {
                     unlink($dir->getPathname());
                 }
             }
             rmdir($modulelocation);
         }
     } else {
         $errors[] = 'Cannot find module';
     }
     $flash = Flash::Instance();
     if (count($errors) > 0) {
         $db->FailTrans();
         $flash->addErrors($errors);
         if (isset($this->_data['id'])) {
             $db->CompleteTrans();
             sendTo($this->name, 'view', $this->_modules, array('id' => $this->_data['id']));
         }
     } else {
         $flash->addMessage('Module ' . $modulename . ' deleted OK');
     }
     $db->CompleteTrans();
     sendTo($this->name, 'index', $this->_modules);
 }
Example #9
0
 public function addDirectory($path, $localpath = null, $exclude_hidden = true)
 {
     if ($localpath === null) {
         $localpath = $path;
     }
     $localpath = rtrim($localpath, '/\\');
     $path = rtrim($path, '/\\');
     $iter = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
     while ($iter->valid()) {
         if (!$iter->isDot() && !$iter->isDir()) {
             if (!$exclude_hidden || !$this->is_path_hidden($iter->key())) {
                 $this->addFile($iter->key(), $localpath . DIRECTORY_SEPARATOR . $iter->getSubPathName());
             }
         }
         $iter->next();
     }
 }
Example #10
0
 /**
  * Execute the command.
  *
  * @return  void
  *
  * @since   1.0
  */
 public function execute()
 {
     $this->getApplication()->outputTitle('Make Documentation');
     $this->usePBar = $this->getApplication()->get('cli-application.progress-bar');
     if ($this->getApplication()->input->get('noprogress')) {
         $this->usePBar = false;
     }
     $this->github = $this->getContainer()->get('gitHub');
     $this->getApplication()->displayGitHubRateLimit();
     /* @type \Joomla\Database\DatabaseDriver $db */
     $db = $this->getContainer()->get('db');
     $docuBase = JPATH_ROOT . '/Documentation';
     /* @type  \RecursiveDirectoryIterator $it */
     $it = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($docuBase, \FilesystemIterator::SKIP_DOTS));
     $this->out('Compiling documentation in: ' . $docuBase)->out();
     $table = new ArticlesTable($db);
     // @todo compile the md text here.
     $table->setGitHub($this->github);
     while ($it->valid()) {
         if ($it->isDir()) {
             $it->next();
             continue;
         }
         $file = new \stdClass();
         $file->filename = $it->getFilename();
         $path = $it->getSubPath();
         $page = substr($it->getFilename(), 0, strrpos($it->getFilename(), '.'));
         $this->debugOut('Compiling: ' . $page);
         $table->reset();
         $table->{$table->getKeyName()} = null;
         try {
             $table->load(array('alias' => $page, 'path' => $path));
         } catch (\RuntimeException $e) {
             // New item
         }
         $table->is_file = '1';
         $table->path = $it->getSubPath();
         $table->alias = $page;
         $table->text_md = file_get_contents($it->key());
         $table->store();
         $this->out('.', false);
         $it->next();
     }
     $this->out()->out('Finished =;)');
 }
Example #11
0
 /**
  * Attempts to remove recursively the directory named by dirname.
  *
  * @author Mehdi Kabab <http://pioupioum.fr>
  * @copyright Copyright (C) 2009 Mehdi Kabab
  * @license http://www.gnu.org/licenses/gpl.html  GNU GPL version 3 or later
  *
  * @param	string	$dirname		Path to the directory.
  * @return	null
  */
 private function _recursive_rmdir($dirname)
 {
     if (is_dir($dirname) && !is_link($dirname)) {
         $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dirname), \RecursiveIteratorIterator::CHILD_FIRST);
         while ($iterator->valid()) {
             if (!$iterator->isDot()) {
                 if ($iterator->isFile()) {
                     unlink($iterator->getPathName());
                 } else {
                     if ($iterator->isDir()) {
                         rmdir($iterator->getPathName());
                     }
                 }
             }
             $iterator->next();
         }
         unset($iterator);
         // Fix for Windows.
         rmdir($dirname);
     }
 }
Example #12
0
 function doModel()
 {
     //specific things for this class
     switch ($this->action) {
         case 'bulk_actions':
             break;
         case 'regions':
             //Return regions given a countryId
             $regions = Region::newInstance()->findByCountry(Params::getParam("countryId"));
             echo json_encode($regions);
             break;
         case 'cities':
             //Returns cities given a regionId
             $cities = City::newInstance()->findByRegion(Params::getParam("regionId"));
             echo json_encode($cities);
             break;
         case 'location':
             // This is the autocomplete AJAX
             $cities = City::newInstance()->ajax(Params::getParam("term"));
             echo json_encode($cities);
             break;
         case 'userajax':
             // This is the autocomplete AJAX
             $users = User::newInstance()->ajax(Params::getParam("term"));
             if (count($users) == 0) {
                 echo json_encode(array(0 => array('id' => '', 'label' => __('No results'), 'value' => __('No results'))));
             } else {
                 echo json_encode($users);
             }
             break;
         case 'date_format':
             echo json_encode(array('format' => Params::getParam('format'), 'str_formatted' => osc_format_date(date('Y-m-d H:i:s'), Params::getParam('format'))));
             break;
         case 'runhook':
             // run hooks
             $hook = Params::getParam('hook');
             if ($hook == '') {
                 echo json_encode(array('error' => 'hook parameter not defined'));
                 break;
             }
             switch ($hook) {
                 case 'item_form':
                     osc_run_hook('item_form', Params::getParam('catId'));
                     break;
                 case 'item_edit':
                     $catId = Params::getParam("catId");
                     $itemId = Params::getParam("itemId");
                     osc_run_hook("item_edit", $catId, $itemId);
                     break;
                 default:
                     osc_run_hook('ajax_admin_' . $hook);
                     break;
             }
             break;
         case 'categories_order':
             // Save the order of the categories
             osc_csrf_check(false);
             $aIds = Params::getParam('list');
             $orderParent = 0;
             $orderSub = 0;
             $catParent = 0;
             $error = 0;
             $catManager = Category::newInstance();
             $aRecountCat = array();
             foreach ($aIds as $id => $parent) {
                 if ($parent == 'root') {
                     $res = $catManager->updateOrder($id, $orderParent);
                     if (is_bool($res) && !$res) {
                         $error = 1;
                     }
                     // find category
                     $auxCategory = Category::newInstance()->findByPrimaryKey($id);
                     // set parent category
                     $conditions = array('pk_i_id' => $id);
                     $array['fk_i_parent_id'] = NULL;
                     $res = $catManager->update($array, $conditions);
                     if (is_bool($res) && !$res) {
                         $error = 1;
                     } else {
                         if ($res == 1) {
                             // updated ok
                             $parentId = $auxCategory['fk_i_parent_id'];
                             if ($parentId) {
                                 // update parent category stats
                                 array_push($aRecountCat, $id);
                                 array_push($aRecountCat, $parentId);
                             }
                         }
                     }
                     $orderParent++;
                 } else {
                     if ($parent != $catParent) {
                         $catParent = $parent;
                         $orderSub = 0;
                     }
                     $res = $catManager->updateOrder($id, $orderSub);
                     if (is_bool($res) && !$res) {
                         $error = 1;
                     }
                     // set parent category
                     $auxCategory = Category::newInstance()->findByPrimaryKey($id);
                     $auxCategoryP = Category::newInstance()->findByPrimaryKey($catParent);
                     $conditions = array('pk_i_id' => $id);
                     $array['fk_i_parent_id'] = $catParent;
                     $res = $catManager->update($array, $conditions);
                     if (is_bool($res) && !$res) {
                         $error = 1;
                     } else {
                         if ($res == 1) {
                             // updated ok
                             // update category parent
                             $prevParentId = $auxCategory['fk_i_parent_id'];
                             $parentId = $auxCategoryP['pk_i_id'];
                             array_push($aRecountCat, $prevParentId);
                             array_push($aRecountCat, $parentId);
                         }
                     }
                     $orderSub++;
                 }
             }
             // update category stats
             foreach ($aRecountCat as $rId) {
                 osc_update_cat_stats_id($rId);
             }
             if ($error) {
                 $result = array('error' => __("An error occurred"));
             } else {
                 $result = array('ok' => __("Order saved"));
             }
             echo json_encode($result);
             break;
         case 'category_edit_iframe':
             $this->_exportVariableToView('category', Category::newInstance()->findByPrimaryKey(Params::getParam("id")));
             $this->_exportVariableToView('languages', OSCLocale::newInstance()->listAllEnabled());
             $this->doView("categories/iframe.php");
             break;
         case 'field_categories_iframe':
             $selected = Field::newInstance()->categories(Params::getParam("id"));
             if ($selected == null) {
                 $selected = array();
             }
             $this->_exportVariableToView("selected", $selected);
             $this->_exportVariableToView("field", Field::newInstance()->findByPrimaryKey(Params::getParam("id")));
             $this->_exportVariableToView("categories", Category::newInstance()->toTreeAll());
             $this->doView("fields/iframe.php");
             break;
         case 'field_categories_post':
             osc_csrf_check(false);
             $error = 0;
             $field = Field::newInstance()->findByName(Params::getParam("s_name"));
             if (!isset($field['pk_i_id']) || isset($field['pk_i_id']) && $field['pk_i_id'] == Params::getParam("id")) {
                 // remove categories from a field
                 Field::newInstance()->cleanCategoriesFromField(Params::getParam("id"));
                 // no error... continue updating fields
                 if ($error == 0) {
                     $slug = Params::getParam("field_slug") != '' ? Params::getParam("field_slug") : Params::getParam("s_name");
                     $slug_tmp = $slug = preg_replace('|([-]+)|', '-', preg_replace('|[^a-z0-9_-]|', '-', strtolower($slug)));
                     $slug_k = 0;
                     while (true) {
                         $field = Field::newInstance()->findBySlug($slug);
                         if (!$field || $field['pk_i_id'] == Params::getParam("id")) {
                             break;
                         } else {
                             $slug_k++;
                             $slug = $slug_tmp . "_" . $slug_k;
                         }
                     }
                     // trim options
                     $s_options = '';
                     $aux = Params::getParam('s_options');
                     $aAux = explode(',', $aux);
                     foreach ($aAux as &$option) {
                         $option = trim($option);
                     }
                     $s_options = implode(',', $aAux);
                     $res = Field::newInstance()->update(array('s_name' => Params::getParam("s_name"), 'e_type' => Params::getParam("field_type"), 's_slug' => $slug, 'b_required' => Params::getParam("field_required") == "1" ? 1 : 0, 's_options' => $s_options), array('pk_i_id' => Params::getParam("id")));
                     if (is_bool($res) && !$res) {
                         $error = 1;
                     }
                 }
                 // no error... continue inserting categories-field
                 if ($error == 0) {
                     $aCategories = Params::getParam("categories");
                     if (is_array($aCategories) && count($aCategories) > 0) {
                         $res = Field::newInstance()->insertCategories(Params::getParam("id"), $aCategories);
                         if (!$res) {
                             $error = 1;
                         }
                     }
                 }
                 // error while updating?
                 if ($error == 1) {
                     $message = __("An error occurred while updating.");
                 }
             } else {
                 $error = 1;
                 $message = __("Sorry, you already have a field with that name");
             }
             if ($error) {
                 $result = array('error' => $message);
             } else {
                 $result = array('ok' => __("Saved"), 'text' => Params::getParam("s_name"), 'field_id' => Params::getParam("id"));
             }
             echo json_encode($result);
             break;
         case 'delete_field':
             osc_csrf_check(false);
             $res = Field::newInstance()->deleteByPrimaryKey(Params::getParam('id'));
             if ($res > 0) {
                 $result = array('ok' => __('The custom field has been deleted'));
             } else {
                 $result = array('error' => __('An error occurred while deleting'));
             }
             echo json_encode($result);
             break;
         case 'add_field':
             osc_csrf_check(false);
             $s_name = __('NEW custom field');
             $slug_tmp = $slug = preg_replace('|([-]+)|', '-', preg_replace('|[^a-z0-9_-]|', '-', strtolower($s_name)));
             $slug_k = 0;
             while (true) {
                 $field = Field::newInstance()->findBySlug($slug);
                 if (!$field || $field['pk_i_id'] == Params::getParam("id")) {
                     break;
                 } else {
                     $slug_k++;
                     $slug = $slug_tmp . "_" . $slug_k;
                 }
             }
             $fieldManager = Field::newInstance();
             $result = $fieldManager->insertField($s_name, 'TEXT', $slug, 0, '', array());
             if ($result) {
                 echo json_encode(array('error' => 0, 'field_id' => $fieldManager->dao->insertedId(), 'field_name' => $s_name));
             } else {
                 echo json_encode(array('error' => 1));
             }
             break;
         case 'enable_category':
             osc_csrf_check(false);
             $id = strip_tags(Params::getParam('id'));
             $enabled = Params::getParam('enabled') != '' ? Params::getParam('enabled') : 0;
             $error = 0;
             $result = array();
             $aUpdated = array();
             $mCategory = Category::newInstance();
             $aCategory = $mCategory->findByPrimaryKey($id);
             if ($aCategory == false) {
                 $result = array('error' => sprintf(__("No category with id %d exists"), $id));
                 echo json_encode($result);
                 break;
             }
             // root category
             if ($aCategory['fk_i_parent_id'] == '') {
                 $mCategory->update(array('b_enabled' => $enabled), array('pk_i_id' => $id));
                 $mCategory->update(array('b_enabled' => $enabled), array('fk_i_parent_id' => $id));
                 $subCategories = $mCategory->findSubcategories($id);
                 $aIds = array($id);
                 $aUpdated[] = array('id' => $id);
                 foreach ($subCategories as $subcategory) {
                     $aIds[] = $subcategory['pk_i_id'];
                     $aUpdated[] = array('id' => $subcategory['pk_i_id']);
                 }
                 Item::newInstance()->enableByCategory($enabled, $aIds);
                 if ($enabled) {
                     $result = array('ok' => __('The category as well as its subcategories have been enabled'));
                 } else {
                     $result = array('ok' => __('The category as well as its subcategories have been disabled'));
                 }
                 $result['affectedIds'] = $aUpdated;
                 echo json_encode($result);
                 break;
             }
             // subcategory
             $parentCategory = $mCategory->findRootCategory($id);
             if (!$parentCategory['b_enabled']) {
                 $result = array('error' => __('Parent category is disabled, you can not enable that category'));
                 echo json_encode($result);
                 break;
             }
             $mCategory->update(array('b_enabled' => $enabled), array('pk_i_id' => $id));
             if ($enabled) {
                 $result = array('ok' => __('The subcategory has been enabled'));
             } else {
                 $result = array('ok' => __('The subcategory has been disabled'));
             }
             $result['affectedIds'] = array(array('id' => $id));
             echo json_encode($result);
             break;
         case 'delete_category':
             osc_csrf_check(false);
             $id = Params::getParam("id");
             $error = 0;
             $categoryManager = Category::newInstance();
             $res = $categoryManager->deleteByPrimaryKey($id);
             if ($res > 0) {
                 $message = __('The categories have been deleted');
             } else {
                 $error = 1;
                 $message = __('An error occurred while deleting');
             }
             if ($error) {
                 $result = array('error' => $message);
             } else {
                 $result = array('ok' => __("Saved"));
             }
             echo json_encode($result);
             break;
         case 'edit_category_post':
             osc_csrf_check(false);
             $id = Params::getParam("id");
             $fields['i_expiration_days'] = Params::getParam("i_expiration_days") != '' ? Params::getParam("i_expiration_days") : 0;
             $error = 0;
             $has_one_title = 0;
             $postParams = Params::getParamsAsArray();
             foreach ($postParams as $k => $v) {
                 if (preg_match('|(.+?)#(.+)|', $k, $m)) {
                     if ($m[2] == 's_name') {
                         if ($v != "") {
                             $has_one_title = 1;
                             $aFieldsDescription[$m[1]][$m[2]] = $v;
                             $s_text = $v;
                         } else {
                             $aFieldsDescription[$m[1]][$m[2]] = NULL;
                             $error = 1;
                         }
                     } else {
                         $aFieldsDescription[$m[1]][$m[2]] = $v;
                     }
                 }
             }
             $l = osc_language();
             if ($error == 0 || $error == 1 && $has_one_title == 1) {
                 $categoryManager = Category::newInstance();
                 $res = $categoryManager->updateByPrimaryKey(array('fields' => $fields, 'aFieldsDescription' => $aFieldsDescription), $id);
                 $categoryManager->updateExpiration($id, $fields['i_expiration_days']);
                 if (is_bool($res)) {
                     $error = 2;
                 }
             }
             if (Params::getParam('apply_changes_to_subcategories') == 1) {
                 $subcategories = $categoryManager->findSubcategories($id);
                 foreach ($subcategories as $subc) {
                     $categoryManager->updateExpiration($subc['pk_i_id'], $fields['i_expiration_days']);
                 }
             }
             if ($error == 0) {
                 $msg = __("Category updated correctly");
             } else {
                 if ($error == 1) {
                     if ($has_one_title == 1) {
                         $error = 4;
                         $msg = __('Category updated correctly, but some titles are empty');
                     } else {
                         $msg = __('Sorry, including at least a title is mandatory');
                     }
                 } else {
                     if ($error == 2) {
                         $msg = __('An error occurred while updating');
                     }
                 }
             }
             echo json_encode(array('error' => $error, 'msg' => $msg, 'text' => $aFieldsDescription[$l]['s_name']));
             break;
         case 'custom':
             // Execute via AJAX custom file
             $ajaxFile = Params::getParam("ajaxfile");
             if ($ajaxFile == '') {
                 echo json_encode(array('error' => 'no action defined'));
                 break;
             }
             // valid file?
             if (stripos($ajaxFile, '../') !== false) {
                 echo json_encode(array('error' => 'no valid ajaxFile'));
                 break;
             }
             if (!file_exists(osc_plugins_path() . $ajaxFile)) {
                 echo json_encode(array('error' => "ajaxFile doesn't exist"));
                 break;
             }
             require_once osc_plugins_path() . $ajaxFile;
             break;
         case 'test_mail':
             $title = sprintf(__('Test email, %s'), osc_page_title());
             $body = __("Test email") . "<br><br>" . osc_page_title();
             $emailParams = array('subject' => $title, 'to' => osc_contact_email(), 'to_name' => 'admin', 'body' => $body, 'alt_body' => $body);
             $array = array();
             if (osc_sendMail($emailParams)) {
                 $array = array('status' => '1', 'html' => __('Email sent successfully'));
             } else {
                 $array = array('status' => '0', 'html' => __('An error occurred while sending email'));
             }
             echo json_encode($array);
             break;
         case 'test_mail_template':
             // replace por valores por defecto
             $email = Params::getParam("email");
             $title = Params::getParam("title");
             $body = urldecode(Params::getParam("body"));
             $emailParams = array('subject' => $title, 'to' => $email, 'to_name' => 'admin', 'body' => $body, 'alt_body' => $body);
             $array = array();
             if (osc_sendMail($emailParams)) {
                 $array = array('status' => '1', 'html' => __('Email sent successfully'));
             } else {
                 $array = array('status' => '0', 'html' => __('An error occurred while sending email'));
             }
             echo json_encode($array);
             break;
         case 'order_pages':
             osc_csrf_check(false);
             $order = Params::getParam("order");
             $id = Params::getParam("id");
             if ($order != '' && $id != '') {
                 $mPages = Page::newInstance();
                 $actual_page = $mPages->findByPrimaryKey($id);
                 $actual_order = $actual_page['i_order'];
                 $array = array();
                 $condition = array();
                 $new_order = $actual_order;
                 if ($order == 'up') {
                     $page = $mPages->findPrevPage($actual_order);
                 } else {
                     if ($order == 'down') {
                         $page = $mPages->findNextPage($actual_order);
                     }
                 }
                 if (isset($page['i_order'])) {
                     $mPages->update(array('i_order' => $page['i_order']), array('pk_i_id' => $id));
                     $mPages->update(array('i_order' => $actual_order), array('pk_i_id' => $page['pk_i_id']));
                 }
             }
             break;
             /******************************
              ** COMPLETE UPGRADE PROCESS **
              ******************************/
         /******************************
          ** COMPLETE UPGRADE PROCESS **
          ******************************/
         case 'upgrade':
             // AT THIS POINT WE KNOW IF THERE'S AN UPDATE OR NOT
             osc_csrf_check(false);
             $message = "";
             $error = 0;
             $sql_error_msg = "";
             $rm_errors = 0;
             $perms = osc_save_permissions();
             osc_change_permissions();
             $maintenance_file = ABS_PATH . '.maintenance';
             $fileHandler = @fopen($maintenance_file, 'w');
             fclose($fileHandler);
             /***********************
              **** DOWNLOAD FILE ****
              ***********************/
             $data = osc_file_get_contents("http://osclass.org/latest_version.php");
             $data = json_decode(substr($data, 1, strlen($data) - 3), true);
             $source_file = $data['url'];
             if ($source_file != '') {
                 $tmp = explode("/", $source_file);
                 $filename = end($tmp);
                 $result = osc_downloadFile($source_file, $filename);
                 if ($result) {
                     // Everything is OK, continue
                     /**********************
                      ***** UNZIP FILE *****
                      **********************/
                     @mkdir(ABS_PATH . 'oc-temp', 0777);
                     $res = osc_unzip_file(osc_content_path() . 'downloads/' . $filename, ABS_PATH . 'oc-temp/');
                     if ($res == 1) {
                         // Everything is OK, continue
                         /**********************
                          ***** COPY FILES *****
                          **********************/
                         $fail = -1;
                         if ($handle = opendir(ABS_PATH . 'oc-temp')) {
                             $fail = 0;
                             while (false !== ($_file = readdir($handle))) {
                                 if ($_file != '.' && $_file != '..' && $_file != 'remove.list' && $_file != 'upgrade.sql' && $_file != 'customs.actions') {
                                     $data = osc_copy(ABS_PATH . "oc-temp/" . $_file, ABS_PATH . $_file);
                                     if ($data == false) {
                                         $fail = 1;
                                     }
                                 }
                             }
                             closedir($handle);
                             //TRY TO REMOVE THE ZIP PACKAGE
                             @unlink(osc_content_path() . 'downloads/' . $filename);
                             if ($fail == 0) {
                                 // Everything is OK, continue
                                 /************************
                                  *** UPGRADE DATABASE ***
                                  ************************/
                                 $error_queries = array();
                                 if (file_exists(osc_lib_path() . 'osclass/installer/struct.sql')) {
                                     $sql = file_get_contents(osc_lib_path() . 'osclass/installer/struct.sql');
                                     $conn = DBConnectionClass::newInstance();
                                     $c_db = $conn->getOsclassDb();
                                     $comm = new DBCommandClass($c_db);
                                     $error_queries = $comm->updateDB(str_replace('/*TABLE_PREFIX*/', DB_TABLE_PREFIX, $sql));
                                 }
                                 if ($error_queries[0]) {
                                     // Everything is OK, continue
                                     /**********************************
                                      ** EXECUTING ADDITIONAL ACTIONS **
                                      **********************************/
                                     if (file_exists(osc_lib_path() . 'osclass/upgrade-funcs.php')) {
                                         // There should be no errors here
                                         define('AUTO_UPGRADE', true);
                                         require_once osc_lib_path() . 'osclass/upgrade-funcs.php';
                                     }
                                     // Additional actions is not important for the rest of the proccess
                                     // We will inform the user of the problems but the upgrade could continue
                                     /****************************
                                      ** REMOVE TEMPORARY FILES **
                                      ****************************/
                                     $path = ABS_PATH . 'oc-temp';
                                     $rm_errors = 0;
                                     $dir = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::CHILD_FIRST);
                                     for ($dir->rewind(); $dir->valid(); $dir->next()) {
                                         if ($dir->isDir()) {
                                             if ($dir->getFilename() != '.' && $dir->getFilename() != '..') {
                                                 if (!rmdir($dir->getPathname())) {
                                                     $rm_errors++;
                                                 }
                                             }
                                         } else {
                                             if (!unlink($dir->getPathname())) {
                                                 $rm_errors++;
                                             }
                                         }
                                     }
                                     if (!rmdir($path)) {
                                         $rm_errors++;
                                     }
                                     $deleted = @unlink(ABS_PATH . '.maintenance');
                                     if ($rm_errors == 0) {
                                         $message = __('Everything looks good! Your Osclass installation is up-to-date');
                                     } else {
                                         $message = __('Nearly everything looks good! Your Osclass installation is up-to-date, but there were some errors removing temporary files. Please manually remove the "oc-temp" folder');
                                         $error = 6;
                                         // Some errors removing files
                                     }
                                 } else {
                                     $sql_error_msg = $error_queries[2];
                                     $message = __('Problems when upgrading the database');
                                     $error = 5;
                                     // Problems upgrading the database
                                 }
                             } else {
                                 $message = __('Problems when copying files. Please check your permissions. ');
                                 $error = 4;
                                 // Problems copying files. Maybe permissions are not correct
                             }
                         } else {
                             $message = __('Nothing to copy');
                             $error = 99;
                             // Nothing to copy. THIS SHOULD NEVER HAPPEN, means we don't update any file!
                         }
                     } else {
                         $message = __('Unzip failed');
                         $error = 3;
                         // Unzip failed
                     }
                 } else {
                     $message = __('Download failed');
                     $error = 2;
                     // Download failed
                 }
             } else {
                 $message = __('Missing download URL');
                 $error = 1;
                 // Missing download URL
             }
             if ($error == 5) {
                 $message .= "<br /><br />" . __('We had some errors upgrading your database. The follwing queries failed:') . implode("<br />", $sql_error_msg);
             }
             echo $message;
             foreach ($perms as $k => $v) {
                 @chmod($k, $v);
             }
             break;
             /*******************************
              ** COMPLETE MARKET PROCESS **
              *******************************/
         /*******************************
          ** COMPLETE MARKET PROCESS **
          *******************************/
         case 'market':
             // AT THIS POINT WE KNOW IF THERE'S AN UPDATE OR NOT
             osc_csrf_check(false);
             $section = Params::getParam('section');
             $code = Params::getParam('code');
             $plugin = false;
             $re_enable = false;
             $message = "";
             $error = 0;
             $data = array();
             /************************
              *** CHECK VALID CODE ***
              ************************/
             if ($code != '' && $section != '') {
                 if (stripos($code, "http://") === FALSE) {
                     // OSCLASS OFFICIAL REPOSITORY
                     $url = osc_market_url($section, $code);
                     $data = json_decode(osc_file_get_contents($url), true);
                 } else {
                     // THIRD PARTY REPOSITORY
                     if (osc_market_external_sources()) {
                         $data = json_decode(osc_file_get_contents($code), true);
                     } else {
                         echo json_encode(array('error' => 8, 'error_msg' => __('No external sources are allowed')));
                         break;
                     }
                 }
                 /***********************
                  **** DOWNLOAD FILE ****
                  ***********************/
                 if (isset($data['s_update_url']) && isset($data['s_source_file']) && isset($data['e_type'])) {
                     if ($data['e_type'] == 'THEME') {
                         $folder = 'themes/';
                     } else {
                         if ($data['e_type'] == 'LANGUAGE') {
                             $folder = 'languages/';
                         } else {
                             // PLUGINS
                             $folder = 'plugins/';
                             $plugin = Plugins::findByUpdateURI($data['s_update_url']);
                             if ($plugin != false) {
                                 if (Plugins::isEnabled($plugin)) {
                                     Plugins::runHook($plugin . '_disable');
                                     Plugins::deactivate($plugin);
                                     $re_enable = true;
                                 }
                             }
                         }
                     }
                     $filename = $data['s_update_url'] . "_" . $data['s_version'] . ".zip";
                     $url_source_file = $data['s_source_file'];
                     //                            error_log('Source file: ' . $url_source_file);
                     //                            error_log('Filename: ' . $filename);
                     $result = osc_downloadFile($url_source_file, $filename);
                     if ($result) {
                         // Everything is OK, continue
                         /**********************
                          ***** UNZIP FILE *****
                          **********************/
                         @mkdir(ABS_PATH . 'oc-temp', 0777);
                         $res = osc_unzip_file(osc_content_path() . 'downloads/' . $filename, osc_content_path() . 'downloads/oc-temp/');
                         if ($res == 1) {
                             // Everything is OK, continue
                             /**********************
                              ***** COPY FILES *****
                              **********************/
                             $fail = -1;
                             if ($handle = opendir(osc_content_path() . 'downloads/oc-temp')) {
                                 $folder_dest = ABS_PATH . "oc-content/" . $folder;
                                 if (function_exists('posix_getpwuid')) {
                                     $current_user = posix_getpwuid(posix_geteuid());
                                     $ownerFolder = posix_getpwuid(fileowner($folder_dest));
                                 }
                                 $fail = 0;
                                 while (false !== ($_file = readdir($handle))) {
                                     if ($_file != '.' && $_file != '..') {
                                         $copyprocess = osc_copy(osc_content_path() . "downloads/oc-temp/" . $_file, $folder_dest . $_file);
                                         if ($copyprocess == false) {
                                             $fail = 1;
                                         }
                                     }
                                 }
                                 closedir($handle);
                                 // Additional actions is not important for the rest of the proccess
                                 // We will inform the user of the problems but the upgrade could continue
                                 // Also remove the zip package
                                 /****************************
                                  ** REMOVE TEMPORARY FILES **
                                  ****************************/
                                 @unlink(osc_content_path() . 'downloads/' . $filename);
                                 $path = osc_content_path() . 'downloads/oc-temp';
                                 $rm_errors = 0;
                                 $dir = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::CHILD_FIRST);
                                 for ($dir->rewind(); $dir->valid(); $dir->next()) {
                                     if ($dir->isDir()) {
                                         if ($dir->getFilename() != '.' && $dir->getFilename() != '..') {
                                             if (!rmdir($dir->getPathname())) {
                                                 $rm_errors++;
                                             }
                                         }
                                     } else {
                                         if (!unlink($dir->getPathname())) {
                                             $rm_errors++;
                                         }
                                     }
                                 }
                                 if (!rmdir($path)) {
                                     $rm_errors++;
                                 }
                                 if ($fail == 0) {
                                     // Everything is OK, continue
                                     if ($data['e_type'] != 'THEME' && $data['e_type'] != 'LANGUAGE') {
                                         if ($plugin != false && $re_enable) {
                                             $enabled = Plugins::activate($plugin);
                                             if ($enabled) {
                                                 Plugins::runHook($plugin . '_enable');
                                             }
                                         }
                                     }
                                     // recount plugins&themes for update
                                     if ($section == 'plugins') {
                                         osc_check_plugins_update(true);
                                     } else {
                                         if ($section == 'themes') {
                                             osc_check_themes_update(true);
                                         } else {
                                             if ($section == 'languages') {
                                                 // load oc-content/
                                                 if (osc_checkLocales()) {
                                                     $message .= __('The language has been installed correctly');
                                                 } else {
                                                     $message .= __('There was a problem adding the language');
                                                     $error = 8;
                                                 }
                                                 osc_check_languages_update(true);
                                             }
                                         }
                                     }
                                     if ($rm_errors == 0) {
                                         $message = __('Everything looks good!');
                                         $error = 0;
                                     } else {
                                         $message = __('Nearly everything looks good! but there were some errors removing temporary files. Please manually remove the \\"oc-temp\\" folder');
                                         $error = 6;
                                         // Some errors removing files
                                     }
                                 } else {
                                     $message = __('Problems when copying files. Please check your permissions. ');
                                     if ($current_user['uid'] != $ownerFolder['uid']) {
                                         if (function_exists('posix_getgrgid')) {
                                             $current_group = posix_getgrgid($current_user['gid']);
                                             $message .= '<p><strong>' . sprintf(__('NOTE: Web user and destination folder user is not the same, you might have an issue there. <br/>Do this in your console:<br/>chown -R %s:%s %s'), $current_user['name'], $current_group['name'], $folder_dest) . '</strong></p>';
                                         }
                                     }
                                     $error = 4;
                                     // Problems copying files. Maybe permissions are not correct
                                 }
                             } else {
                                 $message = __('Nothing to copy');
                                 $error = 99;
                                 // Nothing to copy. THIS SHOULD NEVER HAPPEN, means we don't update any file!
                             }
                         } else {
                             $message = __('Unzip failed');
                             $error = 3;
                             // Unzip failed
                         }
                     } else {
                         $message = __('Download failed');
                         $error = 2;
                         // Download failed
                     }
                 } else {
                     $message = __('Input code not valid');
                     $error = 7;
                     // Input code not valid
                 }
             } else {
                 $message = __('Missing download URL');
                 $error = 1;
                 // Missing download URL
             }
             echo json_encode(array('error' => $error, 'message' => $message, 'data' => $data));
             break;
         case 'check_market':
             // AT THIS POINT WE KNOW IF THERE'S AN UPDATE OR NOT
             $section = Params::getParam('section');
             $code = Params::getParam('code');
             $data = array();
             /************************
              *** CHECK VALID CODE ***
              ************************/
             if ($code != '' && $section != '') {
                 if (stripos($code, "http://") === FALSE) {
                     // OSCLASS OFFICIAL REPOSITORY
                     $data = json_decode(osc_file_get_contents(osc_market_url($section, $code)), true);
                 } else {
                     // THIRD PARTY REPOSITORY
                     if (osc_market_external_sources()) {
                         $data = json_decode(osc_file_get_contents($code), true);
                     } else {
                         echo json_encode(array('error' => 3, 'error_msg' => __('No external sources are allowed')));
                         break;
                     }
                 }
                 if (!isset($data['s_source_file']) || !isset($data['s_update_url'])) {
                     $data = array('error' => 2, 'error_msg' => __('Invalid code'));
                 }
             } else {
                 $data = array('error' => 1, 'error_msg' => __('No code was submitted'));
             }
             echo json_encode($data);
             break;
         case 'market_data':
             $section = Params::getParam('section');
             $page = Params::getParam("mPage");
             $featured = Params::getParam("featured");
             $sort = Params::getParam("sort");
             $order = Params::getParam("order");
             // for the moment this value is static
             $length = 9;
             if ($page >= 1) {
                 $page--;
             }
             $url = osc_market_url($section) . "page/" . $page . '/';
             if ($length != '' && is_numeric($length)) {
                 $url .= 'length/' . $length . '/';
             }
             if ($sort != '') {
                 $url .= 'order/' . $sort;
                 if ($order != '') {
                     $url .= '/' . $order;
                 }
             }
             if ($featured != '') {
                 $url = osc_market_featured_url($section);
             }
             $data = array();
             $data = json_decode(osc_file_get_contents($url), true);
             if (!isset($data[$section])) {
                 $data = array('error' => 1, 'error_msg' => __('No market data'));
             }
             echo 'var market_data = window.market_data || {}; market_data.' . $section . ' = ' . json_encode($data) . ';';
             break;
         case 'local_market':
             // AVOID CROSS DOMAIN PROBLEMS OF AJAX REQUEST
             $marketPage = Params::getParam("mPage");
             if ($marketPage >= 1) {
                 $marketPage--;
             }
             $out = osc_file_get_contents(osc_market_url(Params::getParam("section")) . "page/" . $marketPage);
             $array = json_decode($out, true);
             // do pagination
             $pageActual = $array['page'];
             $totalPages = ceil($array['total'] / $array['sizePage']);
             $params = array('total' => $totalPages, 'selected' => $pageActual, 'url' => '#{PAGE}', 'sides' => 5);
             // set pagination
             $pagination = new Pagination($params);
             $aux = $pagination->doPagination();
             $array['pagination_content'] = $aux;
             // encode to json
             echo json_encode($array);
             break;
         case 'dashboardbox_market':
             $error = 0;
             // make market call
             $url = getPreference('marketURL') . 'dashboardbox/';
             $content = '';
             if (false === ($json = @osc_file_get_contents($url))) {
                 $error = 1;
             } else {
                 $content = $json;
             }
             if ($error == 1) {
                 echo json_encode(array('error' => 1));
             } else {
                 // replace content with correct urls
                 $content = str_replace('{URL_MARKET_THEMES}', osc_admin_base_url(true) . '?page=market&action=themes', $content);
                 $content = str_replace('{URL_MARKET_PLUGINS}', osc_admin_base_url(true) . '?page=market&action=plugins', $content);
                 echo json_encode(array('html' => $content));
             }
             break;
         case 'location_stats':
             osc_csrf_check(false);
             $workToDo = osc_update_location_stats();
             if ($workToDo > 0) {
                 $array['status'] = 'more';
                 $array['pending'] = $workToDo;
                 echo json_encode($array);
             } else {
                 $array['status'] = 'done';
                 echo json_encode($array);
             }
             break;
         case 'error_permissions':
             echo json_encode(array('error' => __("You don't have the necessary permissions")));
             break;
         default:
             echo json_encode(array('error' => __('no action defined')));
             break;
     }
     // clear all keep variables into session
     Session::newInstance()->_dropKeepForm();
     Session::newInstance()->_clearVariables();
 }
Example #13
0
 /**
  * @return string Name of the export zip file
  * @throws \Cms\Exception
  */
 protected function createExportZip()
 {
     $zipFile = $this->currentExportDirectory . DIRECTORY_SEPARATOR . $this->currentExportName . '.' . self::EXPORT_FILE_EXTENSION;
     $zip = new \ZipArchive();
     if ($zip->open($zipFile, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) !== true) {
         throw new CmsException(36, __METHOD__, __LINE__, array('file' => $zipFile));
     }
     $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->currentExportDirectory), \RecursiveIteratorIterator::SELF_FIRST);
     while ($iterator->valid()) {
         if (!$iterator->isDot()) {
             if ($iterator->isDir()) {
                 $test = $iterator->getSubPathName();
                 $zip->addEmptyDir(str_replace('\\', '/', $iterator->getSubPathName()));
             } else {
                 $test = $iterator->getSubPathName();
                 $zip->addFile($iterator->key(), str_replace('\\', '/', $iterator->getSubPathName()));
             }
         }
         $iterator->next();
     }
     $zip->close();
     return $zipFile;
 }
Example #14
0
$config->start_time = time();
if (!$config->quiet) {
    $output->e('');
    $output->e('Scan started on: ' . date("Y-m-d H:i:s", time()), 1, 'white');
    $output->e("Files:                              ", 0, 'white');
    // 30 characters of padding at the end
}
/* The main iterator and some runtime variables */
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('./'));
$infected = array();
$scanned = 0;
$hits = 0;
/* And off we go into the loop */
while ($it->valid()) {
    try {
        if (!$it->isDot() and !$it->isDir()) {
            // First check the MD5 sum of the file.
            // Matched files will not be opened for reading to save time.
            // Only scan files bigger than 0 bytes and less than 2MB
            $fmd5 = md5_file($it->key());
            // Check if AppFocus has been defined and process the file first.
            if ($config->app_focused_run) {
                if (!$config->afo->hash_match($it->key(), $fmd5)) {
                    $hits++;
                    $infected[$it->getRealPath()] = array('explain' => '[modified_core_file]', 'score' => 100);
                    $it->next();
                    continue;
                }
            }
            if ($it->getSize() > 0 and $it->getSize() < 2048576) {
                if (in_array($fmd5, $false_positives)) {
Example #15
0
/**
 * Step 1: Require the Slim Framework
 *
 * If you are not using Composer, you need to require the
 * Slim Framework and register its PSR-0 autoloader.
 *
 * If you are using Composer, you can skip this step.
 */
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
//load WRR namespace
$dir_iterator = new RecursiveDirectoryIterator('./wrr');
$iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::SELF_FIRST);
$availableCommands = [];
foreach ($iterator as $fileInfo) {
    if ($iterator->isDot() || $iterator->isDir()) {
        continue;
    }
    require $fileInfo->getPath() . DIRECTORY_SEPARATOR . $fileInfo->getFilename();
}
/**
 * Step 2: Instantiate a Slim application
 *
 * This example instantiates a Slim application using
 * its default settings. However, you will usually configure
 * your Slim application now by passing an associative array
 * of setting names and values into the application constructor.
 */
$app = new \Slim\Slim();
require '.env';
if (empty($user) || empty($pass) || empty($host) || empty($dbname)) {
Example #16
0
 public function build_files()
 {
     $id = 0;
     $partial_stop = 0;
     $maxSize = 0;
     $indexStep = 0;
     $maxInserts = 0;
     $files = array();
     if (isset($_POST['partialStop'])) {
         $partial_stop = (int) $_POST['partialStop'];
     }
     //Max Filesize check
     if (isset($_POST['maxSize'])) {
         $maxSize = (int) $_POST['maxSize'];
     }
     if (!$maxSize) {
         $maxSize = 5242880;
         //Default value.
     }
     //IndexStep check
     if (isset($_POST['indexStep'])) {
         $indexStep = (int) $_POST['indexStep'];
     }
     if (!$indexStep) {
         $indexStep = 3000;
     }
     //MaxInserts check
     if (isset($_POST['maxInserts'])) {
         $maxInserts = (int) $_POST['maxInserts'];
     }
     if (!$maxInserts) {
         $maxInserts = 300;
     }
     chdir(JPATH_ROOT);
     //If we don't have a partial stop count, then this is a new request.
     //We should therefore clear the database.
     if (!$partial_stop) {
         $db = JFactory::getDbo();
         $query = $db->getQuery(true);
         $db->setQuery("DELETE FROM " . $db->quoteName('#__jhackguard_scan_files'));
         $db->query();
     }
     $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('./'));
     /* And off we go into the loop */
     $sql_delimiter = 0;
     $total_count = 0;
     $stopped = 0;
     while ($it->valid()) {
         //We do no need ., .., or directories. Only files.
         if (!$it->isDot() and !$it->isDir()) {
             if ($it->getSize() > 0 and $it->getSize() < $maxSize) {
                 //We also do not need empty files or files bigger than 5MB.
                 $total_count++;
                 if ($partial_stop > 0 and $partial_stop > $total_count) {
                     $it->next();
                     continue;
                     //We don't want these items. We indexed them the last run.
                 }
                 $files[] = $it->getRealPath();
                 $sql_delimiter++;
                 if ($sql_delimiter > $maxInserts) {
                     //Perform insert.
                     $db = JFactory::getDbo();
                     $query = $db->getQuery(true);
                     $query->insert($db->quoteName('#__jhackguard_scan_files'));
                     $query->columns('fname');
                     foreach ($files as $path) {
                         $query->values($db->quote($path));
                     }
                     $db->setQuery($query);
                     $db->query();
                     //Reset sql_delimiter
                     $sql_delimiter = 0;
                     //Reset files array
                     $files = array();
                 }
                 if ($total_count == $partial_stop + $indexStep) {
                     $stopped = 1;
                     break;
                     //We have reached the 3k limit per run.
                 }
             }
         }
         $it->next();
     }
     //Did we miss to import the last batch of the files?
     if (count($files) > 0) {
         //Yup..
         $db = JFactory::getDbo();
         $query = $db->getQuery(true);
         $query->insert($db->quoteName('#__jhackguard_scan_files'));
         $query->columns('fname');
         foreach ($files as $path) {
             $query->values($db->quote($path));
         }
         $db->setQuery($query);
         $db->query();
         $files = array();
     }
     if ($stopped) {
         $partial_stop = $partial_stop + $indexStep;
         echo json_encode(array("success" => false, "partialStop" => $partial_stop, "partialRun" => true));
     } else {
         //Seems like we finished successfully. WOOHOO!
         //And the total count is...
         $db = JFactory::getDbo();
         $query = $db->getQuery(true);
         $query->select("COUNT(*) as total");
         $query->from($db->quoteName('#__jhackguard_scan_files'));
         $db->setQuery($query);
         $list = $db->loadColumn();
         echo json_encode(array("success" => true, "count" => $list[0]));
     }
 }
Example #17
0
 /**
  * Test that the file_temp_cleanup_task removes directories and
  * files as expected.
  */
 public function test_file_temp_cleanup_task()
 {
     global $CFG;
     // Create directories.
     $dir = $CFG->tempdir . DIRECTORY_SEPARATOR . 'backup' . DIRECTORY_SEPARATOR . 'backup01' . DIRECTORY_SEPARATOR . 'courses';
     mkdir($dir, 0777, true);
     // Create files to be checked and then deleted.
     $file01 = $dir . DIRECTORY_SEPARATOR . 'sections.xml';
     file_put_contents($file01, 'test data 001');
     $file02 = $dir . DIRECTORY_SEPARATOR . 'modules.xml';
     file_put_contents($file02, 'test data 002');
     // Change the time modified for the first file, to a time that will be deleted by the task (greater than seven days).
     touch($file01, time() - 8 * 24 * 3600);
     $task = \core\task\manager::get_scheduled_task('\\core\\task\\file_temp_cleanup_task');
     $this->assertInstanceOf('\\core\\task\\file_temp_cleanup_task', $task);
     $task->execute();
     // Scan the directory. Only modules.xml should be left.
     $filesarray = scandir($dir);
     $this->assertEquals('modules.xml', $filesarray[2]);
     $this->assertEquals(3, count($filesarray));
     // Change the time modified on modules.xml.
     touch($file02, time() - 8 * 24 * 3600);
     // Change the time modified on the courses directory.
     touch($CFG->tempdir . DIRECTORY_SEPARATOR . 'backup' . DIRECTORY_SEPARATOR . 'backup01' . DIRECTORY_SEPARATOR . 'courses', time() - 8 * 24 * 3600);
     // Run the scheduled task to remove the file and directory.
     $task->execute();
     $filesarray = scandir($CFG->tempdir . DIRECTORY_SEPARATOR . 'backup' . DIRECTORY_SEPARATOR . 'backup01');
     // There should only be two items in the array, '.' and '..'.
     $this->assertEquals(2, count($filesarray));
     // Change the time modified on all of the files and directories.
     $dir = new \RecursiveDirectoryIterator($CFG->tempdir);
     // Show all child nodes prior to their parent.
     $iter = new \RecursiveIteratorIterator($dir, \RecursiveIteratorIterator::CHILD_FIRST);
     for ($iter->rewind(); $iter->valid(); $iter->next()) {
         if ($iter->isDir() && !$iter->isDot()) {
             $node = $iter->getRealPath();
             touch($node, time() - 8 * 24 * 3600);
         }
     }
     // Run the scheduled task again to remove all of the files and directories.
     $task->execute();
     $filesarray = scandir($CFG->tempdir);
     // All of the files and directories should be deleted.
     // There should only be two items in the array, '.' and '..'.
     $this->assertEquals(2, count($filesarray));
 }
Example #18
0
 case 'download-file':
     if (Params::getParam('file') != '') {
         $tmp = explode("/", Params::getParam('file'));
         $filename = end($tmp);
         osc_downloadFile(Params::getParam('file'), $filename);
         $message = __('File downloaded correctly');
     } else {
         $message = __('Missing filename');
     }
     break;
 case 'empty-temp':
     $message = __("Removing temp-directory");
     $path = ABS_PATH . 'oc-temp';
     $dir = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::CHILD_FIRST);
     for ($dir->rewind(); $dir->valid(); $dir->next()) {
         if ($dir->isDir()) {
             if ($dir->getFilename() != '.' && $dir->getFilename() != '..') {
                 rmdir($dir->getPathname());
             }
         } else {
             unlink($dir->getPathname());
         }
     }
     rmdir($path);
     break;
 case 'db-backup':
     osc_dbdump();
     break;
 case 'zip-osclass':
     $archive_name = ABS_PATH . "OSClass_backup." . date('YmdHis') . ".zip";
     $archive_folder = ABS_PATH;
Example #19
0
 /**
  * [util function] clears the cached templates if they are older than the given time
  *
  * @param int $olderThan minimum time (in seconds) required for a cached template to be cleared
  * @return int the amount of templates cleared
  */
 public function clearCache($olderThan = -1)
 {
     $cacheDirs = new RecursiveDirectoryIterator($this->getCacheDir());
     $cache = new RecursiveIteratorIterator($cacheDirs);
     $expired = time() - $olderThan;
     $count = 0;
     foreach ($cache as $file) {
         if ($cache->isDot() || $cache->isDir() || substr($file, -5) !== '.html') {
             continue;
         }
         if ($cache->getCTime() < $expired) {
             $count += unlink((string) $file) ? 1 : 0;
         }
     }
     return $count;
 }
Example #20
0
 /**
  * Recursively remove a directory
  *
  * @param string $dirname
  * @param boolean $followSymlinks
  * @return boolean
  */
 function RecursiveRmdir($dirname, $followSymlinks = false)
 {
     if (is_dir($dirname) && !is_link($dirname)) {
         if (!is_writable($dirname)) {
             throw new \Exception(sprintf('%s is not writable!', $dirname));
         }
         $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dirname), \RecursiveIteratorIterator::CHILD_FIRST);
         while ($iterator->valid()) {
             if (!$iterator->isDot()) {
                 if (!$iterator->isWritable()) {
                     throw new \Exception(sprintf('%s is not writable!', $iterator->getPathName()));
                 }
                 if ($iterator->isLink() && $followLinks === false) {
                     $iterator->next();
                 }
                 if ($iterator->isFile()) {
                     @unlink($iterator->getPathName());
                 } elseif ($iterator->isDir()) {
                     @rmdir($iterator->getPathName());
                 }
             }
             $iterator->next();
         }
         unset($iterator);
         return @rmdir($dirname);
     } else {
         throw new \Exception(sprintf('%s does not exist!', $dirname));
     }
 }
Example #21
0
 function doModel()
 {
     //specific things for this class
     switch ($this->action) {
         case 'bulk_actions':
             break;
         case 'regions':
             //Return regions given a countryId
             $regions = Region::newInstance()->getByCountry(Params::getParam("countryId"));
             echo json_encode($regions);
             break;
         case 'cities':
             //Returns cities given a regionId
             $cities = City::newInstance()->getByRegion(Params::getParam("regionId"));
             echo json_encode($cities);
             break;
         case 'location':
             // This is the autocomplete AJAX
             $cities = City::newInstance()->ajax(Params::getParam("term"));
             echo json_encode($cities);
             break;
         case 'alerts':
             // Allow to register to an alert given (not sure it's used on admin)
             $alert = Params::getParam("alert");
             $email = Params::getParam("email");
             $userid = Params::getParam("userid");
             if ($alert != '' && $email != '') {
                 Alerts::newInstance()->insert(array('fk_i_user_id' => $userid, 's_email' => $email, 's_search' => $alert, 'e_type' => 'DAILY'));
                 echo "1";
                 return true;
             }
             echo '0';
             return false;
             break;
         case 'runhook':
             //Run hooks
             $hook = Params::getParam("hook");
             switch ($hook) {
                 case 'item_form':
                     $catId = Params::getParam("catId");
                     if ($catId != '') {
                         osc_run_hook("item_form", $catId);
                     } else {
                         osc_run_hook("item_form");
                     }
                     break;
                 case 'item_edit':
                     $catId = Params::getParam("catId");
                     $itemId = Params::getParam("itemId");
                     osc_run_hook("item_edit", $catId, $itemId);
                     break;
                 default:
                     if ($hook == '') {
                         return false;
                     } else {
                         osc_run_hook($hook);
                     }
                     break;
             }
             break;
         case 'items':
             // Return items (use external file oc-admin/ajax/item_processing.php)
             require_once osc_admin_base_path() . 'ajax/items_processing.php';
             $items_processing = new items_processing_ajax(Params::getParamsAsArray("get"));
             break;
         case 'custom':
             // Execute via AJAX custom file
             $ajaxfile = Params::getParam("ajaxfile");
             if ($ajaxfile != '') {
                 require_once osc_admin_base_path() . $ajaxfile;
             } else {
                 echo json_encode(array('error' => __('no action defined')));
             }
             break;
             /******************************
              ** COMPLETE UPGRADE PROCESS **
              ******************************/
         /******************************
          ** COMPLETE UPGRADE PROCESS **
          ******************************/
         case 'upgrade':
             // AT THIS POINT WE KNOW IF THERE'S AN UPDATE OR NOT
             $message = "";
             $error = 0;
             $remove_error_msg = "";
             $sql_error_msg = "";
             $rm_errors = 0;
             $perms = osc_save_permissions();
             osc_change_permissions();
             /***********************
              **** DOWNLOAD FILE ****
              ***********************/
             if (Params::getParam('file') != '') {
                 $tmp = explode("/", Params::getParam('file'));
                 $filename = end($tmp);
                 $result = osc_downloadFile(Params::getParam('file'), $filename);
                 if ($result) {
                     // Everything is OK, continue
                     /**********************
                      ***** UNZIP FILE *****
                      **********************/
                     @mkdir(ABS_PATH . 'oc-temp', 0777);
                     $res = osc_unzip_file(osc_content_path() . 'downloads/' . $filename, ABS_PATH . 'oc-temp/');
                     if ($res == 1) {
                         // Everything is OK, continue
                         /**********************
                          ***** COPY FILES *****
                          **********************/
                         $fail = -1;
                         if ($handle = opendir(ABS_PATH . 'oc-temp')) {
                             $fail = 0;
                             while (false !== ($_file = readdir($handle))) {
                                 if ($_file != '.' && $_file != '..' && $_file != 'remove.list' && $_file != 'upgrade.sql' && $_file != 'customs.actions') {
                                     $data = osc_copy(ABS_PATH . "oc-temp/" . $_file, ABS_PATH . $_file);
                                     if ($data == false) {
                                         $fail = 1;
                                     }
                                 }
                             }
                             closedir($handle);
                             if ($fail == 0) {
                                 // Everything is OK, continue
                                 /**********************
                                  **** REMOVE FILES ****
                                  **********************/
                                 if (file_exists(ABS_PATH . 'oc-temp/remove.list')) {
                                     $lines = file(ABS_PATH . 'oc-temp/remove.list', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
                                     foreach ($lines as $line_num => $r_file) {
                                         $unlink = @unlink(ABS_PATH . $r_file);
                                         if (!$unlink) {
                                             $remove_error_msg .= __('Error removing file: ') . $r_file . "<br/>";
                                         }
                                     }
                                 }
                                 // Removing files is not important for the rest of the proccess
                                 // We will inform the user of the problems but the upgrade could continue
                                 /************************
                                  *** UPGRADE DATABASE ***
                                  ************************/
                                 $error_queries = array();
                                 if (file_exists(osc_lib_path() . 'osclass/installer/struct.sql')) {
                                     $sql = file_get_contents(osc_lib_path() . 'osclass/installer/struct.sql');
                                     $conn = getConnection();
                                     $error_queries = $conn->osc_updateDB(str_replace('/*TABLE_PREFIX*/', DB_TABLE_PREFIX, $sql));
                                 }
                                 if ($error_queries[0]) {
                                     // Everything is OK, continue
                                     /**********************************
                                      ** EXECUTING ADDITIONAL ACTIONS **
                                      **********************************/
                                     if (file_exists(osc_lib_path() . 'osclass/upgrade-funcs.php')) {
                                         // There should be no errors here
                                         require_once osc_lib_path() . 'osclass/upgrade-funcs.php';
                                     }
                                     // Additional actions is not important for the rest of the proccess
                                     // We will inform the user of the problems but the upgrade could continue
                                     /****************************
                                      ** REMOVE TEMPORARY FILES **
                                      ****************************/
                                     $path = ABS_PATH . 'oc-temp';
                                     $rm_errors = 0;
                                     $dir = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::CHILD_FIRST);
                                     for ($dir->rewind(); $dir->valid(); $dir->next()) {
                                         if ($dir->isDir()) {
                                             if ($dir->getFilename() != '.' && $dir->getFilename() != '..') {
                                                 if (!rmdir($dir->getPathname())) {
                                                     $rm_errors++;
                                                 }
                                             }
                                         } else {
                                             if (!unlink($dir->getPathname())) {
                                                 $rm_errors++;
                                             }
                                         }
                                     }
                                     if (!rmdir($path)) {
                                         $rm_errors++;
                                     }
                                     if ($rm_errors == 0) {
                                         $message = __('Everything was OK! Your OSClass installation is updated');
                                     } else {
                                         $message = __('Almost everything was OK! Your OSClass installation is updated, but there were some errors removing temporary files. Please, remove manually the "oc-temp" folder', 'admin');
                                         $error = 6;
                                         // Some errors removing files
                                     }
                                 } else {
                                     $sql_error_msg = $error_queries[2];
                                     $message = __('Problems upgrading the database', 'admin');
                                     $error = 5;
                                     // Problems upgrading the database
                                 }
                             } else {
                                 $message = __('Problems copying files. Maybe permissions are not correct', 'admin');
                                 $error = 4;
                                 // Problems copying files. Maybe permissions are not correct
                             }
                         } else {
                             $message = __('Nothing to copy', 'admin');
                             $error = 99;
                             // Nothing to copy. THIS SHOULD NEVER HAPPENS, means we dont update any file!
                         }
                     } else {
                         $message = __('Unzip failed', 'admin');
                         $error = 3;
                         // Unzip failed
                     }
                 } else {
                     $message = __('Download failed', 'admin');
                     $error = 2;
                     // Download failed
                 }
             } else {
                 $message = __('Missing download URL', 'admin');
                 $error = 1;
                 // Missing download URL
             }
             if ($remove_error_msg != '') {
                 if ($error == 0) {
                     $message .= "<br /><br />" . __('We had some errors removing files, those are not super-sensitive errors, so we continued upgrading your installation. Please remove the following files (you already have OSClass upgraded, but to ensure maximun performance)', 'admin');
                 }
             }
             if ($error == 5) {
                 $message .= "<br /><br />" . __('We had some errors upgrading your database. The follwing queries failed', 'admin') . implode("<br />", $sql_error_msg);
             }
             echo $message;
             foreach ($perms as $k => $v) {
                 chmod($k, $v);
             }
             break;
         default:
             echo json_encode(array('error' => __('no action defined')));
             break;
     }
 }
Example #22
0
 /**
  * Get an flat array of folder files.
  *
  * @param string $pageFolder Folder path
  * @return array | false
  */
 protected function _folderFilePaths($pageFolder, $indexPagePath)
 {
     $files = array();
     if (!file_exists($pageFolder) || !is_dir($pageFolder)) {
         return $files;
     }
     $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($pageFolder), RecursiveIteratorIterator::SELF_FIRST);
     while ($it->valid()) {
         if (!$it->isDot() && !$it->isDir()) {
             // We account for windows server issue.
             $_path = str_replace(DS, '/', $it->getSubPathName());
             if ($_path != $indexPagePath && array_search($_path, $files) === false && $this->_pathValid($_path)) {
                 $files[] = $_path;
             }
         }
         $it->next();
     }
     return $files;
 }
Example #23
0
 function doModel()
 {
     //specific things for this class
     switch ($this->action) {
         case 'bulk_actions':
             break;
         case 'regions':
             //Return regions given a countryId
             $regions = Region::newInstance()->getByCountry(Params::getParam("countryId"));
             echo json_encode($regions);
             break;
         case 'cities':
             //Returns cities given a regionId
             $cities = City::newInstance()->getByRegion(Params::getParam("regionId"));
             echo json_encode($cities);
             break;
         case 'location':
             // This is the autocomplete AJAX
             $cities = City::newInstance()->ajax(Params::getParam("term"));
             echo json_encode($cities);
             break;
         case 'alerts':
             // Allow to register to an alert given (not sure it's used on admin)
             $alert = Params::getParam("alert");
             $email = Params::getParam("email");
             $userid = Params::getParam("userid");
             if ($alert != '' && $email != '') {
                 Alerts::newInstance()->insert(array('fk_i_user_id' => $userid, 's_email' => $email, 's_search' => $alert, 'e_type' => 'DAILY'));
                 echo "1";
                 return true;
             }
             echo '0';
             break;
         case 'runhook':
             //Run hooks
             $hook = Params::getParam("hook");
             switch ($hook) {
                 case 'item_form':
                     $catId = Params::getParam("catId");
                     if ($catId != '') {
                         osc_run_hook("item_form", $catId);
                     } else {
                         osc_run_hook("item_form");
                     }
                     break;
                 case 'item_edit':
                     $catId = Params::getParam("catId");
                     $itemId = Params::getParam("itemId");
                     osc_run_hook("item_edit", $catId, $itemId);
                     break;
                 default:
                     if ($hook == '') {
                         return false;
                     } else {
                         osc_run_hook($hook);
                     }
                     break;
             }
             break;
         case 'items':
             // Return items (use external file oc-admin/ajax/item_processing.php)
             require_once osc_admin_base_path() . 'ajax/items_processing.php';
             $items_processing = new items_processing_ajax(Params::getParamsAsArray("get"));
             break;
         case 'media':
             // Return items (use external file oc-admin/ajax/media_processing.php)
             require_once osc_admin_base_path() . 'ajax/media_processing.php';
             $media_processing = new media_processing_ajax(Params::getParamsAsArray("get"));
             break;
         case 'categories_order':
             // Save the order of the categories
             $aIds = Params::getParam('list');
             $orderParent = 0;
             $orderSub = 0;
             $catParent = 0;
             $catManager = Category::newInstance();
             foreach ($aIds as $id => $parent) {
                 if ($parent == 'root') {
                     if (!$catManager->update_order($id, $orderParent)) {
                         $error = 1;
                     }
                     // set parent category
                     $conditions = array('pk_i_id' => $id);
                     $array['fk_i_parent_id'] = DB_CONST_NULL;
                     if (!$catManager->update($array, $conditions) > 0) {
                         $error = 1;
                     }
                     $orderParent++;
                 } else {
                     if ($parent != $catParent) {
                         $catParent = $parent;
                         $orderSub = 0;
                     }
                     if (!$catManager->update_order($id, $orderSub)) {
                         $error = 1;
                     }
                     // set parent category
                     $conditions = array('pk_i_id' => $id);
                     $array['fk_i_parent_id'] = $catParent;
                     if (!$catManager->update($array, $conditions) > 0) {
                         $error = 1;
                     }
                     $orderSub++;
                 }
             }
             $result = "{";
             $error = 0;
             if ($error) {
                 $result .= '"error" : "' . __("Some error ocurred") . '"';
             } else {
                 $result .= '"ok" : "' . __("Order saved") . '"';
             }
             $result .= "}";
             echo $result;
             break;
         case 'category_edit_iframe':
             $this->_exportVariableToView("category", Category::newInstance()->findByPrimaryKey(Params::getParam("id")));
             $this->_exportVariableToView("languages", OSCLocale::newInstance()->listAllEnabled());
             $this->doView("categories/iframe.php");
             break;
         case 'field_categories_iframe':
             $selected = Field::newInstance()->categories(Params::getParam("id"));
             if ($selected == null) {
                 $selected = array();
             }
             $this->_exportVariableToView("selected", $selected);
             $this->_exportVariableToView("field", Field::newInstance()->findByPrimaryKey(Params::getParam("id")));
             $this->_exportVariableToView("categories", Category::newInstance()->toTreeAll());
             $this->doView("fields/iframe.php");
             break;
         case 'field_categories_post':
             $error = 0;
             if (!$error) {
                 try {
                     $field = Field::newInstance()->findByName(Params::getParam("s_name"));
                     if (!isset($field['pk_i_id']) || isset($field['pk_i_id']) && $field['pk_i_id'] == Params::getParam("id")) {
                         Field::newInstance()->cleanCategoriesFromField(Params::getParam("id"));
                         $slug = Params::getParam("field_slug") != '' ? Params::getParam("field_slug") : Params::getParam("id");
                         $slug = preg_replace('|([-]+)|', '-', preg_replace('|[^a-z0-9_-]|', '-', strtolower($slug)));
                         Field::newInstance()->update(array('s_name' => Params::getParam("s_name"), 'e_type' => Params::getParam("field_type"), 's_slug' => $slug, 'b_required' => Params::getParam("field_required") == "1" ? 1 : 0, 's_options' => Params::getParam('s_options')), array('pk_i_id' => Params::getParam("id")));
                         Field::newInstance()->insertCategories(Params::getParam("id"), Params::getParam("categories"));
                     } else {
                         $error = 1;
                         $message = __("Sorry, you already have one field with that name");
                     }
                 } catch (Exception $e) {
                     $error = 1;
                     $message = __("Error while updating.");
                 }
             }
             $result = "{";
             if ($error) {
                 $result .= '"error" : "';
                 $result .= $message;
                 $result .= '"';
             } else {
                 $result .= '"ok" : "' . __("Saved") . '", "text" : "' . Params::getParam("s_name") . '"';
             }
             $result .= "}";
             echo $result;
             break;
         case 'delete_field':
             $id = Params::getParam("id");
             $error = 0;
             try {
                 $fieldManager = Field::newInstance();
                 $fieldManager->deleteByPrimaryKey($id);
                 $message = __('The custom field have been deleted');
             } catch (Exception $e) {
                 $error = 1;
                 $message = __('Error while deleting');
             }
             $result = "{";
             if ($error) {
                 $result .= '"error" : "';
                 $result .= $message;
                 $result .= '"';
             } else {
                 $result .= '"ok" : "Saved." ';
             }
             $result .= "}";
             echo $result;
             break;
         case 'enable_category':
             $id = Params::getParam("id");
             $enabled = Params::getParam("enabled") != '' ? Params::getParam("enabled") : 0;
             $error = 0;
             $aUpdated = "";
             try {
                 if ($id != '') {
                     $categoryManager = Category::newInstance();
                     $categoryManager->update(array('b_enabled' => $enabled), array('pk_i_id' => $id));
                     if ($enabled == 1) {
                         $msg = __('The category has been enabled');
                     } else {
                         $msg = __('The category has been disabled');
                     }
                     $categoryManager->update(array('b_enabled' => $enabled), array('fk_i_parent_id' => $id));
                     $aUpdated = $categoryManager->listWhere("fk_i_parent_id = {$id}");
                     if ($enabled == 1) {
                         $msg .= "<br>" . __('The subcategories has been enabled');
                     } else {
                         $msg .= "<br>" . __('The subcategories has been disabled');
                     }
                 } else {
                     $error = 1;
                     $msg = __('There was a problem with this page. The ID for the category hasn\'t been set');
                 }
                 $message = $msg;
             } catch (Exception $e) {
                 $error = 1;
                 $message = __('Error: %s') . " " . $e->getMessage();
             }
             $result = "{";
             $error = 0;
             if ($error) {
                 $result .= '"error" : "' . $message . '"';
             } else {
                 $result .= '"ok" : "' . $message . '"';
                 if (count($aUpdated) > 0) {
                     $result .= ', "afectedIds": [';
                     foreach ($aUpdated as $category) {
                         $result .= '{ "id" : "' . $category['pk_i_id'] . '" },';
                     }
                     $result = substr($result, 0, -1);
                     $result .= ']';
                 } else {
                     $result .= ', "afectedIds": []';
                 }
             }
             $result .= "}";
             echo $result;
             break;
         case 'delete_category':
             $id = Params::getParam("id");
             $error = 0;
             try {
                 $categoryManager = Category::newInstance();
                 $categoryManager->deleteByPrimaryKey($id);
                 $message = __('The categories have been deleted');
             } catch (Exception $e) {
                 $error = 1;
                 $message = __('Error while deleting');
             }
             $result = "{";
             if ($error) {
                 $result .= '"error" : "';
                 $result .= $message;
                 $result .= '"';
             } else {
                 $result .= '"ok" : "Saved." ';
             }
             $result .= "}";
             echo $result;
             break;
         case 'edit_category_post':
             $id = Params::getParam("id");
             $fields['i_expiration_days'] = Params::getParam("i_expiration_days") != '' ? Params::getParam("i_expiration_days") : 0;
             $error = 0;
             $postParams = Params::getParamsAsArray();
             foreach ($postParams as $k => $v) {
                 if (preg_match('|(.+?)#(.+)|', $k, $m)) {
                     if ($m[2] == 's_name') {
                         if ($v != "") {
                             $aFieldsDescription[$m[1]][$m[2]] = $v;
                         } else {
                             $error = 1;
                             $message = __("All titles are required");
                         }
                     } else {
                         $aFieldsDescription[$m[1]][$m[2]] = $v;
                     }
                 }
             }
             $l = osc_language();
             if (!$error) {
                 try {
                     $categoryManager = Category::newInstance();
                     $categoryManager->updateByPrimaryKey($fields, $aFieldsDescription, $id);
                 } catch (Exception $e) {
                     $error = 1;
                     $message = __("Error while updating.");
                 }
             }
             $result = "{";
             if ($error) {
                 $result .= '"error" : "';
                 $result .= $message;
                 $result .= '"';
             } else {
                 $result .= '"ok" : "' . __("Saved") . '", "text" : "' . $aFieldsDescription[$l]['s_name'] . '"';
             }
             $result .= "}";
             echo $result;
             break;
         case 'custom':
             // Execute via AJAX custom file
             $ajaxfile = Params::getParam("ajaxfile");
             if ($ajaxfile != '') {
                 require_once osc_admin_base_path() . $ajaxfile;
             } else {
                 echo json_encode(array('error' => __('no action defined')));
             }
             break;
         case 'test_mail':
             $title = __('Test email') . ", " . osc_page_title();
             $body = __("Test email") . "<br><br>" . osc_page_title();
             $emailParams = array('subject' => $title, 'to' => osc_contact_email(), 'to_name' => 'admin', 'body' => $body, 'alt_body' => $body);
             $array = array();
             if (osc_sendMail($emailParams)) {
                 $array = array('status' => '1', 'html' => __('Email sent successfully'));
             } else {
                 $array = array('status' => '0', 'html' => __('An error has occurred while sending email'));
             }
             echo json_encode($array);
             break;
         case 'order_pages':
             $order = Params::getParam("order");
             $id = Params::getParam("id");
             $count = osc_count_static_pages();
             if ($order != '' && $id != '') {
                 $mPages = Page::newInstance();
                 $actual_page = $mPages->findByPrimaryKey($id);
                 $actual_order = $actual_page['i_order'];
                 $array = array();
                 $condition = array();
                 $new_order = $actual_order;
                 if ($order == 'up') {
                     if ($actual_order > 0) {
                         $new_order = $actual_order - 1;
                     }
                 } else {
                     if ($order == 'down') {
                         if ($actual_order != $count - 1) {
                             $new_order = $actual_order + 1;
                         }
                     }
                 }
                 if ($new_order != $actual_order) {
                     $auxpage = $mPages->findByOrder($new_order);
                     $array = array('i_order' => $actual_order);
                     $conditions = array('pk_i_id' => $auxpage['pk_i_id']);
                     $mPages->update($array, $conditions);
                     $array = array('i_order' => $new_order);
                     $conditions = array('pk_i_id' => $id);
                     $mPages->update($array, $conditions);
                 } else {
                 }
                 // json for datatables
                 $prefLocale = osc_current_admin_locale();
                 $aPages = $mPages->listAll(0);
                 $json = "[";
                 foreach ($aPages as $key => $page) {
                     $body = array();
                     if (isset($page['locale'][$prefLocale]) && !empty($page['locale'][$prefLocale]['s_title'])) {
                         $body = $page['locale'][$prefLocale];
                     } else {
                         $body = current($page['locale']);
                     }
                     $p_body = str_replace("'", "\\'", trim(strip_tags($body['s_title']), "\"'"));
                     $json .= "[\"<input type='checkbox' name='id[]' value='" . $page['pk_i_id'] . "' />\",";
                     $json .= "\"" . $page['s_internal_name'] . "<div id='datatables_quick_edit'>";
                     $json .= "<a href='" . osc_static_page_url() . "'>" . __('View page') . "</a> | ";
                     $json .= "<a href='" . osc_admin_base_url(true) . "?page=pages&action=edit&id=" . $page['pk_i_id'] . "'>";
                     $json .= __('Edit') . "</a>";
                     if (!$page['b_indelible']) {
                         $json .= " | ";
                         $json .= "<a onclick=\\\"javascript:return confirm('";
                         $json .= __('This action can\\\\\'t be undone. Are you sure you want to continue?') . "')\\\" ";
                         $json .= " href='" . osc_admin_base_url(true) . "?page=pages&action=delete&id=" . $page['pk_i_id'] . "'>";
                         $json .= __('Delete') . "</a>";
                     }
                     $json .= "</div>\",";
                     $json .= "\"" . $p_body . "\",";
                     $json .= "\"<img id='up' onclick='order_up(" . $page['pk_i_id'] . ");' style='cursor:pointer;width:15;height:15px;' src='" . osc_current_admin_theme_url('images/arrow_up.png') . "'/> <br/> <img id='down' onclick='order_down(" . $page['pk_i_id'] . ");' style='cursor:pointer;width:15;height:15px;' src='" . osc_current_admin_theme_url('images/arrow_down.png') . "'/>\"]";
                     if ($key != count($aPages) - 1) {
                         $json .= ',';
                     } else {
                         $json .= '';
                     }
                 }
                 $json .= "]";
                 echo $json;
             }
             break;
             /******************************
              ** COMPLETE UPGRADE PROCESS **
              ******************************/
         /******************************
          ** COMPLETE UPGRADE PROCESS **
          ******************************/
         case 'upgrade':
             // AT THIS POINT WE KNOW IF THERE'S AN UPDATE OR NOT
             $message = "";
             $error = 0;
             $remove_error_msg = "";
             $sql_error_msg = "";
             $rm_errors = 0;
             $perms = osc_save_permissions();
             osc_change_permissions();
             $maintenance_file = ABS_PATH . '.maintenance';
             $fileHandler = @fopen($maintenance_file, 'w');
             fclose($fileHandler);
             /***********************
              **** DOWNLOAD FILE ****
              ***********************/
             if (Params::getParam('file') != '') {
                 $tmp = explode("/", Params::getParam('file'));
                 $filename = end($tmp);
                 $result = osc_downloadFile(Params::getParam('file'), $filename);
                 if ($result) {
                     // Everything is OK, continue
                     /**********************
                      ***** UNZIP FILE *****
                      **********************/
                     @mkdir(ABS_PATH . 'oc-temp', 0777);
                     $res = osc_unzip_file(osc_content_path() . 'downloads/' . $filename, ABS_PATH . 'oc-temp/');
                     if ($res == 1) {
                         // Everything is OK, continue
                         /**********************
                          ***** COPY FILES *****
                          **********************/
                         $fail = -1;
                         if ($handle = opendir(ABS_PATH . 'oc-temp')) {
                             $fail = 0;
                             while (false !== ($_file = readdir($handle))) {
                                 if ($_file != '.' && $_file != '..' && $_file != 'remove.list' && $_file != 'upgrade.sql' && $_file != 'customs.actions') {
                                     $data = osc_copy(ABS_PATH . "oc-temp/" . $_file, ABS_PATH . $_file);
                                     if ($data == false) {
                                         $fail = 1;
                                     }
                                 }
                             }
                             closedir($handle);
                             if ($fail == 0) {
                                 // Everything is OK, continue
                                 /**********************
                                  **** REMOVE FILES ****
                                  **********************/
                                 if (file_exists(ABS_PATH . 'oc-temp/remove.list')) {
                                     $lines = file(ABS_PATH . 'oc-temp/remove.list', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
                                     foreach ($lines as $line_num => $r_file) {
                                         $unlink = @unlink(ABS_PATH . $r_file);
                                         if (!$unlink) {
                                             $remove_error_msg .= sprintf(__('Error removing file: %s'), $r_file) . "<br/>";
                                         }
                                     }
                                 }
                                 // Removing files is not important for the rest of the proccess
                                 // We will inform the user of the problems but the upgrade could continue
                                 /************************
                                  *** UPGRADE DATABASE ***
                                  ************************/
                                 $error_queries = array();
                                 if (file_exists(osc_lib_path() . 'osclass/installer/struct.sql')) {
                                     $sql = file_get_contents(osc_lib_path() . 'osclass/installer/struct.sql');
                                     $conn = getConnection();
                                     $error_queries = $conn->osc_updateDB(str_replace('/*TABLE_PREFIX*/', DB_TABLE_PREFIX, $sql));
                                 }
                                 if ($error_queries[0]) {
                                     // Everything is OK, continue
                                     /**********************************
                                      ** EXECUTING ADDITIONAL ACTIONS **
                                      **********************************/
                                     if (file_exists(osc_lib_path() . 'osclass/upgrade-funcs.php')) {
                                         // There should be no errors here
                                         define('AUTO_UPGRADE', true);
                                         require_once osc_lib_path() . 'osclass/upgrade-funcs.php';
                                     }
                                     // Additional actions is not important for the rest of the proccess
                                     // We will inform the user of the problems but the upgrade could continue
                                     /****************************
                                      ** REMOVE TEMPORARY FILES **
                                      ****************************/
                                     $path = ABS_PATH . 'oc-temp';
                                     $rm_errors = 0;
                                     $dir = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::CHILD_FIRST);
                                     for ($dir->rewind(); $dir->valid(); $dir->next()) {
                                         if ($dir->isDir()) {
                                             if ($dir->getFilename() != '.' && $dir->getFilename() != '..') {
                                                 if (!rmdir($dir->getPathname())) {
                                                     $rm_errors++;
                                                 }
                                             }
                                         } else {
                                             if (!unlink($dir->getPathname())) {
                                                 $rm_errors++;
                                             }
                                         }
                                     }
                                     if (!rmdir($path)) {
                                         $rm_errors++;
                                     }
                                     $deleted = @unlink(ABS_PATH . '.maintenance');
                                     if ($rm_errors == 0) {
                                         $message = __('Everything was OK! Your OSClass installation is updated');
                                     } else {
                                         $message = __('Almost everything was OK! Your OSClass installation is updated, but there were some errors removing temporary files. Please, remove manually the "oc-temp" folder');
                                         $error = 6;
                                         // Some errors removing files
                                     }
                                 } else {
                                     $sql_error_msg = $error_queries[2];
                                     $message = __('Problems upgrading the database');
                                     $error = 5;
                                     // Problems upgrading the database
                                 }
                             } else {
                                 $message = __('Problems copying files. Maybe permissions are not correct');
                                 $error = 4;
                                 // Problems copying files. Maybe permissions are not correct
                             }
                         } else {
                             $message = __('Nothing to copy');
                             $error = 99;
                             // Nothing to copy. THIS SHOULD NEVER HAPPENS, means we dont update any file!
                         }
                     } else {
                         $message = __('Unzip failed');
                         $error = 3;
                         // Unzip failed
                     }
                 } else {
                     $message = __('Download failed');
                     $error = 2;
                     // Download failed
                 }
             } else {
                 $message = __('Missing download URL');
                 $error = 1;
                 // Missing download URL
             }
             if ($remove_error_msg != '') {
                 if ($error == 0) {
                     $message .= "<br /><br />" . __('We had some errors removing files, those are not super-sensitive errors, so we continued upgrading your installation. Please remove the following files (you already have OSClass upgraded, but to ensure maximun performance)');
                 }
             }
             if ($error == 5) {
                 $message .= "<br /><br />" . __('We had some errors upgrading your database. The follwing queries failed') . implode("<br />", $sql_error_msg);
             }
             echo $message;
             foreach ($perms as $k => $v) {
                 @chmod($k, $v);
             }
             break;
         default:
             echo json_encode(array('error' => __('no action defined')));
             break;
     }
     // clear all keep variables into session
     Session::newInstance()->_dropKeepForm();
     Session::newInstance()->_clearVariables();
 }
Example #24
0
function osc_market($section, $code)
{
    $plugin = false;
    $re_enable = false;
    $message = "";
    $data = array();
    $download_post_data = array('api_key' => osc_market_api_connect());
    /************************
     *** CHECK VALID CODE ***
     ************************/
    if ($code != '' && $section != '') {
        if (stripos($code, "http://") === FALSE) {
            // OSCLASS OFFICIAL REPOSITORY
            $url = osc_market_url($section, $code);
            $data = osc_file_get_contents($url, array('api_key' => osc_market_api_connect()));
            $data = json_decode(osc_file_get_contents($url, array('api_key' => osc_market_api_connect())), true);
        } else {
            // THIRD PARTY REPOSITORY
            if (osc_market_external_sources()) {
                $download_post_data = array();
                $data = json_decode(osc_file_get_contents($code), true);
            } else {
                return array('error' => 9, 'message' => __('No external sources are allowed'), 'data' => $data);
            }
        }
        /***********************
         **** DOWNLOAD FILE ****
         ***********************/
        if (isset($data['s_update_url']) && isset($data['s_source_file']) && isset($data['e_type'])) {
            if ($data['e_type'] == 'THEME') {
                $folder = 'themes/';
            } else {
                if ($data['e_type'] == 'LANGUAGE') {
                    $folder = 'languages/';
                } else {
                    // PLUGINS
                    $folder = 'plugins/';
                    $plugin = Plugins::findByUpdateURI($data['s_update_url']);
                    if ($plugin != false) {
                        if (Plugins::isEnabled($plugin)) {
                            Plugins::runHook($plugin . '_disable');
                            Plugins::deactivate($plugin);
                            $re_enable = true;
                        }
                    }
                }
            }
            $filename = date('YmdHis') . "_" . osc_sanitize_string($data['s_title']) . "_" . $data['s_version'] . ".zip";
            $url_source_file = $data['s_source_file'];
            $result = osc_downloadFile($url_source_file, $filename, $download_post_data);
            if ($result) {
                // Everything is OK, continue
                /**********************
                 ***** UNZIP FILE *****
                 **********************/
                @mkdir(osc_content_path() . 'downloads/oc-temp/');
                $res = osc_unzip_file(osc_content_path() . 'downloads/' . $filename, osc_content_path() . 'downloads/oc-temp/');
                if ($res == 1) {
                    // Everything is OK, continue
                    /**********************
                     ***** COPY FILES *****
                     **********************/
                    $fail = -1;
                    if ($handle = opendir(osc_content_path() . 'downloads/oc-temp')) {
                        $folder_dest = ABS_PATH . "oc-content/" . $folder;
                        if (function_exists('posix_getpwuid')) {
                            $current_user = posix_getpwuid(posix_geteuid());
                            $ownerFolder = posix_getpwuid(fileowner($folder_dest));
                        }
                        $fail = 0;
                        while (false !== ($_file = readdir($handle))) {
                            if ($_file != '.' && $_file != '..') {
                                $copyprocess = osc_copy(osc_content_path() . "downloads/oc-temp/" . $_file, $folder_dest . $_file);
                                if ($copyprocess == false) {
                                    $fail = 1;
                                }
                            }
                        }
                        closedir($handle);
                        // Additional actions is not important for the rest of the proccess
                        // We will inform the user of the problems but the upgrade could continue
                        // Also remove the zip package
                        /****************************
                         ** REMOVE TEMPORARY FILES **
                         ****************************/
                        @unlink(osc_content_path() . 'downloads/' . $filename);
                        $path = osc_content_path() . 'downloads/oc-temp';
                        $rm_errors = 0;
                        $dir = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::CHILD_FIRST);
                        for ($dir->rewind(); $dir->valid(); $dir->next()) {
                            if ($dir->isDir()) {
                                if ($dir->getFilename() != '.' && $dir->getFilename() != '..') {
                                    if (!rmdir($dir->getPathname())) {
                                        $rm_errors++;
                                    }
                                }
                            } else {
                                if (!unlink($dir->getPathname())) {
                                    $rm_errors++;
                                }
                            }
                        }
                        if (!rmdir($path)) {
                            $rm_errors++;
                        }
                        if ($fail == 0) {
                            // Everything is OK, continue
                            if ($data['e_type'] != 'THEME' && $data['e_type'] != 'LANGUAGE') {
                                if ($plugin != false && $re_enable) {
                                    $enabled = Plugins::activate($plugin);
                                    if ($enabled) {
                                        Plugins::runHook($plugin . '_enable');
                                    }
                                }
                            } else {
                                if ($data['e_type'] == 'LANGUAGE') {
                                    osc_checkLocales();
                                }
                            }
                            // recount plugins&themes for update
                            if ($section == 'plugins') {
                                osc_check_plugins_update(true);
                            } else {
                                if ($section == 'themes') {
                                    osc_check_themes_update(true);
                                } else {
                                    if ($section == 'languages') {
                                        osc_check_languages_update(true);
                                    }
                                }
                            }
                            if ($rm_errors == 0) {
                                $message = __('Everything looks good!');
                                $error = 0;
                            } else {
                                $message = __('Nearly everything looks good! but there were some errors removing temporary files. Please manually remove the \\"oc-content/downloads/oc-temp\\" folder');
                                $error = 6;
                                // Some errors removing files
                            }
                        } else {
                            $message = __('Problems when copying files. Please check your permissions. ');
                            if ($current_user['uid'] != $ownerFolder['uid']) {
                                if (function_exists('posix_getgrgid')) {
                                    $current_group = posix_getgrgid($current_user['gid']);
                                    $message .= '<p><strong>' . sprintf(__('NOTE: Web user and destination folder user is not the same, you might have an issue there. <br/>Do this in your console:<br/>chown -R %s:%s %s'), $current_user['name'], $current_group['name'], $folder_dest) . '</strong></p>';
                                }
                            }
                            $error = 4;
                            // Problems copying files. Maybe permissions are not correct
                        }
                    } else {
                        $message = __('Nothing to copy');
                        $error = 99;
                        // Nothing to copy. THIS SHOULD NEVER HAPPEN, means we don't update any file!
                    }
                } else {
                    $message = __('Unzip failed');
                    $error = 3;
                    // Unzip failed
                }
            } else {
                $message = __('Download failed');
                $error = 2;
                // Download failed
            }
        } else {
            if (isset($data['s_buy_url']) && isset($data['b_paid']) && $data['s_buy_url'] != '' && $data['b_paid'] == 0) {
                $message = __('This is a paid item, you need to buy it before you are able to download it');
                $error = 8;
                // Item not paid
            } else {
                $message = __('Input code not valid');
                $error = 7;
                // Input code not valid
            }
        }
    } else {
        $message = __('Missing download URL');
        $error = 1;
        // Missing download URL
    }
    return array('error' => $error, 'message' => $message, 'data' => $data);
}
 public static function fsRmdirRecursive($path, $includeSelf = false)
 {
     $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::KEY_AS_PATHNAME), RecursiveIteratorIterator::CHILD_FIRST);
     foreach ($it as $key => $child) {
         if ($child->getFilename() == '.' || $child->getFilename() == '..') {
             continue;
         }
         if ($it->isDir()) {
             if (!rmdir($key)) {
                 throw new Engine_Package_Exception(sprintf('Unable to remove directory: %s', $key));
             }
         } else {
             if ($it->isFile()) {
                 if (!unlink($key)) {
                     throw new Engine_Package_Exception(sprintf('Unable to remove file: %s', $key));
                 }
             }
         }
     }
     if (is_dir($path) && $includeSelf) {
         if (!rmdir($path)) {
             throw new Engine_Package_Exception(sprintf('Unable to remove directory: %s', $path));
         }
     }
 }
Example #26
0
 function doModel()
 {
     //specific things for this class
     switch ($this->action) {
         case 'bulk_actions':
             break;
         case 'regions':
             //Return regions given a countryId
             $regions = Region::newInstance()->findByCountry(Params::getParam("countryId"));
             echo json_encode($regions);
             break;
         case 'cities':
             //Returns cities given a regionId
             $cities = City::newInstance()->findByRegion(Params::getParam("regionId"));
             echo json_encode($cities);
             break;
         case 'location':
             // This is the autocomplete AJAX
             $cities = City::newInstance()->ajax(Params::getParam("term"));
             echo json_encode($cities);
             break;
         case 'userajax':
             // This is the autocomplete AJAX
             $users = User::newInstance()->ajax(Params::getParam("term"));
             if (count($users) == 0) {
                 echo json_encode(array(0 => array('id' => '', 'label' => __('No results'), 'value' => __('No results'))));
             } else {
                 echo json_encode($users);
             }
             break;
         case 'date_format':
             echo json_encode(array('format' => Params::getParam('format'), 'str_formatted' => osc_format_date(date(Params::getParam('format')))));
             break;
         case 'runhook':
             // run hooks
             $hook = Params::getParam('hook');
             if ($hook == '') {
                 echo json_encode(array('error' => 'hook parameter not defined'));
                 break;
             }
             switch ($hook) {
                 case 'item_form':
                     osc_run_hook('item_form', Params::getParam('catId'));
                     break;
                 case 'item_edit':
                     $catId = Params::getParam("catId");
                     $itemId = Params::getParam("itemId");
                     osc_run_hook("item_edit", $catId, $itemId);
                     break;
                 default:
                     osc_run_hook('ajax_admin_' . $hook);
                     break;
             }
             break;
         case 'items':
             // Return items (use external file oc-admin/ajax/item_processing.php)
             require_once osc_admin_base_path() . 'ajax/items_processing.php';
             $items_processing = new ItemsProcessingAjax(Params::getParamsAsArray("get"));
             break;
         case 'users':
             // Return items (use external file oc-admin/ajax/item_processing.php)
             require_once osc_admin_base_path() . 'ajax/users_processing.php';
             $users_processing = new UsersProcessingAjax(Params::getParamsAsArray("get"));
             break;
         case 'media':
             // Return items (use external file oc-admin/ajax/media_processing.php)
             require_once osc_admin_base_path() . 'ajax/media_processing.php';
             $media_processing = new MediaProcessingAjax(Params::getParamsAsArray("get"));
             break;
         case 'categories_order':
             // Save the order of the categories
             $aIds = Params::getParam('list');
             $orderParent = 0;
             $orderSub = 0;
             $catParent = 0;
             $error = 0;
             $catManager = Category::newInstance();
             $aRecountCat = array();
             foreach ($aIds as $id => $parent) {
                 if ($parent == 'root') {
                     $res = $catManager->updateOrder($id, $orderParent);
                     if (is_bool($res) && !$res) {
                         $error = 1;
                     }
                     // find category
                     $auxCategory = Category::newInstance()->findByPrimaryKey($id);
                     // set parent category
                     $conditions = array('pk_i_id' => $id);
                     $array['fk_i_parent_id'] = NULL;
                     $res = $catManager->update($array, $conditions);
                     if (is_bool($res) && !$res) {
                         $error = 1;
                     } else {
                         if ($res == 1) {
                             // updated ok
                             $parentId = $auxCategory['fk_i_parent_id'];
                             if ($parentId) {
                                 // update parent category stats
                                 array_push($aRecountCat, $id);
                                 array_push($aRecountCat, $parentId);
                             }
                         }
                     }
                     $orderParent++;
                 } else {
                     if ($parent != $catParent) {
                         $catParent = $parent;
                         $orderSub = 0;
                     }
                     $res = $catManager->updateOrder($id, $orderSub);
                     if (is_bool($res) && !$res) {
                         $error = 1;
                     }
                     // set parent category
                     $auxCategory = Category::newInstance()->findByPrimaryKey($id);
                     $auxCategoryP = Category::newInstance()->findByPrimaryKey($catParent);
                     $conditions = array('pk_i_id' => $id);
                     $array['fk_i_parent_id'] = $catParent;
                     $res = $catManager->update($array, $conditions);
                     if (is_bool($res) && !$res) {
                         $error = 1;
                     } else {
                         if ($res == 1) {
                             // updated ok
                             // update category parent
                             $prevParentId = $auxCategory['fk_i_parent_id'];
                             $parentId = $auxCategoryP['pk_i_id'];
                             array_push($aRecountCat, $prevParentId);
                             array_push($aRecountCat, $parentId);
                         }
                     }
                     $orderSub++;
                 }
             }
             // update category stats
             foreach ($aRecountCat as $rId) {
                 osc_update_cat_stats_id($rId);
             }
             if ($error) {
                 $result = array('error' => __("Some error ocurred"));
             } else {
                 $result = array('ok' => __("Order saved"));
             }
             echo json_encode($result);
             break;
         case 'category_edit_iframe':
             $this->_exportVariableToView('category', Category::newInstance()->findByPrimaryKey(Params::getParam("id")));
             $this->_exportVariableToView('languages', OSCLocale::newInstance()->listAllEnabled());
             $this->doView("categories/iframe.php");
             break;
         case 'field_categories_iframe':
             $selected = Field::newInstance()->categories(Params::getParam("id"));
             if ($selected == null) {
                 $selected = array();
             }
             $this->_exportVariableToView("selected", $selected);
             $this->_exportVariableToView("field", Field::newInstance()->findByPrimaryKey(Params::getParam("id")));
             $this->_exportVariableToView("categories", Category::newInstance()->toTreeAll());
             $this->doView("fields/iframe.php");
             break;
         case 'field_categories_post':
             $error = 0;
             $field = Field::newInstance()->findByName(Params::getParam("s_name"));
             if (!isset($field['pk_i_id']) || isset($field['pk_i_id']) && $field['pk_i_id'] == Params::getParam("id")) {
                 // remove categories from a field
                 Field::newInstance()->cleanCategoriesFromField(Params::getParam("id"));
                 // no error... continue updating fields
                 if ($error == 0) {
                     $slug = Params::getParam("field_slug") != '' ? Params::getParam("field_slug") : Params::getParam("s_name");
                     $slug_tmp = $slug = preg_replace('|([-]+)|', '-', preg_replace('|[^a-z0-9_-]|', '-', strtolower($slug)));
                     $slug_k = 0;
                     while (true) {
                         $field = Field::newInstance()->findBySlug($slug);
                         if (!$field || $field['pk_i_id'] == Params::getParam("id")) {
                             break;
                         } else {
                             $slug_k++;
                             $slug = $slug_tmp . "_" . $slug_k;
                         }
                     }
                     $res = Field::newInstance()->update(array('s_name' => Params::getParam("s_name"), 'e_type' => Params::getParam("field_type"), 's_slug' => $slug, 'b_required' => Params::getParam("field_required") == "1" ? 1 : 0, 's_options' => Params::getParam('s_options')), array('pk_i_id' => Params::getParam("id")));
                     if (is_bool($res) && !$res) {
                         $error = 1;
                     }
                 }
                 // no error... continue inserting categories-field
                 if ($error == 0) {
                     $aCategories = Params::getParam("categories");
                     if (is_array($aCategories) && count($aCategories) > 0) {
                         $res = Field::newInstance()->insertCategories(Params::getParam("id"), $aCategories);
                         if (!$res) {
                             $error = 1;
                         }
                     }
                 }
                 // error while updating?
                 if ($error == 1) {
                     $message = __("Error while updating.");
                 }
             } else {
                 $error = 1;
                 $message = __("Sorry, you already have one field with that name");
             }
             if ($error) {
                 $result = array('error' => $message);
             } else {
                 $result = array('ok' => __("Saved"), 'text' => Params::getParam("s_name"), 'field_id' => $field['pk_i_id']);
             }
             echo json_encode($result);
             break;
         case 'delete_field':
             $id = Params::getParam("id");
             $error = 0;
             $fieldManager = Field::newInstance();
             $res = $fieldManager->deleteByPrimaryKey($id);
             if ($res > 0) {
                 $message = __('The custom field have been deleted');
             } else {
                 $error = 1;
                 $message = __('Error while deleting');
             }
             if ($error) {
                 $result = array('error' => $message);
             } else {
                 $result = array('ok' => __("Saved"));
             }
             echo json_encode($result);
             break;
         case 'add_field':
             $s_name = __('NEW custom field');
             $slug_tmp = $slug = preg_replace('|([-]+)|', '-', preg_replace('|[^a-z0-9_-]|', '-', strtolower($s_name)));
             $slug_k = 0;
             while (true) {
                 $field = Field::newInstance()->findBySlug($slug);
                 if (!$field || $field['pk_i_id'] == Params::getParam("id")) {
                     break;
                 } else {
                     $slug_k++;
                     $slug = $slug_tmp . "_" . $slug_k;
                 }
             }
             $fieldManager = Field::newInstance();
             $result = $fieldManager->insertField($s_name, 'TEXT', $slug, 0, '', array());
             if ($result) {
                 echo json_encode(array('error' => 0, 'field_id' => $fieldManager->dao->insertedId(), 'field_name' => $s_name));
             } else {
                 echo json_encode(array('error' => 1));
             }
             break;
         case 'enable_category':
             $id = strip_tags(Params::getParam('id'));
             $enabled = Params::getParam('enabled') != '' ? Params::getParam('enabled') : 0;
             $error = 0;
             $result = array();
             $aUpdated = array();
             $mCategory = Category::newInstance();
             $aCategory = $mCategory->findByPrimaryKey($id);
             if ($aCategory == false) {
                 $result = array('error' => sprintf(__("It doesn't exist a category with this id: %d"), $id));
                 echo json_encode($result);
                 break;
             }
             // root category
             if ($aCategory['fk_i_parent_id'] == '') {
                 $mCategory->update(array('b_enabled' => $enabled), array('pk_i_id' => $id));
                 $mCategory->update(array('b_enabled' => $enabled), array('fk_i_parent_id' => $id));
                 $subCategories = $mCategory->findSubcategories($id);
                 $aIds = array($id);
                 $aUpdated[] = array('id' => $id);
                 foreach ($subCategories as $subcategory) {
                     $aIds[] = $subcategory['pk_i_id'];
                     $aUpdated[] = array('id' => $subcategory['pk_i_id']);
                 }
                 Item::newInstance()->enableByCategory($enabled, $aIds);
                 if ($enabled) {
                     $result = array('ok' => __('The category and its subcategories have been enabled'));
                 } else {
                     $result = array('ok' => __('The category and its subcategories have been disabled'));
                 }
                 $result['affectedIds'] = $aUpdated;
                 echo json_encode($result);
                 break;
             }
             // subcategory
             $parentCategory = $mCategory->findRootCategory($id);
             if (!$parentCategory['b_enabled']) {
                 $result = array('error' => __('Parent category is disabled, you can not enable that category'));
                 echo json_encode($result);
                 break;
             }
             $mCategory->update(array('b_enabled' => $enabled), array('pk_i_id' => $id));
             if ($enabled) {
                 $result = array('ok' => __('The subcategory has been enabled'));
             } else {
                 $result = array('ok' => __('The subcategory has been disabled'));
             }
             $result['affectedIds'] = array(array('id' => $id));
             echo json_encode($result);
             break;
         case 'delete_category':
             $id = Params::getParam("id");
             $error = 0;
             $categoryManager = Category::newInstance();
             $res = $categoryManager->deleteByPrimaryKey($id);
             if ($res > 0) {
                 $message = __('The categories have been deleted');
             } else {
                 $error = 1;
                 $message = __('Error while deleting');
             }
             if ($error) {
                 $result = array('error' => $message);
             } else {
                 $result = array('ok' => __("Saved"));
             }
             echo json_encode($result);
             break;
         case 'edit_category_post':
             $id = Params::getParam("id");
             $fields['i_expiration_days'] = Params::getParam("i_expiration_days") != '' ? Params::getParam("i_expiration_days") : 0;
             $error = 0;
             $has_one_title = 0;
             $postParams = Params::getParamsAsArray();
             foreach ($postParams as $k => $v) {
                 if (preg_match('|(.+?)#(.+)|', $k, $m)) {
                     if ($m[2] == 's_name') {
                         if ($v != "") {
                             $has_one_title = 1;
                             $aFieldsDescription[$m[1]][$m[2]] = $v;
                             $s_text = $v;
                         } else {
                             $aFieldsDescription[$m[1]][$m[2]] = ' ';
                             $error = 1;
                         }
                     } else {
                         $aFieldsDescription[$m[1]][$m[2]] = $v;
                     }
                 }
             }
             $l = osc_language();
             if ($error == 0 || $error == 1 && $has_one_title == 1) {
                 $categoryManager = Category::newInstance();
                 $res = $categoryManager->updateByPrimaryKey(array('fields' => $fields, 'aFieldsDescription' => $aFieldsDescription), $id);
                 if (is_bool($res)) {
                     $error = 2;
                 }
             }
             if ($error == 0) {
                 $msg = __("Category updated correctly");
             } else {
                 if ($error == 1) {
                     if ($has_one_title == 1) {
                         $error = 4;
                         $msg = __('Category updated correctly, but some titles were empty');
                     } else {
                         $msg = __('Sorry, at least a title is needed');
                     }
                 } else {
                     if ($error == 2) {
                         $msg = __('Error while updating');
                     }
                 }
             }
             echo json_encode(array('error' => $error, 'msg' => $msg, 'text' => $aFieldsDescription[$l]['s_name']));
             break;
         case 'custom':
             // Execute via AJAX custom file
             $ajaxFile = Params::getParam("ajaxfile");
             if ($ajaxFile == '') {
                 echo json_encode(array('error' => 'no action defined'));
                 break;
             }
             // valid file?
             if (stripos($ajaxFile, '../') !== false) {
                 echo json_encode(array('error' => 'no valid ajaxFile'));
                 break;
             }
             if (!file_exists(osc_plugins_path() . $ajaxFile)) {
                 echo json_encode(array('error' => "ajaxFile doesn't exist"));
                 break;
             }
             require_once osc_plugins_path() . $ajaxFile;
             break;
         case 'test_mail':
             $title = sprintf(__('Test email, %s'), osc_page_title());
             $body = __("Test email") . "<br><br>" . osc_page_title();
             $emailParams = array('subject' => $title, 'to' => osc_contact_email(), 'to_name' => 'admin', 'body' => $body, 'alt_body' => $body);
             $array = array();
             if (osc_sendMail($emailParams)) {
                 $array = array('status' => '1', 'html' => __('Email sent successfully'));
             } else {
                 $array = array('status' => '0', 'html' => __('An error has occurred while sending email'));
             }
             echo json_encode($array);
             break;
         case 'order_pages':
             $order = Params::getParam("order");
             $id = Params::getParam("id");
             if ($order != '' && $id != '') {
                 $mPages = Page::newInstance();
                 $actual_page = $mPages->findByPrimaryKey($id);
                 $actual_order = $actual_page['i_order'];
                 $array = array();
                 $condition = array();
                 $new_order = $actual_order;
                 if ($order == 'up') {
                     $page = $mPages->findPrevPage($actual_order);
                 } else {
                     if ($order == 'down') {
                         $page = $mPages->findNextPage($actual_order);
                     }
                 }
                 if (isset($page['i_order'])) {
                     $mPages->update(array('i_order' => $page['i_order']), array('pk_i_id' => $id));
                     $mPages->update(array('i_order' => $actual_order), array('pk_i_id' => $page['pk_i_id']));
                 }
                 // TO BE IMPROVED
                 // json for datatables
                 $prefLocale = osc_current_user_locale();
                 $this->_exportVariableToView('pages', $mPages->listAll(0));
                 $o_json = array();
                 while (osc_has_static_pages()) {
                     $row = array();
                     $page = osc_static_page();
                     $content = array();
                     if (isset($page['locale'][$prefLocale]) && !empty($page['locale'][$prefLocale]['s_title'])) {
                         $content = $page['locale'][$prefLocale];
                     } else {
                         $content = current($page['locale']);
                     }
                     $options = array();
                     $options[] = '<a href="' . osc_static_page_url() . '">' . __('View page') . '</a>';
                     $options[] = '<a href="' . osc_admin_base_url(true) . '?page=pages&amp;action=edit&amp;id=' . osc_static_page_id() . '">' . __('Edit') . '</a>';
                     if (!$page['b_indelible']) {
                         $options[] = '<a onclick="javascript:return confirm(\'' . osc_esc_js("This action can't be undone. Are you sure you want to continue?") . '\')" href="' . osc_admin_base_url(true) . '?page=pages&amp;action=delete&amp;id=' . osc_static_page_id() . '">' . __('Delete') . '</a>';
                     }
                     $row[] = '<input type="checkbox" name="id[]"" value="' . osc_static_page_id() . '"" />';
                     $row[] = $page['s_internal_name'] . '<div id="datatables_quick_edit" style="display: none;">' . implode(' &middot; ', $options) . '</div>';
                     $row[] = $content['s_title'];
                     $row[] = osc_static_page_order() . ' <img id="up" onclick="order_up(' . osc_static_page_id() . ');" style="cursor:pointer; width:15px; height:15px;" src="' . osc_current_admin_theme_url('images/arrow_up.png') . '"/> <br/><img id="down" onclick="order_down(' . osc_static_page_id() . ');" style="cursor:pointer; width:15px; height:15px; margin-left: 10px;" src="' . osc_current_admin_theme_url('images/arrow_down.png') . '"/>';
                     $o_json[] = $row;
                 }
                 echo json_encode($o_json);
             }
             break;
             /******************************
              ** COMPLETE UPGRADE PROCESS **
              ******************************/
         /******************************
          ** COMPLETE UPGRADE PROCESS **
          ******************************/
         case 'upgrade':
             // AT THIS POINT WE KNOW IF THERE'S AN UPDATE OR NOT
             $message = "";
             $error = 0;
             $sql_error_msg = "";
             $rm_errors = 0;
             $perms = osc_save_permissions();
             osc_change_permissions();
             $maintenance_file = ABS_PATH . '.maintenance';
             $fileHandler = @fopen($maintenance_file, 'w');
             fclose($fileHandler);
             /***********************
              **** DOWNLOAD FILE ****
              ***********************/
             $data = osc_file_get_contents("http://osclass.org/latest_version.php");
             $data = json_decode(substr($data, 1, strlen($data) - 3), true);
             $source_file = $data['url'];
             if ($source_file != '') {
                 $tmp = explode("/", $source_file);
                 $filename = end($tmp);
                 $result = osc_downloadFile($source_file, $filename);
                 if ($result) {
                     // Everything is OK, continue
                     /**********************
                      ***** UNZIP FILE *****
                      **********************/
                     @mkdir(ABS_PATH . 'oc-temp', 0777);
                     $res = osc_unzip_file(osc_content_path() . 'downloads/' . $filename, ABS_PATH . 'oc-temp/');
                     if ($res == 1) {
                         // Everything is OK, continue
                         /**********************
                          ***** COPY FILES *****
                          **********************/
                         $fail = -1;
                         if ($handle = opendir(ABS_PATH . 'oc-temp')) {
                             $fail = 0;
                             while (false !== ($_file = readdir($handle))) {
                                 if ($_file != '.' && $_file != '..' && $_file != 'remove.list' && $_file != 'upgrade.sql' && $_file != 'customs.actions') {
                                     $data = osc_copy(ABS_PATH . "oc-temp/" . $_file, ABS_PATH . $_file);
                                     if ($data == false) {
                                         $fail = 1;
                                     }
                                 }
                             }
                             closedir($handle);
                             if ($fail == 0) {
                                 // Everything is OK, continue
                                 /************************
                                  *** UPGRADE DATABASE ***
                                  ************************/
                                 $error_queries = array();
                                 if (file_exists(osc_lib_path() . 'osclass/installer/struct.sql')) {
                                     $sql = file_get_contents(osc_lib_path() . 'osclass/installer/struct.sql');
                                     $conn = DBConnectionClass::newInstance();
                                     $c_db = $conn->getOsclassDb();
                                     $comm = new DBCommandClass($c_db);
                                     $error_queries = $comm->updateDB(str_replace('/*TABLE_PREFIX*/', DB_TABLE_PREFIX, $sql));
                                 }
                                 if ($error_queries[0]) {
                                     // Everything is OK, continue
                                     /**********************************
                                      ** EXECUTING ADDITIONAL ACTIONS **
                                      **********************************/
                                     if (file_exists(osc_lib_path() . 'osclass/upgrade-funcs.php')) {
                                         // There should be no errors here
                                         define('AUTO_UPGRADE', true);
                                         require_once osc_lib_path() . 'osclass/upgrade-funcs.php';
                                     }
                                     // Additional actions is not important for the rest of the proccess
                                     // We will inform the user of the problems but the upgrade could continue
                                     /****************************
                                      ** REMOVE TEMPORARY FILES **
                                      ****************************/
                                     $path = ABS_PATH . 'oc-temp';
                                     $rm_errors = 0;
                                     $dir = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::CHILD_FIRST);
                                     for ($dir->rewind(); $dir->valid(); $dir->next()) {
                                         if ($dir->isDir()) {
                                             if ($dir->getFilename() != '.' && $dir->getFilename() != '..') {
                                                 if (!rmdir($dir->getPathname())) {
                                                     $rm_errors++;
                                                 }
                                             }
                                         } else {
                                             if (!unlink($dir->getPathname())) {
                                                 $rm_errors++;
                                             }
                                         }
                                     }
                                     if (!rmdir($path)) {
                                         $rm_errors++;
                                     }
                                     $deleted = @unlink(ABS_PATH . '.maintenance');
                                     if ($rm_errors == 0) {
                                         $message = __('Everything was OK! Your OSClass installation is updated');
                                     } else {
                                         $message = __('Almost everything was OK! Your OSClass installation is updated, but there were some errors removing temporary files. Please, remove manually the "oc-temp" folder');
                                         $error = 6;
                                         // Some errors removing files
                                     }
                                 } else {
                                     $sql_error_msg = $error_queries[2];
                                     $message = __('Problems upgrading the database');
                                     $error = 5;
                                     // Problems upgrading the database
                                 }
                             } else {
                                 $message = __('Problems copying files. Maybe permissions are not correct');
                                 $error = 4;
                                 // Problems copying files. Maybe permissions are not correct
                             }
                         } else {
                             $message = __('Nothing to copy');
                             $error = 99;
                             // Nothing to copy. THIS SHOULD NEVER HAPPENS, means we dont update any file!
                         }
                     } else {
                         $message = __('Unzip failed');
                         $error = 3;
                         // Unzip failed
                     }
                 } else {
                     $message = __('Download failed');
                     $error = 2;
                     // Download failed
                 }
             } else {
                 $message = __('Missing download URL');
                 $error = 1;
                 // Missing download URL
             }
             if ($error == 5) {
                 $message .= "<br /><br />" . __('We had some errors upgrading your database. The follwing queries failed') . implode("<br />", $sql_error_msg);
             }
             echo $message;
             foreach ($perms as $k => $v) {
                 @chmod($k, $v);
             }
             break;
         case 'location_stats':
             $workToDo = LocationsTmp::newInstance()->count();
             if ($workToDo > 0) {
                 // there are wotk to do
                 $aLocations = LocationsTmp::newInstance()->getLocations(1000);
                 foreach ($aLocations as $location) {
                     $id = $location['id_location'];
                     $type = $location['e_type'];
                     $data = 0;
                     // update locations stats
                     switch ($type) {
                         case 'COUNTRY':
                             $numItems = CountryStats::newInstance()->calculateNumItems($id);
                             $data = CountryStats::newInstance()->setNumItems($id, $numItems);
                             unset($numItems);
                             break;
                         case 'REGION':
                             $numItems = RegionStats::newInstance()->calculateNumItems($id);
                             $data = RegionStats::newInstance()->setNumItems($id, $numItems);
                             unset($numItems);
                             break;
                         case 'CITY':
                             $numItems = CityStats::newInstance()->calculateNumItems($id);
                             $data = CityStats::newInstance()->setNumItems($id, $numItems);
                             unset($numItems);
                             break;
                         default:
                             break;
                     }
                     if ($data >= 0) {
                         LocationsTmp::newInstance()->delete(array('e_type' => $location['e_type'], 'id_location' => $location['id_location']));
                     }
                 }
                 $array['status'] = 'more';
                 $array['pending'] = $workToDo = LocationsTmp::newInstance()->count();
                 echo json_encode($array);
             } else {
                 $array['status'] = 'done';
                 echo json_encode($array);
             }
             break;
         default:
             echo json_encode(array('error' => __('no action defined')));
             break;
     }
     // clear all keep variables into session
     Session::newInstance()->_dropKeepForm();
     Session::newInstance()->_clearVariables();
 }
Example #27
0
/**
 * Delete files and directories older than one week from directory provided by $CFG->tempdir.
 *
 * @exception Exception Failed reading/accessing file or directory
 * @return bool True on successful file and directory deletion; otherwise, false on failure
 */
function cron_delete_from_temp()
{
    global $CFG;
    $tmpdir = $CFG->tempdir;
    // Default to last weeks time.
    $time = strtotime('-1 week');
    try {
        $dir = new RecursiveDirectoryIterator($tmpdir);
        // Show all child nodes prior to their parent.
        $iter = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::CHILD_FIRST);
        for ($iter->rewind(); $iter->valid(); $iter->next()) {
            $node = $iter->getRealPath();
            if (!is_readable($node)) {
                continue;
            }
            // Check if file or directory is older than the given time.
            if ($iter->getMTime() < $time) {
                if ($iter->isDir() && !$iter->isDot()) {
                    if (@rmdir($node) === false) {
                        mtrace("Failed removing directory '{$node}'.");
                    }
                }
                if ($iter->isFile()) {
                    if (@unlink($node) === false) {
                        mtrace("Failed removing file '{$node}'.");
                    }
                }
            }
        }
    } catch (Exception $e) {
        mtrace('Failed reading/accessing file or directory.');
        return false;
    }
    return true;
}
Example #28
0
 public static function build($directory)
 {
     $list = array();
     $unique = array();
     // Build
     $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::KEY_AS_PATHNAME), RecursiveIteratorIterator::SELF_FIRST);
     while ($it->valid()) {
         $key = $it->key();
         // Make sure it's unique, Skip .svn files
         if (isset($unique[$key]) || stripos($key, '.svn') !== false) {
             $it->next();
             continue;
         }
         $unique[$key] = true;
         // Add
         $subpath = $it->getSubPathName();
         // Skip dot files, package files and .svn or CVS folders
         if (!$it->isDot() && substr(basename($subpath), 0, strrpos(basename($subpath), '.')) != 'package' && basename($subpath) != '.svn' && basename($subpath) != 'CVS') {
             $key = $it->key();
             //$list[$it->getSubPathName()] = array(
             $list[] = array('path' => self::fix_path($it->getSubPathName()), 'dir' => $it->isDir(), 'file' => $it->isFile(), 'perms' => substr(sprintf('%o', $it->getPerms()), -4), 'size' => $it->getSize(), 'sha1' => $it->isFile() ? sha1_file($key) : null);
         }
         $it->next();
     }
     ksort($list);
     return $list;
 }
Example #29
0
 private function count_directory()
 {
     $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->input_dir, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST);
     $count = 0;
     while ($iterator->valid()) {
         if ($iterator->isDir()) {
             $count++;
         }
         $iterator->next();
     }
     return $count;
 }
Example #30
0
 /**
  * @param  string         $websiteId
  * @param  string         $name Zip name
  * @param  \Cms\Data\Build $build
  *
  * @return string Name of the export zip file
  */
 private function createBuildZip($websiteId, $name, BuildData $build)
 {
     $zipFile = FS::joinPath($this->getWebsiteBuildsDirectory($websiteId), $name . self::BUILD_FILE_EXTENSION);
     $websiteCreatorDirectory = $this->getLastCreatorDirectory();
     $zip = new \ZipArchive();
     $zip->open($zipFile, \ZipArchive::CREATE);
     $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($websiteCreatorDirectory), \RecursiveIteratorIterator::SELF_FIRST);
     while ($iterator->valid()) {
         if (!$iterator->isDot()) {
             if ($iterator->isDir()) {
                 $zip->addEmptyDir(str_replace('\\', '/', $iterator->getSubPathName()));
             } else {
                 $zip->addEmptyDir(str_replace('\\', '/', $iterator->getSubPath()));
                 $zip->addFile($iterator->key(), str_replace('\\', '/', $iterator->getSubPathName()));
             }
         }
         $iterator->next();
     }
     $zip->setArchiveComment($this->getBuiltArchiveComment($build));
     $zip->close();
     return $zipFile;
 }