DirectoryIterator PHP Class Code Examples

This page contains top rated real world PHP examples of class DirectoryIterator extracted from open source projects. You can rate examples to help us improve the quality of examples

Example #1
Show file File: lib.php Project: janaece/globalclassroom4_clean
0
/**
 * Looks in the export staging area in dataroot and deletes old, unneeded
 * exports.
 */
function export_cleanup_old_exports()
{
    require_once 'file.php';
    $basedir = get_config('dataroot') . 'export/';
    // If the export directory hasn't been created yet, there's no point
    // running the cron.
    if (!is_dir($basedir)) {
        return;
    }
    $exportdir = new DirectoryIterator($basedir);
    $mintime = time() - 24 * 60 * 60;
    // delete exports older than 24 hours
    // The export dir contains one directory for each user who has created
    // an export, named after their UID
    foreach ($exportdir as $userdir) {
        if ($userdir->isDot()) {
            continue;
        }
        // Each user's directory contains one directory for each export
        // they made, named as the unix timestamp of the time they
        // generated it
        $udir = new DirectoryIterator($basedir . $userdir->getFilename());
        foreach ($udir as $dir) {
            if ($dir->isDot()) {
                continue;
            }
            if ($dir->getCTime() < $mintime) {
                rmdirr($basedir . $userdir->getFilename() . '/' . $dir->getFilename());
            }
        }
    }
    // Remove any rows from the export_archive that are older than 24 hours and are not exports for submissions
    delete_records_sql('DELETE FROM {export_archive} WHERE submission = 0 AND ctime < ?', array(date('Y-m-d H:i:s', $mintime)));
}
Example #2
Show file File: Cron.php Project: burbuja/indefero
0
 /**
  * Remove orphan repositories.
  */
 public static function removeOrphanRepositories()
 {
     $path = Pluf::f('idf_plugin_syncgit_base_repositories', '/home/git/repositories');
     if (!is_dir($path) || is_link($path)) {
         throw new Pluf_Exception_SettingError(sprintf('Directory %s does not exist! Setting "idf_plugin_syncgit_base_repositories not set.', $path));
     }
     if (!is_writable($path)) {
         throw new Exception(sprintf('Repository %s is not writable.', $path));
     }
     $projects = array();
     foreach (Pluf::factory('IDF_Project')->getList() as $project) {
         $projects[] = $project->shortname;
     }
     unset($project);
     $it = new DirectoryIterator($path);
     $orphans = array();
     while ($it->valid()) {
         if (!$it->isDot() && $it->isDir() && !in_array(basename($it->getFileName(), '.git'), $projects)) {
             $orphans[] = $it->getPathName();
         }
         $it->next();
     }
     if (count($orphans)) {
         $cmd = Pluf::f('idf_exec_cmd_prefix', '') . 'rm -rf ' . implode(' ', $orphans);
         exec($cmd);
         clearstatcache();
         while (list(, $project) = each($orphans)) {
             if (is_dir($project)) {
                 throw new Exception(sprintf('Cannot remove %s directory.', $project));
             }
         }
     }
 }
Example #3
Show file File: zip_packer.php Project: evltuma/moodle
0
 /**
  * Perform archiving file from file path.
  *
  * @param zip_archive $ziparch zip archive instance
  * @param string $archivepath file path to archive
  * @param string $file path name of the file
  * @param file_progress $progress Progress indicator callback or null if not required
  * @return bool success
  */
 private function archive_pathname($ziparch, $archivepath, $file, file_progress $progress = null)
 {
     // Record progress each time this function is called.
     if ($progress) {
         $progress->progress();
     }
     if (!file_exists($file)) {
         return false;
     }
     if (is_file($file)) {
         if (!is_readable($file)) {
             return false;
         }
         return $ziparch->add_file_from_pathname($archivepath, $file);
     }
     if (is_dir($file)) {
         if ($archivepath !== '') {
             $ziparch->add_directory($archivepath);
         }
         $files = new DirectoryIterator($file);
         foreach ($files as $file) {
             if ($file->isDot()) {
                 continue;
             }
             $newpath = $archivepath . '/' . $file->getFilename();
             $this->archive_pathname($ziparch, $newpath, $file->getPathname(), $progress);
         }
         unset($files);
         // Release file handles.
         return true;
     }
 }
Example #4
Show file File: svgtool.php Project: gabrielrosset/moodle
0
/**
 * Recursively works through directories of this theme, finding and fixing SVG images.
 *
 * @param string $base
 * @param string $sub
 * @param string $filecallback
 * @param array $blacklist
 */
