Example #1
0
 function rmdir_r($path)
 {
     if (!is_dir($path)) {
         return false;
     }
     if (!preg_match("/\\/\$/", $path)) {
         $path .= '/';
     }
     $dh = opendir($path);
     while (($file = readdir($dh)) !== false) {
         if ($file == '.' || $file == '..') {
             continue;
         }
         if (is_dir($path . $file)) {
             rmdir_r($path . $file);
         } else {
             if (is_file($path . $file)) {
                 unlink($path . $file);
             }
         }
     }
     closedir($dh);
     rmdir($path);
     return true;
 }
Example #2
0
File: erase.php Project: philum/cms
function plug_erase($del, $dir)
{
    //$del='';
    //$dir='';
    if ($_SESSION['auth'] < 6) {
        return 'no';
    }
    echo $del . '-' . $dir . '-';
    if ($del) {
        unlink($del);
    } elseif ($dir && strpos($dir, '/') != false) {
        rmdir_r($dir);
    }
    //$func='rmdir_r';
    //$r=explore($dir); explode_dir($r,$dir,$func?$func:"removef"); p($r);
    //walk_dir($dir,"removef");
    //rmdir($dir);
    //chmod($dir,0777);
    if ($del) {
        return $del;
    }
    if ($dir) {
        return $dir;
    }
    return lkc('', '/plug/erase.php?del=', 'del file');
}
Example #3
0
File: ifrm.php Project: philum/cms
function ifrgz($dr)
{
    $r = explore($dr);
    $f = 'users/public/ifr' . date('ymd') . '.tar';
    if (!is_file($f)) {
        $ret = plugin('tar', $f, $dr);
    }
    rmdir_r($dr);
    return $ret;
}
Example #4
0
function rmdir_r($dir, $DeleteMe = TRUE)
{
    if (!($dh = @opendir($dir))) {
        return;
    }
    while (false !== ($obj = readdir($dh))) {
        if ($obj == '.' || $obj == '..') {
            continue;
        }
        if (!@unlink($dir . '/' . $obj)) {
            rmdir_r($dir . '/' . $obj, true);
        }
    }
    closedir($dh);
    if ($DeleteMe) {
        @rmdir($dir);
    }
}
Example #5
0
File: del.php Project: philum/cms
function delj($p, $o, $res)
{
    $f = ajxg($res);
    if (!auth(7)) {
        return 'no';
    }
    if ($p == 'file') {
        if (is_file($f)) {
            unlink($f);
        } else {
            return 'error';
        }
    }
    if ($p == 'dir' && $f && strpos($f, '/') != false) {
        echo $f;
        if (is_dir($f)) {
            rmdir_r($f);
        } else {
            return 'error';
        }
    }
    return btn('txtyl', $p . ' ' . $f . ': deleted');
}
Example #6
0
    /**
     * Delete those users from the database which corresponds to the given condition or to the given ids array
     * Note: the delete cascade arrays are handled!
     *
     * @param string the name of this class
     *   Note: This is required until min phpversion will be 5.3. Since PHP 5.3 we can use static::function_name to achieve late static bindings
     * @param string where condition
     * @param array object ids
     * @return mixed # of rows affected or false if error
     */
    static function db_delete_where($class_name, $sql_where, $object_ids = NULL, $params = NULL)
    {
        global $DB;
        $DB->begin();
        if (!empty($sql_where)) {
            $object_ids = $DB->get_col('SELECT user_ID FROM T_users WHERE ' . $sql_where);
        }
        if (!$object_ids) {
            // There is no user to delete
            $DB->commit();
            return;
        }
        // Delete orphan threads per users
        $result = delete_orphan_threads($object_ids);
        // Remove deleted user(s) from posts where it was as last edit user
        $user_ids = implode(',', $object_ids);
        $result = $result && $DB->query('UPDATE T_items__item
								    SET post_lastedit_user_ID = NULL
								  WHERE post_lastedit_user_ID IN ( ' . $user_ids . ' )') !== false;
        $result = $result && $DB->query('UPDATE T_items__version
								    SET iver_edit_user_ID = NULL
								  WHERE iver_edit_user_ID IN ( ' . $user_ids . ' )') !== false;
        // Remove this user from links where it was as last edit user
        $result = $result && $DB->query('UPDATE T_links
								    SET link_lastedit_user_ID = NULL
								  WHERE link_lastedit_user_ID IN ( ' . $user_ids . ' )') !== false;
        if ($result) {
            // Delete the user(s) with all of the cascade objects
            $params['use_transaction'] = false;
            // no need to start a new transaction
            $result = parent::db_delete_where($class_name, $sql_where, $object_ids, $params);
        }
        if ($result !== false) {
            // delete the users' media folders recursively, for all deleted users
            $FileRootCache =& get_FileRootCache();
            foreach ($object_ids as $user_ID) {
                if ($root_directory = $FileRootCache->get_root_dir('user', $user_ID)) {
                    // Delete the folder only when it is detected:
                    rmdir_r($root_directory);
                }
            }
        }
        $result !== false ? $DB->commit() : $DB->rollback();
        return $result;
    }
/**
 * Read messages from server and create posts
 *
 * @param resource $mbox created by pbm_connect() (by reference)
 * @param integer the number of messages to process
 * @return boolean true on success
 */
function pbm_process_messages(&$mbox, $limit)
{
    global $Settings;
    global $pbm_item_files, $pbm_messages, $pbm_items, $post_cntr, $del_cntr, $is_cron_mode;
    // No execution time limit
    set_max_execution_time(0);
    // Are we in test mode?
    $test_mode_on = $Settings->get('eblog_test_mode');
    $post_cntr = 0;
    $del_cntr = 0;
    for ($index = 1; $index <= $limit; $index++) {
        pbm_msg('<hr /><h3>Processing message #' . $index . ':</h3>');
        $strbody = '';
        $hasAttachment = false;
        $hasRelated = false;
        $pbm_item_files = array();
        // reset the value for each new Item
        // Save email to hard drive, otherwise attachments may take a lot of RAM
        if (!($tmpMIME = tempnam(sys_get_temp_dir(), 'b2evoMail'))) {
            pbm_msg(T_('Could not create temporary file.'), true);
            continue;
        }
        imap_savebody($mbox, $tmpMIME, $index);
        // Create random temp directory for message parts
        $tmpDirMIME = pbm_tempdir(sys_get_temp_dir(), 'b2evo_');
        $mimeParser = new mime_parser_class();
        $mimeParser->mbox = 0;
        // Set to 0 for parsing a single message file
        $mimeParser->decode_headers = 1;
        $mimeParser->ignore_syntax_errors = 1;
        $mimeParser->extract_addresses = 0;
        $MIMEparameters = array('File' => $tmpMIME, 'SaveBody' => $tmpDirMIME, 'SkipBody' => 1);
        if (!$mimeParser->Decode($MIMEparameters, $decodedMIME)) {
            pbm_msg(sprintf('MIME message decoding error: %s at position %d.', $mimeParser->error, $mimeParser->error_position), true);
            rmdir_r($tmpDirMIME);
            unlink($tmpMIME);
            continue;
        } else {
            pbm_msg('MIME message decoding successful');
            if (!$mimeParser->Analyze($decodedMIME[0], $parsedMIME)) {
                pbm_msg(sprintf('MIME message analyse error: %s', $mimeParser->error), true);
                rmdir_r($tmpDirMIME);
                unlink($tmpMIME);
                continue;
            }
            // Get message $subject and $post_date from headers (by reference)
            if (!pbm_process_header($parsedMIME, $subject, $post_date)) {
                // Couldn't process message headers
                rmdir_r($tmpDirMIME);
                unlink($tmpMIME);
                continue;
            }
            // TODO: handle type == "message" recursively
            // sam2kb> For some reason imap_qprint() demages HTML text... needs more testing
            if ($parsedMIME['Type'] == 'html') {
                // Mail is HTML
                if ($Settings->get('eblog_html_enabled')) {
                    // HTML posting enabled
                    pbm_msg('HTML message part saved as ' . $parsedMIME['DataFile']);
                    $html_body = file_get_contents($parsedMIME['DataFile']);
                }
                foreach ($parsedMIME['Alternative'] as $alternative) {
                    // First try to get HTML alternative (when possible)
                    if ($alternative['Type'] == 'html' && $Settings->get('eblog_html_enabled')) {
                        // HTML text
                        pbm_msg('HTML alternative message part saved as ' . $alternative['DataFile']);
                        // sam2kb> TODO: we may need to use $html_body here instead
                        $strbody = file_get_contents($alternative['DataFile']);
                        break;
                        // stop after first alternative
                    } elseif ($alternative['Type'] == 'text') {
                        // Plain text
                        pbm_msg('Text alternative message part saved as ' . $alternative['DataFile']);
                        $strbody = imap_qprint(file_get_contents($alternative['DataFile']));
                        break;
                        // stop after first alternative
                    }
                }
            } elseif ($parsedMIME['Type'] == 'text') {
                // Mail is plain text
                pbm_msg('Plain-text message part saved as ' . $parsedMIME['DataFile']);
                $strbody = imap_qprint(file_get_contents($parsedMIME['DataFile']));
            }
            // Check for attachments
            if (!empty($parsedMIME['Attachments'])) {
                $hasAttachment = true;
                foreach ($parsedMIME['Attachments'] as $file) {
                    pbm_msg('Attachment: ' . $file['FileName'] . ' stored as ' . $file['DataFile']);
                }
            }
            // Check for inline images
            if (!empty($parsedMIME['Related'])) {
                $hasRelated = true;
                foreach ($parsedMIME['Related'] as $file) {
                    pbm_msg('Related file with content ID: ' . $file['ContentID'] . ' stored as ' . $file['DataFile']);
                }
            }
            if (count($mimeParser->warnings) > 0) {
                pbm_msg(sprintf('<h4>%d warnings during decode:</h4>', count($mimeParser->warnings)));
                foreach ($mimeParser->warnings as $k => $v) {
                    pbm_msg('Warning: ' . $v . ' at position ' . $k);
                }
            }
        }
        unlink($tmpMIME);
        if (empty($html_body)) {
            // Plain text message
            pbm_msg('Message type: TEXT');
            pbm_msg('Message body: <pre style="font-size:10px">' . htmlspecialchars($strbody) . '</pre>');
            // Process body. First fix different line-endings (dos, mac, unix), remove double newlines
            $content = str_replace(array("\r", "\n\n"), "\n", trim($strbody));
            // First see if there's an <auth> tag with login and password
            if (($auth = pbm_get_auth_tag($content)) === false) {
                // No <auth> tag, let's detect legacy "username:password" on the first line
                $a_body = explode("\n", $content, 2);
                // tblue> splitting only into 2 parts allows colons in the user PW
                // Note: login and password cannot include '<' !
                $auth = explode(':', strip_tags($a_body[0]), 2);
                // Drop the first line with username and password
                $content = $a_body[1];
            }
        } else {
            // HTML message
            pbm_msg('Message type: HTML');
            if (($parsed_message = pbm_prepare_html_message($html_body)) === false) {
                // No 'auth' tag provided, skip to the next message
                rmdir_r($tmpDirMIME);
                continue;
            }
            list($auth, $content) = $parsed_message;
        }
        // TODO: dh> should the password really get trimmed here?!
        $user_pass = isset($auth[1]) ? trim(remove_magic_quotes($auth[1])) : NULL;
        $user_login = trim(evo_strtolower(remove_magic_quotes($auth[0])));
        if (empty($user_login) || empty($user_pass)) {
            pbm_msg(sprintf(T_('Please add username and password in message body in format %s.'), '"&lt;auth&gt;username:password&lt;/auth&gt;"'), true);
            rmdir_r($tmpDirMIME);
            continue;
        }
        // Authenticate user
        pbm_msg('Authenticating user: &laquo;' . $user_login . '&raquo;');
        $pbmUser =& pbm_validate_user_password($user_login, $user_pass);
        if (!$pbmUser) {
            pbm_msg(sprintf(T_('Authentication failed for user &laquo;%s&raquo;'), htmlspecialchars($user_login)), true);
            rmdir_r($tmpDirMIME);
            continue;
        }
        $pbmUser->get_Group();
        // Load group
        if (!empty($is_cron_mode)) {
            // Assign current User if we are in cron mode. This is needed in order to check user permissions
            global $current_User;
            $current_User = duplicate($pbmUser);
        }
        // Activate User's locale
        locale_activate($pbmUser->get('locale'));
        pbm_msg('<b class="green">Success</b>');
        if ($post_categories = xmlrpc_getpostcategories($content)) {
            $main_cat_ID = array_shift($post_categories);
            $extra_cat_IDs = $post_categories;
            pbm_msg('Extra categories: ' . implode(', ', $extra_cat_IDs));
        } else {
            $main_cat_ID = $Settings->get('eblog_default_category');
            $extra_cat_IDs = array();
        }
        pbm_msg('Main category ID: ' . $main_cat_ID);
        $ChapterCache =& get_ChapterCache();
        $pbmChapter =& $ChapterCache->get_by_ID($main_cat_ID, false, false);
        if (empty($pbmChapter)) {
            pbm_msg(sprintf(T_('Requested category %s does not exist!'), $main_cat_ID), true);
            rmdir_r($tmpDirMIME);
            continue;
        }
        $blog_ID = $pbmChapter->blog_ID;
        pbm_msg('Blog ID: ' . $blog_ID);
        $BlogCache =& get_BlogCache();
        $pbmBlog =& $BlogCache->get_by_ID($blog_ID, false, false);
        if (empty($pbmBlog)) {
            pbm_msg(sprintf(T_('Requested blog %s does not exist!'), $blog_ID), true);
            rmdir_r($tmpDirMIME);
            continue;
        }
        // Check permission:
        pbm_msg(sprintf('Checking permissions for user &laquo;%s&raquo; to post to Blog #%d', $user_login, $blog_ID));
        if (!$pbmUser->check_perm('blog_post!published', 'edit', false, $blog_ID)) {
            pbm_msg(T_('Permission denied.'), true);
            rmdir_r($tmpDirMIME);
            continue;
        }
        if (($hasAttachment || $hasRelated) && !$pbmUser->check_perm('files', 'add', false, $blog_ID)) {
            pbm_msg(T_('You have no permission to add/upload files.'), true);
            rmdir_r($tmpDirMIME);
            continue;
        }
        pbm_msg('<b class="green">Success</b>');
        // Remove content after terminator
        $eblog_terminator = $Settings->get('eblog_body_terminator');
        if (!empty($eblog_terminator) && ($os_terminator = evo_strpos($content, $eblog_terminator)) !== false) {
            $content = evo_substr($content, 0, $os_terminator);
        }
        $post_title = pbm_get_post_title($content, $subject);
        // Remove 'title' and 'category' tags
        $content = xmlrpc_removepostdata($content);
        // Remove <br> tags from string start and end
        // We do it here because there might be extra <br> left after deletion of <auth>, <category> and <title> tags
        $content = preg_replace(array('~^(\\s*<br[\\s/]*>\\s*){1,}~i', '~(\\s*<br[\\s/]*>\\s*){1,}$~i'), '', $content);
        if ($hasAttachment || $hasRelated) {
            // Handle attachments
            if (isset($GLOBALS['files_Module'])) {
                if ($mediadir = $pbmBlog->get_media_dir()) {
                    if ($hasAttachment) {
                        pbm_process_attachments($content, $parsedMIME['Attachments'], $mediadir, $pbmBlog->get_media_url(), $Settings->get('eblog_add_imgtag'), 'attach');
                    }
                    if ($hasRelated) {
                        pbm_process_attachments($content, $parsedMIME['Related'], $mediadir, $pbmBlog->get_media_url(), true, 'related');
                    }
                } else {
                    pbm_msg(T_('Unable to access media directory. No attachments processed.'), true);
                }
            } else {
                pbm_msg(T_('Files module is disabled or missing!'), true);
            }
        }
        // CHECK and FORMAT content
        global $Plugins;
        $renderer_params = array('Blog' => &$pbmBlog, 'setting_name' => 'coll_apply_rendering');
        $renderers = $Plugins->validate_renderer_list($Settings->get('eblog_renderers'), $renderer_params);
        pbm_msg('Applying the following text renderers: ' . implode(', ', $renderers));
        // Do some optional filtering on the content
        // Typically stuff that will help the content to validate
        // Useful for code display
        // Will probably be used for validation also
        $Plugins_admin =& get_Plugins_admin();
        $params = array('object_type' => 'Item', 'object_Blog' => &$pbmBlog);
        $Plugins_admin->filter_contents($post_title, $content, $renderers, $params);
        pbm_msg('Filtered post content: <pre style="font-size:10px">' . htmlspecialchars($content) . '</pre>');
        $context = $Settings->get('eblog_html_tag_limit') ? 'commenting' : 'posting';
        $post_title = check_html_sanity($post_title, $context, $pbmUser);
        $content = check_html_sanity($content, $context, $pbmUser);
        global $Messages;
        if ($Messages->has_errors()) {
            // Make it easier for user to find and correct the errors
            pbm_msg("\n" . sprintf(T_('Processing message: %s'), $post_title), true);
            pbm_msg($Messages->get_string(T_('Cannot post, please correct these errors:'), 'error'), true);
            $Messages->clear();
            rmdir_r($tmpDirMIME);
            continue;
        }
        if ($test_mode_on) {
            // Test mode
            pbm_msg('<b class="green">It looks like the post can be successfully saved in the database. However we will not do it in test mode.</b>');
        } else {
            load_class('items/model/_item.class.php', 'Item');
            global $pbm_items, $DB, $localtimenow;
            $post_status = 'published';
            pbm_msg(sprintf('<h4>Saving item "%s" in the database</h4>', $post_title));
            // INSERT NEW POST INTO DB:
            $edited_Item = new Item();
            $edited_Item->set_creator_User($pbmUser);
            $edited_Item->set($edited_Item->lasteditor_field, $pbmUser->ID);
            $edited_Item->set('title', $post_title);
            $edited_Item->set('content', $content);
            $edited_Item->set('datestart', $post_date);
            $edited_Item->set('datemodified', date('Y-m-d H:i:s', $localtimenow));
            $edited_Item->set('main_cat_ID', $main_cat_ID);
            $edited_Item->set('extra_cat_IDs', $extra_cat_IDs);
            $edited_Item->set('status', $post_status);
            $edited_Item->set('locale', $pbmUser->locale);
            $edited_Item->set('renderers', $renderers);
            // INSERT INTO DB:
            $edited_Item->dbinsert('through_email');
            pbm_msg(sprintf('Item created?: ' . (isset($edited_Item->ID) ? 'yes' : 'no')));
            // Execute or schedule notifications & pings:
            $edited_Item->handle_post_processing(true);
            if (!empty($pbm_item_files)) {
                // Attach files
                $FileCache =& get_FileCache();
                $order = 1;
                foreach ($pbm_item_files as $filename) {
                    pbm_msg(sprintf('Saving file "%s" in the database', $filename));
                    $pbmFile =& $FileCache->get_by_root_and_path('collection', $pbmBlog->ID, $filename);
                    $pbmFile->meta = 'notfound';
                    // Save time and don't try to load meta from DB, it's not there anyway
                    $pbmFile->dbsave();
                    pbm_msg(sprintf('File saved?: ' . (isset($pbmFile->ID) ? 'yes' : 'no')));
                    pbm_msg(sprintf('Attaching file "%s" to the post', $filename));
                    // Let's make the link!
                    $pbmLink = new Link();
                    $pbmLink->set('itm_ID', $edited_Item->ID);
                    $pbmLink->set('file_ID', $pbmFile->ID);
                    $pbmLink->set('position', 'aftermore');
                    $pbmLink->set('order', $order++);
                    $pbmLink->dbinsert();
                    pbm_msg(sprintf('File attached?: ' . (isset($pbmLink->ID) ? 'yes' : 'no')));
                }
            }
            // Save posted items sorted by author user for reports
            $pbm_items['user_' . $pbmUser->ID][] = $edited_Item;
            ++$post_cntr;
        }
        pbm_msg('Message posting successful');
        // Delete temporary directory
        rmdir_r($tmpDirMIME);
        if (!$test_mode_on && $Settings->get('eblog_delete_emails')) {
            pbm_msg('Marking message for deletion from inbox: ' . $index);
            imap_delete($mbox, $index);
            ++$del_cntr;
        }
    }
    // Expunge messages marked for deletion
    imap_expunge($mbox);
    return true;
}
/**
 * Read messages from server and save returned emails into DB
 *
 * @param resource $mbox created by dre_connect() (by reference)
 * @param integer the number of messages to process
 * @return boolean true on success
 */
function dre_process_messages(&$mbox, $limit)
{
    //return; // Exit, in development...
    global $Settings;
    global $dre_messages, $dre_emails, $email_cntr, $del_cntr, $is_cron_mode;
    // No execution time limit
    set_max_execution_time(0);
    $email_cntr = 0;
    $del_cntr = 0;
    for ($index = 1; $index <= $limit; $index++) {
        dre_msg('<hr /><h3>Processing message #' . $index . ':</h3>');
        $strbody = '';
        $hasAttachment = false;
        $hasRelated = false;
        // Save email to hard drive, otherwise attachments may take a lot of RAM
        if (!($tmpMIME = tempnam(sys_get_temp_dir(), 'b2evoMail'))) {
            dre_msg(T_('Could not create temporary file.'), true);
            continue;
        }
        imap_savebody($mbox, $tmpMIME, $index);
        // Create random temp directory for message parts
        $tmpDirMIME = dre_tempdir(sys_get_temp_dir(), 'b2evo_');
        $mimeParser = new mime_parser_class();
        $mimeParser->mbox = 0;
        // Set to 0 for parsing a single message file
        $mimeParser->decode_headers = 1;
        $mimeParser->ignore_syntax_errors = 1;
        $mimeParser->extract_addresses = 0;
        $MIMEparameters = array('File' => $tmpMIME, 'SaveBody' => $tmpDirMIME, 'SkipBody' => 1);
        if (!$mimeParser->Decode($MIMEparameters, $decodedMIME)) {
            dre_msg(sprintf('MIME message decoding error: %s at position %d.', $mimeParser->error, $mimeParser->error_position), true);
            rmdir_r($tmpDirMIME);
            unlink($tmpMIME);
            continue;
        } else {
            dre_msg('MIME message decoding successful');
            if (!$mimeParser->Analyze($decodedMIME[0], $parsedMIME)) {
                dre_msg(sprintf('MIME message analyse error: %s', $mimeParser->error), true);
                rmdir_r($tmpDirMIME);
                unlink($tmpMIME);
                continue;
            }
            // Get message $subject and $post_date from headers (by reference)
            if (!dre_process_header($parsedMIME, $subject, $post_date)) {
                // Couldn't process message headers
                rmdir_r($tmpDirMIME);
                unlink($tmpMIME);
                continue;
            }
            // TODO: handle type == "message" recursively
            // sam2kb> For some reason imap_qprint() demages HTML text... needs more testing
            if ($parsedMIME['Type'] == 'html') {
                // Mail is HTML
                dre_msg('HTML message part saved as ' . $parsedMIME['DataFile']);
                $html_body = file_get_contents($parsedMIME['DataFile']);
                foreach ($parsedMIME['Alternative'] as $alternative) {
                    // First try to get HTML alternative (when possible)
                    if ($alternative['Type'] == 'html') {
                        // HTML text
                        dre_msg('HTML alternative message part saved as ' . $alternative['DataFile']);
                        // sam2kb> TODO: we may need to use $html_body here instead
                        $strbody = file_get_contents($alternative['DataFile']);
                        break;
                        // stop after first alternative
                    } elseif ($alternative['Type'] == 'text') {
                        // Plain text
                        dre_msg('Text alternative message part saved as ' . $alternative['DataFile']);
                        $strbody = imap_qprint(file_get_contents($alternative['DataFile']));
                        break;
                        // stop after first alternative
                    }
                }
            } elseif ($parsedMIME['Type'] == 'text') {
                // Mail is plain text
                dre_msg('Plain-text message part saved as ' . $parsedMIME['DataFile']);
                $strbody = imap_qprint(file_get_contents($parsedMIME['DataFile']));
            } elseif ($parsedMIME['Type'] == 'delivery-status') {
                // Mail is delivery-status
                $strbody = '';
                foreach ($decodedMIME[0]['Parts'] as $part) {
                    $strbody .= imap_qprint(file_get_contents($part['BodyFile']));
                }
            }
            if (count($mimeParser->warnings) > 0) {
                dre_msg(sprintf('<h4>%d warnings during decode:</h4>', count($mimeParser->warnings)));
                foreach ($mimeParser->warnings as $k => $v) {
                    dre_msg('Warning: ' . $v . ' at position ' . $k);
                }
            }
        }
        unlink($tmpMIME);
        if (empty($html_body)) {
            // Plain text message
            dre_msg('Message type: TEXT');
            dre_msg('Message body: <pre style="font-size:10px">' . htmlspecialchars($strbody) . '</pre>');
            // Process body. First fix different line-endings (dos, mac, unix), remove double newlines
            $content = str_replace(array("\r", "\n\n"), "\n", trim($strbody));
        } else {
            // HTML message
            dre_msg('Message type: HTML');
            if (($parsed_message = dre_prepare_html_message($html_body)) === false) {
                // No 'auth' tag provided, skip to the next message
                rmdir_r($tmpDirMIME);
                continue;
            }
            list($auth, $content) = $parsed_message;
        }
        dre_msg('<b class="green">Success</b>');
        $message_text = $content;
        // Remove content after terminators
        $content = dre_limit_by_terminators($content);
        global $Messages;
        if ($Messages->has_errors()) {
            // Make it easier for user to find and correct the errors
            dre_msg("\n" . sprintf(T_('Processing message: %s'), $post_title), true);
            dre_msg($Messages->get_string(T_('Cannot post, please correct these errors:'), 'error'), true);
            $Messages->clear();
            rmdir_r($tmpDirMIME);
            continue;
        }
        global $dre_emails, $DB, $localtimenow;
        dre_msg(sprintf('<h4>Saving the returned email in the database</h4>'));
        // Insert a returned email's data into DB
        if ($returned_email = dre_insert_returned_email($content, $message_text, dre_get_headers($decodedMIME))) {
            dre_msg('Error Type: ' . dre_decode_error_type($returned_email['errtype']));
            dre_msg('Error Message: ' . $returned_email['errormsg']);
            ++$email_cntr;
        }
        // Delete temporary directory
        rmdir_r($tmpDirMIME);
        if ($Settings->get('repath_delete_emails')) {
            dre_msg('Marking message for deletion from inbox: ' . $index);
            imap_delete($mbox, $index);
            ++$del_cntr;
        }
    }
    // Expunge messages market for deletion
    imap_expunge($mbox);
    return true;
}
Example #9
0
	public function CleanUpAfterUpload()
	{
			fwrite($this->logger , "Cleaning up after upload\n");
			$dataFolderPath = $this->baseFolderPath.$this->layerName;
			unlink($this->zipFile);
			rmdir_r($dataFolderPath);
			fclose($this->logger);
	}
Example #10
0
function rmdir_r($path)
{
    if (is_dir($path)) {
        foreach (glob($path . "/*") as $file) {
            if ($file != "." && $file != "..") {
                if (is_dir($file)) {
                    rmdir_r($file);
                } else {
                    if (!unlink($file)) {
                        return FALSE;
                    }
                }
            }
        }
        if (rmdir($path)) {
            return TRUE;
        }
    }
    return FALSE;
}
Example #11
0
/**
 * rmdir_r - Remove a directory and all it's contents.
 *
 * @param mixed $dir
 */
function rmdir_r($dir)
{
    $files = array_diff(scandir($dir), array('.', '..'));
    foreach ($files as $file) {
        is_dir("{$dir}/{$file}") ? rmdir_r("{$dir}/{$file}") : unlink("{$dir}/{$file}");
    }
    return rmdir($dir);
}
Example #12
0
    /**
     * Delete user and dependencies from database
     *
     * Includes WAY TOO MANY requests because we try to be compatible with MySQL 3.23, bleh!
     *
     * @param Log Log object where output gets added (by reference).
     */
    function dbdelete(&$Log)
    {
        global $DB, $Plugins;
        if ($this->ID == 0) {
            debug_die('Non persistant object cannot be deleted!');
        }
        $deltype = param('deltype', 'string', '');
        // spammer
        $DB->begin();
        if ($deltype == 'spammer') {
            // If we delete user as spammer we should delete private messaged of this user
            $this->delete_messages();
        } else {
            // If we delete user as not spammer we keep his comments as from anonymous user
            // Transform registered user comments to unregistered:
            $ret = $DB->query('UPDATE T_comments
													SET comment_author_ID = NULL,
															comment_author = ' . $DB->quote($this->get('preferredname')) . ',
															comment_author_email = ' . $DB->quote($this->get('email')) . ',
															comment_author_url = ' . $DB->quote($this->get('url')) . '
													WHERE comment_author_ID = ' . $this->ID);
            if (is_a($Log, 'log')) {
                $Log->add('Transforming user\'s comments to unregistered comments... ' . sprintf('(%d rows)', $ret), 'note');
            }
        }
        // Get list of posts that are going to be deleted (3.23)
        $post_list = implode(',', $DB->get_col('
				SELECT post_ID
				  FROM T_items__item
				 WHERE post_creator_user_ID = ' . $this->ID));
        if (!empty($post_list)) {
            // Delete comments
            $ret = $DB->query("DELETE FROM T_comments\n\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE comment_post_ID IN ({$post_list})");
            if (is_a($Log, 'log')) {
                $Log->add(sprintf('Deleted %d comments on user\'s posts.', $ret), 'note');
            }
            // Delete post extracats
            $ret = $DB->query("DELETE FROM T_postcats\n\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE postcat_post_ID IN ({$post_list})");
            if (is_a($Log, 'log')) {
                $Log->add(sprintf('Deleted %d extracats of user\'s posts\'.', $ret));
                // TODO: geeky wording.
            }
            // Posts will we auto-deleted by parent method
        } else {
            // no posts
            if (is_a($Log, 'log')) {
                $Log->add('No posts to delete.', 'note');
            }
        }
        // Get list of sessions that are going to be deleted
        $sessions_SQL = new SQL();
        $sessions_SQL->SELECT('sess_ID');
        $sessions_SQL->FROM('T_sessions');
        $sessions_SQL->WHERE('sess_user_ID = ' . $this->ID);
        $sessions_list = $DB->get_col($sessions_SQL->get());
        if (!empty($sessions_list)) {
            // Delete all hit logs of this user
            $DB->query('DELETE FROM T_hitlog
					WHERE hit_sess_ID IN ( ' . $DB->quote($sessions_list) . ' )');
        }
        // delete user involved ophan threads
        delete_orphan_threads($this->ID);
        // Remove this user from posts where it was as last edit user
        $DB->query('UPDATE T_items__item
								    SET post_lastedit_user_ID = NULL
								  WHERE post_lastedit_user_ID = ' . $this->ID);
        $DB->query('UPDATE T_items__version
								    SET iver_edit_user_ID = NULL
								  WHERE iver_edit_user_ID = ' . $this->ID);
        // Remove this user from links where it was as last edit user
        $DB->query('UPDATE T_links
								    SET link_lastedit_user_ID = NULL
								  WHERE link_lastedit_user_ID = ' . $this->ID);
        // remember ID, because parent method resets it to 0
        $old_ID = $this->ID;
        $old_email = $this->get('email');
        // Delete main object:
        if (!parent::dbdelete()) {
            $DB->rollback();
            $Log->add('User has not been deleted.', 'error');
            return false;
        }
        // user was deleted, also delete this user's media folder recursively
        $FileRootCache =& get_FileRootCache();
        $root_directory = $FileRootCache->get_root_dir('user', $old_ID);
        rmdir_r($root_directory);
        if ($deltype == 'spammer') {
            // User was deleted as spammer, we should mark email of this user as 'Spammer'
            load_class('tools/model/_emailblocked.class.php', 'EmailBlocked');
            $EmailBlockedCache =& get_EmailBlockedCache();
            $EmailBlocked =& $EmailBlockedCache->get_by_name($old_email, false, false);
            if (!$EmailBlocked) {
                // Create new record in the T_email_blocked table
                $EmailBlocked = new EmailBlocked();
                $EmailBlocked->set('address', $old_email);
            }
            if (!empty($EmailBlocked)) {
                // Save status of an email address
                $EmailBlocked->set('status', 'spammer');
                $EmailBlocked->dbsave();
            }
        }
        $DB->commit();
        if (is_a($Log, 'log')) {
            $Log->add('Deleted User.', 'note');
        }
        // Notify plugins:
        $this->ID = $old_ID;
        $Plugins->trigger_event('AfterUserDelete', $params = array('User' => &$this));
        $this->ID = 0;
        return true;
    }
Example #13
0
     break;
 case "chmod_directory":
     if ($directory && $_POST['permissions']) {
         if (chmod($directory, octdec(0 . $_POST['permissions']))) {
             print json_encode(array('success' => true, 'message' => 'Directory chmod\'d successfully'));
         } else {
             print json_encode(array('success' => false, 'message' => 'Could not chmod ' . $directory));
         }
     } else {
         print json_encode(array('success' => false, 'message' => 'Could not chmod ' . $directory));
     }
     exit;
     break;
 case "delete_directory":
     if ($_POST['directory'] && $directory != DIRECTORY && stristr($directory, DIRECTORY)) {
         if (rmdir_r($directory)) {
             print json_encode(array('success' => true, 'message' => 'Directory deleted successfully'));
         } else {
             print json_encode(array('success' => false, 'message' => 'Could not delete ' . $directory));
         }
     } else {
         print json_encode(array('success' => false, 'message' => 'Could not delete ' . $directory));
     }
     exit;
     break;
 case "create_temp_image":
     if ($_POST['image']) {
         // Create a temp image copy of the image we are trying to edit
         $temp_image = str_replace(basename($_POST['image']), '_fm_' . basename($_POST['image']), $_POST['image']);
         if (copy(DIRECTORY . $_POST['image'], DIRECTORY . $temp_image)) {
             list($width, $height) = getimagesize(DIRECTORY . $temp_image);
Example #14
0
 /**
  * Delete cache for a file
  */
 function rm_cache()
 {
     global $Messages;
     // Remove cached elts for teh current file:
     $ads_filecache = $this->get_ads_evocache(false);
     if ($ads_filecache[0] == '!') {
         // This creates unwanted noise
         // $Messages->add( 'Cannot remove .evocache for file. - '.$ads_filecache, 'error' );
     } else {
         rmdir_r($ads_filecache);
         // In case cache is now empty, delete the folder:
         $adp_evocache = $this->_dir . '.evocache';
         @rmdir($adp_evocache);
     }
 }
Example #15
0
         $action = 'start';
         break;
         // Stop an upgrade from SVN
     } else {
         // Use only correct revision
         $phpsvnclient->setVersion($svn_revision);
     }
 }
 $repository_version = $phpsvnclient->getVersion();
 $upgrade_name = 'export_svn_' . $repository_version;
 memorize_param('upd_name', 'string', '', $upgrade_name);
 $upgrade_folder = $upgrade_path . $upgrade_name;
 if ($action == 'force_export_svn' && file_exists($upgrade_folder)) {
     // The exported folder already exists
     // Try to delete previous package
     if (!rmdir_r($upgrade_folder)) {
         echo '<p class="red">' . sprintf(T_('Unable to delete previous exported package %s before forcing the export.'), '<b>' . $upgrade_folder . '</b>') . '</p>';
     }
     evo_flush();
 }
 if (file_exists($upgrade_folder)) {
     // Current version already is downloaded
     echo '<p class="green">' . sprintf(T_('Revision %s has already been downloaded. Using: %s'), $repository_version, $upgrade_folder);
     $revision_is_exported = true;
 } else {
     // Download files
     echo '<p>' . sprintf(T_('Downloading package to &laquo;<strong>%s</strong>&raquo;...'), $upgrade_folder);
     evo_flush();
     // Export all files in temp folder for following coping
     $svn_result = $phpsvnclient->checkOut($svn_folder, $upgrade_folder, false, true);
     echo '</p>';
Example #16
0
/**
 * Deletes a dir recursively, wiping out all subdirectories!!
 *
 * @param string the dir
 */
function rmdir_r($path)
{
    $path = trailing_slash($path);
    // echo "<br>rmdir_r($path)";
    if ($dir = @opendir($path)) {
        while (($file = readdir($dir)) !== false) {
            if ($file == '.' || $file == '..') {
                continue;
            }
            $adfp_filepath = $path . $file;
            // echo "<br> - $os_filepath ";
            if (is_dir($adfp_filepath) && !is_link($adfp_filepath)) {
                // Note: we do NOT follow symlinks
                // echo 'D';
                rmdir_r($adfp_filepath);
            } else {
                // File or symbolic link
                //echo 'F/S';
                @unlink($adfp_filepath);
            }
        }
        closedir($dir);
        @rmdir($path);
    }
}
Example #17
0
File: lib.php Project: philum/cms
function rmdir_r($dr)
{
    $dir = opendir($dr);
    if (!auth(6)) {
        return;
    }
    while ($f = readdir($dir)) {
        $drb = $dr . '/' . $f;
        if (is_dir($drb) && $f != '..' && $f != '.') {
            rmdir_r($drb);
            rmdir($drb);
        } elseif (is_file($drb)) {
            unlink($drb);
            echo $drb . br();
        }
    }
    rmdir($dr);
}
Example #18
0
File: tarim.php Project: philum/cms
function tarim_copy($rc)
{
    $dr = 'imgd/';
    rmdir_r('imgd');
    mkdir_r($dr);
    foreach ($rc as $v) {
        copy($v, $dr . substr($v, 4));
    }
}
Example #19
0
 /**
  * Delete all cache files
  */
 function cache_delete()
 {
     rmdir_r($this->ads_collcache_path);
 }
/**
 * Remove orphan file roots ( with no matching Blog or User entry in the database ) recursively with all of the content
 */
function dbm_delete_orphan_file_roots()
{
    global $DB, $media_path;
    echo T_('Removing orphan file roots recursively with all of their content... ');
    evo_flush();
    // Store all directories that must be deleted
    $delete_dirs = array();
    /* BLOGS */
    // Get the media diretories of all existing blogs
    $BlogCache =& get_BlogCache();
    $BlogCache->load_all();
    $blog_dirs = array();
    foreach ($BlogCache->cache as $Blog) {
        $blog_dirs[] = $Blog->get_media_dir();
    }
    $BlogCache->clear();
    $media_path_blogs = $media_path . 'blogs/';
    if (($media_dir_blogs = @opendir($media_path_blogs)) === false) {
        // Could not open blogs media dir
        echo '<p class="red">' . sprintf(T_('Cannot open blogs media directory %s'), '<b>' . $media_path_blogs . '</b>') . '</p>';
    } else {
        // Find the blog dirs that must be deleted
        while (($folder = readdir($media_dir_blogs)) !== false) {
            if ($folder == '.' || $folder == '..' || !is_dir($media_path_blogs . $folder)) {
                // Skip files
                continue;
            }
            if (!in_array($media_path_blogs . $folder . '/', $blog_dirs)) {
                // This dir must be deleted because it is not media dir of the existing blogs
                $delete_dirs[] = $media_path_blogs . $folder . '/';
            }
        }
        closedir($media_dir_blogs);
    }
    /* USERS */
    echo '. ';
    evo_flush();
    // Get logins of all existing users
    $SQL = new SQL();
    $SQL->SELECT('user_login');
    $SQL->FROM('T_users');
    $user_logins = $DB->get_col($SQL->get());
    $media_path_users = $media_path . 'users/';
    if (($media_dir_users = @opendir($media_path_users)) === false) {
        // Could not open users media dir
        echo '<p class="red">' . sprintf(T_('Cannot open users media directory %s'), '<b>' . $media_path_users . '</b>') . '</p>';
    } else {
        // Find the user dirs that must be deleted
        while (($folder = readdir($media_dir_users)) !== false) {
            if ($folder == '.' || $folder == '..' || !is_dir($media_path_users . $folder)) {
                // Skip files
                continue;
            }
            if (!in_array($folder, $user_logins)) {
                // This dir must be deleted because it is not media dir of the existing users
                $delete_dirs[] = $media_path_users . $folder . '/';
            }
        }
        closedir($media_dir_users);
    }
    /* DELETE broken  file roots */
    echo '. ';
    evo_flush();
    foreach ($delete_dirs as $delete_dir) {
        if (rmdir_r($delete_dir)) {
            // Success deleting
            echo '<p class="green">' . sprintf(T_('Invalid file root %s was found and removed with all of its content.'), '<b>' . $delete_dir . '</b>') . '</p>';
        } else {
            // Failed deleting
            echo '<p class="red">' . sprintf(T_('Cannot delete directory %s. Please check the permissions or delete it manually.'), '<b>' . $delete_dir . '</b>') . '</p>';
        }
    }
    /* DELETE orphan DB file records of the blogs and the users */
    echo '. ';
    evo_flush();
    $count_files_deleted = $DB->query('DELETE f, l, lv FROM T_files AS f
			 LEFT JOIN T_links AS l ON l.link_file_ID = f.file_ID
			 LEFT JOIN T_links__vote AS lv ON l.link_ID = lv.lvot_link_ID
		WHERE ( file_root_type = "collection"
		        AND file_root_ID NOT IN ( SELECT blog_ID FROM T_blogs ) )
		   OR ( file_root_type = "user"
		        AND file_root_ID NOT IN ( SELECT user_ID FROM T_users ) )');
    echo 'OK.<p>';
    echo sprintf(T_('%d File roots have been removed from the disk.'), count($delete_dirs)) . '<br />';
    echo sprintf(T_('%d File objects have been deleted from DB.'), intval($count_files_deleted)) . '</p>';
}
Example #21
0
            $unused_File = $FileCache->get_by_ID($file_ID, false);
            if ($unused_File) {
                if (empty($checked_attachments) && empty($attachment_dir)) {
                    // None of the previously attached file was checked to be attached
                    $attachment_dir = dirname($unused_File->get_full_path()) . '/';
                }
                $unused_File->unlink();
            }
        }
    }
    if (empty($checked_attachments) && !empty($attachment_dir)) {
        // None of the previously attached files were finally attached
        $dir_content = get_filenames($attachment_dir, array('recurse' => false, 'inc_hidden' => false));
        if (empty($dir_content)) {
            // The attachment dir is empty, delete the directory
            rmdir_r($attachment_dir);
        }
    }
}
/*
 * ---------------
 * Handle cookies:
 * ---------------
 */
if (!is_logged_in()) {
    if ($comment_cookies) {
        // Set cookies:
        if ($email == '') {
            $email = ' ';
        }
        // this to make sure a cookie is set for 'no email'
Example #22
0
/**
 * Import WordPress data from XML file into b2evolution database
 */
function wpxml_import()
{
    global $DB, $tableprefix;
    // Load classes:
    load_class('regional/model/_country.class.php', 'Country');
    load_class('regional/model/_region.class.php', 'Region');
    load_class('regional/model/_subregion.class.php', 'Subregion');
    load_class('regional/model/_city.class.php', 'City');
    // Set Blog from request blog ID
    $wp_blog_ID = param('wp_blog_ID', 'integer', 0);
    $BlogCache =& get_BlogCache();
    $wp_Blog =& $BlogCache->get_by_ID($wp_blog_ID);
    // The import type ( replace | append )
    $import_type = param('import_type', 'string', 'replace');
    // Should we delete files on 'replace' mode?
    $delete_files = param('delete_files', 'integer', 0);
    $XML_file_path = get_param('wp_file');
    $XML_file_name = basename($XML_file_path);
    if (preg_match('/\\.(xml|txt)$/i', $XML_file_name)) {
        // XML format
        // Check WordPress XML file
        if (!wpxml_check_xml_file($XML_file_path)) {
            // Errors are in XML file
            return;
        }
        // Use this folder to upload files if they exist in subfolder "/b2evolution_export_files"
        $attached_files_path = dirname($XML_file_path);
    } else {
        if (preg_match('/\\.zip$/i', $XML_file_name)) {
            // ZIP format
            // Extract ZIP and check WordPress XML file
            global $media_path;
            $ZIP_folder_path = $media_path . 'import/temp-' . md5(rand());
            if (!unpack_archive($XML_file_path, $ZIP_folder_path, true, $XML_file_name)) {
                // Errors on unpack ZIP file
                return;
            }
            // Find valid XML file in ZIP package
            $ZIP_files_list = scandir($ZIP_folder_path);
            $xml_exists_in_zip = false;
            foreach ($ZIP_files_list as $ZIP_file) {
                if (preg_match('/\\.(xml|txt)$/i', $ZIP_file)) {
                    // XML file is found in ZIP package
                    if (wpxml_check_xml_file($ZIP_folder_path . '/' . $ZIP_file)) {
                        // XML file is valid
                        $XML_file_path = $ZIP_folder_path . '/' . $ZIP_file;
                        $xml_exists_in_zip = true;
                        break;
                    }
                }
            }
            if (!$xml_exists_in_zip) {
                // No XML is detected in ZIP package
                echo '<p style="color:red">' . T_('XML file is not detected in your ZIP package.') . '</p>';
                // Delete temporary folder that contains the files from extracted ZIP package
                rmdir_r($ZIP_folder_path);
                return;
            }
            // Use this folder to upload files, $ZIP_folder_path must be deleted after import
            $attached_files_path = $ZIP_folder_path;
        } else {
            // Unrecognized extension
            echo '<p style="color:red">' . sprintf(T_('%s has an unrecognized extension.'), '<b>' . $xml_file['name'] . '</b>') . '</p>';
            return;
        }
    }
    // Parse WordPress XML file into array
    $xml_data = wpxml_parser($XML_file_path);
    $DB->begin();
    if ($import_type == 'replace') {
        // Remove data from selected blog
        // Get existing categories
        $SQL = new SQL();
        $SQL->SELECT('cat_ID');
        $SQL->FROM('T_categories');
        $SQL->WHERE('cat_blog_ID = ' . $DB->quote($wp_blog_ID));
        $old_categories = $DB->get_col($SQL->get());
        if (!empty($old_categories)) {
            // Get existing posts
            $SQL = new SQL();
            $SQL->SELECT('post_ID');
            $SQL->FROM('T_items__item');
            $SQL->WHERE('post_main_cat_ID IN ( ' . implode(', ', $old_categories) . ' )');
            $old_posts = $DB->get_col($SQL->get());
        }
        echo T_('Removing the comments... ');
        evo_flush();
        if (!empty($old_posts)) {
            $SQL = new SQL();
            $SQL->SELECT('comment_ID');
            $SQL->FROM('T_comments');
            $SQL->WHERE('comment_item_ID IN ( ' . implode(', ', $old_posts) . ' )');
            $old_comments = $DB->get_col($SQL->get());
            $DB->query('DELETE FROM T_comments WHERE comment_item_ID IN ( ' . implode(', ', $old_posts) . ' )');
            if (!empty($old_comments)) {
                $DB->query('DELETE FROM T_comments__votes WHERE cmvt_cmt_ID IN ( ' . implode(', ', $old_comments) . ' )');
                $DB->query('DELETE FROM T_links WHERE link_cmt_ID IN ( ' . implode(', ', $old_comments) . ' )');
            }
        }
        echo T_('OK') . '<br />';
        echo T_('Removing the posts... ');
        evo_flush();
        if (!empty($old_categories)) {
            $DB->query('DELETE FROM T_items__item WHERE post_main_cat_ID IN ( ' . implode(', ', $old_categories) . ' )');
            if (!empty($old_posts)) {
                // Remove the post's data from related tables
                if ($delete_files) {
                    // Get the file IDs that should be deleted from hard drive
                    $SQL = new SQL();
                    $SQL->SELECT('DISTINCT link_file_ID');
                    $SQL->FROM('T_links');
                    $SQL->WHERE('link_itm_ID IN ( ' . implode(', ', $old_posts) . ' )');
                    $deleted_file_IDs = $DB->get_col($SQL->get());
                }
                $DB->query('DELETE FROM T_items__item_settings WHERE iset_item_ID IN ( ' . implode(', ', $old_posts) . ' )');
                $DB->query('DELETE FROM T_items__prerendering WHERE itpr_itm_ID IN ( ' . implode(', ', $old_posts) . ' )');
                $DB->query('DELETE FROM T_items__subscriptions WHERE isub_item_ID IN ( ' . implode(', ', $old_posts) . ' )');
                $DB->query('DELETE FROM T_items__version WHERE iver_itm_ID IN ( ' . implode(', ', $old_posts) . ' )');
                $DB->query('DELETE FROM T_postcats WHERE postcat_post_ID IN ( ' . implode(', ', $old_posts) . ' )');
                $DB->query('DELETE FROM T_slug WHERE slug_itm_ID IN ( ' . implode(', ', $old_posts) . ' )');
                $DB->query('DELETE l, lv FROM T_links AS l
											 LEFT JOIN T_links__vote AS lv ON lv.lvot_link_ID = l.link_ID
											WHERE l.link_itm_ID IN ( ' . implode(', ', $old_posts) . ' )');
                $DB->query('DELETE FROM T_users__postreadstatus WHERE uprs_post_ID IN ( ' . implode(', ', $old_posts) . ' )');
            }
        }
        echo T_('OK') . '<br />';
        echo T_('Removing the categories... ');
        evo_flush();
        $DB->query('DELETE FROM T_categories WHERE cat_blog_ID = ' . $DB->quote($wp_blog_ID));
        echo T_('OK') . '<br />';
        echo T_('Removing the tags that are no longer used... ');
        evo_flush();
        if (!empty($old_posts)) {
            // Remove the tags
            // Get tags from selected blog
            $SQL = new SQL();
            $SQL->SELECT('itag_tag_ID');
            $SQL->FROM('T_items__itemtag');
            $SQL->WHERE('itag_itm_ID IN ( ' . implode(', ', $old_posts) . ' )');
            $old_tags_this_blog = array_unique($DB->get_col($SQL->get()));
            if (!empty($old_tags_this_blog)) {
                // Get tags from other blogs
                $SQL = new SQL();
                $SQL->SELECT('itag_tag_ID');
                $SQL->FROM('T_items__itemtag');
                $SQL->WHERE('itag_itm_ID NOT IN ( ' . implode(', ', $old_posts) . ' )');
                $old_tags_other_blogs = array_unique($DB->get_col($SQL->get()));
                $old_tags_other_blogs_sql = !empty($old_tags_other_blogs) ? ' AND tag_ID NOT IN ( ' . implode(', ', $old_tags_other_blogs) . ' )' : '';
                // Remove the tags that are no longer used
                $DB->query('DELETE FROM T_items__tag
					WHERE tag_ID IN ( ' . implode(', ', $old_tags_this_blog) . ' )' . $old_tags_other_blogs_sql);
            }
            // Remove the links of tags with posts
            $DB->query('DELETE FROM T_items__itemtag WHERE itag_itm_ID IN ( ' . implode(', ', $old_posts) . ' )');
        }
        echo T_('OK') . '<br />';
        if ($delete_files) {
            // Delete the files
            echo T_('Removing the files... ');
            if (!empty($deleted_file_IDs)) {
                // Commit the DB changes before files deleting
                $DB->commit();
                // Get the deleted file IDs that are linked to other objects
                $SQL = new SQL();
                $SQL->SELECT('DISTINCT link_file_ID');
                $SQL->FROM('T_links');
                $SQL->WHERE('link_file_ID IN ( ' . implode(', ', $deleted_file_IDs) . ' )');
                $linked_file_IDs = $DB->get_col($SQL->get());
                // We can delete only the files that are NOT linked to other objects
                $deleted_file_IDs = array_diff($deleted_file_IDs, $linked_file_IDs);
                $FileCache =& get_FileCache();
                foreach ($deleted_file_IDs as $deleted_file_ID) {
                    if (!($deleted_File =& $FileCache->get_by_ID($deleted_file_ID, false, false))) {
                        // Incorrect file ID
                        echo '<p class="red">' . sprintf(T_('No file #%s found in DB. It cannot be deleted.'), $deleted_file_ID) . '</p>';
                    }
                    if (!$deleted_File->unlink()) {
                        // No permission to delete file
                        echo '<p class="red">' . sprintf(T_('Could not delete the file &laquo;%s&raquo;.'), $deleted_File->get_full_path()) . '</p>';
                    }
                    // Clear cache to save memory
                    $FileCache->clear();
                }
                // Start new transaction for the data inserting
                $DB->begin();
            }
            echo T_('OK') . '<br />';
        }
        echo '<br />';
    }
    /* Import authors */
    $authors = array();
    $authors_IDs = array();
    if (isset($xml_data['authors']) && count($xml_data['authors']) > 0) {
        global $Settings, $UserSettings;
        echo T_('Importing the users... ');
        evo_flush();
        // Get existing users
        $SQL = new SQL();
        $SQL->SELECT('user_login, user_ID');
        $SQL->FROM('T_users');
        $existing_users = $DB->get_assoc($SQL->get());
        $authors_count = 0;
        foreach ($xml_data['authors'] as $author) {
            if (empty($existing_users[(string) $author['author_login']])) {
                // Insert new user into DB if User doesn't exist with current login name
                $GroupCache =& get_GroupCache();
                if (!empty($author['author_group'])) {
                    // Set user group from xml data
                    if (($UserGroup =& $GroupCache->get_by_name($author['author_group'], false)) === false) {
                        // If user's group doesn't exist yet, we should create new
                        $UserGroup = new Group();
                        $UserGroup->set('name', $author['author_group']);
                        $UserGroup->dbinsert();
                    }
                } else {
                    // Set default user group is it is not defined in xml
                    if (($UserGroup =& $GroupCache->get_by_name('Normal Users', false)) === false) {
                        // Exit from import of users, because we cannot set default user group
                        break;
                    }
                }
                unset($author_created_from_country);
                if (!empty($author['author_created_from_country'])) {
                    // Get country ID from DB by code
                    $CountryCache =& get_CountryCache();
                    if (($Country =& $CountryCache->get_by_name($author['author_created_from_country'], false)) !== false) {
                        $author_created_from_country = $Country->ID;
                    }
                }
                // Get regional IDs by their names
                $author_regions = wp_get_regional_data($author['author_country'], $author['author_region'], $author['author_subregion'], $author['author_city']);
                $User = new User();
                $User->set('login', $author['author_login']);
                $User->set('email', $author['author_email']);
                $User->set('firstname', $author['author_first_name']);
                $User->set('lastname', $author['author_last_name']);
                $User->set('pass', $author['author_pass']);
                $User->set_Group($UserGroup);
                $User->set('status', !empty($author['author_status']) ? $author['author_status'] : 'autoactivated');
                $User->set('nickname', $author['author_nickname']);
                $User->set('url', $author['author_url']);
                $User->set('level', $author['author_level']);
                $User->set('locale', $author['author_locale']);
                $User->set('gender', $author['author_gender'] == 'female' ? 'F' : ($author['author_gender'] == 'male' ? 'M' : ''));
                if ($author['author_age_min'] > 0) {
                    $User->set('age_min', $author['author_age_min']);
                }
                if ($author['author_age_max'] > 0) {
                    $User->set('age_max', $author['author_age_max']);
                }
                if (isset($author_created_from_country)) {
                    // User was created from this country
                    $User->set('reg_ctry_ID', $author_created_from_country);
                }
                if (!empty($author_regions['country'])) {
                    // Country
                    $User->set('ctry_ID', $author_regions['country']);
                    if (!empty($author_regions['region'])) {
                        // Region
                        $User->set('rgn_ID', $author_regions['region']);
                        if (!empty($author_regions['subregion'])) {
                            // Subregion
                            $User->set('subrg_ID', $author_regions['subregion']);
                        }
                        if (!empty($author_regions['city'])) {
                            // City
                            $User->set('city_ID', $author_regions['city']);
                        }
                    }
                }
                $User->set('source', $author['author_source']);
                $User->set_datecreated(empty($author['author_created_ts']) ? mktime() : intval($author['author_created_ts']));
                $User->set('lastseen_ts', empty($author['author_lastseen_ts']) ? NULL : $author['author_lastseen_ts'], true);
                $User->set('profileupdate_date', empty($author['author_profileupdate_date']) ? date('Y-m-d', mktime()) : $author['author_profileupdate_date']);
                $User->dbinsert();
                $user_ID = $User->ID;
                if (!empty($user_ID) && !empty($author['author_created_fromIPv4'])) {
                    $UserSettings->set('created_fromIPv4', ip2int($author['author_created_fromIPv4']), $user_ID);
                }
                $authors_count++;
            } else {
                // Get ID of existing user
                $user_ID = $existing_users[(string) $author['author_login']];
            }
            // Save user ID of current author
            $authors[$author['author_login']] = (string) $user_ID;
            $authors_IDs[$author['author_id']] = (string) $user_ID;
        }
        $UserSettings->dbupdate();
        echo sprintf(T_('%d records'), $authors_count) . '<br />';
    }
    /* Import files, Copy them all to media folder */
    if (isset($xml_data['files']) && count($xml_data['files']) > 0) {
        echo T_('Importing the files... ');
        evo_flush();
        if (!file_exists($attached_files_path . '/b2evolution_export_files')) {
            // Display an error if files are attached but folder doesn't exist
            echo '<p class="red">' . sprintf(T_('No folder %s found. It must exists to import the attached files properly.'), '<b>' . $attached_files_path . '/b2evolution_export_files' . '</b>') . '</p>';
        } else {
            // The attached files are located in this subfolder
            $subfolder_path = '/b2evolution_export_files';
            $files_count = 0;
            $files = array();
            foreach ($xml_data['files'] as $file) {
                switch ($file['file_root_type']) {
                    case 'shared':
                        // Shared files
                        $file_root_ID = 0;
                        break;
                    case 'user':
                        // User's files
                        if (isset($authors_IDs[$file['file_root_ID']])) {
                            // If owner of this file exists in our DB
                            $file_root_ID = $authors_IDs[$file['file_root_ID']];
                            break;
                        }
                        // Otherwise we should upload this file into blog's folder:
                    // Otherwise we should upload this file into blog's folder:
                    default:
                        // 'collection', 'absolute', 'skins'
                        // The files from other blogs and from other places must be moved in the folder of the current blog
                        $file['file_root_type'] = 'collection';
                        $file_root_ID = $wp_blog_ID;
                        break;
                }
                // Get FileRoot by type and ID
                $FileRootCache =& get_FileRootCache();
                $FileRoot =& $FileRootCache->get_by_type_and_ID($file['file_root_type'], $file_root_ID);
                if (is_dir($attached_files_path . $subfolder_path . '/' . $file['zip_path'] . $file['file_path'])) {
                    // Folder
                    $file_destination_path = $FileRoot->ads_path;
                } else {
                    // File
                    $file_destination_path = $FileRoot->ads_path . $file['file_path'];
                }
                if (!file_exists($attached_files_path . $subfolder_path . '/' . $file['zip_path'] . $file['file_path'])) {
                    // File doesn't exist
                    echo '<p class="orange">' . sprintf(T_('Unable to copy file %s, because it does not exist.'), '<b>' . $file['zip_path'] . $file['file_path'] . '</b>') . '</p>';
                    // Skip it
                    continue;
                } else {
                    if (!copy_r($attached_files_path . $subfolder_path . '/' . $file['zip_path'] . $file['file_path'], $file_destination_path)) {
                        // No permission to copy to this folder
                        if (is_dir($attached_files_path . $subfolder_path . '/' . $file['zip_path'] . $file['file_path'])) {
                            // Folder
                            echo '<p class="orange">' . sprintf(T_('Unable to copy folder %s to %s. Please, check the permissions assigned to this folder.'), '<b>' . $file['zip_path'] . $file['file_path'] . '</b>', '<b>' . $file_destination_path . '</b>') . '</p>';
                        } else {
                            // File
                            echo '<p class="orange">' . sprintf(T_('Unable to copy file %s to %s. Please, check the permissions assigned to this folder.'), '<b>' . $file['zip_path'] . $file['file_path'] . '</b>', '<b>' . $file_destination_path . '</b>') . '</p>';
                        }
                        // Skip it
                        continue;
                    }
                }
                // Create new File object, It will be linked to the items below
                $File = new File($file['file_root_type'], $file_root_ID, $file['file_path']);
                $File->set('title', $file['file_title']);
                $File->set('alt', $file['file_alt']);
                $File->set('desc', $file['file_desc']);
                $files[$file['file_ID']] = $File;
                $files_count++;
            }
            echo sprintf(T_('%d records'), $files_count) . '<br />';
            if (isset($ZIP_folder_path) && file_exists($ZIP_folder_path)) {
                // This folder was created only to extract files from ZIP package, Remove it now
                rmdir_r($ZIP_folder_path);
            }
        }
    }
    /* Import categories */
    $category_default = 0;
    load_class('chapters/model/_chapter.class.php', 'Chapter');
    // Get existing categories
    $SQL = new SQL();
    $SQL->SELECT('cat_urlname, cat_ID');
    $SQL->FROM('T_categories');
    $SQL->WHERE('cat_blog_ID = ' . $DB->quote($wp_blog_ID));
    $categories = $DB->get_assoc($SQL->get());
    if (isset($xml_data['categories']) && count($xml_data['categories']) > 0) {
        echo T_('Importing the categories... ');
        evo_flush();
        load_funcs('locales/_charset.funcs.php');
        $categories_count = 0;
        foreach ($xml_data['categories'] as $cat) {
            if (empty($categories[(string) $cat['category_nicename']])) {
                $Chapter = new Chapter(NULL, $wp_blog_ID);
                $Chapter->set('name', $cat['cat_name']);
                $Chapter->set('urlname', $cat['category_nicename']);
                $Chapter->set('description', $cat['category_description']);
                if (!empty($cat['category_parent']) && isset($categories[(string) $cat['category_parent']])) {
                    // Set category parent ID
                    $Chapter->set('parent_ID', $categories[(string) $cat['category_parent']]);
                }
                $Chapter->dbinsert();
                // Save new category
                $categories[$cat['category_nicename']] = $Chapter->ID;
                if (empty($category_default)) {
                    // Set first category as default
                    $category_default = $Chapter->ID;
                }
                $categories_count++;
            }
        }
        echo sprintf(T_('%d records'), $categories_count) . '<br />';
    }
    if (empty($category_default)) {
        // No categories in XML file, Try to use first category(from DB) as default
        foreach ($categories as $category_name => $category_ID) {
            $category_default = $category_ID;
            break;
        }
    }
    if (empty($category_default)) {
        // If category is still not defined then we should create default, because blog must has at least one category
        $new_Chapter = new Chapter(NULL, $wp_blog_ID);
        $new_Chapter->set('name', T_('Uncategorized'));
        $new_Chapter->set('urlname', $wp_Blog->get('urlname') . '-main');
        $new_Chapter->dbinsert();
        $category_default = $new_Chapter->ID;
    }
    /* Import tags */
    $tags = array();
    if (isset($xml_data['tags']) && count($xml_data['tags']) > 0) {
        echo T_('Importing the tags... ');
        evo_flush();
        // Get existing tags
        $SQL = new SQL();
        $SQL->SELECT('tag_name, tag_ID');
        $SQL->FROM('T_items__tag');
        $tags = $DB->get_assoc($SQL->get());
        $tags_count = 0;
        foreach ($xml_data['tags'] as $tag) {
            if (empty($tags[(string) $tag['tag_name']])) {
                // Insert new tag into DB if tag doesn't exist with current name
                mysqli_query($DB->dbhandle, 'INSERT INTO ' . $tableprefix . 'items__tag ( tag_name )
					VALUES ( ' . $DB->quote($tag['tag_name']) . ' )');
                $tag_ID = mysqli_insert_id($DB->dbhandle);
                // Save new tag
                $tags[$tag['tag_name']] = (string) $tag_ID;
                $tags_count++;
            }
        }
        echo sprintf(T_('%d records'), $tags_count) . '<br />';
    }
    /* Import posts */
    $posts = array();
    $comments = array();
    if (isset($xml_data['posts']) && count($xml_data['posts']) > 0) {
        load_class('items/model/_item.class.php', 'Item');
        // Set status's links between WP and b2evo names
        $post_statuses = array('publish' => 'published', 'pending' => 'review', 'draft' => 'draft', 'trash' => 'deprecated', 'community' => 'community', 'deprecated' => 'deprecated', 'protected' => 'protected', 'private' => 'private', 'review' => 'review', 'redirected' => 'redirected');
        // Get post types
        $SQL = new SQL();
        $SQL->SELECT('LOWER( ityp_name ), ityp_ID');
        $SQL->FROM('T_items__type');
        $post_types = $DB->get_assoc($SQL->get());
        echo T_('Importing the posts... ');
        evo_flush();
        foreach ($xml_data['posts'] as $post) {
            $author_ID = isset($authors[(string) $post['post_author']]) ? $authors[(string) $post['post_author']] : 1;
            $last_edit_user_ID = isset($authors[(string) $post['post_lastedit_user']]) ? $authors[(string) $post['post_lastedit_user']] : $author_ID;
            $post_main_cat_ID = $category_default;
            $post_extra_cat_IDs = array();
            $post_tags = array();
            if (!empty($post['terms'])) {
                // Set categories and tags
                foreach ($post['terms'] as $term) {
                    switch ($term['domain']) {
                        case 'category':
                            if (isset($categories[(string) $term['slug']])) {
                                if ($post_main_cat_ID == $category_default) {
                                    // Set main category
                                    $post_main_cat_ID = $categories[(string) $term['slug']];
                                }
                                // Set extra categories
                                $post_extra_cat_IDs[] = $categories[(string) $term['slug']];
                            }
                            break;
                        case 'post_tag':
                            if (isset($tags[(string) $term['slug']])) {
                                // Set tag
                                $post_tags[] = $term['slug'];
                            }
                            break;
                    }
                }
            }
            // Set post type ID
            $post_type_ID = isset($post_types[strtolower($post['post_type'])]) ? $post_types[strtolower($post['post_type'])] : '1';
            // Get regional IDs by their names
            $item_regions = wp_get_regional_data($post['post_country'], $post['post_region'], $post['post_subregion'], $post['post_city']);
            $Item = new Item();
            $Item->set('main_cat_ID', $post_main_cat_ID);
            $Item->set('creator_user_ID', $author_ID);
            $Item->set('lastedit_user_ID', $last_edit_user_ID);
            $Item->set('title', $post['post_title']);
            $Item->set('content', $post['post_content']);
            $Item->set('excerpt', $post['post_excerpt']);
            $Item->set('datestart', $post['post_date']);
            $Item->set('datecreated', !empty($post['post_datecreated']) ? $post['post_datecreated'] : $post['post_date']);
            $Item->set('datemodified', !empty($post['post_datemodified']) ? $post['post_datemodified'] : $post['post_date']);
            $Item->set('urltitle', !empty($post['post_urltitle']) ? $post['post_urltitle'] : $post['post_title']);
            $Item->set('url', $post['post_url']);
            $Item->set('status', isset($post_statuses[(string) $post['status']]) ? $post_statuses[(string) $post['status']] : 'review');
            // If 'comment_status' has the unappropriate value set it to 'open'
            $Item->set('comment_status', in_array($post['comment_status'], array('open', 'closed', 'disabled')) ? $post['comment_status'] : 'open');
            $Item->set('ityp_ID', $post_type_ID);
            if (empty($post['post_excerpt']) && !empty($post['post_content'])) {
                // Generate excerpt
                $Item->set('excerpt', excerpt($post['post_content']));
                $Item->set('excerpt_autogenerated', '1');
            }
            $Item->set('extra_cat_IDs', $post_extra_cat_IDs);
            $Item->set('dateset', $post['post_date_mode'] == 'set' ? 1 : 0);
            if (isset($authors[(string) $post['post_assigned_user']])) {
                $Item->set('assigned_user', $authors[(string) $post['post_assigned_user']]);
            }
            $Item->set('datedeadline', $post['post_datedeadline']);
            $Item->set('locale', $post['post_locale']);
            $Item->set('excerpt_autogenerated', $post['post_excerpt_autogenerated']);
            $Item->set('titletag', $post['post_titletag']);
            $Item->set('notifications_status', empty($post['post_notifications_status']) ? 'noreq' : $post['post_notifications_status']);
            $Item->set('renderers', array($post['post_renderers']));
            $Item->set('priority', $post['post_priority']);
            $Item->set('featured', $post['post_featured']);
            $Item->set('order', $post['post_order']);
            if (!empty($item_regions['country'])) {
                // Country
                $Item->set('ctry_ID', $item_regions['country']);
                if (!empty($item_regions['region'])) {
                    // Region
                    $Item->set('rgn_ID', $item_regions['region']);
                    if (!empty($item_regions['subregion'])) {
                        // Subregion
                        $Item->set('subrg_ID', $item_regions['subregion']);
                    }
                    if (!empty($item_regions['city'])) {
                        // City
                        $Item->set('city_ID', $item_regions['city']);
                    }
                }
            }
            if (count($post_tags) > 0) {
                $Item->tags = $post_tags;
            }
            $Item->dbinsert();
            $posts[$post['post_id']] = $Item->ID;
            if (!empty($files) && !empty($post['links'])) {
                // Link the files to the Item if it has them
                foreach ($post['links'] as $link) {
                    if (isset($files[$link['link_file_ID']])) {
                        // Link a file to Item
                        $File = $files[$link['link_file_ID']];
                        $LinkOwner = new LinkItem($Item);
                        $File->link_to_Object($LinkOwner, $link['link_order'], $link['link_position']);
                    }
                }
            }
            if (!empty($post['comments'])) {
                // Set comments
                $comments[$Item->ID] = $post['comments'];
            }
        }
        foreach ($xml_data['posts'] as $post) {
            // Set post parents
            if (!empty($post['post_parent']) && isset($posts[(string) $post['post_parent']])) {
                mysqli_query($DB->dbhandle, 'UPDATE ' . $tableprefix . 'items__item
						  SET post_parent_ID = ' . $DB->quote($posts[(string) $post['post_parent']]) . '
						WHERE post_ID = ' . $DB->quote($posts[(string) $post['post_id']]));
            }
        }
        echo sprintf(T_('%d records'), count($xml_data['posts'])) . '<br />';
    }
    /* Import comments */
    if (!empty($comments)) {
        echo T_('Importing the comments... ');
        evo_flush();
        $comments_count = 0;
        $comments_IDs = array();
        foreach ($comments as $post_ID => $comments) {
            if (empty($comments)) {
                // Skip if no comments
                continue;
            }
            foreach ($comments as $comment) {
                $comment_author_user_ID = 0;
                if (!empty($comment['comment_user_id']) && isset($authors_IDs[(string) $comment['comment_user_id']])) {
                    // Author ID
                    $comment_author_user_ID = $authors_IDs[(string) $comment['comment_user_id']];
                }
                $comment_parent_ID = 0;
                if (!empty($comment['comment_parent']) && isset($comments_IDs[(string) $comment['comment_parent']])) {
                    // Parent comment ID
                    $comment_parent_ID = $comments_IDs[(string) $comment['comment_parent']];
                }
                unset($comment_IP_country);
                if (!empty($comment['comment_IP_country'])) {
                    // Get country ID by code
                    $CountryCache =& get_CountryCache();
                    if ($Country =& $CountryCache->get_by_name($comment['comment_IP_country'], false)) {
                        $comment_IP_country = $Country->ID;
                    }
                }
                $Comment = new Comment();
                $Comment->set('item_ID', $post_ID);
                if (!empty($comment_parent_ID)) {
                    $Comment->set('in_reply_to_cmt_ID', $comment_parent_ID);
                }
                $Comment->set('date', $comment['comment_date']);
                if (!empty($comment_author_user_ID)) {
                    $Comment->set('author_user_ID', $comment_author_user_ID);
                }
                $Comment->set('author', utf8_substr($comment['comment_author'], 0, 100));
                $Comment->set('author_IP', $comment['comment_author_IP']);
                $Comment->set('author_email', $comment['comment_author_email']);
                $Comment->set('content', $comment['comment_content']);
                if (empty($comment['comment_status'])) {
                    // If comment status is empty (the export of wordpress doesn't provide this field)
                    $Comment->set('status', $comment['comment_approved'] == '1' ? 'published' : 'draft');
                } else {
                    // Set status when we have predefined value
                    $Comment->set('status', $comment['comment_status']);
                }
                if (!empty($comment_IP_country)) {
                    // Country
                    $Comment->set('IP_ctry_ID', $comment_IP_country);
                }
                $Comment->set('rating', $comment['comment_rating']);
                $Comment->set('featured', $comment['comment_featured']);
                $Comment->set('nofollow', $comment['comment_nofollow']);
                $Comment->set('helpful_addvotes', $comment['comment_helpful_addvotes']);
                $Comment->set('helpful_countvotes', $comment['comment_helpful_countvotes']);
                $Comment->set('spam_addvotes', $comment['comment_spam_addvotes']);
                $Comment->set('spam_countvotes', $comment['comment_spam_countvotes']);
                $Comment->set('karma', $comment['comment_karma']);
                $Comment->set('spam_karma', $comment['comment_spam_karma']);
                $Comment->set('allow_msgform', $comment['comment_allow_msgform']);
                $Comment->set('notif_status', empty($comment['comment_notif_status']) ? 'noreq' : $comment['comment_notif_status']);
                $Comment->dbinsert();
                $comments_IDs[$comment['comment_id']] = $Comment->ID;
                $comments_count++;
            }
        }
        echo sprintf(T_('%d records'), $comments_count) . '<br />';
    }
    echo '<p>' . T_('Import complete.') . '</p>';
    $DB->commit();
}
Example #23
0
/**
 * Delete any ?evocache folders.
 *
 * @param Log Pass a Log object here to have error messages added to it.
 * @return integer Number of deleted dirs.
 */
function delete_cachefolders($Log = NULL)
{
    global $media_path, $Settings;
    // Get this, just in case someone comes up with a different naming:
    $evocache_foldername = $Settings->get('evocache_foldername');
    $filename_params = array('inc_files' => false, 'inc_evocache' => true);
    $dirs = get_filenames($media_path, $filename_params);
    $deleted_dirs = 0;
    foreach ($dirs as $dir) {
        $basename = basename($dir);
        if ($basename == '.evocache' || $basename == '_evocache' || $basename == $evocache_foldername) {
            // Delete .evocache directory recursively
            if (rmdir_r($dir)) {
                $deleted_dirs++;
            } elseif ($Log) {
                $Log->add(sprintf(T_('Could not delete directory: %s'), $dir), 'error');
            }
        }
    }
    return $deleted_dirs;
}
Example #24
0
 /**
  * Check if the media directory or it's location was changed and perform the required data migration
  *
  * @param string the media directory path before update
  * @param string the media directory location before update
  * @return boolean true if the media directory was not changed or the change was successful, false otherwise
  */
 function check_media_dir_change($old_media_dir, $old_media_location = NULL)
 {
     global $Messages;
     $new_media_dir = $this->get_media_dir(false);
     if ($new_media_dir == $old_media_dir) {
         // The media dir was not changed, no need fo further updates
         return true;
     }
     $new_media_location = $this->get('media_location');
     if ($old_media_location == NULL) {
         // Media location was not changed
         $old_media_location = $new_media_location;
     }
     switch ($new_media_location) {
         case 'none':
             if (is_empty_directory($old_media_dir)) {
                 // Delete old media dir if it is empty
                 if (file_exists($old_media_dir) && !rmdir_r($old_media_dir)) {
                     $Messages->add(T_('The old media dir could not be removed, please remove it manually!'), 'warning');
                 }
             } else {
                 // The old media dir is not empty, but it must be cleared before it can be changed to none
                 $Messages->add(T_('Blog media folder is not empty, you cannot change it to "None".'), 'error');
                 return false;
             }
             break;
         case 'default':
         case 'subdir':
         case 'custom':
             global $media_path;
             if (file_exists($new_media_dir)) {
                 // Don't use the existing folder twice
                 $Messages->add(sprintf(T_('Folder %s already exists, it cannot be used for several media locations.'), '<b>' . $new_media_dir . '</b>'), 'error');
                 return false;
             }
             if (in_array(trim($new_media_dir, '/\\'), array($media_path . 'blogs', $media_path . 'import', $media_path . 'shared', $media_path . 'users'))) {
                 // Don't use the reserved paths
                 $Messages->add(sprintf(T_('Please use another folder name, because %s is reserved.'), '<b>' . $new_media_dir . '</b>'), 'error');
                 return false;
             }
             if ($new_media_location == 'custom') {
                 // Check for folder is not used by other blog, and it is not a sub-folder of other blog folder
                 $BlogCache =& get_BlogCache();
                 $BlogCache->clear(true);
                 $BlogCache->load_where('blog_ID != ' . $this->ID);
                 $other_blog_IDs = $BlogCache->get_ID_array();
                 foreach ($other_blog_IDs as $other_blog_ID) {
                     $other_Blog =& $BlogCache->get_by_ID($other_blog_ID, false, false);
                     $other_media_dir = $other_Blog->get_media_dir(false);
                     if (!empty($other_media_dir) && strpos($new_media_dir, $other_media_dir) === 0) {
                         $Messages->add(sprintf(T_('Please use another folder name, because %s is already used for another media location.'), '<b>' . $new_media_dir . '</b>'), 'error');
                         return false;
                     }
                 }
             }
             if ($old_media_location == 'none' || !file_exists($old_media_dir)) {
                 // The media folder was not used before, create the new media folder
                 return $this->get_media_dir(true);
             }
             if (copy_r($old_media_dir, $new_media_dir, '', array('_evocache', '.evocache'))) {
                 // The file have been copied to new folder successfully
                 if (!rmdir_r($old_media_dir)) {
                     // Display a warning if old folder could not be deleted
                     $Messages->add(sprintf(T_('Could not delete the old media folder "%s", please try to delete it manually.'), '<b>' . $old_media_dir . '</b>'), 'warning');
                 }
             } else {
                 // Display a message if some error on copying
                 $Messages->add(sprintf(T_('Could not move the media folder content from "%s" to the new "%s" location.'), '<b>' . $old_media_dir . '</b>', '<b>' . $new_media_dir . '</b>'), 'error');
                 return false;
             }
             break;
         default:
             debug_die('Invalid media location setting received!');
     }
     $Messages->add(T_('The media directory and all of its content were successfully moved to the new location.'), 'note');
     return true;
 }
/**
 * Remove files/folders after upgrade, See file upgrade_policy.conf
 */
function remove_after_upgrade()
{
    global $basepath, $conf_path;
    $upgrade_removed_files = get_upgrade_config('remove');
    echo '<h4>' . T_('Cleaning up...') . '</h4>';
    evo_flush();
    if (is_string($upgrade_removed_files)) {
        // Errors on opening of upgrade_policy.conf
        $config_error = $upgrade_removed_files;
    } elseif (empty($upgrade_removed_files)) {
        // No files/folders to remove, Exit here
        $config_error = sprintf(T_('No "remove" sections have been defined in the file %s.'), '<code>upgrade_policy.conf</code>');
    }
    if (!empty($config_error)) {
        // Display config error
        echo '<div class="red">';
        echo $config_error;
        echo ' ' . T_('No cleanup is being done. You should manually remove the <code>/install</code> folder and check for other unwanted files...');
        echo '</div>';
        return;
    }
    foreach ($upgrade_removed_files as $file_path) {
        $file_path = $basepath . $file_path;
        $log_message = sprintf(T_('Removing %s as stated in upgrade_policy.conf...'), '<code>' . $file_path . '</code>') . ' ';
        $success = true;
        if (file_exists($file_path)) {
            // File exists
            if (is_dir($file_path)) {
                // Remove folder recursively
                if (rmdir_r($file_path)) {
                    // Success
                    $log_message .= T_('OK');
                } else {
                    // Failed
                    $log_message .= T_('Failed') . ': ' . T_('No permissions to delete the folder');
                    $success = false;
                }
            } elseif (is_writable($file_path)) {
                // Remove file
                if (@unlink($file_path)) {
                    // Success
                    $log_message .= T_('OK');
                } else {
                    // Failed
                    $log_message .= T_('Failed') . ': ' . T_('No permissions to delete the file');
                    $success = false;
                }
            } else {
                // File is not writable
                $log_message .= T_('Failed') . ': ' . T_('No permissions to delete the file');
                $success = false;
            }
        } else {
            // No file/folder
            $log_message .= T_('Failed') . ': ' . T_('No file found');
            $success = false;
        }
        echo $success ? $log_message . '<br />' : '<div class="orange">' . $log_message . '</div>';
        evo_flush();
    }
}
Example #26
0
         evo_flush();
         // Unpack package
         if ($success = unpack_archive($upgrade_file, $upgrade_path . $upgrade_name, true)) {
             global $debug;
             echo ' OK.</p>';
             evo_flush();
             $new_version_status = check_version($upgrade_name);
             if ($debug == 0 && !empty($new_version_status)) {
                 echo '<h4 style="color:red">' . $new_version_status . '</h4>';
                 evo_flush();
                 break;
             }
         } else {
             echo '</p>';
             // Additional check
             @rmdir_r($upgrade_path . $upgrade_name);
         }
     }
     if ($success) {
         // Pause a process before upgrading
         $action = 'backup_and_overwrite';
         $AdminUI->disp_view('maintenance/views/_upgrade_continue.form.php');
         unset($block_item_Widget);
     }
     break;
 case 'backup_and_overwrite':
     // STEP 4: BACKUP AND OVERWRITE.
 // STEP 4: BACKUP AND OVERWRITE.
 case 'backup_and_overwrite_svn':
     // SVN STEP 2: BACKUP AND OVERWRITE.
     if ($demo_mode) {
Example #27
0
    }
    $html .= '</table>';
    $conteudo = utf8_decode($html);
    file_put_contents("{$path}/" . $empresa['razao_social'] . "/" . $arquivo, $conteudo);
}
//echo "<p>".$path;
$directory = $path;
//diretorio para compactar
$zipfile = './uploads/' . $path . '.zip';
// nome do zip gerado
// Array de arquivos
$filenames = array();
// Lê os arquivos
$filenames = browse($directory);
// cria zip, adiciona arquivos...
$zip = new ZipArchive();
if ($zip->open($zipfile, ZIPARCHIVE::CREATE) !== TRUE) {
    exit("Não pode abrir: <{$zipfile}>\n");
}
foreach ($filenames as $filename) {
    $file = $filename;
    $arquivo = substr($file, -3);
    $zip->addFile($filename, $filename);
}
$zip->close();
if (rmdir_r($path)) {
    // Para quem vai ser enviado o email
    mail_attachment("envio_grafica_" . date('dmYhis') . ".zip", $zipfile, "*****@*****.**", "*****@*****.**", "Eviar arquivos para a gráfica " . date("d-m-Y"), "*****@*****.**", "Crachás a confeccionar", "<p>Conforme ajustado, seguem novos pedidos de confecção de crachá.</p>");
    redirect('movimentacoes/envio');
}
exit;
/**
 * Read messages from server and save returned emails into DB
 *
 * @param resource $mbox created by dre_connect() (by reference)
 * @param integer the number of messages to process
 * @param boolean TRUE if script is executed by cron
 * @return boolean true on success
 */
function dre_process_messages(&$mbox, $limit, $cron = false)
{
    global $Settings, $debug;
    global $dre_messages, $dre_emails, $email_cntr, $del_cntr, $is_cron_mode;
    // This may take a very long time if there are many messages; No execution time limit:
    set_max_execution_time(0);
    if ($Settings->get('repath_ignore_read')) {
        // Read status info of all messages in order to know which have already been read:
        $msg_statuses = imap_fetch_overview($mbox, '1:' . $limit);
    }
    $email_cntr = 0;
    $del_cntr = 0;
    for ($index = 1; $index <= $limit; $index++) {
        // Repeat for as many messages as allowed...
        dre_msg('<hr /><h3>' . sprintf(T_('Processing message %s:'), '#' . $index) . '</h3>', $cron);
        if ($Settings->get('repath_ignore_read')) {
            // Check if we can read this message or we should skip this:
            if (isset($msg_statuses[$index - 1]) && $msg_statuses[$index - 1]->seen == 1) {
                // Skip this message because it has already been read:
                dre_msg(T_('Ignoring this message because it has aleady been read.'), $cron);
                continue;
            } else {
                // Mark this message as "Seen" in order to don't read it twice:
                imap_setflag_full($mbox, $index, '\\Seen');
            }
        }
        $html_body = '';
        $strbody = '';
        $hasAttachment = false;
        $hasRelated = false;
        // Save email to a temporary file on hard drive, otherwise BIG attachments may take a lot of RAM:
        if (!($tmpMIME = tempnam(sys_get_temp_dir(), 'b2evoMail'))) {
            dre_msg(T_('Could not create temporary file.'), $cron);
            continue;
        }
        // Save the whole body of a specific message from the mailbox:
        imap_savebody($mbox, $tmpMIME, $index);
        // fp> TODO: soemwhere here we should skip messages that already have the "seen" flag. This should be optional but should be the default.
        // This will allow to keep the emails in the INBOX without reprocessing them but to easily try them again my marking them unread.
        // Create random temp directory for message parts:
        $tmpDirMIME = dre_tempdir(sys_get_temp_dir(), 'b2evo_');
        // Instanciate mime_parser.php library:
        $mimeParser = new mime_parser_class();
        $mimeParser->mbox = 0;
        // Set to 0 for parsing a *single* RFC 2822 message
        $mimeParser->decode_headers = 1;
        // Set to 1 if it is	necessary to decode message headers that may have non-ASCII	characters and use other character set encodings
        $mimeParser->ignore_syntax_errors = 1;
        // ignore syntax errors in	malformed messages.
        $mimeParser->extract_addresses = 0;
        // Associative array to specify parameters for the messagedata parsing and decoding operation.
        $MIMEparameters = array('File' => $tmpMIME, 'SaveBody' => $tmpDirMIME, 'SkipBody' => 1);
        // STEP 1: Parse and decode message data and retrieve its structure:
        if (!$mimeParser->Decode($MIMEparameters, $decodedMIME)) {
            // error:
            dre_msg(sprintf(T_('MIME message decoding error: %s at position %d.'), $mimeParser->error, $mimeParser->error_position), $cron);
            rmdir_r($tmpDirMIME);
            unlink($tmpMIME);
            continue;
        } else {
            // the specified message data was parsed successfully:
            dre_msg(T_('MIME message decoding successful'), $cron);
            // STEP 2: Analyze (the first) parsed message to describe its contents:
            if (!$mimeParser->Analyze($decodedMIME[0], $parsedMIME)) {
                // error:
                dre_msg(sprintf(T_('MIME message analyze error: %s'), $mimeParser->error), $cron);
                rmdir_r($tmpDirMIME);
                unlink($tmpMIME);
                continue;
            }
            // Get message $subject and $post_date from headers (by reference)
            if (!dre_process_header($parsedMIME, $subject, $post_date, $cron)) {
                // Couldn't process message headers:
                rmdir_r($tmpDirMIME);
                unlink($tmpMIME);
                continue;
            }
            // TODO: handle type == "message" recursively
            // fp> where is type == "message" ???
            // yura> I don't find the type == 'message' in dump of $decodedMIME and $parsedMIME
            // sam2kb> For some reason imap_qprint() demages HTML text... needs more testing
            // yura> I replaced imap_qprint() with quoted_printable_decode() to avoid notices about invalid quoted-printable sequence
            // yura> imap_qprint() and quoted_printable_decode() do empty the message text, thus they were deleted.
            dre_msg(T_('Email Type') . ': ' . $parsedMIME['Type'], $cron);
            if ($parsedMIME['Type'] == 'html') {
                // Mail is HTML:
                if ($debug) {
                    // Display this info only in debug mode:
                    dre_msg(sprintf(T_('HTML message part saved as %s'), $parsedMIME['DataFile']), $cron);
                }
                $html_body = file_get_contents($parsedMIME['DataFile']);
                if (empty($html_body)) {
                    // Try to get a body text from alternative parts if main html body is empty:
                    foreach ($parsedMIME['Alternative'] as $alternative) {
                        // First try to get HTML alternative (when possible)
                        if ($alternative['Type'] == 'html') {
                            // HTML text
                            if ($debug) {
                                // Display this info only in debug mode:
                                dre_msg(sprintf(T_('HTML alternative message part saved as %s'), $alternative['DataFile']), $cron);
                            }
                            $strbody = file_get_contents($alternative['DataFile']);
                            break;
                            // stop after first alternative
                        } elseif ($alternative['Type'] == 'text') {
                            // Plain text
                            if ($debug) {
                                // Display this info only in debug mode:
                                dre_msg(sprintf(T_('Text alternative message part saved as %s'), $alternative['DataFile']), $cron);
                            }
                            $strbody = file_get_contents($alternative['DataFile']);
                            break;
                            // stop after first alternative
                        }
                    }
                }
            } elseif ($parsedMIME['Type'] == 'text') {
                // Mail is plain text:
                if ($debug) {
                    // Display this info only in debug mode:
                    dre_msg(sprintf(T_('Plain-text message part saved as %s'), $parsedMIME['DataFile']), $cron);
                }
                $strbody = file_get_contents($parsedMIME['DataFile']);
            } elseif ($parsedMIME['Type'] == 'delivery-status') {
                // Mail is delivery-status:
                $strbody = $parsedMIME['Response'];
            }
            if (count($mimeParser->warnings) > 0) {
                // Record potential warnings:
                dre_msg('<h4>' . sprintf(T_('%d warnings during decode:'), count($mimeParser->warnings)) . '</h4>', $cron);
                foreach ($mimeParser->warnings as $k => $v) {
                    dre_msg(sprintf(T_('Warning: %s at position %s'), $v, $k), $cron);
                }
            }
        }
        unlink($tmpMIME);
        if (empty($html_body)) {
            // Plain-text message
            dre_msg(sprintf(T_('Message type: %s'), 'TEXT'), $cron);
            // Process body. First fix different line-endings (dos, mac, unix), remove double newlines
            $content = str_replace(array("\r", "\n\n"), "\n", trim($strbody));
            dre_msg(sprintf(T_('Message body: %s'), '<pre style="font-size:10px">' . htmlspecialchars($strbody) . '</pre>'), $cron);
        } else {
            // HTML message
            dre_msg(sprintf(T_('Message type: %s'), 'HTML'), $cron);
            dre_msg(sprintf(T_('Message body (original): %s'), '<pre style="font-size:10px">' . htmlspecialchars($html_body) . '</pre>', $cron));
            // Prepare html message body text:
            $content = dre_prepare_html_message($html_body);
            dre_msg(sprintf(T_('Message body (processed): %s'), '<pre style="font-size:10px">' . htmlspecialchars($content) . '</pre>', $cron));
        }
        dre_msg('<b class="green">' . T_('MIME Decoding Successful') . '</b>', $cron);
        $message_text = $content;
        // Remove content after terminators
        $content = dre_limit_by_terminators($content);
        global $Messages;
        if ($Messages->has_errors()) {
            // Make it easier for user to find and correct the errors
            dre_msg("\n" . sprintf(T_('Processing message: %s'), $post_title), $cron);
            dre_msg($Messages->get_string(T_('Cannot post, please correct these errors:'), 'error'), $cron);
            $Messages->clear();
            rmdir_r($tmpDirMIME);
            continue;
        }
        global $dre_emails, $DB, $localtimenow;
        dre_msg('<h4>' . T_('Saving the returned email in the database') . '</h4>', $cron);
        // Get Headers from Decoded MIME Data:
        $email_headers = dre_get_headers($decodedMIME);
        // Get data of the returned email:
        $email_data = dre_get_email_data($content, $message_text, $email_headers);
        dre_msg(T_('Email Address') . ': ' . $email_data['address'], $cron);
        dre_msg(T_('Error Type') . ': ' . dre_decode_error_type($email_data['errtype']), $cron);
        dre_msg(T_('Error Message') . ': ' . $email_data['errormsg'], $cron);
        // Insert a returned email's data into DB
        if (dre_insert_returned_email($email_data)) {
            ++$email_cntr;
        }
        // Delete temporary directory:
        rmdir_r($tmpDirMIME);
        // Mark message to be deleted:
        if ($Settings->get('repath_delete_emails')) {
            dre_msg(sprintf(T_('Marking message for deletion from inbox: %s'), $index), $cron);
            imap_delete($mbox, $index);
            ++$del_cntr;
        }
    }
    // Expunge messages marked for deletion
    imap_expunge($mbox);
    return true;
}
Example #29
0
 public function destroy($path, $entry)
 {
     $target = $this->normalize($path) . $entry;
     $this->ensureAccess($target);
     if (is_dir($target)) {
         rmdir_r($target);
     } else {
         unlink($target);
     }
 }
Example #30
0
 /**
  * Start backup
  */
 function start_backup()
 {
     global $basepath, $backup_path, $servertimenow;
     // Create current backup path
     $cbackup_path = $backup_path . date('Y-m-d-H-i-s', $servertimenow) . '/';
     echo '<p>' . sprintf(T_('Starting backup to: &laquo;%s&raquo; ...'), $cbackup_path) . '</p>';
     evo_flush();
     // Prepare backup directory
     $success = prepare_maintenance_dir($backup_path, true);
     // Backup directories and files
     if ($success && $this->has_included($this->backup_paths)) {
         $backup_files_path = $this->pack_backup_files ? $cbackup_path : $cbackup_path . 'files/';
         // Prepare files backup directory
         if ($success = prepare_maintenance_dir($backup_files_path, false)) {
             // We can backup files
             $success = $this->backup_files($backup_files_path);
         }
     }
     // Backup database
     if ($success && $this->has_included($this->backup_tables)) {
         $backup_tables_path = $this->pack_backup_files ? $cbackup_path : $cbackup_path . 'db/';
         // Prepare database backup directory
         if ($success = prepare_maintenance_dir($backup_tables_path, false)) {
             // We can backup database
             $success = $this->backup_database($backup_tables_path);
         }
     }
     if ($success) {
         echo '<p>' . sprintf(T_('Backup complete. Directory: &laquo;%s&raquo;'), $cbackup_path) . '</p>';
         evo_flush();
         return true;
     }
     @rmdir_r($cbackup_path);
     return false;
 }