/**
 * Find and delete orphan File objects with no matching file on disk
 */
function dbm_delete_orphan_files()
{
    global $DB;
    $FileCache =& get_FileCache();
    echo T_('Deleting of the orphan File objects from the database...');
    evo_flush();
    $files_SQL = new SQL();
    $files_SQL->SELECT('file_ID');
    $files_SQL->FROM('T_files');
    $files_SQL->ORDER_BY('file_ID');
    $count_files_valid = 0;
    $count_files_deleted = 0;
    $page_size = 100;
    $current_page = 0;
    while (1) {
        // Search the files by page to save memory
        $files_SQL->LIMIT($current_page * $page_size . ', ' . $page_size);
        $files = $DB->get_col($files_SQL->get());
        if (empty($files)) {
            // All files were verified, Stop here
            break;
        }
        foreach ($files as $file_ID) {
            $File = $FileCache->get_by_ID($file_ID, false, false);
            if ($File->exists()) {
                // File exists on the disk
                $count_files_valid++;
            } else {
                // File doesn't exist on the disk, Remove it from DB
                $File->dbdelete();
                $count_files_deleted++;
            }
        }
        echo ' .';
        evo_flush();
        // Clear cache after each page to save memory
        $FileCache->clear();
        $current_page++;
    }
    echo 'OK<br /><br />';
    echo sprintf(T_('%d File objects have been deleted.'), $count_files_deleted) . '<br />';
    echo sprintf(T_('%d File objects are valid entries.'), $count_files_valid);
}
    /**
     * Display the widget!
     *
     * @param array MUST contain at least the basic display params
     */
    function display($params)
    {
        global $localtimenow;
        $this->init_display($params);
        if ($this->disp_params['order_by'] == 'RAND' && isset($this->BlockCache)) {
            // Do NOT cache if display order is random
            $this->BlockCache->abort_collect();
        }
        global $Blog;
        $list_blogs = $this->disp_params['blog_ID'] ? $this->disp_params['blog_ID'] : $Blog->ID;
        //pre_dump( $list_blogs );
        // Display photos:
        // TODO: permissions, complete statuses...
        // TODO: A FileList object based on ItemListLight but adding File data into the query?
        //          overriding ItemListLigth::query() for starters ;)
        $FileCache =& get_FileCache();
        $FileList = new DataObjectList2($FileCache);
        // Query list of files:
        $SQL = new SQL();
        $SQL->SELECT('post_ID, post_datestart, post_datemodified, post_main_cat_ID, post_urltitle, post_canonical_slug_ID,
									post_tiny_slug_ID, post_ptyp_ID, post_title, post_excerpt, post_url, file_ID,
									file_title, file_root_type, file_root_ID, file_path, file_alt, file_desc');
        $SQL->FROM('T_categories INNER JOIN T_postcats ON cat_ID = postcat_cat_ID
									INNER JOIN T_items__item ON postcat_post_ID = post_ID
									INNER JOIN T_links ON post_ID = link_itm_ID
									INNER JOIN T_files ON link_file_ID = file_ID');
        $SQL->WHERE('cat_blog_ID IN (' . $list_blogs . ')');
        // fp> TODO: want to restrict on images :]
        $SQL->WHERE_and('post_status = "published"');
        // TODO: this is a dirty hack. More should be shown.
        $SQL->WHERE_and('post_datestart <= \'' . remove_seconds($localtimenow) . '\'');
        if (!empty($this->disp_params['item_type'])) {
            // Get items only with specified type
            $SQL->WHERE_and('post_ptyp_ID = ' . intval($this->disp_params['item_type']));
        }
        $SQL->GROUP_BY('link_ID');
        $SQL->LIMIT($this->disp_params['limit'] * 4);
        // fp> TODO: because we have no way of getting images only, we get 4 times more data than requested and hope that 25% at least will be images :/
        $SQL->ORDER_BY(gen_order_clause($this->disp_params['order_by'], $this->disp_params['order_dir'], 'post_', 'post_ID ' . $this->disp_params['order_dir'] . ', link_ID'));
        $FileList->sql = $SQL->get();
        $FileList->query(false, false, false, 'Media index widget');
        $layout = $this->disp_params['thumb_layout'];
        $nb_cols = $this->disp_params['grid_nb_cols'];
        $count = 0;
        $r = '';
        /**
         * @var File
         */
        while ($File =& $FileList->get_next()) {
            if ($count >= $this->disp_params['limit']) {
                // We have enough images already!
                break;
            }
            if (!$File->is_image()) {
                // Skip anything that is not an image
                // fp> TODO: maybe this property should be stored in link_ltype_ID or in the files table
                continue;
            }
            if ($layout == 'grid') {
                if ($count % $nb_cols == 0) {
                    $r .= $this->disp_params['grid_colstart'];
                }
                $r .= $this->disp_params['grid_cellstart'];
            } else {
                $r .= $this->disp_params['item_start'];
            }
            // 1/ Hack a dirty permalink( will redirect to canonical):
            // $link = url_add_param( $Blog->get('url'), 'p='.$post_ID );
            // 2/ Hack a link to the right "page". Very daring!!
            // $link = url_add_param( $Blog->get('url'), 'paged='.$count );
            // 3/ Instantiate a light object in order to get permamnent url:
            $ItemLight = new ItemLight($FileList->get_row_by_idx($FileList->current_idx - 1));
            // index had already been incremented
            $r .= '<a href="' . $ItemLight->get_permanent_url() . '">';
            // Generate the IMG THUMBNAIL tag with all the alt, title and desc if available
            $r .= $File->get_thumb_imgtag($this->disp_params['thumb_size'], '', '', $ItemLight->title);
            $r .= '</a>';
            if ($this->disp_params['disp_image_title']) {
                $title = $File->get('title') ? $this->get('title') : $ItemLight->title;
                $r .= '<span class="note">' . $title . '</span>';
            }
            ++$count;
            if ($layout == 'grid') {
                $r .= $this->disp_params['grid_cellend'];
                if ($count % $nb_cols == 0) {
                    $r .= $this->disp_params['grid_colend'];
                }
            } else {
                $r .= $this->disp_params['item_end'];
            }
        }
        // Exit if no files found
        if (empty($r)) {
            return;
        }
        echo $this->disp_params['block_start'];
        // Display title if requested
        $this->disp_title();
        if ($layout == 'grid') {
            echo $this->disp_params['grid_start'];
        } else {
            echo $this->disp_params['list_start'];
        }
        echo $r;
        if ($layout == 'grid') {
            if ($count && $count % $nb_cols != 0) {
                echo $this->disp_params['grid_colend'];
            }
            echo $this->disp_params['grid_end'];
        } else {
            echo $this->disp_params['list_end'];
        }
        echo $this->disp_params['block_end'];
        return true;
    }
foreach ($params['fields'] as $field_key => $field_data) {
    $highlighted = '';
    if ($field_data['old'] != $field_data['new']) {
        $td_class = emailskin_style('table.email_table.bordered tr.row_red td');
    } else {
        $td_class = emailskin_style('table.email_table.bordered td');
    }
    echo '<tr><th' . emailskin_style('table.email_table.bordered th') . '>' . T_($field_data['title']) . '</th>' . '<td' . $td_class . '>' . ($field_data['old'] == '' ? '&nbsp;' : $field_data['old']) . '</td>' . '<td' . $td_class . '>' . ($field_data['new'] == '' ? '&nbsp;' : $field_data['new']) . '</td></tr>' . "\n";
}
echo '</table>' . "\n";
$UserCache =& get_UserCache();
if ($User =& $UserCache->get_by_ID($params['user_ID'], false, false)) {
    $duplicated_files_message = '';
    if ($params['new_avatar_upload']) {
        // Get warning message about duplicated files when any new profile picture has been uploaded
        $FileCache =& get_FileCache();
        $new_File =& $FileCache->get_by_ID($params['new_avatar_upload']);
        $duplicated_files_message = $new_File->get_duplicated_files_message(array('message' => '<p' . emailskin_style('.p') . '><b' . emailskin_style('.important') . '>' . T_('WARNING: the same profile picture is used by these other users: %s.') . '</b></p>' . "\n", 'use_style' => true));
    }
    if ($params['avatar_changed']) {
        // If profile pictre has been changed
        echo '<p' . emailskin_style('.p') . '>' . T_('The main profile picture was changed to:') . '</p>' . "\n";
        echo '<p' . emailskin_style('.p') . '>' . $User->get_avatar_File()->get_tag('', '', '', '', 'fit-320x320', 'original', '', '', '', '', '', '#', '', 1, 'none') . '</p>' . "\n";
    } elseif ($params['new_avatar_upload']) {
        // Display the newly uploaded file only if it was not set as main profile picture
        echo '<p' . emailskin_style('.p') . '>' . T_('A new profile picture file was uploaded:') . '</p>' . "\n";
        echo '<p' . emailskin_style('.p') . '>' . $new_File->get_tag('', '', '', '', 'fit-320x320', 'original', '', '', '', '', '', '#', '', 1, 'none') . '</p>' . "\n";
    }
    // Display warning message about duplicated files
    echo $duplicated_files_message;
    // User's pictures:
 /**
  * Add new link to owner Item
  *
  * @param integer file ID
  * @param integer link position ( 'teaser', 'teaserperm', 'teaserlink', 'aftermore', 'inline', 'fallback' )
  * @param int order of the link
  * @param boolean true to update owner last touched timestamp after link was created, false otherwise
  * @return integer|boolean Link ID on success, false otherwise
  */
 function add_link($file_ID, $position = NULL, $order = 1, $update_owner = true)
 {
     if (is_null($position)) {
         // Use default link position
         $position = $this->get_default_position($file_ID);
     }
     $edited_Link = new Link();
     $edited_Link->set('itm_ID', $this->Item->ID);
     $edited_Link->set('file_ID', $file_ID);
     $edited_Link->set('position', $position);
     $edited_Link->set('order', $order);
     if ($edited_Link->dbinsert()) {
         // New link was added to the item, invalidate blog's media BlockCache
         BlockCache::invalidate_key('media_coll_ID', $this->Item->get_blog_ID());
         $FileCache =& get_FileCache();
         $File = $FileCache->get_by_ID($file_ID, false, false);
         $file_name = empty($File) ? '' : $File->get_name();
         syslog_insert(sprintf('File %s was linked to %s with ID=%s', '<b>' . $file_name . '</b>', $this->type, $this->link_Object->ID), 'info', 'file', $file_ID);
         if ($update_owner) {
             // Update last touched date of the Item
             $this->update_last_touched_date();
         }
         // Reset the Links
         $this->Links = NULL;
         $this->load_Links();
         return $edited_Link->ID;
     }
     return false;
 }
 /**
  * Get list of attached files
  * 
  * INNER JOIN on files ensures we only get back file links
  * 
  * @param integer Limit max result
  * @param string Restrict to files/images linked to a specific position.
  *               Position can be 'teaser'|'aftermore'|'inline'
  *               Use comma as separator
  * @param string order by
  * @return DataObjectList2 on success or NULL if no linked files found
  */
 function get_attachment_FileList($limit = 1000, $position = NULL, $order = 'link_ID')
 {
     if (!isset($GLOBALS['files_Module'])) {
         return NULL;
     }
     load_class('_core/model/dataobjects/_dataobjectlist2.class.php', 'DataObjectList2');
     $FileCache =& get_FileCache();
     $FileList = new DataObjectList2($FileCache);
     // IN FUNC
     $SQL = new SQL();
     $SQL->SELECT('file_ID, file_title, file_root_type, file_root_ID, file_path, file_alt, file_desc, link_ID');
     $SQL->FROM('T_links INNER JOIN T_files ON link_file_ID = file_ID');
     $SQL->WHERE($this->get_where_condition());
     if (!empty($position)) {
         global $DB;
         $position = explode(',', $position);
         $SQL->WHERE_and('link_position IN ( ' . $DB->quote($position) . ' )');
     }
     //$SQL->ORDER_BY( $order );
     $SQL->ORDER_BY('link_order');
     $SQL->LIMIT($limit);
     $FileList->sql = $SQL->get();
     $FileList->query(false, false, false, 'get_attachment_FileList');
     if ($FileList->result_num_rows == 0) {
         // Nothing found
         $FileList = NULL;
     }
     return $FileList;
 }
Beispiel #6
0
/**
 * metaWeblog.newMediaObject image upload
 * wp.uploadFile
 *
 * Supplied image is encoded into the struct as bits
 *
 * @see http://www.xmlrpc.com/metaWeblogApi#metaweblognewmediaobject
 * @see http://codex.wordpress.org/XML-RPC_wp#wp.uploadFile
 *
 * @param xmlrpcmsg XML-RPC Message
 *					0 blogid (string): Unique identifier of the blog the post will be added to.
 *						Currently ignored in b2evo, in favor of the category.
 *					1 username (string): Login for a Blogger user who has permission to edit the given
 *						post (either the user who originally created it or an admin of the blog).
 *					2 password (string): Password for said username.
 *					3 struct (struct)
 * 							- name : filename
 * 							- type : mimetype
 * 							- bits : base64 encoded file
 * @return xmlrpcresp XML-RPC Response
 */
function _wp_mw_newmediaobject($m)
{
    global $Settings, $Plugins, $force_upload_forbiddenext;
    // CHECK LOGIN:
    /**
     * @var User
     */
    if (!($current_User =& xmlrpcs_login($m, 1, 2))) {
        // Login failed, return (last) error:
        return xmlrpcs_resperror();
    }
    // GET BLOG:
    /**
     * @var Blog
     */
    if (!($Blog =& xmlrpcs_get_Blog($m, 0))) {
        // Login failed, return (last) error:
        return xmlrpcs_resperror();
    }
    // CHECK PERMISSION:
    if (!$current_User->check_perm('files', 'add', false, $Blog->ID)) {
        // Permission denied
        return xmlrpcs_resperror(3);
        // User error 3
    }
    logIO('Permission granted.');
    if (!$Settings->get('upload_enabled')) {
        return xmlrpcs_resperror(2, 'Object upload not allowed');
    }
    $xcontent = $m->getParam(3);
    // Get the main data - and decode it properly for the image - sorry, binary object
    logIO('Decoding content...');
    $contentstruct = xmlrpc_decode_recurse($xcontent);
    $data = $contentstruct['bits'];
    $file_mimetype = isset($contentstruct['type']) ? $contentstruct['type'] : '(none)';
    logIO('Received MIME type: ' . $file_mimetype);
    $overwrite = false;
    if (isset($contentstruct['overwrite'])) {
        $overwrite = (bool) $contentstruct['overwrite'];
    }
    logIO('Overwrite if exists: ' . ($overwrite ? 'yes' : 'no'));
    load_funcs('files/model/_file.funcs.php');
    $filesize = evo_bytes($data);
    if (($maxfilesize = $Settings->get('upload_maxkb') * 1024) && $filesize > $maxfilesize) {
        return xmlrpcs_resperror(4, sprintf(T_('The file is too large: %s but the maximum allowed is %s.'), bytesreadable($filesize, false), bytesreadable($maxfilesize, false)));
    }
    logIO('File size is OK: ' . bytesreadable($filesize, false));
    $FileRootCache =& get_FileRootCache();
    $fm_FileRoot =& $FileRootCache->get_by_type_and_ID('collection', $Blog->ID, true);
    if (!$fm_FileRoot) {
        // fileRoot not found:
        return xmlrpcs_resperror(14, 'File root not found');
    }
    $rf_filepath = $contentstruct['name'];
    logIO('Received filepath: ' . $rf_filepath);
    // Split into path + name:
    $filepath_parts = explode('/', $rf_filepath);
    $filename = array_pop($filepath_parts);
    logIO('Original file name: ' . $filename);
    // Validate and sanitize filename
    if ($error_filename = process_filename($filename, true)) {
        return xmlrpcs_resperror(5, $error_filename);
    }
    logIO('Sanitized file name: ' . $filename);
    // Check valid path parts:
    $rds_subpath = '';
    foreach ($filepath_parts as $filepath_part) {
        if (empty($filepath_part) || $filepath_part == '.') {
            // self ref not useful
            continue;
        }
        if ($error = validate_dirname($filepath_part)) {
            // invalid relative path:
            logIO($error);
            return xmlrpcs_resperror(6, $error);
        }
        $rds_subpath .= $filepath_part . '/';
    }
    logIO('Subpath: ' . $rds_subpath);
    // Create temporary file and insert contents into it.
    $tmpfile_name = tempnam(sys_get_temp_dir(), 'fmupload');
    if ($tmpfile_name) {
        if (save_to_file($data, $tmpfile_name, 'wb')) {
            $image_info = @getimagesize($tmpfile_name);
        } else {
            return xmlrpcs_resperror(13, 'Error while writing to temp file.');
        }
    }
    if (!empty($image_info)) {
        // This is an image file, let's check mimetype and correct extension
        if ($image_info['mime'] != $file_mimetype) {
            // Invalid file type
            $FiletypeCache =& get_FiletypeCache();
            // Get correct file type based on mime type
            $correct_Filetype = $FiletypeCache->get_by_mimetype($image_info['mime'], false, false);
            $file_mimetype = $image_info['mime'];
            // Check if file type is known by us, and if it is allowed for upload.
            // If we don't know this file type or if it isn't allowed we don't change the extension! The current extension is allowed for sure.
            if ($correct_Filetype && $correct_Filetype->is_allowed()) {
                // A FileType with the given mime type exists in database and it is an allowed file type for current User
                // The "correct" extension is a plausible one, proceed...
                $correct_extension = array_shift($correct_Filetype->get_extensions());
                $path_info = pathinfo($filename);
                $current_extension = $path_info['extension'];
                // change file extension to the correct extension, but only if the correct extension is not restricted, this is an extra security check!
                if (strtolower($current_extension) != strtolower($correct_extension) && !in_array($correct_extension, $force_upload_forbiddenext)) {
                    // change the file extension to the correct extension
                    $old_filename = $filename;
                    $filename = $path_info['filename'] . '.' . $correct_extension;
                }
            }
        }
    }
    // Get File object for requested target location:
    $FileCache =& get_FileCache();
    $newFile =& $FileCache->get_by_root_and_path($fm_FileRoot->type, $fm_FileRoot->in_type_ID, trailing_slash($rds_subpath) . $filename, true);
    if ($newFile->exists()) {
        if ($overwrite && $newFile->unlink()) {
            // OK, file deleted
            // Delete thumb caches from old location:
            logIO('Old file deleted');
            $newFile->rm_cache();
        } else {
            return xmlrpcs_resperror(8, sprintf(T_('The file &laquo;%s&raquo; already exists.'), $filename));
        }
    }
    // Trigger plugin event
    if ($Plugins->trigger_event_first_false('AfterFileUpload', array('File' => &$newFile, 'name' => &$filename, 'type' => &$file_mimetype, 'tmp_name' => &$tmpfile_name, 'size' => &$filesize))) {
        // Plugin returned 'false'.
        // Abort upload for this file:
        @unlink($tmpfile_name);
        return xmlrpcs_resperror(16, 'File upload aborted by a plugin.');
    }
    if (!mkdir_r($newFile->get_dir())) {
        // Dir didn't already exist and could not be created
        return xmlrpcs_resperror(9, 'Error creating sub directories: ' . $newFile->get_rdfs_rel_path());
    }
    if (!@rename($tmpfile_name, $newFile->get_full_path())) {
        return xmlrpcs_resperror(13, 'Error while writing to file.');
    }
    // chmod the file
    $newFile->chmod();
    // Initializes file properties (type, size, perms...)
    $newFile->load_properties();
    // Load meta data AND MAKE SURE IT IS CREATED IN DB:
    $newFile->meta == 'unknown';
    $newFile->load_meta(true);
    // Resize and rotate
    logIO('Running file post-processing (resize and rotate)...');
    prepare_uploaded_files(array($newFile));
    logIO('Done');
    $url = $newFile->get_url();
    logIO('URL of new file: ' . $url);
    $struct = new xmlrpcval(array('file' => new xmlrpcval($filename, 'string'), 'url' => new xmlrpcval($url, 'string'), 'type' => new xmlrpcval($file_mimetype, 'string')), 'struct');
    logIO('OK.');
    return new xmlrpcresp($struct);
}
    /**
     * Display the widget!
     *
     * @param array MUST contain at least the basic display params
     */
    function display($params)
    {
        global $localtimenow, $DB, $Blog;
        $this->init_display($params);
        $blog_ID = intval($this->disp_params['blog_ID']);
        if (empty($blog_ID)) {
            // Use current blog by default
            $blog_ID = $Blog->ID;
        }
        $BlogCache =& get_BlogCache();
        if (!$BlogCache->get_by_ID($blog_ID, false, false)) {
            // No blog exists
            return;
        }
        // Display photos:
        // TODO: permissions, complete statuses...
        // TODO: A FileList object based on ItemListLight but adding File data into the query?
        //          overriding ItemListLigth::query() for starters ;)
        // Init caches
        $FileCache =& get_FileCache();
        $ItemCache =& get_ItemCache();
        // Query list of files and posts fields:
        // Note: We use ItemQuery to get attachments from all posts which should be visible ( even in case of aggregate blogs )
        $ItemQuery = new ItemQuery($ItemCache->dbtablename, $ItemCache->dbprefix, $ItemCache->dbIDname);
        $ItemQuery->SELECT('post_ID, post_datestart, post_datemodified, post_main_cat_ID, post_urltitle, post_canonical_slug_ID,
									post_tiny_slug_ID, post_ityp_ID, post_title, post_excerpt, post_url, file_ID, file_type,
									file_title, file_root_type, file_root_ID, file_path, file_alt, file_desc, file_path_hash');
        $ItemQuery->FROM_add('INNER JOIN T_links ON post_ID = link_itm_ID');
        $ItemQuery->FROM_add('INNER JOIN T_files ON link_file_ID = file_ID');
        $ItemQuery->where_chapter($blog_ID);
        if ($this->disp_params['item_visibility'] == 'public') {
            // Get images only of the public items
            $ItemQuery->where_visibility(array('published'));
        } else {
            // Get image of all available posts for current user
            $ItemQuery->where_visibility(NULL);
        }
        $ItemQuery->WHERE_and('( file_type = "image" ) OR ( file_type IS NULL )');
        $ItemQuery->WHERE_and('post_datestart <= \'' . remove_seconds($localtimenow) . '\'');
        $ItemQuery->WHERE_and('link_position != "cover"');
        if (!empty($this->disp_params['item_type'])) {
            // Get items only with specified type
            $ItemQuery->WHERE_and('post_ityp_ID = ' . intval($this->disp_params['item_type']));
        }
        $ItemQuery->GROUP_BY('link_ID');
        // fp> TODO: because no way of getting images only, we get 4 times more data than requested and hope that 25% at least will be images :/
        // asimo> This was updated and we get images and those files where we don't know the file type yet. Now we get 2 times more data than requested.
        // Maybe it would be good to get only the requested amount of files, because after a very short period the file types will be set for all images.
        $ItemQuery->LIMIT(intval($this->disp_params['limit']) * 2);
        $ItemQuery->ORDER_BY(gen_order_clause($this->disp_params['order_by'], $this->disp_params['order_dir'], 'post_', 'post_ID ' . $this->disp_params['order_dir'] . ', link_ID'));
        // Init FileList with the above defined query
        $FileList = new DataObjectList2($FileCache);
        $FileList->sql = $ItemQuery->get();
        $FileList->query(false, false, false, 'Media index widget');
        $layout = $this->disp_params['thumb_layout'];
        $nb_cols = $this->disp_params['grid_nb_cols'];
        $count = 0;
        $r = '';
        /**
         * @var File
         */
        while ($File =& $FileList->get_next()) {
            if ($count >= $this->disp_params['limit']) {
                // We have enough images already!
                break;
            }
            if (!$File->is_image()) {
                // Skip anything that is not an image
                // Only images are selected or those files where we don't know the file type yet.
                // This check is only for those files where we don't know the filte type. The file type will be set during the check.
                continue;
            }
            if ($layout == 'grid') {
                // Grid layout
                if ($count % $nb_cols == 0) {
                    $r .= $this->disp_params['grid_colstart'];
                }
                $r .= $this->disp_params['grid_cellstart'];
            } elseif ($layout == 'flow') {
                // Flow block layout
                $r .= $this->disp_params['flow_block_start'];
            } else {
                // List layout
                $r .= $this->disp_params['item_start'];
            }
            // 1/ Hack a dirty permalink( will redirect to canonical):
            // $link = url_add_param( $Blog->get('url'), 'p='.$post_ID );
            // 2/ Hack a link to the right "page". Very daring!!
            // $link = url_add_param( $Blog->get('url'), 'paged='.$count );
            // 3/ Instantiate a light object in order to get permamnent url:
            $ItemLight = new ItemLight($FileList->get_row_by_idx($FileList->current_idx - 1));
            // index had already been incremented
            $r .= '<a href="' . $ItemLight->get_permanent_url() . '">';
            // Generate the IMG THUMBNAIL tag with all the alt, title and desc if available
            $r .= $File->get_thumb_imgtag($this->disp_params['thumb_size'], '', '', $ItemLight->title);
            $r .= '</a>';
            if ($this->disp_params['disp_image_title']) {
                // Dislay title of image or item
                $title = $File->get('title') ? $File->get('title') : $ItemLight->title;
                if (!empty($title)) {
                    $r .= '<span class="note">' . $title . '</span>';
                }
            }
            ++$count;
            if ($layout == 'grid') {
                // Grid layout
                $r .= $this->disp_params['grid_cellend'];
                if ($count % $nb_cols == 0) {
                    $r .= $this->disp_params['grid_colend'];
                }
            } elseif ($layout == 'flow') {
                // Flow block layout
                $r .= $this->disp_params['flow_block_end'];
            } else {
                // List layout
                $r .= $this->disp_params['item_end'];
            }
        }
        // Exit if no files found
        if (empty($r)) {
            return;
        }
        echo $this->disp_params['block_start'];
        // Display title if requested
        $this->disp_title();
        echo $this->disp_params['block_body_start'];
        if ($layout == 'grid') {
            // Grid layout
            echo $this->disp_params['grid_start'];
        } elseif ($layout == 'flow') {
            // Flow block layout
            echo $this->disp_params['flow_start'];
        } else {
            // List layout
            echo $this->disp_params['list_start'];
        }
        echo $r;
        if ($layout == 'grid') {
            // Grid layout
            if ($count && $count % $nb_cols != 0) {
                echo $this->disp_params['grid_colend'];
            }
            echo $this->disp_params['grid_end'];
        } elseif ($layout == 'flow') {
            // Flow block layout
            echo $this->disp_params['flow_end'];
        } else {
            // List layout
            echo $this->disp_params['list_end'];
        }
        echo $this->disp_params['block_body_end'];
        echo $this->disp_params['block_end'];
        return true;
    }
Beispiel #8
0
 /**
  * Template function: display content of comment
  *
  * @param string Output format, see {@link format_to_output()}
  * @param boolean Add ban url action icon after each url or not
  * @param boolean show comment attachments
  * @param array attachment display params
  */
 function content($format = 'htmlbody', $ban_urls = false, $show_attachments = true, $params = array())
 {
     global $current_User;
     global $Plugins;
     // Make sure we are not missing any param:
     $params = array_merge(array('before_image' => '<figure class="evo_image_block">', 'before_image_legend' => '<figcaption class="evo_image_legend">', 'after_image_legend' => '</figcaption>', 'after_image' => '</figure>', 'image_size' => 'fit-400x320', 'image_class' => '', 'image_text' => '', 'attachments_mode' => 'read', 'attachments_view_text' => ''), $params);
     $attachments = array();
     if ($show_attachments) {
         if (empty($this->ID) && isset($this->checked_attachments)) {
             // PREVIEW
             $attachment_ids = explode(',', $this->checked_attachments);
             $FileCache =& get_FileCache();
             foreach ($attachment_ids as $ID) {
                 $File = $FileCache->get_by_ID($ID, false, false);
                 if ($File != NULL) {
                     $attachments[] = $File;
                 }
             }
         } else {
             // Get all Links
             $LinkOwner = new LinkComment($this);
             $attachments =& $LinkOwner->get_Links();
         }
     }
     $images_above_content = '';
     $images_below_content = '';
     foreach ($attachments as $index => $attachment) {
         if (!empty($this->ID)) {
             // Normal mode when comment exists in DB (NOT PREVIEW mode)
             $Link = $attachment;
             $link_position = $Link->get('position');
             $params['Link'] = $Link;
             $attachment = $attachment->get_File();
         } else {
             // Set default position for preview files
             $link_position = 'aftermore';
         }
         $File = $attachment;
         if (empty($File)) {
             // File object doesn't exist in DB
             global $Debuglog;
             $Debuglog->add(sprintf('File object linked to comment #%d does not exist in DB!', $this->ID), array('error', 'files'));
             continue;
         }
         if (!$File->exists()) {
             // File doesn't exist on the disk
             global $Debuglog;
             $Debuglog->add(sprintf('File linked to comment #%d does not exist (%s)!', $this->ID, $File->get_full_path()), array('error', 'files'));
             continue;
         }
         $r = '';
         $params['File'] = $File;
         $params['Comment'] = $this;
         $params['data'] =& $r;
         $temp_params = $params;
         foreach ($params as $param_key => $param_value) {
             // Pass all params by reference, in order to give possibility to modify them by plugin
             // So plugins can add some data before/after image tag (E.g. used by infodots plugin)
             $params[$param_key] =& $params[$param_key];
         }
         if (count($Plugins->trigger_event_first_true('RenderCommentAttachment', $params)) != 0) {
             // File was processed by plugin
             if ($link_position == 'teaser') {
                 // Image should be displayed above content
                 $images_above_content .= $r;
             } else {
                 // Image should be displayed below content
                 $images_below_content .= $r;
             }
             unset($attachments[$index]);
             continue;
         }
         if ($File->is_image()) {
             // File is image
             if ($params['attachments_mode'] == 'view') {
                 // Only preview attachments
                 $image_link_rel = '';
                 $image_link_to = '';
             } else {
                 // Read attachments
                 $image_link_rel = 'lightbox[c' . $this->ID . ']';
                 $image_link_to = 'original';
             }
             if (empty($this->ID)) {
                 // PREVIEW mode
                 $r = $File->get_tag($params['before_image'], $params['before_image_legend'], $params['after_image_legend'], $params['after_image'], $params['image_size'], $image_link_to, T_('Posted by ') . $this->get_author_name(), $image_link_rel, $params['image_class'], '', '', '#');
             } else {
                 $r = $Link->get_tag(array_merge(array('image_link_to' => $image_link_to, 'image_link_title' => T_('Posted by ') . $this->get_author_name(), 'image_link_rel' => $image_link_rel), $params));
             }
             if ($link_position == 'teaser') {
                 // Image should be displayed above content
                 $images_above_content .= $r;
             } else {
                 // Image should be displayed below content
                 $images_below_content .= $r;
             }
             unset($attachments[$index]);
         }
         $params = $temp_params;
     }
     if (!empty($images_above_content)) {
         // Display images above content
         echo $images_above_content;
         if ($params['image_text'] != '') {
             // Display info text below pictures
             echo $params['image_text'];
         }
     }
     if ($ban_urls) {
         // add ban icons if user has edit permission for this comment
         $ban_urls = $current_User->check_perm('comment!CURSTATUS', 'edit', false, $this);
     }
     if ($ban_urls) {
         // ban urls and user has permission
         echo add_ban_icons($this->get_content($format));
     } else {
         // don't ban urls
         echo $this->get_content($format);
     }
     if (!empty($images_below_content)) {
         // Display images below content
         echo $images_below_content;
         if (empty($images_above_content) && $params['image_text'] != '') {
             // Display info text below pictures
             echo $params['image_text'];
         }
     }
     if (isset($attachments)) {
         // show not image attachments
         $after_docs = '';
         if (count($attachments) > 0) {
             echo '<br /><b>' . T_('Attachments:') . '</b>';
             echo '<ul class="bFiles">';
             $after_docs = '</ul>';
         }
         foreach ($attachments as $attachment) {
             // $attachment is a File in preview mode, but it is a Link in normal mode
             $doc_File = empty($this->ID) ? $attachment : $attachment->get_File();
             echo '<li>';
             if (empty($doc_File)) {
                 // Broken File object
                 $attachment_download_link = '';
                 $attachment_name = empty($attachment) ? '' : T_('Link ID') . '#' . $attachment->ID;
             } elseif (!$doc_File->exists()) {
                 $attachment_download_link = '';
                 $attachment_name = $doc_File->get_name();
             } elseif ($params['attachments_mode'] == 'view') {
                 // Only preview attachments
                 $attachment_download_link = '';
                 $attachment_name = $doc_File->get_type();
             } else {
                 // Read attachments
                 $attachment_download_link = action_icon(T_('Download file'), 'download', $doc_File->get_url(), '', 5) . ' ';
                 $attachment_name = $doc_File->get_view_link($doc_File->get_name());
             }
             echo $attachment_download_link;
             echo $attachment_name;
             if (!empty($doc_File) && $doc_File->exists()) {
                 // Display file size if it exists
                 echo ' (' . bytesreadable($doc_File->get_size()) . ')';
             } else {
                 // Display warning if File is broken
                 echo ' - <span class="red nowrap">' . get_icon('warning_yellow') . ' ' . T_('Missing attachment!') . '</span>';
             }
             if (!empty($params['attachments_view_text'])) {
                 echo $params['attachments_view_text'];
             }
             echo '</li>';
         }
         echo $after_docs;
     }
 }
Beispiel #9
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();
}
Beispiel #10
0
 /**
  * Attempt to load meta data for all files in the list.
  *
  * Will attempt only once per file and cache the result.
  */
 function load_meta()
 {
     global $DB, $Debuglog;
     $to_load = array();
     for ($i = 0; $i < count($this->_entries); $i++) {
         // For each file:
         $loop_File =& $this->_entries[$i];
         // echo '<br>'.$loop_File->get_full_path();
         if ($loop_File->meta != 'unknown') {
             // We have already loaded meta data:
             continue;
         }
         $to_load[] = $DB->quote(md5($this->_FileRoot->type . $this->_FileRoot->in_type_ID . $loop_File->get_rdfp_rel_path(), true));
     }
     if (count($to_load)) {
         // We have something to load...
         /**
          * @var FileCache
          */
         $FileCache =& get_FileCache();
         $rows = $DB->get_results("\n\t\t\t\tSELECT *\n\t\t\t\t  FROM T_files\n\t\t\t\t WHERE file_path_hash IN (" . implode(',', $to_load) . ")", OBJECT, 'Load FileList meta data');
         if (count($rows)) {
             // Go through rows of loaded meta data...
             foreach ($rows as $row) {
                 // Retrieve matching File object:
                 /**
                  * @var File
                  */
                 $loop_File =& $FileCache->get_by_root_and_path($row->file_root_type, $row->file_root_ID, $row->file_path);
                 // Associate meta data to File object:
                 $loop_File->load_meta(false, $row);
             }
         }
     }
     // For all Files that still have no meta data, memorize that we could not find any meta data
     for ($i = 0; $i < count($this->_entries); $i++) {
         // For each file:
         $loop_File =& $this->_entries[$i];
         if ($loop_File->meta == 'unknown') {
             $loop_File->meta = 'notfound';
         }
     }
     // Has sth been loaded?
     return count($to_load) && count($rows);
 }
Beispiel #11
0
 /**
  * Get message if the duplicates exist for this file
  *
  * @param array Params
  * @return string Message text
  */
 function get_duplicated_files_message($params = array())
 {
     $params = array_merge(array('message' => '%s', 'file_type' => 'image', 'root_type' => 'user', 'root_ID' => NULL, 'link_to' => 'user', 'use_style' => false), $params);
     // Find the duplicated files
     $duplicated_file_IDs = $this->get_duplicated_files($params);
     if (empty($duplicated_file_IDs)) {
         // No duplicates
         return false;
     }
     $FileCache =& get_FileCache();
     $duplicated_files = array();
     foreach ($duplicated_file_IDs as $file_ID => $file_root_ID) {
         if (!($duplicated_File =& $FileCache->get_by_ID($file_ID, false, false))) {
             // Broken file object
             continue;
         }
         if ($params['link_to'] == 'user') {
             // Link to profile picture edit form
             global $admin_url;
             $UserCache =& get_UserCache();
             $User =& $UserCache->get_by_ID($file_root_ID, false, false);
             $link_text = $User ? $User->get_colored_login(array('use_style' => $params['use_style'])) : T_('Deleted user');
             $link_class = $User ? $User->get_gender_class() : 'user';
             $link_url = $admin_url . '?ctrl=user&amp;user_tab=avatar&amp;user_ID=' . $file_root_ID;
             $duplicated_files[] = '<a href="' . $link_url . '" class="nowrap ' . $link_class . '">' . $duplicated_File->get_tag('', '', '', '', 'crop-top-15x15', '', '', 'lightbox[d' . $this->ID . ']', 'avatar_before_login') . ' ' . $link_text . '</a>';
         } else {
             // Default link
             $duplicated_files[] = $duplicated_File->get_tag('', '', '', '', 'crop-top-15x15', 'original', '', 'lightbox[d' . $this->ID . ']');
         }
     }
     return sprintf($params['message'], implode(', ', $duplicated_files));
 }
Beispiel #12
0
 function get_gallery_images($limit = 1000, $order = '')
 {
     if ($filenames = $this->get_directory_files('relative')) {
         $FileCache =& get_FileCache();
         switch (strtoupper($order)) {
             case 'ASC':
                 sort($filenames);
                 break;
             case 'DESC':
                 rsort($filenames);
                 break;
             case 'RAND':
                 shuffle($filenames);
                 break;
         }
         $i = 1;
         foreach ($filenames as $filename) {
             if ($i > $limit) {
                 // We've got enough images
                 break;
             }
             /*
             sam2kb> TODO: we may need to filter files by extension first, it doesn't make sence
             		to query the database for every single .txt or .zip file.
             		The best solution would be to have file MIME type field in DB
             */
             $l_File =& $FileCache->get_by_root_and_path($this->_FileRoot->type, $this->_FileRoot->in_type_ID, $filename);
             $l_File->load_meta();
             if (!$l_File->is_image()) {
                 // Not an image
                 continue;
             }
             $Files[] = $l_File;
             $i++;
         }
         if (!empty($Files)) {
             return $Files;
         }
     }
     return false;
 }
/**
 * Get a link to object of system log
 *
 * @param string Object type
 * @param integer Object ID
 * @return string
 */
function syslog_object_link($object_type, $object_ID)
{
    global $current_User, $admin_url;
    $link = '';
    if (empty($object_ID)) {
        // Invalid object ID
        return 'Empty object ID';
    }
    switch ($object_type) {
        case 'comment':
            // Link to comment
            $CommentCache =& get_CommentCache();
            if (($Comment =& $CommentCache->get_by_ID($object_ID, false, false)) !== false) {
                if ($current_User->check_perm('comment!CURSTATUS', 'edit', false, $Comment)) {
                    // Current user has permission to edit this comment
                    $Item =& $Comment->get_Item();
                    $link = '<a href="' . $admin_url . '?ctrl=comments&action=edit&comment_ID=' . $Comment->ID . '">' . $Item->title . ' #' . $Comment->ID . '</a>';
                }
            } else {
                // Comment was deleted or ID is incorrect
                $link = 'No comment';
            }
            break;
        case 'item':
            // Link to item
            $ItemCache =& get_ItemCache();
            if (($Item =& $ItemCache->get_by_ID($object_ID, false, false)) !== false) {
                if ($current_User->check_perm('item_post!CURSTATUS', 'edit', false, $Item)) {
                    // Current user has permission to edit this item
                    $link = '<a href="' . $Item->get_edit_url() . '">' . $Item->title . '</a>';
                }
            } else {
                // Item was deleted or ID is incorrect
                $link = 'No item';
            }
            break;
        case 'user':
            // Link to user
            if ($current_User->check_perm('users', 'view')) {
                // Current user has permission to view users
                $UserCache = get_UserCache();
                if (($User =& $UserCache->get_by_ID($object_ID, false, false)) !== false) {
                    // User exists
                    $link = $User->get_identity_link();
                } else {
                    // User was deleted or ID is incorrect
                    $link = 'No user';
                }
            }
            break;
        case 'file':
            // Link to file
            $FileCache =& get_FileCache();
            if (($File =& $FileCache->get_by_ID($object_ID, false, false)) !== false) {
                // File exists
                $link = $File->is_dir() ? '' : $File->get_view_link();
                $link .= ' ' . $File->get_target_icon();
            } else {
                // User was deleted or ID is incorrect
                $link = 'No file';
            }
            break;
    }
    return $link;
}
/**
 * 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;
}
 /**
  * Load required Files into the FileCache before Link class constructor will be called.
  * It's imporatnt to load all Files with one query instead of loading the one by one
  * 
  * private function
  * 
  * @param array link rows
  */
 function load_linked_files(&$link_rows)
 {
     if (empty($link_rows)) {
         // There are nothing to load
         return;
     }
     // Collect required file Ids
     $link_file_ids = array();
     foreach ($link_rows as $row) {
         $link_file_ids[] = $row->link_file_ID;
     }
     if (!empty($link_file_ids)) {
         // Load required Files into FileCache
         $FileCache =& get_FileCache();
         $FileCache->load_where('file_ID IN ( ' . implode(',', $link_file_ids) . ' )');
     }
 }
Beispiel #16
0
 /**
  * Delete user avatar file
  *
  * @param integer the avatar file ID
  * @return mixed true on success, allowed action otherwise
  */
 function delete_avatar($file_ID)
 {
     global $current_User, $Messages;
     if (!$current_User->can_moderate_user($this->ID) && $this->ID != $current_User->ID) {
         // user is only allowed to update him/herself
         $Messages->add(T_('You are only allowed to update your own profile!'), 'error');
         return 'view';
     }
     if ($file_ID == NULL) {
         $Messages->add(T_('Profile picture could not be changed!'), 'error');
         return 'edit';
     }
     $LinkOwner = new LinkUser($this);
     $Link =& $LinkOwner->get_link_by_file_ID($file_ID);
     if ($Link) {
         $File = $Link->get_File();
         $LinkOwner->remove_link($Link);
     } else {
         $FileCache =& get_FileCache();
         $File = $FileCache->get_by_ID($file_ID);
     }
     if ($file_ID == $this->avatar_file_ID) {
         // Unset this picture from user avatar if it is used as main picture
         $this->set('avatar_file_ID', NULL, true);
         $this->dbupdate();
     }
     if ($File->_FileRoot->type == 'user' && $File->_FileRoot->in_type_ID == $this->ID && strpos($File->get_rdfp_rel_path(), 'profile_pictures') === 0) {
         // Delete the file if it is in the current User profile_pictures folder
         $File->unlink();
     }
     $Messages->add(T_('Profile picture has been deleted.'), 'success');
     return true;
 }
Beispiel #17
0
 /**
  * Get {@link File} of the link.
  *
  * @return File
  */
 function &get_File()
 {
     if (!isset($this->File)) {
         if (isset($GLOBALS['files_Module'])) {
             $FileCache =& get_FileCache();
             // fp> do not halt on error. For some reason (ahem bug) a file can disappear and if we fail here then we won't be
             // able to delete the link
             $this->File =& $FileCache->get_by_ID($this->file_ID, false, false);
         } else {
             $this->File = NULL;
         }
     }
     return $this->File;
 }
} else {
    // check to fit at least one of the minimum requirements
    // Set the main query having condition
    $SQL->HAVING('( total_inappropriate >= ' . $DB->quote($min_inappropriate_votes) . ' ) AND ( total_spam >= ' . $DB->quote($min_spam_votes) . ' )');
    // Create count result query
    $count_SQL = new SQL();
    $count_SQL->SELECT('link_file_ID');
    $count_SQL->FROM('T_links__vote');
    $count_SQL->FROM_add('INNER JOIN T_links ON link_ID = lvot_link_ID');
    $count_SQL->GROUP_BY('link_file_ID');
    $count_SQL->HAVING('( SUM( lvot_inappropriate ) >= ' . $DB->quote($min_inappropriate_votes) . ' ) AND ( SUM( lvot_spam ) >= ' . $DB->quote($min_spam_votes) . ' )');
    // count the number of filtered result ( we need subquery because we can't count all when we have group by )
    $filtered_num_results = $DB->get_var("SELECT COUNT(*) FROM (" . $count_SQL->get() . " )  AS TotalSelected ");
}
$Results = new Results($SQL->get(), 'fsusp_', $default_order, $UserSettings->get('results_per_page'), (int) $filtered_num_results);
$Results->Cache =& get_FileCache();
$Results->title = T_('Suspicious files') . get_manual_link('file-moderation-suspicious');
/**
 * Callback to add filters on top of the result set
 *
 * @param Form
 */
function callback_filter_file_suspicious(&$Form)
{
    $Form->text('miv', get_param('miv'), 5, T_('Minimun inappropriate votes'), '', 6);
    $Form->text('msv', get_param('msv'), 5, T_('Minimun spam votes'), '', 6);
}
$filter_presets = array('all' => array(T_('All'), '?ctrl=filemod&amp;miv=0&amp;msv=0'), 'inappropriate' => array(T_('Inappropriate'), '?ctrl=filemod&amp;miv=1&amp;msv=0'), 'spam' => array(T_('Spam'), '?ctrl=filemod&amp;miv=0&amp;msv=1'));
$Results->filter_area = array('callback' => 'callback_filter_file_suspicious', 'url_ignore' => 'results_fsusp_page', 'presets' => $filter_presets);
$Results->cols[] = array('th' => T_('Icon/Type'), 'th_class' => 'shrinkwrap', 'td_class' => 'shrinkwrap', 'td' => '% {Obj}->get_preview_thumb( "fulltype", array( "init" => true ) ) %');
$Results->cols[] = array('th' => T_('Path'), 'td' => '% {Obj}->get_view_link() % % {Obj}->get_target_icon() %', 'order' => 'file_path');
/**
 * Find and delete orphan File objects with no matching file on disk
 */
function dbm_delete_orphan_files()
{
    global $DB, $admin_url;
    $FileCache =& get_FileCache();
    $FileCache->clear();
    echo T_('Deleting of the orphan File objects from the database...');
    evo_flush();
    $files_SQL = new SQL();
    $files_SQL->SELECT('*');
    $files_SQL->FROM('T_files');
    $files_SQL->ORDER_BY('file_ID');
    $count_files_valid = 0;
    $count_files_invalid = 0;
    $count_files_deleted = 0;
    $page_size = 100;
    $current_page = 0;
    // Search the files by page to save memory
    $files_SQL->LIMIT('0, ' . $page_size);
    while ($loaded_Files = $FileCache->load_by_sql($files_SQL)) {
        // Check all loaded files
        foreach ($loaded_Files as $File) {
            if (is_null($File)) {
                // The File object couldn't be created because the db entry is invalid
                $count_files_invalid++;
                continue;
            }
            if ($File->exists()) {
                // File exists on the disk
                $count_files_valid++;
            } else {
                // File doesn't exist on the disk, Remove it from DB
                $File->dbdelete();
                $count_files_deleted++;
            }
        }
        echo ' .';
        evo_flush();
        // Clear cache after each page to save memory
        $FileCache->clear();
        $current_page++;
        $files_SQL->LIMIT($current_page * $page_size . ', ' . $page_size);
    }
    echo 'OK<p>';
    echo sprintf(T_('Number of deleted orphan File objects: %d.'), $count_files_deleted) . '<br />';
    echo sprintf(T_('Number of valid File objects in the database: %d.'), $count_files_valid) . '</p>';
    if ($count_files_invalid) {
        // There are invalid files in the database
        // Display warning to show that the 'Remove orphan file roots' tool should be also called
        $remove_orphan_file_roots = 'href="' . $admin_url . 'ctrl=tools&amp;action=delete_orphan_file_roots&amp;' . url_crumb('tools') . '"';
        $invalid_files_note = $count_files_invalid == 1 ? T_('An invalid File object was found in the database.') : sprintf(T_('%d invalid File objects were found in the database.'), $count_files_invalid);
        echo '<p class="warning">' . $invalid_files_note . "<br/>" . sprintf(T_('It is strongly recommended to also execute the &lt;<a %s>Remove orphan file roots</a>&gt; tool to remove invalid files from the database and from the disk as well!'), $remove_orphan_file_roots) . '</p>';
    }
}
Beispiel #20
0
 /**
  * Add new link to owner User
  *
  * @param integer file ID
  * @param integer link position ( 'teaser', 'aftermore' )
  * @param int order of the link
  * @return integer|boolean Link ID on success, false otherwise
  */
 function add_link($file_ID, $position = NULL, $order = 1)
 {
     global $current_User;
     if (is_null($position)) {
         // Use default link position
         $position = $this->get_default_position($file_ID);
     }
     $edited_Link = new Link();
     $edited_Link->set('usr_ID', $this->User->ID);
     $edited_Link->set('file_ID', $file_ID);
     $edited_Link->set('position', $position);
     $edited_Link->set('order', $order);
     if (empty($current_User)) {
         // Current User not is set because probably we are creating links from upgrade script. Set the owner as creator and last editor.
         $edited_Link->set('creator_user_ID', $this->User->ID);
         $edited_Link->set('lastedit_user_ID', $this->User->ID);
     }
     if ($edited_Link->dbinsert()) {
         if (!is_null($this->Links)) {
             // If user Links were already loaded update its content
             $this->Links[$edited_Link->ID] =& $edited_Link;
         }
         $FileCache =& get_FileCache();
         $File = $FileCache->get_by_ID($file_ID, false, false);
         $file_name = empty($File) ? '' : $File->get_name();
         syslog_insert(sprintf('File %s was linked to %s with ID=%s', '<b>' . $file_name . '</b>', $this->type, $this->link_Object->ID), 'info', 'file', $file_ID);
         return $edited_Link->ID;
     }
     return false;
 }
Beispiel #21
0
/**
 * Replace the old file with the new one
 *
 * @param string Root type: 'user', 'group' or 'collection'
 * @param integer ID of the user, the group or the collection the file belongs to...
 * @param string Subpath for this file/folder, relative the associated root, including trailing slash (if directory)
 * @param string Name of NEW file
 * @param string Name of OLD file
 * @param boolean TRUE to display message
 * @return boolean|string TRUE on success, otherwise an error message
 */
function replace_old_file_with_new($root_type, $root_in_type_ID, $path, $new_name, $old_name, $display_message = true)
{
    $error_message = '';
    if (empty($new_name)) {
        $error_message = T_('The new file name is empty!');
    } elseif (empty($new_name)) {
        $error_message = T_('The old file name is empty!');
    }
    if (empty($error_message)) {
        $FileCache =& get_FileCache();
        $newFile =& $FileCache->get_by_root_and_path($root_type, $root_in_type_ID, trailing_slash($path) . $new_name, true);
        $oldFile =& $FileCache->get_by_root_and_path($root_type, $root_in_type_ID, trailing_slash($path) . $old_name, true);
        $new_filename = $newFile->get_name();
        $old_filename = $oldFile->get_name();
        $dir = $newFile->get_dir();
        $oldFile->rm_cache();
        $newFile->rm_cache();
        // rename new uploaded file to temp file name
        $index = 0;
        $temp_filename = 'temp' . $index . '-' . $new_filename;
        while (file_exists($dir . $temp_filename)) {
            // find an unused filename
            $index++;
            $temp_filename = 'temp' . $index . '-' . $new_filename;
        }
    }
    // @rename will overwrite a file with the same name if exists. In this case it shouldn't be a problem.
    if (empty($error_message) && !@rename($newFile->get_full_path(), $dir . $temp_filename)) {
        // rename new file to temp file name failed
        $error_message = sprintf(T_('The new file could not be renamed to %s'), $temp_filename);
    }
    if (empty($error_message) && !@rename($oldFile->get_full_path(), $dir . $new_filename)) {
        // rename original file to the new file name failed
        $error_message = sprintf(T_('The original file could not be renamed to %s. The new file is now named %s.'), $new_filename, $temp_filename);
    }
    if (empty($error_message) && !@rename($dir . $temp_filename, $dir . $old_filename)) {
        // rename new file to the original file name failed
        $error_message = sprintf(T_('The new file could not be renamed to %s. It is now named %s.'), $old_filename, $temp_filename);
    }
    if ($display_message) {
        global $Messages;
        if (empty($error_message)) {
            $Messages->add(sprintf(T_('%s has been replaced with the new version!'), $old_filename), 'success');
        } else {
            $Messages->add($error_message, 'error');
        }
    }
    return empty($error_message) ? true : $error_message;
}
Beispiel #22
0
 /**
  * Template function: display content of comment
  *
  * @param string Output format, see {@link format_to_output()}
  * @param boolean Add ban url action icon after each url or not
  * @param boolean show comment attachments
  * @param array attachment display params
  */
 function content($format = 'htmlbody', $ban_urls = false, $show_attachments = true, $params = array())
 {
     global $current_User;
     global $Plugins;
     // Make sure we are not missing any param:
     $params = array_merge(array('before_image' => '<div class="image_block">', 'before_image_legend' => '<div class="image_legend">', 'after_image_legend' => '</div>', 'after_image' => '</div>', 'image_size' => 'fit-400x320', 'image_text' => '', 'attachments_mode' => 'read', 'attachments_view_text' => ''), $params);
     $attachments = array();
     if ($show_attachments) {
         if (empty($this->ID) && isset($this->checked_attachments)) {
             // PREVIEW
             $attachment_ids = explode(',', $this->checked_attachments);
             $FileCache =& get_FileCache();
             foreach ($attachment_ids as $ID) {
                 $File = $FileCache->get_by_ID($ID, false, false);
                 if ($File != NULL) {
                     $attachments[] = $File;
                 }
             }
         } else {
             // Get links
             $LinkCache =& get_LinkCache();
             $commentLinks = $LinkCache->get_by_comment_ID($this->ID);
             if (!empty($commentLinks)) {
                 foreach ($commentLinks as $Link) {
                     $File = $Link->get_File();
                     $attachments[] = $File;
                 }
             }
         }
     }
     $images_is_attached = false;
     foreach ($attachments as $index => $attachment) {
         $r = '';
         $params['File'] = $attachment;
         $params['data'] =& $r;
         if (count($Plugins->trigger_event_first_true('RenderCommentAttachment', $params)) != 0) {
             echo $r;
             unset($attachments[$index]);
             continue;
         }
         if ($attachment->is_image()) {
             if ($params['attachments_mode'] == 'view') {
                 // Only preview attachments
                 $image_link_rel = '';
                 $image_link_to = '';
             } else {
                 // Read attachments
                 $image_link_rel = 'lightbox[c' . $this->ID . ']';
                 $image_link_to = 'original';
             }
             echo $attachment->get_tag($params['before_image'], $params['before_image_legend'], $params['after_image_legend'], $params['after_image'], $params['image_size'], $image_link_to, T_('Posted by ') . $this->get_author_name(), $image_link_rel);
             unset($attachments[$index]);
             $images_is_attached = true;
         }
     }
     if ($images_is_attached && $params['image_text'] != '') {
         // Display info text below pictures
         echo $params['image_text'];
     }
     if ($ban_urls) {
         // add ban icons if user has edit permission for this comment
         $ban_urls = $current_User->check_perm('comment!CURSTATUS', 'edit', false, $this);
     }
     if ($ban_urls) {
         // ban urls and user has permission
         echo add_ban_icons($this->get_content($format));
     } else {
         // don't ban urls
         echo $this->get_content($format);
     }
     if (isset($attachments)) {
         // show not image attachments
         $after_docs = '';
         if (count($attachments) > 0) {
             echo '<br /><b>' . T_('Attachments:') . '</b>';
             echo '<ul class="bFiles">';
             $after_docs = '</ul>';
         }
         foreach ($attachments as $doc_File) {
             if ($params['attachments_mode'] == 'view') {
                 // Only preview attachments
                 $attachment_download_link = '';
                 $attachment_name = $doc_File->get_type();
             } else {
                 // Read attachments
                 $attachment_download_link = action_icon(T_('Download file'), 'download', $doc_File->get_url(), '', 5) . ' ';
                 $attachment_name = $doc_File->get_view_link($doc_File->get_name());
             }
             echo '<li>';
             echo $attachment_download_link;
             echo $attachment_name;
             echo ' (' . bytesreadable($doc_File->get_size()) . ')';
             if (!empty($params['attachments_view_text'])) {
                 echo $params['attachments_view_text'];
             }
             echo '</li>';
         }
         echo $after_docs;
     }
 }
Beispiel #23
0
/**
 * Remove files with the given ids
 *
 * @param array file ids to remove, default to remove all orphan file IDs
 * @param integer remove files older than the given hour, default NULL will remove all
 * @return integer the number of removed files
 */
function remove_orphan_files($file_ids = NULL, $older_then = NULL)
{
    global $DB, $localtimenow;
    // asimo> This SQL query should use file class delete_restrictions array (currently T_links and T_users is explicitly used)
    // select orphan comment attachment file ids
    $sql = 'SELECT file_ID FROM T_files
				WHERE ( file_path LIKE "comments/p%" OR file_path LIKE "anonymous_comments/p%" ) AND file_ID NOT IN (
					SELECT * FROM (
						( SELECT DISTINCT link_file_ID FROM T_links
							WHERE link_file_ID IS NOT NULL ) UNION
						( SELECT DISTINCT user_avatar_file_ID FROM T_users
							WHERE user_avatar_file_ID IS NOT NULL ) ) AS linked_files )';
    if ($file_ids != NULL) {
        // remove only from the given files
        $sql .= ' AND file_ID IN ( ' . implode(',', $file_ids) . ' )';
    }
    $result = $DB->get_col($sql);
    $FileCache =& get_FileCache();
    $FileCache->load_list($result);
    $count = 0;
    foreach ($result as $file_ID) {
        $File = $FileCache->get_by_ID($file_ID, false, false);
        if ($older_then != NULL) {
            // we have to check if the File is older then the given value
            $datediff = $localtimenow - filemtime($File->_adfp_full_path);
            if ($datediff > $older_then * 3600) {
                // not older
                continue;
            }
        }
        // delete the file
        if ($File->unlink()) {
            $count++;
        }
    }
    // Clear FileCache to save memory
    $FileCache->clear();
    return $count;
}
 /**
  * Add new link to owner Comment
  *
  * @param integer file ID
  * @param integer link position ( 'teaser', 'aftermore' )
  * @param int order of the link
  * @param boolean true to update owner last touched timestamp after link was created, false otherwise
  * @return integer|boolean Link ID on success, false otherwise
  */
 function add_link($file_ID, $position = NULL, $order = 1, $update_owner = true)
 {
     if (is_null($position)) {
         // Use default link position
         $position = $this->get_default_position($file_ID);
     }
     $edited_Link = new Link();
     $edited_Link->set('cmt_ID', $this->Comment->ID);
     $edited_Link->set('file_ID', $file_ID);
     $edited_Link->set('position', $position);
     $edited_Link->set('order', $order);
     if ($edited_Link->dbinsert()) {
         $FileCache =& get_FileCache();
         $File = $FileCache->get_by_ID($file_ID, false, false);
         $file_name = empty($File) ? '' : $File->get_name();
         syslog_insert(sprintf('File %s was linked to %s with ID=%s', '<b>' . $file_name . '</b>', $this->type, $this->link_Object->ID), 'info', 'file', $file_ID);
         if ($update_owner) {
             // Update last touched date of the Comment & Item
             $this->update_last_touched_date();
         }
         return $edited_Link->ID;
     }
     return false;
 }
Beispiel #25
0
/**
 * Get a default avatar url depending on user gender
 *
 * @param string User gender: M - Men; F - Female/Women; Empty string - Unknown gender
 * @param string|NULL Avatar thumbnail size or NULL to get real image
 * @return string URL of avatar
 */
function get_default_avatar_url($gender = '', $size = NULL)
{
    switch ($gender) {
        case 'M':
            // Default avatar for men
            $avatar_url = '/avatars/default_avatar_men.jpg';
            break;
        case 'F':
            // Default avatar for women
            $avatar_url = '/avatars/default_avatar_women.jpg';
            break;
        default:
            // Default avatar for users without defined gender
            $avatar_url = '/avatars/default_avatar_unknown.jpg';
            break;
    }
    if ($size !== NULL) {
        // Get a thumbnail url
        $FileCache =& get_FileCache();
        if ($File =& $FileCache->get_by_root_and_path('shared', 0, $avatar_url)) {
            if ($File->is_image()) {
                // Check if the default avatar files are real images and not broken by some reason
                return $File->get_thumb_url($size, '&');
            }
        }
    }
    // We couldn't get a thumbnail url OR access the folder, Return the full size image URL without further ado:
    global $media_url;
    return $media_url . 'shared/global' . $avatar_url;
}