function core_admin_recurse_svgs($base, $sub, $filecallback, $blacklist)
{
    if (is_dir("{$base}/{$sub}")) {
        $items = new DirectoryIterator("{$base}/{$sub}");
        foreach ($items as $item) {
            if ($item->isDot()) {
                continue;
            }
            $file = $item->getFilename();
            core_admin_recurse_svgs("{$base}/{$sub}", $file, $filecallback, $blacklist);
        }
        unset($item);
        unset($items);
        return;
    } else {
        if (is_file("{$base}/{$sub}")) {
            if (substr($sub, -4) !== '.svg') {
                return;
            }
            $file = realpath("{$base}/{$sub}");
            if (in_array($file, $blacklist)) {
                return;
            }
            $filecallback($file);
        }
    }
}
Example #5
Show file File: session.php Project: klas/joomla-cms
0
 /**
  * Get the session handlers
  *
  * @return  array  An array of available session handlers
  *
  * @since   11.1
  */
 public static function getStores()
 {
     $connectors = array();
     // Get an iterator and loop trough the driver classes.
     $iterator = new DirectoryIterator(__DIR__ . '/storage');
     /* @type  $file  DirectoryIterator */
     foreach ($iterator as $file) {
         $fileName = $file->getFilename();
         // Only load for php files.
         if (!$file->isFile() || $file->getExtension() != 'php') {
             continue;
         }
         // Derive the class name from the type.
         $class = str_ireplace('.php', '', 'JSessionStorage' . ucfirst(trim($fileName)));
         // If the class doesn't exist we have nothing left to do but look at the next type. We did our best.
         if (!class_exists($class)) {
             continue;
         }
         // Sweet!  Our class exists, so now we just need to know if it passes its test method.
         if ($class::isSupported()) {
             // Connector names should not have file extensions.
             $connectors[] = str_ireplace('.php', '', $fileName);
         }
     }
     return $connectors;
 }
Example #6
Show file File: resetfilesrights.cmd.php Project: CREASIG/lizmap-web-client
0
 protected function setRights($path)
 {
     if ($path == '' || $path == '/' || $path == DIRECTORY_SEPARATOR || !file_exists($path)) {
         return false;
     }
     if (is_file($path)) {
         if ($this->config->doChmod) {
             chmod($path, intval($this->config->chmodFileValue, 8));
         }
         if ($this->config->doChown) {
             chown($path, $this->config->chownUser);
             chgrp($path, $this->config->chownGroup);
         }
         return true;
     }
     if (!is_dir($path)) {
         return false;
     }
     if ($this->config->doChmod) {
         chmod($path, intval($this->config->chmodDirValue, 8));
     }
     if ($this->config->doChown) {
         chown($path, $this->config->chownUser);
         chgrp($path, $this->config->chownGroup);
     }
     $dir = new DirectoryIterator($path);
     foreach ($dir as $dirContent) {
         if (!$dirContent->isDot()) {
             $this->setRights($dirContent->getPathName());
         }
     }
     unset($dir);
     unset($dirContent);
     return true;
 }
Example #7
Show file File: InvoicesCountersController.php Project: malamalca/lil-documents
0
 /**
  * admin_edit method
  *
  * @param int $id
  * @return void
  */
 public function admin_edit($id = null)
 {
     $this->InvoicesCounter->recursive = -1;
     if (!empty($this->data)) {
         if ($this->InvoicesCounter->save($this->data)) {
             Cache::delete('LilInvoices.sidebarCounters', 'Lil');
             $this->setFlash(__d('lil_invoices', 'Counter has been saved.'));
             $this->doRedirect(array('action' => 'index'));
         } else {
             $this->setFlash(__d('lil_invoices', 'Please verify that the information is correct.'), 'error');
         }
     } else {
         if (!empty($id)) {
             $this->data = $this->InvoicesCounter->read(null, $id);
         }
     }
     $this->setupRedirect();
     $layouts = array();
     $files = new DirectoryIterator(App::pluginPath('LilInvoices') . 'View' . DS . 'Reports');
     foreach ($files as $item) {
         if ($item->isFile() && ($basename = $item->getBasename('.ctp'))) {
             $layouts[$basename] = $basename;
         }
     }
     $this->set(compact('layouts'));
 }
Example #8
Show file File: CodeSniffer.php Project: Flesh192/magento
0
 /**
  * Get a list of all coding standards installed.
  *
  * Coding standards are directories located in the
  * CodeSniffer/Standards directory. Valid coding standards
  * include a Sniffs subdirectory.
  *
  * @param boolean $includeGeneric If true, the special "Generic"
  *                                coding standard will be included
  *                                if installed.
  * @param string  $standardsDir   A specific directory to look for standards
  *                                in. If not specified, PHP_CodeSniffer will
  *                                look in its default locations.
  *
  * @return array
  * @see isInstalledStandard()
  */
 public static function getInstalledStandards($includeGeneric = false, $standardsDir = '')
 {
     $installedStandards = array();
     if ($standardsDir === '') {
         $installedPaths = array(dirname(__FILE__) . '/CodeSniffer/Standards');
         $configPaths = PHP_CodeSniffer::getConfigData('installed_paths');
         if ($configPaths !== null) {
             $installedPaths = array_merge($installedPaths, explode(',', $configPaths));
         }
     } else {
         $installedPaths = array($standardsDir);
     }
     foreach ($installedPaths as $standardsDir) {
         $di = new DirectoryIterator($standardsDir);
         foreach ($di as $file) {
             if ($file->isDir() === true && $file->isDot() === false) {
                 $filename = $file->getFilename();
                 // Ignore the special "Generic" standard.
                 if ($includeGeneric === false && $filename === 'Generic') {
                     continue;
                 }
                 // Valid coding standard dirs include a standard class.
                 $csFile = $file->getPathname() . '/ruleset.xml';
                 if (is_file($csFile) === true) {
                     // We found a coding standard directory.
                     $installedStandards[] = $filename;
                 }
             }
         }
     }
     //end foreach
     return $installedStandards;
 }
