public function transform(CGImageBase $src)
 {
     $_dest = new CGImageBase($src);
     $watermarker = \cge_setup::get_watermarker();
     if ($this->_wmtext) {
         // clean up the text
         $text = strip_tags($this->_wmtext);
         $text = substr($text, 0, 50);
         $text = trim($text);
         if (is_null(\cge_utils::to_bool($text, TRUE))) {
             $watermarker->set_watermark_text($text);
         }
     }
     $_dest['rsrc'] = $watermarker->get_watermarked_image($_dest['rsrc']);
     return $_dest;
 }
function _uploads_AttemptUpload(&$mod, $id, &$params, $returnid)
{
    $fieldname = $id . 'input_browse';
    if (isset($params['field_name'])) {
        $fieldname = $params['field_name'];
    }
    // check for the filetypes param
    if (isset($params['file_extensions'])) {
        $mod->upload_extensions = $params['file_extensions'];
    }
    // check the author
    if (!isset($params['input_author'])) {
        return array(FALSE, $mod->Lang('error_invalidauthor'));
    }
    // see if there's a key
    $key = null;
    if (isset($params['input_key'])) {
        $key = $params['input_key'];
    }
    // validate the upload name
    if (!isset($_FILES[$fieldname])) {
        return array(FALSE, $mod->Lang('error_nofilesuploaded'));
    }
    // handle filename prefix
    $filePrefix = '';
    if (isset($params['prefix']) && $params['prefix'] == 1) {
        $filePrefix = dechex(time()) . "_";
        if (isset($params['prefix_feu']) && $params['prefix_feu'] == 1) {
            $filePrefix = $params['input_author'] . "_";
        }
    }
    // handle destination name
    $destname = '';
    if (isset($params['input_destname']) && $params['input_destname'] != '') {
        $destname = trim(basename($params['input_destname']));
    }
    // handle replace existing
    $replace_existing = false;
    if (isset($params['input_replace']) && $params['input_replace'] == 1) {
        $replace_existing = true;
    }
    // check the summary
    if (!isset($params['input_summary']) || $params['input_summary'] == '') {
        // we'll cheat, if the summary is left as empty
        // we'll use the upload name
        $p = strpos($destname, '.');
        if ($p) {
            $params['input_summary'] = substr($destname, 0, $p);
        } else {
            $params['input_summary'] = $destname;
        }
        //return array( FALSE, $mod->Lang('error_invalidsummary') );
    }
    // check the category
    $db = $mod->GetDb();
    $dbresult = "";
    $row = array();
    $category_id = 0;
    if (isset($params['category_id'])) {
        $category_id = $params['category_id'];
        $query = "SELECT upload_category_id, upload_category_name, upload_category_path FROM " . cms_db_prefix() . "module_uploads_categories WHERE upload_category_id = ?";
        $dbresult = $db->Execute($query, array($category_id));
    } else {
        if (isset($params['category'])) {
            // get the category info given it's name
            $query = "SELECT upload_category_id, upload_category_name, upload_category_path FROM " . cms_db_prefix() . "module_uploads_categories WHERE upload_category_name = ?";
            $dbresult = $db->Execute($query, array($params['category']));
        }
    }
    if (!$dbresult) {
        return array(FALSE, $mod->Lang('error_invalidcategory'));
    }
    $row = $dbresult->FetchRow();
    if (!$row) {
        return array(FALSE, $mod->Lang('error_invalidcategory'));
    }
    $category_id = $row['upload_category_id'];
    $category_name = $row['upload_category_name'];
    // now do the upload, hopefully
    // first the file itself.
    $dir = $mod->_categoryPath($row['upload_category_path']);
    $result = $mod->_handleUpload($dir, $fieldname, false, $destname, true, $replace_existing, $filePrefix);
    if (!$result[0]) {
        return array(FALSE, $result[1]);
    }
    $destname = $result[1]['name'];
    // see about watermarking
    if ($mod->GetPreference('autowatermark', 0)) {
        $srcname = cms_join_path($dir, $destname);
        $wmname = cms_join_path($dir, 'wm_' . $destname);
        $wmobj = cge_setup::get_watermarker();
        $res = $wmobj->create_watermarked_image($srcname, $wmname);
        if (FALSE !== $res) {
            @unlink($srcname);
            @rename($wmname, $srcname);
        }
    }
    // check for an existing database entry
    $query = "SELECT upload_id FROM " . cms_db_prefix() . "module_uploads WHERE upload_name = ? AND\n\t\t\tupload_category_id = ?";
    $tmp_id = $db->GetOne($query, array($destname, $category_id));
    $fileid = '';
    if ($replace_existing === false && $tmp_id) {
        return array(FALSE, $mod->Lang('error_fileexists'));
    } else {
        if ($tmp_id) {
            // we're allowing overwrite
            $fileid = $tmp_id;
            $replace_existing = true;
            // delete field definitions.
            $query = 'DELETE FROM ' . cms_db_prefix() . 'module_uploads_fieldvals WHERE upload_id = ?';
            $db->Execute($query, array($tmp_id));
        }
    }
    // create a new upload id here.
    if ($fileid == '') {
        $newid = $db->GenID(cms_db_prefix() . "module_uploads_seq");
    }
    // and then maybe the thumbnail
    $thumb_name = '';
    if (isset($_FILES[$id . 'input_thumbnail']['name']) && $_FILES[$id . 'input_thumbnail']['name'] != '' && $_FILES[$id . 'input_thumbnail']['size'] > 0) {
        // build the thumbnail name
        $thumb_extension = strtolower(strrchr($_FILES[$id . 'input_thumbnail']['name'], '.'));
        $fileextension = strtolower(strrchr($destname, '.'));
        $filenamewoext = substr($destname, 0, strlen($destname) - strlen($fileextension));
        $thumb_name = 'thumb_' . $filenamewoext . $thumb_extension;
        $fid = $fileid;
        if ($fid == '') {
            $fid = $newid;
        }
        $result2 = $mod->_handleUpload($dir, $id . 'input_thumbnail', false, $thumb_name, false, $replace_existing, $filePrefix);
        if (!$result2[0]) {
            // uh-oh, the second upload failed.... now we've gotta
            // delete the first file to avoid any corruption
            // todo
            unlink($result[1]['dir'] . DIRECTORY_SEPARATOR . $result[1]['name']);
            return array(FALSE, $result2[1]);
        }
    } else {
        // see if we can auto-create a thumbnail
        if ($mod->GetPreference('autothumbnail_extensions') != '' && $mod->GetPreference('autothumbnail_size') != '') {
            $fid = $fileid;
            if ($fid == '') {
                $fid = $newid;
            }
            $fileextension = strtolower(strrchr($destname, '.'));
            $thumb_ext_arr = explode(",", $mod->GetPreference('autothumbnail_extensions'));
            foreach ($thumb_ext_arr as $thumb_ext) {
                if ("." . $thumb_ext == $fileextension) {
                    // woohoo, we can create a thumbnail
                    $dest = $dir . DIRECTORY_SEPARATOR . 'thumb_' . $destname;
                    $src = $dir . DIRECTORY_SEPARATOR . $destname;
                    $thumb_name = 'thumb_' . $destname;
                    $mod->imageTransform($src, $dest, $mod->GetPreference('autothumbnail_size'));
                    break;
                }
            }
        }
    }
    // apparently the upload succeeded, now we have to log it
    $desc = "";
    if (isset($params['input_description'])) {
        $desc = $params['input_description'];
    }
    $audit_msg = '';
    if ($fileid == '') {
        $query = "INSERT INTO " . cms_db_prefix() . "module_uploads \n           (upload_id,upload_category_id,upload_name,upload_author,\n            upload_summary,upload_description,upload_ip,upload_size,\n            upload_date, upload_key, upload_thumbnail)\n           VALUES (?,?,?,?,?,?,?,?,?,?,?)";
        $dbresult = $db->Execute($query, array($newid, $row['upload_category_id'], $destname, $params['input_author'], $params['input_summary'], $desc, getenv("REMOTE_ADDR"), $result[1]['size'], trim($db->DBTimeStamp(time()), "'"), $key, $thumb_name));
        $audit_msg = $mod->lang('uploaded', array($destname, $params['input_author']));
    } else {
        $query = "UPDATE " . cms_db_prefix() . "module_uploads\n           SET upload_name = ?, upload_author = ?,\n               upload_summary = ?, upload_description = ?,\n               upload_ip = ?, upload_size = ?, upload_date = ?,\n               upload_key = ?, upload_thumbnail = ?\n           WHERE upload_id = ?";
        $dbresult = $db->Execute($query, array($destname, $params['input_author'], $params['input_summary'], $desc, getenv("REMOTE_ADDR"), $result[1]['size'], trim($db->DBTimeStamp(time()), "'"), $key, $thumb_name, $fileid));
        $newid = $fileid;
        $audit_msg = $mod->lang('replaced', $destname, $params['input_author']);
    }
    if (!$dbresult) {
        return array(FALSE, $mod->Lang('error_dberror'));
    }
    // do custom fields.
    $iquery = 'INSERT INTO ' . cms_db_prefix() . 'module_uploads_fieldvals 
                 (upload_id, fld_id, value) VALUES (?,?,?)';
    foreach ($params as $key => $value) {
        if (!startswith($key, 'field_')) {
            continue;
        }
        $field_id = (int) substr($key, 6);
        if (is_array($value)) {
            $value = implode(',', $value);
        }
        $db->Execute($iquery, array($newid, $field_id, $value));
    }
    $mod->Audit(0, $mod->lang('friendlyname'), $audit_msg);
    // that should do the trick
    // now maybe we'll send an email
    $to_address = $mod->GetPreference('send_upload_notifications_to');
    if ($to_address && $to_address != '') {
        // fill out the template, and send an email
        $cmsmailer = $mod->GetModuleInstance('CMSMailer');
        if (!$cmsmailer) {
            // we're not gonna return an error, but put
            // a message into the admin log
            $mod->Audit(0, $mod->Lang('friendlyname'), $mod->Lang('error_nomailermodule'));
        } else {
            $mod->smarty->assign('name', $destname);
            $mod->smarty->assign('size', $result[1]['size']);
            $mod->smarty->assign('summary', $params['input_summary']);
            $mod->smarty->assign('description', $desc);
            $mod->smarty->assign('author', $params['input_author']);
            $mod->smarty->assign('ip_address', getenv("REMOTE_ADDR"));
            $body = $mod->ProcessTemplateFromDatabase('upload_emailtemplate');
            $tmp = explode(',', $to_address);
            foreach ($tmp as $one) {
                $cmsmailer->AddAddress($one);
            }
            $cmsmailer->SetBody($body);
            $cmsmailer->IsHTML(true);
            $cmsmailer->SetSubject($mod->Lang('upload_notification'));
            $cmsmailer->Send();
        }
    }
    // update search words
    $search =& $mod->GetModuleInstance('Search');
    if ($search != FALSE) {
        $str = $destname . ' ' . $params['input_author'] . ' ' . $params['input_summary'] . ' ' . $desc;
        $search->AddWords($mod->GetName(), $newid, 'upload', $str);
    }
    // send an event
    $parms = array();
    $parms['categorypath'] = $dir;
    $parms['category'] = $category_name;
    $parms['name'] = $destname;
    $parms['size'] = $result[1]['size'];
    $parms['summary'] = $params['input_summary'];
    $parms['description'] = $desc;
    $parms['author'] = $params['input_author'];
    $parms['ip_address'] = getenv("REMOTE_ADDR");
    $mod->SendEvent("OnUpload", $parms);
    if ($fileid == '') {
        return array(TRUE, $newid, $destname);
    }
    return array(TRUE, $fileid, $destname);
}
 /**
  * Get the watermark object that will be used to watermark images.
  *
  * @internal
  * @return cg_watermark
  */
 public function &get_watermark_obj()
 {
     if (!is_object($this->_watermarker)) {
         $this->_watermarker = cge_setup::get_watermarker();
     }
     return $this->_watermarker;
 }
 public function handle_file()
 {
     $uploads = cms_utils::get_module('Uploads');
     // validate the data.
     if (!isset($this->_data['src'])) {
         throw UploadsException('Invalid attributes... no source file set');
     }
     if (!$this->_category) {
         throw UploadsException('Invalid/Null upload category speciried');
     }
     if (!isset($this->_data['summary'])) {
         $sumamry = basename($this->_data['src']);
         $this->set_summary($summary);
     }
     if (!isset($this->_data['description'])) {
         $this->_data['description'] = '';
     }
     if (!isset($this->_data['key'])) {
         $this->_data['key'] = '';
     }
     if (!isset($this->_data['author'])) {
         // author hasn't been previously set.
         // try to find something we can use.
         global $CMS_ADMIN_PAGE;
         $author = 'Anonymous';
         if (isset($CMS_ADMIN_PAGE)) {
             // it's an admin action... get the currently logged in username
             $uid = get_userid(FALSE);
             if ($uid) {
                 $userops = cmsms()->GetUserOperations();
                 $user = $userops->LoadUserById($uid);
                 if ($user) {
                     $author = $user->username;
                 }
             }
         } else {
             $feu = cms_utils::get_module('FrontEndUsers');
             if ($feu) {
                 $tmp = $feu->LoggedInName();
                 if ($tmp) {
                     $author = $tmp;
                 }
             }
         }
         $this->_data['author'] = $author;
     }
     $db = cmsms()->GetDb();
     $destfile = $this->get_destfile();
     $existing_fileid = null;
     if (file_exists($destfile) && !isset($this->_data['allow_overwrite'])) {
         // not allowing overwrite
         throw new UploadsException('Destination File Exists: ' . $destfile);
     } else {
         if (file_exists($destfile)) {
             // allowing overwrite... try to find a file id.
             $query = 'SELECT upload_id FROM ' . cms_db_prefix() . 'module_uploads 
               WHERE upload_name = ? AND upload_category_id = ?';
             $existing_fileid = $db->GetOne($query, basename($destname), $this->_category['uploads_category_id']);
         }
     }
     // see if we're gonna watermark
     $_created = array();
     $can_unlink = FALSE;
     $srcfile = $this->_data['src'];
     if (isset($this->_data['do_watermark'])) {
         $dn = dirname($destfile);
         $fn = basename($destfile);
         $wmname = cms_join_path($dn, 'wm_', $fn);
         $wmobj = cge_setup::get_watermarker();
         $res = $wmobj->create_watermarked_image($srcfile, $wmname);
         if ($res !== FALSE) {
             $can_unlink = TRUE;
             $srcfile = $wmname;
             $_created[] = $srcfile;
         }
     }
     // see if we're gonna thumbnail.
     $thumb_name = '';
     if (isset($this->_data['do_thumbnail'])) {
         $thumb_name = basename($destname);
         $dn = dirname($destname);
         $thumbfile = cms_join_path($dn, 'thumb_' . $thumb_name);
         $uploads->imageTransform($srcfile, $thumbfile);
         $_created[] = $thumbfile;
     } else {
         if (isset($this->_data['thumbnail'])) {
             $thumb_name = basename($destname);
             $dn = dirname($destname);
             $thumbfile = cms_join_path($dn, 'thumb_' . $thumb_name);
             @copy($this->_data['thumbnail'], $thumbfile);
             $_created[] = $thumbfile;
         }
     }
     // do the copy.
     @unlink($destfile);
     @copy($srcfile, $destfile);
     $_created[] = $destfile;
     // do the insert or update
     $dbr = '';
     if (!$existing_fileid) {
         $existing_fileid = $db->GenId(cms_db_prefix() . 'module_uploads_seq');
         // insert
         $query = 'INSERT INTO ' . cms_db_prefix() . 'module_uploads
               (upload_id,upload_category_id,upload_name,upload_author,
                upload_summary,upload_description,upload_ip,upload_size,
                upload_date, upload_key, upload_thumbnail)
               VALUES (?,?,?,?,?,?,?,?,NOW(),?,?)';
         $dbr = $db->Execute($query, array($existing_fileid, $this->_category['upload_category_id'], basename($destfile), $this->_data['author'], $this->_data['summary'], $this->_data['desciption'], cge_utils::get_real_ip(), filesize($this->_data['src']), $this->_data['key'], $thumb_name));
     } else {
         // update... delete custom fields.
         $query = 'DELETE FROM ' . cms_db_prefix() . 'module_uploads_fieldvals WHERE upload_id = ?';
         $dbr = $db->Execute($query, array($existing_fileid));
         $query = 'UPDATE ' . cms_db_prefix() . 'module_uploads
               SET upload_name = ?, upload_author = ?,
                   upload_summary = ?, upload_description = ?,
                   upload_ip = ?, upload_size = ?, upload_date = NOW(),
                   upload_key = ?, upload_thumbnail = ?
              WHERE upload_id = ?';
         $dbr = $db->Execute($query, array(basename($destfile), $this->_data['author'], $this->_data['summary'], $this->_data['desc'], cge_array::get_real_ip(), filesize($destfile), $this->_data['key'], $thumb_name, $existing_fileid));
     }
     if (!$dbr) {
         foreach ($_created as $one) {
             @unlink($one);
         }
         throw new UploadsException('Database operation failed: ' . $db->sql . ' -- ' . $db->ErrorMsg());
     }
     $fields = '';
     $query = 'SELECT id,name FROM ' . cms_db_prefix() . 'module_uploads_fielddefs ORDER BY iorder';
     $tmp = $db->GetArray($query);
     if (!is_array($tmp)) {
         $fields = cge_array::to_hash($tmp, 'name');
     }
     if (is_array($fields) && isset($this->_data['fields'])) {
         // do the custom fields.
         $iquery = 'INSERT INTO ' . cms_db_prefix() . 'module_uploads_fieldvals 
              (upload_id, fld_id, value) VALUES (?,?,?)';
         foreach ($this->_data['fields'] as $key => $value) {
             if (!isset($fields[$key])) {
                 continue;
             }
             $field_id = $fields[$key]['id'];
             $db->Execute($iquery, array($existing_fileid, $ield_id, $value));
         }
     }
     // add something to the audit log.
     audit($existing_fileid, $uploads->GetName(), 'Uploaded file ' . basename($destfile));
     // and we're done...
     return $existing_fileid;
 }