Example #9
Show file File: Autobackup.php Project: Maxlander/shixi
0
 private function getAllBackups($path)
 {
     $backupsArr = array();
     if (is_dir($path)) {
         $di = new DirectoryIterator($path);
         $backupsArr = array();
         foreach ($di as $file) {
             $fileName = $file->getFilename();
             if (!$file->isDir() && !$file->isLink() && $fileName != '.htaccess') {
                 $cTime = $file->getCTime();
                 $backupsArr[$cTime]['name'] = $fileName;
                 if (preg_match('/mysqldump/', $fileName)) {
                     $backupsArr[$cTime]['type'] = 'Site database only';
                 } elseif (preg_match('/full_backup/', $fileName)) {
                     $backupsArr[$cTime]['type'] = 'Full site backup';
                 } elseif (preg_match('/backup/', $fileName)) {
                     $backupsArr[$cTime]['type'] = 'Site files only';
                 } else {
                     $backupsArr[$cTime]['type'] = 'Unknown';
                 }
                 $pattern = '/(\\w+)_(\\d+)_(\\d+)_(\\d+)__(\\d+)_(\\d+).tar.gz/i';
                 $replacement = '$2-$3-$4 $5:$6';
                 $backupsArr[$cTime]['date'] = preg_replace($pattern, $replacement, $fileName);
             }
         }
         return $backupsArr;
     }
     return $backupsArr;
 }
Example #10
Show file File: driver.php Project: SysBind/joomla-cms
0
 /**
  * Get a list of available database connectors.  The list will only be populated with connectors that both
  * the class exists and the static test method returns true.  This gives us the ability to have a multitude
  * of connector classes that are self-aware as to whether or not they are able to be used on a given system.
  *
  * @return  array  An array of available database connectors.
  *
  * @since   11.1
  */
 public static function getConnectors()
 {
     $connectors = array();
     // Get an iterator and loop trough the driver classes.
     $iterator = new DirectoryIterator(__DIR__ . '/driver');
     /* @type  $file  DirectoryIterator */
     foreach ($iterator as $file) {
         $fileName = $file->getFilename();
         // Only load for php files.
         if (!$file->isFile() || $file->getExtension() != 'php') {
             continue;
         }
         // Block the ext/mysql driver for PHP 7
         if ($fileName === 'mysql.php' && PHP_MAJOR_VERSION >= 7) {
             continue;
         }
         // Derive the class name from the type.
         $class = str_ireplace('.php', '', 'JDatabaseDriver' . ucfirst(trim($fileName)));
         // If the class doesn't exist we have nothing left to do but look at the next type. We did our best.
         if (!class_exists($class)) {
             continue;
         }
         // Sweet!  Our class exists, so now we just need to know if it passes its test method.
         if ($class::isSupported()) {
             // Connector names should not have file extensions.
             $connectors[] = str_ireplace('.php', '', $fileName);
         }
     }
     return $connectors;
 }
Example #11
Show file File: AnotherComplexClass.php Project: maab127/default7
0
 /**
  * Builds and returns an array of class names => file names of all
  * tx_*.php files in the extension's Classes directory and its sub-
  * directories.
  *
  * @param string $packageKey
  * @param string $subDirectory: for recursion
  * @param int $recursionLevel: maximum depth of recursion
  * @return array
  * @author Robert Lemke <robert@typo3.org>
  * @author adapted for TYPO3v4 by Jochen Rau <jochen.rau@typoplanet.de>
  * @throws Exception if recursion into directories was too deep or another error occurred
  */
 protected function buildArrayOfClassFiles($packageKey, $subDirectory = '', $recursionLevel = 0)
 {
     $classFiles = array();
     if (strpos($packageKey, '/') === FALSE) {
         $currentPath = $this->getPackagePath($packageKey) . self::DIRECTORY_CLASSES . $subDirectory;
     } else {
         $currentPath = $this->getPackagePath($packageKey) . $subDirectory;
     }
     if (!is_dir($currentPath)) {
         return array();
     }
     if ($recursionLevel > 100) {
         throw new Exception('Recursion too deep.');
     }
     try {
         $classesDirectoryIterator = new DirectoryIterator($currentPath);
         while ($classesDirectoryIterator->valid()) {
             $filename = $classesDirectoryIterator->getFilename();
             if ($filename[0] != '.') {
                 if (is_dir($currentPath . $filename)) {
                     $classFiles = array_merge($classFiles, $this->buildArrayOfClassFiles($packageKey, $subDirectory . $filename . '/', $recursionLevel + 1));
                 } else {
                     if (substr($filename, 0, 3) == self::PACKAGE_PREFIX . '_' && substr($filename, -4, 4) == '.php') {
                         $classFiles[substr($filename, 0, -4)] = $currentPath . $filename;
                     }
                 }
             }
             $classesDirectoryIterator->next();
         }
     } catch (Exception $exception) {
         throw new Exception($exception->getMessage());
     }
     return $classFiles;
 }
Example #12
Show file File: Command.php Project: buttasg/cowgirlk
0
 /**
  * Try to register commands automatically
  *
  * @return null
  */
 public static function registerCommands()
 {
     $pathCommands = dirname(__FILE__) . DIRECTORY_SEPARATOR . basename(__FILE__, ".php");
     $f = new DirectoryIterator($pathCommands);
     foreach ($f as $file) {
         /** @var $file DirectoryIterator */
         if (!$file->isFile()) {
             continue;
         }
         $pattern = preg_match("/(.*)_Header\\.php/imsu", $file->getFilename(), $matches);
         if (!$pattern) {
             continue;
         }
         include $file->getPathname();
         if (!isset($commands)) {
             continue;
         }
         $class = __CLASS__ . "_" . $matches[1];
         foreach ($commands as $k => $v) {
             $commands[$k]['class'] = $class;
             self::$_commandsAll[$k] = $commands[$k];
         }
         self::$_commandsByClass[$class] = $commands;
     }
 }
Example #13
Show file File: base.php Project: 453111208/bbc
0
 public function maintenance_theme_files($platform, $theme_dir = '')
 {
     if (!$theme_dir) {
         return;
     }
     set_time_limit(0);
     cacheobject::init(false);
     header('Content-type: text/html;charset=utf-8');
     ignore_user_abort(false);
     ob_implicit_flush(1);
     ini_set('implicit_flush', true);
     kernel::$console_output = true;
     while (ob_get_level()) {
         ob_end_flush();
     }
     echo str_repeat("", 1024);
     echo '<pre>';
     echo '>update themes' . "\n";
     if ($theme_dir == THEME_DIR) {
         $dir = new DirectoryIterator($theme_dir);
         foreach ($dir as $file) {
             $filename = $file->getFilename();
             if ($filename[0] == '.') {
                 continue;
             } else {
                 $this->update_theme_widgets($platform, $filename);
             }
         }
     } else {
         $this->update_theme_widgets($platform, $theme_dir);
     }
     echo 'ok.</pre>';
 }
Example #14
Show file File: helper.php Project: Keneth1212/moodle
0
 /**
  * Returns an array of plugins without using core methods.
  *
  * This function explicitly does NOT use core functions as it will in some circumstances be called before Moodle has
  * finished initialising. This happens when loading configuration for instance.
  *
  * @return string
  */
 public static function early_get_cache_plugins()
 {
     global $CFG;
     $result = array();
     $ignored = array('CVS', '_vti_cnf', 'simpletest', 'db', 'yui', 'tests');
     $fulldir = $CFG->dirroot . '/cache/stores';
     $items = new DirectoryIterator($fulldir);
     foreach ($items as $item) {
         if ($item->isDot() or !$item->isDir()) {
             continue;
         }
         $pluginname = $item->getFilename();
         if (in_array($pluginname, $ignored)) {
             continue;
         }
         if (!is_valid_plugin_name($pluginname)) {
             // Better ignore plugins with problematic names here.
             continue;
         }
         $result[$pluginname] = $fulldir . '/' . $pluginname;
         unset($item);
     }
     unset($items);
     return $result;
 }
Example #15
Show file File: package.php Project: bellodox/ITPConnect
0
 public function buildPlugins()
 {
     $types = array();
     $pluginFiles = array();
     // Get plugins types
     $pluginsDir = new DirectoryIterator($this->pluginsDir);
     foreach ($pluginsDir as $pluginTypeInfo) {
         if (!$pluginTypeInfo->isDot()) {
             $types[] = $pluginTypeInfo->getFilename();
         }
     }
     foreach ($types as $type) {
         $typeDir = $this->pluginsDir . DIRECTORY_SEPARATOR . $type;
         // Get the plugin type
         $typeDirIterator = new DirectoryIterator($typeDir);
         foreach ($typeDirIterator as $pluginInfo) {
             if (!$pluginInfo->isDot()) {
                 $pluginFiles = array();
                 // Get a module directory
                 $sourceDir = $typeDir . DIRECTORY_SEPARATOR . $pluginInfo->getFilename();
                 // Get the files of the module
                 $pluginDirIterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($sourceDir));
                 while ($pluginDirIterator->valid()) {
                     if (!$pluginDirIterator->isDot()) {
                         $pluginFiles[] = $pluginDirIterator->getSubPathName();
                     }
                     $pluginDirIterator->next();
                 }
                 $destFile = $this->dest . DIRECTORY_SEPARATOR . $pluginInfo->getFilename() . ".zip";
                 // Build archive
                 $this->createArchive($pluginFiles, $sourceDir, $destFile);
             }
         }
     }
 }
Example #16
Show file File: TearDownAfter.php Project: cboelter/credis
0
 public static function tearDownAfterClass()
 {
     if (preg_match('/^WIN/', strtoupper(PHP_OS))) {
         echo "Please kill all Redis instances manually:" . PHP_EOL;
     } else {
         chdir(__DIR__);
         $directoryIterator = new DirectoryIterator(__DIR__);
         foreach ($directoryIterator as $item) {
             if (!$item->isfile() || !preg_match('/^redis\\-(.+)\\.pid$/', $item->getFilename())) {
                 continue;
             }
             $pid = trim(file_get_contents($item->getFilename()));
             if (function_exists('posix_kill')) {
                 posix_kill($pid, 15);
             } else {
                 exec('kill ' . $pid);
             }
         }
         unlink('dump.rdb');
         unlink('redis-master.conf');
         unlink('redis-slave.conf');
         unlink('redis-sentinel.conf');
         rename('redis-master.conf.bak', 'redis-master.conf');
         rename('redis-slave.conf.bak', 'redis-slave.conf');
         rename('redis-sentinel.conf.bak', 'redis-sentinel.conf');
     }
 }
Example #17
Show file File: analytics.php Project: SwiftDeal/detectr
0
 /**
  * @before _secure, _admin
  */
 public function logs($action = "", $name = "")
 {
     $this->seo(array("title" => "Activity Logs", "view" => $this->getLayoutView()));
     $view = $this->getActionView();
     if ($action == "unlink") {
         $file = APP_PATH . "/logs/" . $name . ".txt";
         @unlink($file);
         $this->redirect("/analytics/logs");
     }
     $logs = array();
     $path = APP_PATH . "/logs";
     $iterator = new DirectoryIterator($path);
     foreach ($iterator as $item) {
         if (!$item->isDot() && substr($item->getFilename(), 0, 1) != ".") {
             $logs[] = $item->getFilename();
         }
     }
     arsort($logs);
     // find the directory size
     exec('du -h ' . $path, $output, $return);
     if ($return == 0) {
         $output = array_pop($output);
         $output = explode("/", $output);
         $size = array_shift($output);
         $size = trim($size);
     } else {
         $size = 'Failed to get size';
     }
     $view->set("size", $size);
     $view->set("logs", $logs);
 }
Example #18
Show file File: session.php Project: shoffmann52/install-from-web-server
0
 /**
  * Get the session handlers
  *
  * @return  array  An array of available session handlers
  *
  * @since   11.1
  */
 public static function getStores()
 {
     $connectors = array();
     // Get an iterator and loop trough the driver classes.
     $iterator = new DirectoryIterator(__DIR__ . '/storage');
     foreach ($iterator as $file) {
         $fileName = $file->getFilename();
         // Only load for php files.
         // Note: DirectoryIterator::getExtension only available PHP >= 5.3.6
         if (!$file->isFile() || substr($fileName, strrpos($fileName, '.') + 1) != 'php') {
             continue;
         }
         // Derive the class name from the type.
         $class = str_ireplace('.php', '', 'JSessionStorage' . ucfirst(trim($fileName)));
         // If the class doesn't exist we have nothing left to do but look at the next type. We did our best.
         if (!class_exists($class)) {
             continue;
         }
         // Sweet!  Our class exists, so now we just need to know if it passes its test method.
         if ($class::isSupported()) {
             // Connector names should not have file extensions.
             $connectors[] = str_ireplace('.php', '', $fileName);
         }
     }
     return $connectors;
 }
Example #19
Show file File: api.php Project: raylouis/kvwebme
0
/**
 * make a purchase order
 *
 * @return null
 */
function ClassifiedAds_makePurchaseOrder()
{
    if (!isset($_SESSION['userdata']['id'])) {
        $email = $_REQUEST['email'];
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return array('error' => __('invalid email address'));
        }
        dbQuery('insert into user_accounts set email="' . addslashes($email) . '",' . 'name="' . addslashes($email) . '",active=1,date_created=now()');
        $user_id = dbLastInsertId();
        $dirname = USERBASE . '/f/userfiles/' . $user_id . '/classified-ads-upload';
        mkdir($dirname, 0777, true);
        $olddirname = USERBASE . '/f/userfiles/' . $_SESSION['tmpUID'] . '/classified-ads-upload';
        $dir = new DirectoryIterator($olddirname);
        foreach ($dir as $file) {
            if ($file->isDot()) {
                continue;
            }
            $fname = $file->getFilename();
            rename($olddirname . '/' . $fname, $dirname . '/' . $fname);
        }
    } else {
        $user_id = $_SESSION['userdata']['id'];
        $dirname = USERBASE . '/f/userfiles/' . $user_id . '/classified-ads-upload';
    }
    $type_id = (int) $_REQUEST['type_id'];
    $days = (int) $_REQUEST['days'];
    $phone = $_REQUEST['phone'];
    $location = $_REQUEST['location'];
    $cost = $_REQUEST['cost'];
    $title = $_REQUEST['title'];
    $description = $_REQUEST['description'];
    dbQuery('insert into classifiedads_purchase_orders set user_id=' . $user_id . ', type_id=' . $type_id . ', days=' . $days . ', title="' . addslashes($title) . '"' . ', phone="' . addslashes($phone) . '", location="' . addslashes($location) . '"' . ', cost="' . addslashes($cost) . '", category_id=' . (int) $_REQUEST['category_id'] . ', description="' . addslashes($description) . '"');
    $ad_id = dbLastInsertId();
    $dir = new DirectoryIterator($dirname);
    mkdir($dirname . '/' . $ad_id, 0777, true);
    foreach ($dir as $file) {
        if ($file->isDot() || $file->isDir()) {
            continue;
        }
        $fname = $file->getFilename();
        rename($dirname . '/' . $fname, $dirname . '/' . $ad_id . '/' . $fname);
    }
    $id = dbLastInsertId();
    if ($cost == 0) {
        ClassifiedAds_publish($id);
    }
    return array('id' => $id);
}
Example #20
Show file File: getIncomingMedia.php Project: ChapResearch/CROMA
0
function getIncomingMedia()
{
    $media = array();
    if (TYPE == 'release') {
        $basepath = '/home/pics/imageimport/';
    } else {
        if (TYPE == 'test') {
            $basepath = '/home/test-pics/imageimport/';
        }
    }
    $dir = new DirectoryIterator($basepath);
    // loop through all messages
    foreach ($dir as $fileinfo) {
        // if this is a valid file
        if (!$fileinfo->isDot()) {
            $dir_name = $fileinfo->getFilename();
            $sub_dir = new DirectoryIterator($basepath . $dir_name);
            $full_contents = file_get_contents($basepath . $dir_name . "/message");
            $UID = getSender($full_contents);
            // set up the UID for the message
            if ($UID != false) {
                $media['UID'] = $UID;
                $title = getSubject($full_contents);
                // set up the title for the pictures
                $media['title'] = $title;
                // process sent date
                $sentDate = getSentDate($full_contents);
                $sentDate = strtotime($sentDate);
                $media['dateEntered'] = dbDatePHP2SQL($sentDate);
                // cut the body of the email down to size (and add "...")
                $media['description'] = chopString(file_get_contents("{$basepath}{$dir_name}/part1"), MAX_DESCRIPTION_CHAR - 3, true);
                // loop through all attachments
                foreach ($sub_dir as $fileinfo2) {
                    // if this is a valid file
                    if (!$fileinfo2->isDot()) {
                        $fileName = $fileinfo2->getFilename();
                        $filepath = $basepath . $dir_name . '/' . $fileName;
                        // if this is an image
                        if ($fileName != 'part1' && $fileName != 'part2' && $fileName != 'message') {
                            // save the image to drupal
                            $contents = file_get_contents($filepath);
                            $file = file_save_data($contents, 'public://' . $fileName, FILE_EXISTS_REPLACE);
                            $media['FID'] = $file->fid;
                            dbAddMedia($media);
                            // add the final media entry
                        }
                        unlink($filepath);
                        // delete the file
                    }
                }
                // end of attachment processing
                rmdir($basepath . $dir_name);
                // delete the directory
            }
            // end of single message processing
        }
    }
    // end of big foreach
}
Example #21
Show file File: file.php Project: janaece/globalclassroom4_clean
0
function file_cleanup_old_cached_files()
{
    global $THEME;
    $dirs = array('', '/profileicons');
    foreach (get_all_theme_objects() as $basename => $theme) {
        $dirs[] = '/profileicons/no_userphoto/' . $basename;
    }
    foreach ($dirs as $dir) {
        $basedir = get_config('dataroot') . 'artefact/file' . $dir . '/resized/';
        if (!check_dir_exists($basedir, false)) {
            continue;
        }
        $mintime = time() - 12 * 7 * 24 * 60 * 60;
        // delete caches older than 12 weeks
        // Cached files are stored in a three tier md5sum layout
        // The actual files are stored in the third directory
        // This loops through all three directories, then checks the files for age
        // It cleans up any empty directories on the way down again
        $iter1 = new DirectoryIterator($basedir);
        foreach ($iter1 as $dir1) {
            if ($dir1->isDot()) {
                continue;
            }
            $dir1path = $dir1->getPath() . '/' . $dir1->getFilename();
            $iter2 = new DirectoryIterator($dir1path);
            foreach ($iter2 as $dir2) {
                if ($dir2->isDot()) {
                    continue;
                }
                $dir2path = $dir2->getPath() . '/' . $dir2->getFilename();
                $iter3 = new DirectoryIterator($dir2path);
                foreach ($iter3 as $dir3) {
                    if ($dir3->isDot()) {
                        continue;
                    }
                    $dir3path = $dir3->getPath() . '/' . $dir3->getFilename();
                    $fileiter = new DirectoryIterator($dir3path);
                    foreach ($fileiter as $file) {
                        if ($file->isFile() && $file->getCTime() < $mintime) {
                            unlink($file->getPath() . '/' . $file->getFilename());
                        }
                    }
                    if (sizeof(scandir($dir3path)) <= 2) {
                        // first 2 entries are . and ..
                        rmdir($dir3path);
                    }
                }
                if (sizeof(scandir($dir2path)) <= 2) {
                    // first 2 entries are . and ..
                    rmdir($dir2path);
                }
            }
            if (sizeof(scandir($dir1path)) <= 2) {
                // first 2 entries are . and ..
                rmdir($dir1path);
            }
        }
    }
}
Example #22
Show file File: class.lang.php Project: jurajkapsz/symphony-2
0
 /**
  * Fetch all languages available in the core language folder and the language extensions.
  * The function stores all language information in the private variable `$_languages`.
  * It contains an array with the name and handle of each language and an array of all
  * extensions available in that language.
  *
  * @throws UnexpectedValueException
  * @throws RuntimeException
  */
 private static function fetch()
 {
     // Fetch extensions
     $extensions = new DirectoryIterator(EXTENSIONS);
     // Language extensions
     foreach ($extensions as $extension) {
         if ($extension->isDot() || $extension->isFile()) {
             continue;
         }
         // Core translations
         $core_handle = strpos($extension->getFilename(), 'lang_') !== false ? str_replace('lang_', '', $extension->getFilename()) : null;
         // Loop over the `/lang` directory of this `$extension` searching for language
         // files. If `/lang` isn't a directory, `UnexpectedValueException` will be
         // thrown.
         try {
             $path = $extension->getPathname() . '/lang';
             if (!is_dir($path)) {
                 continue;
             }
             $directory = new DirectoryIterator($path);
             foreach ($directory as $file) {
                 if ($file->isDot() || !preg_match('/\\.php$/', $file->getPathname())) {
                     continue;
                 }
                 include $file->getPathname();
                 // Get language code
                 $code = explode('.', $file);
                 $code = $code[1];
                 $lang = isset(self::$_languages[$code]) ? self::$_languages[$code] : null;
                 // Available extensions
                 $extensions = isset($lang) ? $lang['extensions'] : array();
                 // Core translations
                 if ($core_handle) {
                     $handle = $core_handle;
                     // Extension translations
                 } else {
                     $handle = isset($lang) ? $lang['handle'] : null;
                     $extensions = array_merge(array($extension->getFilename()), $extensions);
                 }
                 // Merge languages ($about is declared inside the included $file)
                 $temp = self::createLanguage($code, $about['name'], $handle, $extensions);
                 if (isset($lang)) {
                     foreach ($lang as $key => $value) {
                         // Prevent missing or nulled values overwriting existing values
                         // which can occur if a translation file is not correct.
                         if (!isset($temp[$code][$key]) || empty($temp[$code][$key])) {
                             continue;
                         }
                         self::$_languages[$code][$key] = $temp[$code][$key];
                     }
                 } else {
                     self::$_languages[$code] = $temp[$code];
                 }
             }
         } catch (Exception $ex) {
             continue;
         }
     }
 }
Example #23
Show file File: Document.php Project: fredcido/simuweb
0
 /**
  *
  * @param string $dir
  * @return array 
  */
 protected function _listCasesFiles($dir)
 {
     $dir .= $this->_ds . 'cases';
     if (!is_dir($dir)) {
         mkdir($dir);
     }
     $ceops = $this->_listCeops();
     $casesClient = $this->_casesClient();
     $userCeop = md5(Zend_Auth::getInstance()->getIdentity()->fk_id_dec);
     $cases = array();
     $ceopIterator = new DirectoryIterator($dir);
     foreach ($ceopIterator as $ceop) {
         if (!$ceop->isDir() || $ceop->isDot()) {
             continue;
         }
         $caseIterator = new DirectoryIterator($ceop->getPathname());
         $currentCeop = $ceop->getFilename();
         $ceop = array('name' => $ceops[$currentCeop], 'cases' => array());
         foreach ($caseIterator as $caseItem) {
             if (!$caseItem->isDir() || $caseItem->isDot()) {
                 continue;
             }
             $currentCase = $caseItem->getFilename();
             $case = array('name' => $casesClient[$currentCase], 'files' => array());
             $fileIterator = new FilesystemIterator($caseItem->getPathname(), FilesystemIterator::SKIP_DOTS);
             foreach ($fileIterator as $file) {
                 $case['files'][] = array('path' => $this->publicFileUrl($file->getPathname()), 'name' => $file->getBasename(), 'editable' => $userCeop == $currentCeop);
             }
             $ceop['cases'][] = $case;
         }
         $cases[] = $ceop;
     }
     return $cases;
 }
Example #24
Show file File: Command.php Project: Tjorriemorrie/app
0
 /**
  * Collects all logger options and the configuration name.
  *
  * @return array(string=>string)
  */
 protected function collectLogOptions()
 {
     if ($this->_logOptions !== null) {
         return $this->_logOptions;
     }
     $this->_logOptions = array();
     // Get all include paths
     $paths = explode(PATH_SEPARATOR, get_include_path());
     $paths[] = dirname(__FILE__) . '/../../../';
     foreach ($paths as $path) {
         $path .= '/PHP/Depend/Log';
         if (is_dir($path) === false) {
             continue;
         }
         $dirs = new DirectoryIterator($path);
         foreach ($dirs as $dir) {
             if (!$dir->isDir() || substr($dir->getFilename(), 0, 1) === '.') {
                 continue;
             }
             $files = new DirectoryIterator($dir->getPathname());
             foreach ($files as $file) {
                 if (!$file->isFile()) {
                     continue;
                 }
                 if (substr($file->getFilename(), -4, 4) !== '.xml') {
                     continue;
                 }
                 $option = '--' . strtolower($dir->getFilename()) . '-' . strtolower(substr($file->getFilename(), 0, -4));
                 $this->_logOptions[$option] = $file->getPathname();
             }
         }
     }
     return $this->_logOptions;
 }
Example #25
Show file File: Storage.php Project: grlf/eyedock
0
 public function getItems($path, array &$actions)
 {
     $items = array();
     $path = filterFilename($path, true);
     $it = new DirectoryIterator($this->root . '/' . $path);
     if ($path && count($it)) {
         $items[] = new Am_Storage_Folder($this, '..', $this->parentPath($path));
     }
     foreach ($it as $r) {
         if ($r->isDot()) {
             continue;
         }
         if ($r->isDir() && $r->isReadable()) {
             $items[] = new Am_Storage_Folder($this, $r->getFilename(), trim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $it->getFilename());
         }
     }
     $it = new DirectoryIterator($this->root . '/' . $path);
     foreach ($it as $r) {
         if ($r->isDot()) {
             continue;
         }
         if ($r->isFile() && $r->isReadable()) {
             $items[] = new Am_Storage_File($this, $r->getFilename(), $r->getSize(), trim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $it->getFilename(), null, null);
         }
     }
     usort($items, array('Am_Storage_Item', '_cmpName'));
     return $items;
 }
Example #26
Show file File: TranslationsCommand.php Project: super-d2/codeigniter_demo
0
 /**
  * Generates summary report for given translation and original directories
  *
  * @param string $sourcePath the directory where the original documentation files are
  * @param string $translationPath the directory where the translated documentation files are
  * @param string $title custom title to use for report
  */
 public function actionReport($sourcePath, $translationPath, $title = 'Translation report')
 {
     $sourcePath = trim($sourcePath, '/\\');
     $translationPath = trim($translationPath, '/\\');
     $results = array();
     $dir = new DirectoryIterator($sourcePath);
     foreach ($dir as $fileinfo) {
         if (!$fileinfo->isDot() && !$fileinfo->isDir()) {
             $translatedFilePath = $translationPath . '/' . $fileinfo->getFilename();
             $sourceFilePath = $sourcePath . '/' . $fileinfo->getFilename();
             $errors = $this->checkFiles($translatedFilePath);
             $diff = empty($errors) ? $this->getDiff($translatedFilePath, $sourceFilePath) : '';
             if (!empty($diff)) {
                 $errors[] = 'Translation outdated.';
             }
             $result = array('errors' => $errors, 'diff' => $diff);
             $results[$fileinfo->getFilename()] = $result;
         }
     }
     // checking if there are obsolete translation files
     $dir = new DirectoryIterator($translationPath);
     foreach ($dir as $fileinfo) {
         if (!$fileinfo->isDot() && !$fileinfo->isDir()) {
             $translatedFilePath = $translationPath . '/' . $fileinfo->getFilename();
             $errors = $this->checkFiles(null, $translatedFilePath);
             if (!empty($errors)) {
                 $results[$fileinfo->getFilename()]['errors'] = $errors;
             }
         }
     }
     $this->renderFile(dirname(__FILE__) . '/translations/report_html.php', array('results' => $results, 'sourcePath' => $sourcePath, 'translationPath' => $translationPath, 'title' => $title));
 }
Example #27
Show file File: component.php Project: EmmanuelYupit/educursos
0
 /**
  * Find classes in directory and recurse to subdirs.
  * @param string $component
  * @param string $fulldir
  * @param string $namespace
  */
 protected static function load_classes($component, $fulldir, $namespace = '')
 {
     if (!is_dir($fulldir)) {
         return;
     }
     $items = new \DirectoryIterator($fulldir);
     foreach ($items as $item) {
         if ($item->isDot()) {
             continue;
         }
         if ($item->isDir()) {
             $dirname = $item->getFilename();
             self::load_classes($component, "{$fulldir}/{$dirname}", $namespace . '\\' . $dirname);
             continue;
         }
         $filename = $item->getFilename();
         $classname = preg_replace('/\\.php$/', '', $filename);
         if ($filename === $classname) {
             // Not a php file.
             continue;
         }
         if ($namespace === '') {
             // Legacy long frankenstyle class name.
             self::$classmap[$component . '_' . $classname] = "{$fulldir}/{$filename}";
         }
         // New namespaced classes.
         self::$classmap[$component . $namespace . '\\' . $classname] = "{$fulldir}/{$filename}";
     }
     unset($item);
     unset($items);
 }