/**
  * Delete all items for a invoice
  *
  * @param Invoice $invoice
  * @return null
  */
 function deleteByInvoice($invoice)
 {
     db_begin_work();
     $execute = db_execute('DELETE FROM ' . TABLE_PREFIX . 'invoice_time_records WHERE invoice_id = ?', $invoice->getId());
     if ($execute && !is_error($execute)) {
         $delete = InvoiceItems::delete(array('invoice_id = ?', $invoice->getId()));
         if ($delete && !is_error($delete)) {
             db_commit();
         } else {
             db_rollback();
         }
         // if
         return $delete;
     } else {
         db_rollback();
         return $execute;
     }
     // if
 }
 /**
  * Set $currency as default
  *
  * @param Currency $currency
  * @return boolean
  */
 function setDefault($currency)
 {
     if ($currency->getIsDefault()) {
         return true;
     }
     // if
     db_begin_work();
     $currency->setIsDefault(true);
     $update = $currency->save();
     if ($update && !is_error($update)) {
         $update = db_execute('UPDATE ' . TABLE_PREFIX . 'currencies SET is_default = ? WHERE id != ?', false, $currency->getId());
         cache_remove_by_pattern(TABLE_PREFIX . 'currencies_id_*');
         if ($update && !is_error($update)) {
             db_commit();
             return true;
         }
         // if
     }
     // if
     db_rollback();
     return $update;
 }
Пример #3
0
/**
 * Called when the login form is submitted. Validates the user and password, and
 * if they are valid, starts a new session for the user.
 *
 * @param object $form   The Pieform form object
 * @param array  $values The submitted values
 * @access private
 */
function login_submit(Pieform $form, $values)
{
    global $SESSION, $USER;
    $username = trim($values['login_username']);
    $password = $values['login_password'];
    $authenticated = false;
    try {
        $authenticated = $USER->login($username, $password);
        if (empty($authenticated)) {
            $SESSION->add_error_msg(get_string('loginfailed'));
            return;
        }
    } catch (AuthUnknownUserException $e) {
        // If the user doesn't exist, check for institutions that
        // want to create users automatically.
        try {
            // Reset the LiveUser object, since we are attempting to create a
            // new user
            $SESSION->destroy_session();
            $USER = new LiveUser();
            $authinstances = get_records_sql_array("\n                SELECT a.id, a.instancename, a.priority, a.authname, a.institution, i.suspended, i.displayname\n                FROM {institution} i JOIN {auth_instance} a ON a.institution = i.name\n                WHERE a.authname != 'internal'\n                ORDER BY a.institution, a.priority, a.instancename", null);
            if ($authinstances == false) {
                throw new AuthUnknownUserException("\"{$username}\" is not known");
            }
            $USER->username = $username;
            reset($authinstances);
            while ((list(, $authinstance) = each($authinstances)) && false == $authenticated) {
                $auth = AuthFactory::create($authinstance->id);
                if (!$auth->can_auto_create_users()) {
                    continue;
                }
                // catch semi-fatal auth errors, but allow next auth instance to be
                // tried
                try {
                    if ($auth->authenticate_user_account($USER, $password)) {
                        $authenticated = true;
                    } else {
                        continue;
                    }
                } catch (AuthInstanceException $e) {
                    continue;
                }
                // Check now to see if the institution has its maximum quota of users
                require_once 'institution.php';
                $institution = new Institution($authinstance->institution);
                if ($institution->isFull()) {
                    $institution->send_admin_institution_is_full_message();
                    throw new AuthUnknownUserException('Institution has too many users');
                }
                $USER->authinstance = $authinstance->id;
                $userdata = $auth->get_user_info($username);
                if (empty($userdata)) {
                    throw new AuthUnknownUserException("\"{$username}\" is not known");
                }
                // Check for a suspended institution
                if ($authinstance->suspended) {
                    $sitename = get_config('sitename');
                    throw new AccessTotallyDeniedException(get_string('accesstotallydenied_institutionsuspended', 'mahara', $authinstance->displayname, $sitename));
                }
                // We have the data - create the user
                $USER->lastlogin = db_format_timestamp(time());
                if (isset($userdata->firstname)) {
                    $USER->firstname = sanitize_firstname($userdata->firstname);
                }
                if (isset($userdata->lastname)) {
                    $USER->lastname = sanitize_firstname($userdata->lastname);
                }
                if (isset($userdata->email)) {
                    $USER->email = sanitize_email($userdata->email);
                } else {
                    // The user will be asked to populate this when they log in.
                    $USER->email = null;
                }
                $profilefields = array();
                foreach (array('studentid', 'preferredname') as $pf) {
                    if (isset($userdata->{$pf})) {
                        $sanitize = 'sanitize_' . $pf;
                        if (($USER->{$pf} = $sanitize($userdata->{$pf})) !== '') {
                            $profilefields[$pf] = $USER->{$pf};
                        }
                    }
                }
                try {
                    // If this authinstance is a parent auth for some xmlrpc authinstance, pass it along to create_user
                    // so that this username also gets recorded as the username for sso from the remote sites.
                    $remoteauth = $auth->is_parent_authority();
                    create_user($USER, $profilefields, $institution, $remoteauth);
                    $USER->reanimate($USER->id, $authinstance->id);
                } catch (Exception $e) {
                    db_rollback();
                    throw $e;
                }
            }
            if (!$authenticated) {
                $SESSION->add_error_msg(get_string('loginfailed'));
                return;
            }
        } catch (AuthUnknownUserException $e) {
            // We weren't able to authenticate the user for some reason that
            // probably isn't their fault (e.g. ldap extension not available
            // when using ldap authentication)
            log_info($e->getMessage());
            $SESSION->add_error_msg(get_string('loginfailed'));
            return;
        }
    }
    auth_check_admin_section();
    // This is also checked in $USER->login(), but it's good to check it again here in case a buggy auth plugin
    // lets a suspended user through somehow.
    ensure_user_account_is_active();
    // User is allowed to log in
    //$USER->login($userdata);
    auth_check_required_fields();
}
Пример #4
0
 /**
  * Delete this company from database
  *
  * @param void
  * @return boolean
  */
 function delete()
 {
     db_begin_work();
     $delete = parent::delete();
     if ($delete && !is_error($delete)) {
         cache_remove('companies_id_name');
         // remove ID - name map from cache
         $users = $this->getUsers();
         if (is_foreachable($users)) {
             foreach ($users as $user) {
                 $user->delete();
             }
             // foreach
         }
         // if
         Projects::resetByCompany($this);
         db_commit();
     } else {
         db_rollback();
     }
     // if
     return $delete;
 }
Пример #5
0
            //exec($cmd,$output);
            $userfile_name = $ftp_filename;
            $userfile = $upload_dir . '/' . $ftp_filename;
            //echo $cmd.'***'.$output.'***'.$userfile;
        }
        //
        //  Now create the new FRSFile in the db
        //
        $frsf = new FRSFile($frsr);
        if (!$frsf || !is_object($frsf)) {
            exit_error('Error', 'Could Not Get FRSFile');
        } elseif ($frsf->isError()) {
            exit_error('Error', $frsf->getErrorMessage());
        } else {
            if (!$frsf->create($userfile_name, $userfile['tmp_name'], $type_id, $processor_id, $release_date)) {
                db_rollback();
                exit_error('Error', $frsf->getErrorMessage());
            }
            $feedback = _('File Released');
        }
    }
}
// Edit/Delete files in a release
if (getStringFromRequest('step3')) {
    $step3 = getStringFromRequest('step3');
    $file_id = getIntFromRequest('file_id');
    $processor_id = getIntFromRequest('processor_id');
    $type_id = getIntFromRequest('type_id');
    $new_release_id = getIntFromRequest('new_release_id');
    $release_time = getStringFromRequest('release_time');
    $group_id = getIntFromRequest('group_id');
Пример #6
0
function import_next_user($filename, $username, $authinstance)
{
    global $ADDEDUSERS, $FAILEDUSERS;
    log_debug('adding user ' . $username . ' from ' . $filename);
    $authobj = get_record('auth_instance', 'id', $authinstance);
    $institution = new Institution($authobj->institution);
    $date = time();
    $nicedate = date('Y/m/d h:i:s', $date);
    $niceuser = preg_replace('/[^a-zA-Z0-9_-]/', '-', $username);
    $uploaddir = get_config('dataroot') . 'import/' . $niceuser . '-' . $date . '/';
    check_dir_exists($uploaddir);
    // Unzip the file
    $archive = new ZipArchive();
    if ($archive->open($filename) && $archive->extractTo($uploaddir)) {
        // successfully extracted
        $archive->close();
    } else {
        $FAILEDUSERS[$username] = get_string('unzipfailed', 'admin', hsc($filename));
        return;
    }
    $leap2afilename = $uploaddir . 'leap2a.xml';
    if (!is_file($leap2afilename)) {
        $FAILEDUSERS[$username] = get_string('noleap2axmlfiledetected', 'admin');
        log_debug($FAILEDUSERS[$username]);
        return;
    }
    // If the username is already taken, append something to the end
    while (get_record('usr', 'username', $username)) {
        $username .= "_";
    }
    $user = (object) array('authinstance' => $authinstance, 'username' => $username, 'firstname' => 'Imported', 'lastname' => 'User', 'password' => get_random_key(6), 'passwordchange' => 1);
    db_begin();
    try {
        $user->id = create_user($user, array(), $institution, $authobj);
    } catch (EmailException $e) {
        // Suppress any emails (e.g. new institution membership) sent out
        // during user creation, becuase the user doesn't have an email
        // address until we've imported them from the Leap2A file.
        log_debug("Failed sending email during user import");
    }
    $niceuser = preg_replace('/[^a-zA-Z0-9_-]/', '-', $user->username);
    $record = (object) array('token' => '', 'usr' => $user->id, 'queue' => (int) (!PluginImport::import_immediately_allowed()), 'ready' => 0, 'expirytime' => db_format_timestamp(time() + 60 * 60 * 24), 'format' => 'leap', 'data' => array('importfile' => $filename, 'importfilename' => $filename, 'importid' => $niceuser . time(), 'mimetype' => file_mime_type($filename)), 'loglevel' => PluginImportLeap::LOG_LEVEL_VERBOSE, 'logtargets' => LOG_TARGET_FILE, 'profile' => true);
    $tr = new LocalImporterTransport($record);
    $tr->extract_file();
    $importer = PluginImport::create_importer(null, $tr, $record);
    unset($record, $tr);
    try {
        $importer->process();
        log_info("Imported user account {$user->id} from Leap2A file, see" . $importer->get('logfile') . 'for a full log');
    } catch (ImportException $e) {
        log_info("Leap2A import failed: " . $e->getMessage());
        $FAILEDUSERS[$username] = get_string("leap2aimportfailed");
        db_rollback();
    }
    db_commit();
    if (empty($FAILEDUSERS[$username])) {
        // Reload the user details, as various fields are changed by the
        // importer when importing (e.g. firstname/lastname)
        $newuser = get_record('usr', 'id', $user->id);
        $newuser->clearpasswd = $user->password;
        $ADDEDUSERS[] = $newuser;
    }
    return;
}
 /**
  *
  *
  */
 function delete($sure, $really_sure)
 {
     if (!$sure || !$really_sure) {
         $this->setMissingParamsError();
         return false;
     }
     if (!$this->ArtifactType->userIsAdmin()) {
         $this->setPermissionDeniedError();
         return false;
     }
     db_begin();
     $sql = "DELETE FROM artifact_extra_field_data \n\t\t\tWHERE extra_field_id='" . $this->getID() . "'";
     $result = db_query($sql);
     if ($result) {
         $sql = "DELETE FROM artifact_extra_field_elements\n\t\t\t\tWHERE extra_field_id='" . $this->getID() . "'";
         $result = db_query($sql);
         if ($result) {
             $sql = "DELETE FROM artifact_extra_field_list\n                WHERE extra_field_id='" . $this->getID() . "'";
             $result = db_query($sql);
             if ($result) {
                 if ($this->getType() == ARTIFACT_EXTRAFIELDTYPE_STATUS) {
                     if (!$this->ArtifactType->setCustomStatusField(0)) {
                         db_rollback();
                         return false;
                     }
                 }
                 db_commit();
                 return true;
             } else {
                 $this->setError(db_error());
                 db_rollback();
                 return false;
             }
         } else {
             $this->setError(db_error());
             db_rollback();
             return false;
         }
     } else {
         $this->setError(db_error());
         db_rollback();
         return false;
     }
 }
Пример #8
0
 /**
  * Find project objects in commit message, make them links and
  * save the relations to database
  *
  * @param string $commit_message
  * @param string $commit_author
  * @param integer $revision
  * @param Repository $repository
  * @param Project $project
  * @return string
  */
 function analyze_message($commit_message, $commit_author, $revision, $repository, $project)
 {
     if (define('PURIFY_HTML') && PURIFY_HTML) {
         $commit_message = purify_html($commit_message);
         // Clean!
     }
     // if
     $pattern = '/((complete[d]*)[\\s]+)?(ticket|milestone|discussion|task)[s]*[\\s]+[#]*\\d+/i';
     if (preg_match_all($pattern, $commit_message, $matches)) {
         $i = 0;
         $search = array();
         $replace = array();
         $matches_unique = array_unique($matches['0']);
         foreach ($matches_unique as $key => $match) {
             $match_data = preg_split('/[\\s,]+/', $match, null, PREG_SPLIT_NO_EMPTY);
             // check if the object got completed by this commit
             $object_completed = false;
             if (strpos(strtolower($match_data['0']), 'complete') !== false) {
                 $object_completed = true;
                 unset($match_data['0']);
                 $match_data = array_values($match_data);
             }
             // if
             $object_class_name = $match_data['0'];
             $module_name = Inflector::pluralize($object_class_name);
             $object_id = trim($match_data['1'], '#');
             $search[$i] = $match;
             if (class_exists($module_name) && class_exists($object_class_name)) {
                 $object = null;
                 switch (strtolower($module_name)) {
                     case 'tickets':
                         $object = Tickets::findByTicketId($project, $object_id);
                         break;
                     case 'discussions':
                         $object = Discussions::findById($object_id);
                         break;
                     case 'milestones':
                         $object = Milestones::findById($object_id);
                         break;
                     case 'tasks':
                         $object = Tasks::findById($object_id);
                         break;
                 }
                 // switch
                 if (instance_of($object, $object_class_name)) {
                     $link_already_created = CommitProjectObjects::count("object_id = '" . $object->getId() . "' AND revision = '{$revision}'") > 0;
                     if (!$link_already_created) {
                         $comit_project_object = new CommitProjectObject();
                         $comit_project_object->setProjectId($object->getProjectId());
                         $comit_project_object->setObjectId($object->getId());
                         $comit_project_object->setObjectType(ucfirst($object_class_name));
                         $comit_project_object->setRepositoryId($repository->getId());
                         $comit_project_object->setRevision($revision);
                         db_begin_work();
                         $save = $comit_project_object->save();
                         if ($save && !is_error($save)) {
                             db_commit();
                         } else {
                             db_rollback();
                         }
                         // if save
                     }
                     // if
                     $replace[$i] = ($object_completed ? 'Completed ' : '') . '<a href="' . $object->getViewUrl() . '">' . $match_data['0'] . ' ' . $match_data['1'] . '</a>';
                     // set the object as completed
                     if ($object_completed && !instance_of($object, 'Discussion')) {
                         $completed_by = $repository->getMappedUser($commit_author);
                         $object->complete($completed_by);
                     }
                     // if
                 } else {
                     $replace[$i] = ($object_completed ? 'Completed ' : '') . '<a href="#" class="project_object_missing" title="' . lang('Project object does not exist in this project') . '">' . $match_data['0'] . ' ' . $match_data['1'] . '</a>';
                 }
                 // if instance_of
                 $i++;
             }
             // if module loaded
         }
         // foreach
         return str_ireplace($search, $replace, htmlspecialchars($commit_message));
         // linkify
     }
     // if preg_match
     return $commit_message;
 }
 /**
  * Show and process edit attachment form
  *
  * @param void
  * @return null
  */
 function edit()
 {
     $this->wireframe->print_button = false;
     if ($this->active_attachment->isNew()) {
         $this->httpError(HTTP_ERR_NOT_FOUND);
     }
     // if
     $parent = $this->active_attachment->getParent();
     if (!instance_of($parent, 'ProjectObject')) {
         $this->httpError(HTTP_ERR_NOT_FOUND);
     }
     // if
     $attachment_data = $this->request->post('attachment');
     if (!is_array($attachment_data)) {
         $attachment_data = array('name' => $this->active_attachment->getName());
     }
     // if
     $this->smarty->assign('attachment_data', $attachment_data);
     if ($this->request->isSubmitted()) {
         db_begin_work();
         $old_name = $this->active_attachment->getName();
         $this->active_attachment->setName(array_var($attachment_data, 'name'));
         $save = $this->active_attachment->save();
         if ($save && !is_error($save)) {
             db_commit();
             $this->active_attachment->ready();
             if ($this->request->getFormat() == FORMAT_HTML) {
                 flash_success('File :filename has been updated', array('filename' => $old_name));
                 $this->redirectToUrl($parent->getViewUrl());
             } else {
                 $this->serveData($this->active_attachment);
             }
             // if
         } else {
             db_rollback();
             if ($this->request->getFormat() == FORMAT_HTML) {
                 flash_error('Failed to update :filename', array('filename' => $old_name));
                 $this->redirectToUrl($parent->getViewUrl());
             } else {
                 $this->serveData($save);
             }
             // if
         }
         // if
     }
     // if
 }
Пример #10
0
 /**
  * Delete from database
  *
  * @param void
  * @return boolean
  */
 function delete()
 {
     db_begin_work();
     $delete = parent::delete();
     if ($delete && !is_error($delete)) {
         unlink($this->getAvatarPath());
         unlink($this->getAvatarPath(true));
         ProjectUsers::deleteByUser($this);
         Assignments::deleteByUser($this);
         Subscriptions::deleteByUser($this);
         StarredObjects::deleteByUser($this);
         PinnedProjects::deleteByUser($this);
         UserConfigOptions::deleteByUser($this);
         Reminders::deleteByUser($this);
         search_index_remove($this->getId(), 'User');
         $cleanup = array();
         event_trigger('on_user_cleanup', array(&$cleanup));
         if (is_foreachable($cleanup)) {
             foreach ($cleanup as $table_name => $fields) {
                 foreach ($fields as $field) {
                     $condition = '';
                     if (is_array($field)) {
                         $id_field = array_var($field, 'id');
                         $name_field = array_var($field, 'name');
                         $email_field = array_var($field, 'email');
                         $condition = array_var($field, 'condition');
                     } else {
                         $id_field = $field . '_id';
                         $name_field = $field . '_name';
                         $email_field = $field . '_email';
                     }
                     // if
                     if ($condition) {
                         db_execute('UPDATE ' . TABLE_PREFIX . "{$table_name} SET {$id_field} = 0, {$name_field} = ?, {$email_field} = ? WHERE {$id_field} = ? AND {$condition}", $this->getName(), $this->getEmail(), $this->getId());
                     } else {
                         db_execute('UPDATE ' . TABLE_PREFIX . "{$table_name} SET {$id_field} = 0, {$name_field} = ?, {$email_field} = ? WHERE {$id_field} = ?", $this->getName(), $this->getEmail(), $this->getId());
                     }
                     // if
                 }
                 // foreach
             }
             // foreach
         }
         // if
         db_commit();
         return true;
     } else {
         db_rollback();
         return $delete;
     }
     // if
 }
Пример #11
0
function viewlayout_submit(Pieform $form, $values)
{
    global $view, $SESSION, $new, $layoutrows, $layoutcolumns;
    $oldrows = $view->get('numrows');
    $oldlayout = $view->get_layout();
    $newlayout = $values['layoutselect'];
    if (!isset($layoutrows[$newlayout])) {
        throw new ParamOutOfRangeException(get_string('invalidlayoutselection', 'error', $action));
    } else {
        $newrows = count($layoutrows[$newlayout]);
    }
    db_begin();
    // for each existing row which will still exist after the update, check whether to add or remove columns
    for ($i = 0; $i < min(array($oldrows, $newrows)); $i++) {
        // compare oldlayout column structure with newlayout
        $oldcolumns = $oldlayout->rows[$i + 1]['columns'];
        $newcolumnindex = $layoutrows[$newlayout][$i + 1];
        $newcolumns = $layoutcolumns[$newcolumnindex]->columns;
        // Specify row when adding or removing columns
        if ($oldcolumns > $newcolumns) {
            for ($j = $oldcolumns; $j > $newcolumns; $j--) {
                $view->removecolumn(array('row' => $i + 1, 'column' => $j));
            }
        } else {
            if ($oldcolumns < $newcolumns) {
                for ($j = $oldcolumns; $j < $newcolumns; $j++) {
                    $view->addcolumn(array('row' => $i + 1, 'before' => $j + 1, 'returndata' => false));
                }
            }
        }
        $dbcolumns = get_field('view_rows_columns', 'columns', 'view', $view->get('id'), 'row', $i + 1);
        if ($dbcolumns != $newcolumns) {
            db_rollback();
            $SESSION->add_error_msg(get_string('changecolumnlayoutfailed', 'view'));
            redirect(get_config('wwwroot') . 'view/layout.php?id=' . $view->get('id') . ($new ? '&new=1' : ''));
        }
    }
    // add or remove rows and move content accordingly if required
    if ($oldrows > $newrows) {
        for ($i = $oldrows; $i > $newrows; $i--) {
            $view->removerow(array('row' => $i, 'layout' => $oldlayout));
        }
    } else {
        if ($oldrows < $newrows) {
            for ($i = $oldrows; $i < $newrows; $i++) {
                $view->addrow(array('before' => $i + 1, 'newlayout' => $newlayout, 'returndata' => false));
            }
        }
    }
    if ($view->get('numrows') != $newrows) {
        db_rollback();
        $SESSION->add_error_msg(get_string('changerowlayoutfailed', 'view'));
        redirect(get_config('wwwroot') . 'view/layout.php?id=' . $view->get('id') . ($new ? '&new=1' : ''));
    }
    db_commit();
    $view->set('layout', $newlayout);
    $view->commit();
    $SESSION->add_ok_msg(get_string('viewlayoutchanged', 'view'));
    redirect('/view/blocks.php?id=' . $view->get('id') . ($new ? '&new=1' : ''));
}
Пример #12
0
    /**
     *	create - use this function to create a new entry in the database.
     *
     *	@param	string	The name of the mailing list
     *	@param	string	The description of the mailing list
     *	@param	int	Pass (1) if it should be public (0) for private.
     *
     *	@return	boolean	success.
     */
    function create($listName, $description, $isPublic = MAIL__MAILING_LIST_IS_PUBLIC, $creator_id = false)
    {
        //
        //	During the group creation, the current user_id will not match the admin's id
        //
        if (!$creator_id) {
            $creator_id = user_getid();
            if (!$this->userIsAdmin()) {
                $this->setPermissionDeniedError();
                return false;
            }
        }
        if (!$listName || strlen($listName) < MAIL__MAILING_LIST_NAME_MIN_LENGTH) {
            $this->setError(_('Must Provide List Name That Is 4 or More Characters Long'));
            return false;
        }
        $realListName = strtolower($this->Group->getUnixName() . '-' . $listName);
        if (!validate_email($realListName . '@' . $GLOBALS['sys_lists_host'])) {
            $this->setError(_('Invalid List Name') . ': ' . $realListName . '@' . $GLOBALS['sys_lists_host']);
            return false;
        }
        $result = db_query('SELECT 1 FROM mail_group_list WHERE lower(list_name)=\'' . $realListName . '\'');
        if (db_numrows($result) > 0) {
            $this->setError(_('List Already Exists'));
            return false;
        }
        $result_forum_samename = db_query('SELECT 1 FROM forum_group_list WHERE forum_name=\'' . $listName . '\' AND group_id=' . $this->Group->getID() . '');
        if (db_numrows($result_forum_samename) > 0) {
            $this->setError(_('Forum exists with the same name'));
            return false;
        }
        $listPassword = substr(md5($GLOBALS['session_hash'] . time() . rand(0, 40000)), 0, 16);
        $sql = 'INSERT INTO mail_group_list ' . '(group_id, list_name, is_public, password, list_admin, status, description) VALUES (' . $this->Group->getID() . ', ' . "'" . $realListName . "'," . "'" . $isPublic . "'," . "'" . $listPassword . "'," . "'" . $creator_id . "'," . "'" . MAIL__MAILING_LIST_IS_REQUESTED . "'," . "'" . $description . "')";
        db_begin();
        $result = db_query($sql);
        if (!$result) {
            db_rollback();
            $this->setError(sprintf(_('Error Creating %1$s'), _('Error Creating %1$s')) . db_error());
            return false;
        }
        $this->groupMailingListId = db_insertid($result, 'mail_group_list', 'group_list_id');
        $this->fetchData($this->groupMailingListId);
        $user =& user_get_object($creator_id);
        $userEmail = $user->getEmail();
        if (empty($userEmail) || !validate_email($userEmail)) {
            db_rollback();
            $this->setInvalidEmailError();
            return false;
        } else {
            $mailBody = stripcslashes(sprintf(_('A mailing list will be created on %1$s in 6-24 hours 
and you are the list administrator.

This list is: %3$s@%2$s .

Your mailing list info is at:
%4$s .

List administration can be found at:
%5$s .

Your list password is: %6$s .
You are encouraged to change this password as soon as possible.

Thank you for registering your project with %1$s.

-- the %1$s staff
'), $GLOBALS['sys_name'], $GLOBALS['sys_lists_host'], $realListName, $this->getExternalInfoUrl(), $this->getExternalAdminUrl(), $listPassword));
            $mailSubject = sprintf(_('%1$s New Mailing List'), $GLOBALS['sys_name']);
            util_send_message($userEmail, $mailSubject, $mailBody, 'admin@' . $GLOBALS['sys_default_domain']);
        }
        db_commit();
        return true;
    }
Пример #13
0
 /**
  * Delete document
  * 
  * @param void
  * @return null 
  */
 function delete()
 {
     $filepath = $this->getFilePath();
     db_begin_work();
     $delete = parent::delete();
     if (!$delete || is_error($delete)) {
         db_rollback();
         return $delete;
     }
     // if
     $delete_attachments = Attachments::deleteByObject($this);
     if (!$delete_attachments || is_error($delete_attachments)) {
         db_rollback();
         return $delete_attachments;
     }
     // if
     if (is_file($filepath)) {
         @unlink($filepath);
     }
     // if
     db_commit();
     return true;
 }
 /**
  * Edit repository
  *
  * @param null
  * @return void
  */
 function edit()
 {
     if (!$this->active_repository->canEdit($this->logged_user)) {
         $this->httpError(HTTP_ERR_FORBIDDEN);
     }
     // if
     $repository_data = $this->request->post('repository');
     if (!is_array($repository_data)) {
         $repository_data = array('name' => $this->active_repository->getName(), 'url' => $this->active_repository->getUrl(), 'username' => $this->active_repository->getUsername(), 'password' => $this->active_repository->getPassword(), 'repositorytype' => $this->active_repository->getRepositoryType(), 'updatetype' => $this->active_repository->getUpdateType(), 'visibility' => $this->active_repository->getVisibility());
     }
     if ($this->request->isSubmitted()) {
         db_begin_work();
         $this->active_repository->setAttributes($repository_data);
         $this->active_repository->loadEngine($this->active_repository->getRepositoryType());
         $this->repository_engine = new RepositoryEngine($this->active_repository);
         $this->repository_engine->triggerred_by_handler = true;
         $result = $this->repository_engine->testRepositoryConnection();
         if ($result === true) {
             $save = $this->active_repository->save();
             if ($save && !is_error($save)) {
                 db_commit();
                 flash_success(lang('Repository has been successfully updated'));
                 $this->redirectToUrl($this->active_repository->getHistoryUrl());
             } else {
                 db_rollback();
                 $this->smarty->assign('errors', $save);
             }
             //if
         } else {
             db_rollback();
             $errors = new ValidationErrors();
             $errors->addError(lang('Failed to connect to repository: :message', array('message' => $result)));
             $this->smarty->assign('errors', $errors);
         }
         // if
     }
     // if
     js_assign('repository_test_connection_url', assemble_url('repository_test_connection', array('project_id' => $this->active_project->getId())));
     $this->smarty->assign(array('types' => $this->active_repository->types, 'update_types' => $this->active_repository->update_types, 'repository_data' => $repository_data, 'active_repository' => $this->active_repository, 'disable_url_and_type' => instance_of($this->active_repository->getLastCommit(), 'Commit'), 'aid_url' => lang('The path to the existing repository cannot be changed'), 'aid_engine' => lang('Repository type cannot be changed')));
 }
Пример #15
0
 /**
  * Creates a View for the given user, based off a given template and other 
  * View information supplied.
  *
  * Will set a default title of 'Copy of $viewtitle' if title is not 
  * specified in $viewdata.
  *
  * @param array $viewdata See View::_create
  * @param int $templateid The ID of the View to copy
  * @param int $userid     The user who has issued the command to create the 
  *                        view. See View::_create
  * @param int $checkaccess Whether to check that the user can see the view before copying it
  * @return array A list consisting of the new view, the template view and 
  *               information about the copy - i.e. how many blocks and 
  *               artefacts were copied
  * @throws SystemException under various circumstances, see the source for 
  *                         more information
  */
 public static function create_from_template($viewdata, $templateid, $userid = null, $checkaccess = true)
 {
     if (is_null($userid)) {
         global $USER;
         $userid = $USER->get('id');
     }
     $user = new User();
     $user->find_by_id($userid);
     db_begin();
     $template = new View($templateid);
     if ($template->get('deleted')) {
         throw new SystemException("View::create_from_template: This template has been deleted");
     }
     if (!$template->get('template') && !$user->can_edit_view($template)) {
         throw new SystemException("View::create_from_template: Attempting to create a View from another View that is not marked as a template");
     } else {
         if ($checkaccess && !can_view_view($templateid, $userid)) {
             throw new SystemException("View::create_from_template: User {$userid} is not permitted to copy View {$templateid}");
         }
     }
     $view = self::_create($viewdata, $userid);
     // Set a default title if one wasn't set
     if (!isset($viewdata['title'])) {
         $view->set('title', self::new_title(get_string('Copyof', 'mahara', $template->get('title')), (object) $viewdata));
         $view->set('dirty', true);
     }
     try {
         $copystatus = $view->copy_contents($template);
     } catch (QuotaExceededException $e) {
         db_rollback();
         return array(null, $template, array('quotaexceeded' => true));
     }
     $view->commit();
     db_commit();
     return array($view, $template, $copystatus);
 }
 /**
  * Create new comment
  *
  * @param void
  * @return null
  */
 function add()
 {
     $this->wireframe->print_button = false;
     $active_object = ProjectObjects::findById($this->request->getId('parent_id'));
     if (!instance_of($active_object, 'ProjectObject')) {
         $this->httpError(HTTP_ERR_NOT_FOUND, null, true, $this->request->isApiCall());
     }
     // if
     if (!$active_object->canComment($this->logged_user)) {
         $this->httpError(HTTP_ERR_FORBIDDEN, null, true, $this->request->isApiCall());
     }
     // if
     $active_object->prepareProjectSectionBreadcrumb($this->wireframe);
     $this->wireframe->addBreadCrumb($active_object->getName(), $active_object->getViewUrl());
     if (!$active_object->canComment($this->logged_user)) {
         if ($this->request->isApiCall()) {
             $this->httpError(HTTP_ERR_FORBIDDEN, null, true, true);
         } else {
             flash_error('Parent object not found');
             $this->redirectToReferer($this->active_project->getOverviewUrl());
         }
         // if
     }
     // if
     $comment_data = $this->request->post('comment');
     $this->smarty->assign(array('active_object' => $active_object, 'page_tab' => $active_object->getProjectTab(), 'comment_data' => $comment_data, 'recent_comments' => Comments::findRecentObject($active_object, 5, STATE_VISIBLE, $this->logged_user->getVisibility())));
     if ($this->request->isSubmitted()) {
         db_begin_work();
         $complete_parent_object = (bool) array_var($comment_data, 'complete_parent_object');
         $this->active_comment = new Comment();
         $this->active_comment->log_activities = false;
         if ($complete_parent_object) {
             $this->active_comment->send_notification = false;
         }
         // if
         attach_from_files($this->active_comment, $this->logged_user);
         $this->active_comment->setAttributes($comment_data);
         $this->active_comment->setParent($active_object);
         $this->active_comment->setProjectId($this->active_project->getId());
         $this->active_comment->setState(STATE_VISIBLE);
         $this->active_comment->setVisibility($active_object->getVisibility());
         if (trim($this->active_comment->getCreatedByName()) == '' || trim($this->active_comment->getCreatedByEmail()) == '') {
             $this->active_comment->setCreatedBy($this->logged_user);
         }
         // if
         $save = $this->active_comment->save();
         if ($save && !is_error($save)) {
             $active_object->subscribe($this->logged_user);
             $activity = new NewCommentActivityLog();
             $activity->log($this->active_comment, $this->logged_user);
             if ($complete_parent_object && $active_object->canChangeCompleteStatus($this->logged_user)) {
                 $active_object->complete($this->logged_user, $this->active_comment->getFormattedBody(true));
             }
             // if
             db_commit();
             $this->active_comment->ready();
             //BOF: mod
             $subscribers_to_notify = array_var($comment_data, 'subscribers_to_notify');
             $action_request_user_id = array_var($comment_data, 'action_request');
             //$priority_actionrequest = array_var($comment_data, 'priority_actionrequest');
             //BOF:mod 20110517
             if ($complete_parent_object) {
                 $subscribers_to_notify = array();
                 $action_request_user_id = array();
             }
             //EOF:mod 20110517
             //BOF:mod 20110719
             /*
             //EOF:mod 20110719
             if (!empty($action_request_user_id)){
                 $link = mysql_connect(DB_HOST, DB_USER, DB_PASS);
                 mysql_select_db(DB_NAME);
                 foreach ($action_request_user_id as $id){
                     $query = "select * from healingcrystals_assignments_action_request where comment_id='" . $this->active_comment->getId() . "' and selected_by_user_id='" . $this->logged_user->getId() . "' and user_id='" . $id . "'";
             						$result = mysql_query($query);
             						if (mysql_num_rows($result)){
                         $query = "update healingcrystals_assignments_action_request set is_action_request='1' where comment_id='" . $this->active_comment->getId() . "' and selected_by_user_id='" . $this->logged_user->getId() . "' and user_id='" . $id . "'";
                         mysql_query($query);
             						} else {
                         $query = "insert into healingcrystals_assignments_action_request (user_id, is_action_request, is_fyi, selected_by_user_id, comment_id, date_added) values ('" . $id . "', '1', '0', '" . $this->logged_user->getId() . "', '" . $this->active_comment->getId() . "', now())";
                         mysql_query($query);
                     }
                 }
             
                 foreach($priority_actionrequest as $val){
                     $temp = explode('_', $val);
             						list($temp_user_id, $priority) = $temp;
             						if (in_array($temp_user_id, $action_request_user_id)){
                         $query = "update healingcrystals_assignments_action_request set priority_actionrequest='" . $priority . "' where comment_id='" . $this->active_comment->getId() . "' and selected_by_user_id='" . $this->logged_user->getId() . "' and user_id='" . $temp_user_id . "'";
                         mysql_query($query);
             						}
                 }
                 mysql_close($link);
             }
             //BOF:mod 20110719
             */
             //EOF:mod 20110719
             //BOF:mod 20110719
             //$action_request_user_id = array();
             //if (!empty($priority_actionrequest)){
             $link = mysql_connect(DB_HOST, DB_USER, DB_PASS);
             mysql_select_db(DB_NAME);
             if (!empty($action_request_user_id)) {
                 //foreach($priority_actionrequest as $val){
                 foreach ($action_request_user_id as $val) {
                     //$temp = explode('_', $val);
                     //list($temp_user_id, $priority) = $temp;
                     $temp_user_id = $val;
                     $priority = '0';
                     //if ((int)$priority>-10){
                     $query = "select * from healingcrystals_assignments_action_request where comment_id='" . $this->active_comment->getId() . "' and selected_by_user_id='" . $this->logged_user->getId() . "' and user_id='" . $temp_user_id . "'";
                     $result = mysql_query($query, $link);
                     if (mysql_num_rows($result)) {
                         $query1 = "update healingcrystals_assignments_action_request set is_action_request='1', priority_actionrequest='" . $priority . "' where comment_id='" . $this->active_comment->getId() . "' and selected_by_user_id='" . $this->logged_user->getId() . "' and user_id='" . $temp_user_id . "'";
                         mysql_query($query1, $link);
                     } else {
                         $query1 = "insert into healingcrystals_assignments_action_request (user_id, is_action_request, is_fyi, selected_by_user_id, comment_id, date_added, priority_actionrequest) values ('" . $temp_user_id . "', '1', '0', '" . $this->logged_user->getId() . "', '" . $this->active_comment->getId() . "', now(), '" . $priority . "')";
                         mysql_query($query1, $link);
                     }
                     //$action_request_user_id[] = $temp_user_id;
                     $task = new Task();
                     $task->setProjectId(TASK_LIST_PROJECT_ID);
                     $task->setParentId(Page::getTaskPageIdForUser($val));
                     $task->setParentType('Page');
                     $task->setCreatedBy($this->logged_user);
                     $task->setVisibility(VISIBILITY_NORMAL);
                     $task->setState(STATE_VISIBLE);
                     $task_body = '';
                     $parent = $this->active_comment->getParent();
                     $url = $parent->getViewUrl() . '#comment' . $this->active_comment->getId();
                     $comment_body = $this->active_comment->getBody();
                     $comment_body = strip_tags($comment_body);
                     //$task_body = substr($comment_body, 0, 10) . '.. <br/><a href="' . $url . '">View Task in Full</a>';
                     if (strlen($comment_body) > 525) {
                         $task_body .= substr($comment_body, 0, 525) . '..';
                     } else {
                         $task_body .= $comment_body;
                     }
                     $task_body .= '<br/><a href="' . $url . '">View Task in Full</a>';
                     $attachments = $this->active_comment->getAttachments();
                     if (is_foreachable($attachments)) {
                         $task_body .= '<br/>Attachments:<br/>';
                         foreach ($attachments as $attachment) {
                             $task_body .= '<a href="' . $attachment->getViewUrl() . '">' . $attachment->getName() . '</a><br/>';
                         }
                     }
                     $task->setBody($task_body);
                     $savetask = $task->save();
                     if ($savetask && !is_error($savetask)) {
                         $task->ready();
                         mysql_query("insert into actionrequests_to_tasklist (comment_id, user_id, type, object_id) values ('" . $this->active_comment->getId() . "', '" . $temp_user_id . "', 'Task', '" . $task->getId() . "')");
                     }
                     //}
                 }
             }
             //EOF:mod 20110719
             if (!empty($subscribers_to_notify)) {
                 //BOF:task_1260
                 /*
                                     //EOF:task_1260
                                     mysql_query("update healingcrystals_assignments_action_request set is_fyi='0' where object_id='" . $active_object->getId() . "'");
                 if (!empty($subscribers_to_notify)){
                 	$temp = $subscribers_to_notify;
                 	foreach($temp as $id){
                 		$query = "select * from healingcrystals_assignments_action_request where object_id='" . $active_object->getId() . "' and user_id='" . $id . "'";
                 		$result = mysql_query($query, $link);
                 		if (mysql_num_rows($result)){
                 			mysql_query("update healingcrystals_assignments_action_request set is_fyi='1' where user_id='" . $id . "' and object_id='" . $active_object->getId() . "'");
                 		} else {
                 			mysql_query("insert into healingcrystals_assignments_action_request (user_id, object_id, is_fyi) values ('" . $id . "', '" . $active_object->getId() . "', '1')");
                 		}
                 	}
                 }
                 mysql_query("delete from healingcrystals_assignments_action_request where object_id='" . $active_object->getId() . "' and is_action_request='0' and is_fyi='0'");
                 //BOF:task_1260
                 */
                 foreach ($subscribers_to_notify as $id) {
                     $query = "select * from healingcrystals_assignments_action_request where comment_id='" . $this->active_comment->getId() . "' and selected_by_user_id='" . $this->logged_user->getId() . "' and user_id='" . $id . "'";
                     $result = mysql_query($query);
                     if (mysql_num_rows($result)) {
                         $query = "update healingcrystals_assignments_action_request set is_fyi='1' where comment_id='" . $this->active_comment->getId() . "' and selected_by_user_id='" . $this->logged_user->getId() . "' and user_id='" . $id . "'";
                         mysql_query($query);
                     } else {
                         $query = "insert into healingcrystals_assignments_action_request (user_id, is_action_request, is_fyi, selected_by_user_id, comment_id, date_added) values ('" . $id . "', '0', '1', '" . $this->logged_user->getId() . "', '" . $this->active_comment->getId() . "', now())";
                         mysql_query($query);
                     }
                 }
                 //EOF:task_1260
             }
             //shawn wants to fire emails for only action request users and not for FYI users
             // for this, $subscribers_to_notify is set to $action_request_user_id, which will
             // take care of any assignments that were made above the code : 22-MAR-2011
             //BOF:mod 20110623
             $fyi_users = $subscribers_to_notify;
             $fyi_to = '';
             //EOF:mod 20110623
             $subscribers_to_notify = $action_request_user_id;
             //BOF:mod
             $email_to_user_ids = array_var($comment_data, 'email');
             $emailed_to = '';
             foreach ($email_to_user_ids as $user_id) {
                 $temp_user = new User($user_id);
                 //BOF:mod 20130429
                 /*
                 //EOF:mod 20130429
                 					$emailed_to .= $temp_user->getName() . ', ';
                 //BOF:mod 20130429
                 */
                 //EOF:mod 20130429
                 $query = "select * from healingcrystals_assignments_action_request where comment_id='" . $this->active_comment->getId() . "' and selected_by_user_id='" . $this->logged_user->getId() . "' and user_id='" . $user_id . "'";
                 $result = mysql_query($query);
                 if (mysql_num_rows($result)) {
                     $query = "update healingcrystals_assignments_action_request set marked_for_email='1' where comment_id='" . $this->active_comment->getId() . "' and selected_by_user_id='" . $this->logged_user->getId() . "' and user_id='" . $user_id . "'";
                     mysql_query($query);
                 } else {
                     $query = "insert into healingcrystals_assignments_action_request (user_id, is_action_request, is_fyi, marked_for_email, selected_by_user_id, comment_id, date_added) values ('" . $user_id . "', '0', '0', '1', '" . $this->logged_user->getId() . "', '" . $this->active_comment->getId() . "', now())";
                     mysql_query($query);
                 }
             }
             reset($email_to_user_ids);
             //EOF:mod
             if (!empty($subscribers_to_notify)) {
                 //$subscribers_to_notify = implode(',', $subscribers_to_notify);
                 //mysql_query("insert into healingcrystals_testing (query, fired_at) values ('" . $subscribers_to_notify . "', now())");
                 $notified_to = '';
                 //$subscribers = explode(',', $subscribers_to_notify);
                 $subscribers = $subscribers_to_notify;
                 $all_subscribers = $active_object->getSubscribers();
                 $excluded = array();
                 $included = array();
                 //$excluded_temp = array();
                 //$included_temp = array();
                 $subscribers_name = '';
                 foreach ($all_subscribers as $reg_subscriber) {
                     $subscribers_name .= $reg_subscriber->getName() . "<br/>";
                     $subscriber_excluded = true;
                     //if ($this->logged_user->getId()!=$reg_subscriber->getId()){
                     foreach ($subscribers as $subscriber_id) {
                         $subscriber_id = trim($subscriber_id);
                         if ($reg_subscriber->getId() == $subscriber_id) {
                             $included[] = $reg_subscriber;
                             //BOF:mod 20130429
                             /*
                             //EOF:mod 20130429
                             								$notified_to .= $reg_subscriber->getName() . ', ';
                             //BOF:mod 20130429
                             */
                             //EOF:mod 20130429
                             //$included_temp[] = $reg_subscriber->getId();
                             $subscriber_excluded = false;
                             //$subscribers_name .= $reg_subscriber->getName() . "<br/>";
                             break;
                         }
                     }
                     //BOF:mod 20110623
                     foreach ($fyi_users as $fyi_user_id) {
                         $fyi_user_id = trim($fyi_user_id);
                         if ($reg_subscriber->getId() == $fyi_user_id) {
                             //BOF:mod 20130429
                             /*
                             //EOF:mod 20130429
                             								$fyi_to .= $reg_subscriber->getName() . ', ';
                             //BOF:mod 20130429
                             */
                             //EOF:mod 20130429
                             break;
                         }
                     }
                     //EOF:mod 20110623
                     //}
                     if ($subscriber_excluded) {
                         $excluded[] = $reg_subscriber->getId();
                         //$excluded_temp[] = $reg_subscriber->getId();
                     }
                 }
                 //$link = mysql_connect(DB_HOST, DB_USER, DB_PASS);
                 //mysql_select_db(DB_NAME);
                 //mysql_query("insert into healingcrystals_testing (query, fired_at) values ('" . implode('|', $included_temp) . ' = ' . implode('|', $excluded_temp) . "', now())");
                 //mysql_close($link);
                 //BOF:mod 20110517
                 //if (count($included)){
                 if (!$complete_parent_object && count($included)) {
                     //EOF:mod 20110517
                     //BOF:mod 20110623
                     //$notified_to = '<br/><br/>Notification emailed to: ' . substr($notified_to, 0, -2);
                     //$this->active_comment->setBody($this->active_comment->getBody() . $notified_to . $fyi_to);
                     //BOF:mod 20130429
                     /*
                                     //EOF:mod 20130429
                     if (!empty($notified_to)){
                     							$notified_to = '<br/><br/>Action Request marked to: ' . substr($notified_to, 0, -2);
                     }
                     if (!empty($fyi_to)){
                     							$fyi_to = (empty($notified_to) ? '<br/><br/>' : '<br/>') . 'FYI Comment marked to: ' . substr($fyi_to, 0, -2);
                     }
                     if (!empty($emailed_to)){
                     							$emailed_to = (empty($notified_to) && empty($fyi_to) ? '<br/><br/>' : '<br/>') . 'Email sent to: ' . substr($emailed_to, 0, -2);
                     }
                     $this->active_comment->setBody($this->active_comment->getBody() . $notified_to . $fyi_to . $emailed_to);
                     //EOF:mod 20110623
                     $this->active_comment->save();
                                     //BOF:mod 20130429
                     */
                     //EOF:mod 20130429
                     //BOF:mod 20110720 ticketid246
                     /*
                     //EOF:mod 20110720 ticketid246
                     $created_by = $this->active_comment->getCreatedBy();
                     $parent = $active_object;
                     $parent->sendToSubscribers('resources/new_comment', array(
                     			'comment_body' => $this->active_comment->getFormattedBody(),
                     			'comment_url' => $this->active_comment->getViewUrl(),
                     			'created_by_url' => $created_by->getViewUrl(),
                     			'created_by_name' => $created_by->getDisplayName(),
                     			'subscribers_name' => "<br/><br/>-- SET NOTIFICATIONS --<br/>" . $subscribers_name . "<br/><br/>",
                     			'comment_id' => $this->active_comment->getId(),
                     			), $excluded, $parent);
                     //BOF:mod 20110720 ticketid246
                     */
                     //EOF:mod 20110720 ticketid246
                     /*$created_by = $this->active_comment->getCreatedBy();
                     		$variables = array('owner_company_name' => get_owner_company(),
                     				'project_name'       => $this->active_project->getName(),
                     				'project_url'        => $this->active_project->getOverviewUrl(),
                     				'object_type'        => $this->active_comment->getVerboseType(),
                     				'object_name'        => $this->active_comment->getName(),
                     				'comment_body' => $this->active_comment->getFormattedBody(),
                     				'comment_url' => $this->active_comment->getViewUrl(),
                     				'created_by_url' => $created_by->getViewUrl(),
                     				'created_by_name' => $created_by->getDisplayName(),);
                     		ApplicationMailer::send($users, 'resources/new_comment', $variables, $this->active_milestone);*/
                 }
             } elseif (!empty($fyi_users)) {
                 $all_subscribers = $active_object->getSubscribers();
                 foreach ($all_subscribers as $reg_subscriber) {
                     foreach ($fyi_users as $fyi_user_id) {
                         $fyi_user_id = trim($fyi_user_id);
                         if ($reg_subscriber->getId() == $fyi_user_id) {
                             $fyi_to .= $reg_subscriber->getName() . ', ';
                             break;
                         }
                     }
                 }
                 /*$fyi_to = '<br/><br/>FYI Comment marked to: ' . substr($fyi_to, 0, -2);
                 		if (!empty($emailed_to)){
                 			$emailed_to = (empty($fyi_to) ? '<br/><br/>' : '<br/>') . 'Email sent to: ' . substr($emailed_to, 0, -2);
                                  }
                 		$this->active_comment->setBody($this->active_comment->getBody() . $fyi_to . $emailed_to);
                 		$this->active_comment->save();*/
             } elseif (!empty($email_to_user_ids)) {
                 /*$emailed_to = '<br/><br/>Email sent to: ' . substr($emailed_to, 0, -2);
                 		$this->active_comment->setBody($this->active_comment->getBody() . $emailed_to);
                 		$this->active_comment->save();*/
             }
             if (count($email_to_user_ids)) {
                 $users = array();
                 foreach ($email_to_user_ids as $user_id) {
                     if ($user_id != $this->logged_user->getId()) {
                         $users[] = new User($user_id);
                     }
                 }
                 $created_by = $this->active_comment->getCreatedBy();
                 $variables = array('owner_company_name' => get_owner_company(), 'project_name' => $this->active_project->getName(), 'project_url' => $this->active_project->getOverviewUrl(), 'object_type' => $this->active_comment->getVerboseType(), 'object_name' => $this->active_comment->getName(), 'object_body' => $this->active_comment->getFormattedBody(), 'object_url' => $this->active_comment->getViewUrl(), 'comment_body' => $this->active_comment->getFormattedBody(), 'comment_url' => $this->active_comment->getViewUrl(), 'created_by_url' => $created_by->getViewUrl(), 'created_by_name' => $created_by->getDisplayName(), 'details_body' => '', 'comment_id' => $this->active_comment->getId());
                 //BOF:mod 20111101
                 /*
                 //EOF:mod 20111101
                 ApplicationMailer::send($users, 'resources/new_comment', $variables, $this->active_milestone);
                 //BOF:mod 20111101
                 */
                 $parent_id = $this->active_comment->getParentId();
                 $parent_type = $this->active_comment->getParentType();
                 $parent_obj = new $parent_type($parent_id);
                 $attachments = null;
                 $object_attachments = $this->active_comment->getAttachments();
                 if ($object_attachments) {
                     $attachments = array();
                     foreach ($object_attachments as $object_attachment) {
                         $attachments[] = array('path' => $object_attachment->getFilePath(), 'name' => $object_attachment->getName(), 'mime_type' => $object_attachment->getMimeType());
                     }
                 }
                 ApplicationMailer::send($users, 'resources/new_comment', $variables, $parent_obj, $attachments);
                 //EOF:mod 20111101
             }
             //BOF:mod 20121030
             $modify_comments_sorting = false;
             $reply_to_comment_id = $this->request->post('reply_to_comment_id');
             if (!empty($reply_to_comment_id)) {
                 $sql_data = array('integer_field_2' => $reply_to_comment_id);
                 Comments::update($sql_data, "id='" . $this->active_comment->getId() . "'", TABLE_PREFIX . 'project_objects');
                 //$modify_comments_sorting = true;
             }
             //$count = 0;
             /*$link = mysql_connect(DB_HOST, DB_USER, DB_PASS);
             		mysql_select_db(DB_NAME);
             		$sql = "select * from " . TABLE_PREFIX . "project_objects where parent_id='" . $this->active_comment->getParentId() . "' and parent_type='" . $this->active_comment->getParentType() . "' and type='Comment' and (position is null or position='0')";
             		$result = mysql_query($sql, $link);
             		if (!mysql_num_rows($result) ){
             			$sql = "select max(position) as count from " . TABLE_PREFIX . "project_objects where parent_id='" . $this->active_comment->getParentId() . "' and parent_type='" . $this->active_comment->getParentType() . "' and type='Comment'";
             			$result = mysql_query($sql, $link);
             			$info = mysql_fetch_assoc($result);
             			$count = $info['count'];
             			$sql_data = array('position' => ++$count);
             			Comments::update($sql_data, "id='" . $this->active_comment->getId() . "'", TABLE_PREFIX . 'project_objects');
             		} else {
             			$modify_comments_sorting = true;
             		}
             		mysql_close($link);*/
             //if ($modify_comments_sorting) $this->modify_comments_sorting($count);
             //EOF:mod 20121030
             if ($this->request->isApiCall()) {
                 $this->serveData($this->active_comment, 'comment');
             } else {
                 flash_success('Comment successfully posted');
                 //$this->redirectToUrl($this->active_comment->getRealViewUrl());
                 $this->redirectToUrl($this->active_comment->getParent()->getViewUrl());
             }
             // if
         } else {
             db_rollback();
             if ($this->request->isApiCall()) {
                 $this->serveData($save);
             } else {
                 $this->smarty->assign('errors', $save);
             }
             // if
         }
         // if
     } else {
         if ($this->request->isApiCall()) {
             $this->httpError(HTTP_ERR_BAD_REQUEST, null, true, true);
         }
         // if
     }
     // if
 }
 /**
  * Reschedule selected milestone
  *
  * @param void
  * @return null
  */
 function reschedule()
 {
     if ($this->active_milestone->isNew()) {
         $this->httpError(HTTP_ERR_NOT_FOUND);
     }
     // if
     if (!$this->active_milestone->canEdit($this->logged_user)) {
         $this->httpError($this->logged_user);
     }
     // if
     $milestone_data = $this->request->post('milestone');
     if (!is_array($milestone_data)) {
         $milestone_data = array('start_on' => $this->active_milestone->getStartOn(), 'due_on' => $this->active_milestone->getDueOn(), 'reschedule_milstone_objects' => false);
     }
     // if
     $this->smarty->assign('milestone_data', $milestone_data);
     if ($this->request->isSubmitted()) {
         db_begin_work();
         $old_due_on = new DateValue($this->active_milestone->getDueOn());
         $new_start_on = new DateValue(array_var($milestone_data, 'start_on'));
         $new_due_on = new DateValue(array_var($milestone_data, 'due_on'));
         $reschedule_tasks = (bool) array_var($milestone_data, 'reschedule_milstone_objects');
         $successive_milestones = Milestones::findSuccessiveByMilestone($this->active_milestone, STATE_VISIBLE, $this->logged_user->getVisibility());
         // before we update timestamp
         $reschedule = $this->active_milestone->reschedule($new_start_on, $new_due_on, $reschedule_tasks);
         if ($reschedule && !is_error($reschedule)) {
             //if (instance_of($new_due_on, 'DateValue')){
             if ($new_due_on->getTimestamp() != $old_due_on->getTimestamp()) {
                 $with_successive = array_var($milestone_data, 'with_sucessive');
                 $to_move = null;
                 switch (array_var($with_successive, 'action')) {
                     case 'move_all':
                         $to_move = $successive_milestones;
                         break;
                     case 'move_selected':
                         $selected_milestones = array_var($with_successive, 'milestones');
                         if (is_foreachable($selected_milestones)) {
                             $to_move = Milestones::findByIds($selected_milestones, STATE_VISIBLE, $this->logged_user->getVisibility());
                         }
                         // if
                         break;
                 }
                 // switch
                 if (is_foreachable($to_move)) {
                     $diff = $new_due_on->getTimestamp() - $old_due_on->getTimestamp();
                     foreach ($to_move as $to_move_milestone) {
                         $milestone_start_on = $to_move_milestone->getStartOn();
                         $milestone_due_on = $to_move_milestone->getDueOn();
                         $new_milestone_start_on = $milestone_start_on->advance($diff, false);
                         $new_milestone_due_on = $milestone_due_on->advance($diff, false);
                         $to_move_milestone->reschedule($new_milestone_start_on, $new_milestone_due_on, $reschedule_tasks);
                     }
                     // foreach
                 }
                 // if
             }
             // if
             db_commit();
             if ($this->request->getFormat() == FORMAT_HTML) {
                 //flash_success('Milestone ":name" has been updated', array('name' => $this->active_milestone->getName()), false, true);
                 flash_success('Project ":name" has been updated', array('name' => $this->active_milestone->getName()), false, true);
                 $this->redirectToUrl($this->active_milestone->getViewUrl());
             } else {
                 $this->serveData($this->active_milestone);
             }
             // if
             //}
         } else {
             db_rollback();
             if ($this->request->getFormat() == FORMAT_HTML) {
                 $this->smarty->assign('errors', $reschedule);
             } else {
                 $this->serveData($save);
             }
             // if
         }
         // if
     }
     // if
 }
Пример #18
0
 /**
  *	update - update an FRSPackage in the database.
  *
  *	@param	string	The name of this package.
  *	@param	int	The status_id of this package from frs_status table.
  *	@return	boolean success.
  */
 function update($name, $status)
 {
     if (strlen($name) < 3) {
         $this->setError(_('FRSPackage Name Must Be At Least 3 Characters'));
         return false;
     }
     $perm =& $this->Group->getPermission(session_get_user());
     if (!$perm || !is_object($perm) || !$perm->isReleaseTechnician()) {
         $this->setPermissionDeniedError();
         return false;
     }
     if ($this->getName() != htmlspecialchars($name)) {
         $res = db_query("SELECT * FROM frs_package WHERE group_id='" . $this->Group->getID() . "'\n\t\t\tAND name='" . htmlspecialchars($name) . "'");
         if (db_numrows($res)) {
             $this->setError('FRSPackage::update() Error Updating Package: Name Already Exists');
             return false;
         }
     }
     db_begin();
     $res = db_query("UPDATE frs_package SET\n\t\t\tname='" . htmlspecialchars($name) . "',\n\t\t\tstatus_id='{$status}'\n\t\t\tWHERE group_id='" . $this->Group->getID() . "'\n\t\t\tAND package_id='" . $this->getID() . "'");
     if (!$res || db_affected_rows($res) < 1) {
         db_rollback();
         $this->setError('FRSPackage::update() Error On Update: ' . db_error());
         return false;
     }
     $olddirname = $this->getFileName();
     if (!$this->fetchData($this->getID())) {
         db_rollback();
         $this->setError('FRSPackage::update() Error Updating Package: Couldn´t fetch data');
         return false;
     }
     $newdirname = $this->getFileName();
     $olddirlocation = $GLOBALS['sys_upload_dir'] . '/' . $this->Group->getUnixName() . '/' . $olddirname;
     $newdirlocation = $GLOBALS['sys_upload_dir'] . '/' . $this->Group->getUnixName() . '/' . $newdirname;
     if ($olddirname != $newdirname) {
         if (is_dir($newdirlocation)) {
             db_rollback();
             $this->setError('FRSPackage::update() Error Updating Package: Directory Already Exists');
             return false;
         } else {
             if (!@rename($olddirlocation, $newdirlocation)) {
                 db_rollback();
                 $this->setError('FRSPackage::update() Error Updating Package: Couldn´t rename dir');
                 return false;
             }
         }
     }
     db_commit();
     return true;
 }
 function update_gui_wms($myWMS)
 {
     $mySubmit = null;
     $sql = "SELECT * FROM gui_wms where fkey_wms_id = \$1";
     $v = array($myWMS);
     $t = array('i');
     $res = db_prep_query($sql, $v, $t);
     $cnt = 0;
     while ($row = db_fetch_array($res)) {
         unset($mySubmit);
         $myGUI[$cnt] = $row["fkey_gui_id"];
         $sql = "UPDATE gui_wms SET ";
         $v = array();
         $t = array();
         $paramCount = 0;
         for ($i = 0; $i < count($this->data_type); $i++) {
             # gui_wms_mapformat
             if (mb_strtolower($this->data_type[$i]) == "map" && mb_strtolower($this->data_format[$i]) == mb_strtolower($row["gui_wms_mapformat"])) {
                 $myMapFormat = true;
             }
             # gui_wms_featureinfoformat
             if (mb_strtolower($this->data_type[$i]) == "featureinfo" && mb_strtolower($this->data_format[$i]) == mb_strtolower($row["gui_wms_featureinfoformat"])) {
                 $myFeatureInfoFormat = true;
             }
             # gui_wms_exceptionformat
             if (mb_strtolower($this->data_type[$i]) == "exception" && mb_strtolower($this->data_format[$i]) == mb_strtolower($row["gui_wms_exceptionformat"])) {
                 $myExceptionFormat = true;
             }
         }
         if (!$myMapFormat) {
             $paramCount++;
             $sql .= "gui_wms_mapformat = \$" . $paramCount . " ";
             $mySubmit = true;
             array_push($v, $this->gui_wms_mapformat);
             array_push($t, "s");
         }
         if (!$myFeatureInfoFormat) {
             if ($mySubmit) {
                 $sql .= ",";
             }
             $paramCount++;
             $sql .= "gui_wms_featureinfoformat = \$" . $paramCount . " ";
             array_push($v, $this->gui_wms_featureinfoformat);
             array_push($t, "s");
             $mySubmit = true;
         }
         if (!$myExceptionFormat) {
             if ($mySubmit) {
                 $sql .= ",";
             }
             $paramCount++;
             $sql .= "gui_wms_exceptionformat = \$" . $paramCount . " ";
             array_push($v, $this->gui_wms_exceptionformat);
             array_push($t, "s");
             $mySubmit = true;
         }
         # gui_wms_epsg
         for ($j = 0; $j < count($this->objLayer[0]->layer_epsg); $j++) {
             if ($this->objLayer[0]->layer_epsg[$j][epsg] == mb_strtoupper($row["gui_wms_epsg"])) {
                 $myGUI_EPSG = true;
             }
         }
         if (!$myGUI_EPSG) {
             if ($mySubmit) {
                 $sql .= ",";
             }
             $paramCount++;
             $sql .= "gui_wms_epsg = \$" . $paramCount . " ";
             array_push($v, $this->gui_wms_epsg);
             array_push($t, "s");
             $mySubmit = true;
         }
         $paramCount++;
         $sql .= " WHERE fkey_gui_id = \$" . $paramCount . " ";
         array_push($v, $row["fkey_gui_id"]);
         array_push($t, "s");
         $paramCount++;
         $sql .= "AND fkey_wms_id = \$" . $paramCount;
         array_push($v, $myWMS);
         array_push($t, "i");
         if ($mySubmit) {
             $res = db_prep_query($sql, $v, $t);
             if (!$res) {
                 db_rollback();
                 echo "<pre>" . $sql . "</pre><br> <br><p>";
                 echo db_error();
                 echo "<br /> UPDATE ERROR -> KILL PROCESS AND ROLLBACK....................no update<br><br>";
                 $e = new mb_exception("class_wms.php: transaction: Transaction aborted, rollback.");
             }
         }
         $cnt++;
     }
 }
Пример #20
0
 /**
  *	createTrackers - creates all the standard trackers for a given Group.
  *
  *	@return	boolean	success.
  */
 function createTrackers()
 {
     // first, check if trackers already exist
     $res = db_query("SELECT * FROM artifact_group_list \n\t\t\tWHERE group_id='" . $this->Group->getID() . "' AND datatype > 0");
     if (db_numrows($res) > 0) {
         return true;
     }
     include $GLOBALS['gfcommon'] . 'tracker/artifact_type_definitions.php';
     db_begin();
     foreach ($trackers as $trk) {
         $at = new ArtifactType($this->Group);
         if (!$at || !is_object($at)) {
             db_rollback();
             $this->setError('Error Getting Tracker Object');
             return false;
         }
         //
         //	Create a tracker
         //
         if (!$at->create(addslashes($trk[0]), addslashes($trk[1]), $trk[2], $trk[3], $trk[4], $trk[5], $trk[6], $trk[7], $trk[8], $trk[9], $trk[10])) {
             db_rollback();
             $this->setError('Error Creating Tracker: ' . $at->getErrorMessage());
             return false;
         } else {
             //
             //	Create each field in the tracker
             //
             foreach ($trk[11] as $fld) {
                 $aef = new ArtifactExtraField($at);
                 //print($fld[0])."***|";
                 if (!$aef->create(addslashes($fld[0]), $fld[1], $fld[2], $fld[3], $fld[4])) {
                     db_rollback();
                     $this->setError('Error Creating Extra Field: ' . $aef->getErrorMessage());
                     return false;
                 } else {
                     //
                     //	create each element in the field
                     //
                     foreach ($fld[5] as $el) {
                         //print($el)."**";
                         $aefe = new ArtifactExtraFieldElement($aef);
                         /*	 Allow us to provide a list as an element
                         			 value - in doing so, we can provide a
                         			 status field value for people wanting to
                         			 set up custom statuses. The first element
                         			 of any given array is the name, the second
                         			 is the status_id (0, 1 or 2)*/
                         $el_name = $el;
                         $el_status = 0;
                         if (is_array($el) && $fld[1] == ARTIFACT_EXTRAFIELDTYPE_STATUS) {
                             $el_name = $el[0];
                             $el_status = $el[1];
                         }
                         if (!$aefe->create(addslashes($el_name), $el_status)) {
                             db_rollback();
                             $this->setError('Error Creating Extra Field Element: ' . $aefe->getErrorMessage());
                             return false;
                         }
                     }
                 }
             }
         }
     }
     db_commit();
     return true;
 }
Пример #21
0
/**
 * Add a entry in the DataBase for a Tracker associated to a commit
 *
 * @param   array    $Config Config
 * @param   string   $GroupId The GroupId to insert it into
 * @param   string   $Num The tracker_id
 *
 * @return  array    Returns 'check'=true if check passed, group, group_id
 */
function addTaskLog($Config, $GroupId, $Num)
{
    $return = array();
    $Query = "SELECT * from project_task,project_group_list WHERE " . "project_task.group_project_id=" . "project_group_list.group_project_id " . "AND project_task.project_task_id='" . $Num . "' AND " . " project_group_list.group_id='" . $GroupId . "'";
    var_dump($Query);
    $Result = db_query($Query);
    $Rows = db_numrows($Result);
    if ($Rows == 0) {
        $return['Error'] .= "Task:{$Num} Not Found.";
    }
    if ($Rows == 1) {
        db_begin();
        $Query = "INSERT INTO plugin_svntracker_data_artifact " . "(kind, project_task_id) VALUES " . "('1', '" . $Num . "')";
        $DBRes = db_query($Query);
        $HolderID = db_insertid($DBRes, 'plugin_svntracker_data_artifact', 'id');
        if (!$DBRes || !$HolderID) {
            $return['Error'] = 'Problems with Task $Num: ' . db_error($DBRes);
            db_rollback();
        } else {
            $Query = "INSERT INTO plugin_svntracker_data_master " . "(holder_id, svn_date, log_text, file, prev_version, " . "actual_version, author)" . " VALUES ('" . $HolderID . "','" . $Config['SvnDate'] . "','" . $Config['Log'] . "','" . $Config['FileName'] . "','" . $Config['PrevVersion'] . "','" . $Config['ActualVersion'] . "','" . $Config['UserName'] . "')";
            $DBRes = db_query($Query);
            if (!$DBRes) {
                db_rollback();
            } else {
                db_commit();
            }
        }
    }
    if ($Rows > 1) {
        $return['Error'] .= "Unknown problem adding Task:{$Num}.";
    }
    return $return;
}
 /**
  * Set ID-s of related time records
  *
  * @param array $ids
  * @return boolean
  */
 function setTimeRecordIds($ids)
 {
     db_begin_work();
     $execute = db_execute('DELETE FROM ' . TABLE_PREFIX . 'invoice_time_records WHERE invoice_id = ? && item_id = ?', $this->getInvoiceId(), $this->getId());
     if ($execute && !is_error($execute)) {
         if (is_foreachable($ids)) {
             $to_insert = array();
             $invoice_id = $this->getInvoiceId();
             $item_id = $this->getId();
             foreach ($ids as $id) {
                 $id = (int) $id;
                 if ($id && !isset($to_insert[$id])) {
                     $to_insert[$id] = "({$invoice_id}, {$item_id}, {$id})";
                 }
                 // if
             }
             // foreach
             if (is_foreachable($to_insert)) {
                 $execute = db_execute('INSERT INTO ' . TABLE_PREFIX . 'invoice_time_records (invoice_id, item_id, time_record_id) VALUES ' . implode(', ', $to_insert));
                 if (!$execute || is_error($execute)) {
                     db_rollback();
                     return $execute;
                 }
                 // if
             }
             // if
         }
         // if
         db_commit();
         return true;
     } else {
         db_rollback();
         return $execute;
     }
     // if
 }
Пример #23
0
 /**
  * removes an entire row and redistributes its blocks
  *
  * @param array $values parameters for this function
  *                      row => int row to remove
  *
  */
 public function removerow($values)
 {
     // $layoutrows declared in layout.php
     global $SESSION;
     if (!array_key_exists('row', $values) || empty($values['row'])) {
         throw new ParamOutOfRangeException(get_string('missingparamrow', 'error'));
     }
     db_begin();
     // for each column, call removecolumn
     // first retrieve number of columns in row
     $layoutrows = $this->get_layoutrows();
     $layout = $values['layout'];
     $thisrownumcolumns = $layout->rows[$values['row']]['columns'];
     for ($i = $thisrownumcolumns; $i > 0; $i--) {
         $this->removecolumn(array('row' => $values['row'], 'column' => $i, 'removerow' => true));
     }
     // check for sucessful removal of columns
     $dbcolumns = get_field('view_rows_columns', 'columns', 'view', $this->get('id'), 'row', $values['row']);
     if ($dbcolumns != 0) {
         db_rollback();
         $SESSION->add_error_msg(get_string('changecolumnlayoutfailed', 'view'));
         redirect(get_config('wwwroot') . 'view/layout.php?id=' . $this->get('id') . ($new ? '&new=1' : ''));
     }
     $this->set('numrows', $this->get('numrows') - 1);
     $this->set('layout', null);
     $columnsperrow = $this->get('columnsperrow');
     unset($columnsperrow[$values['row']]);
     $this->set('columnsperrow', $columnsperrow);
     //set makes dirty=1, which enables commit; columnsperrrow used as check by layout submit function
     $this->commit();
     db_commit();
     unset($this->rows[$values['row']]);
 }
Пример #24
0
 /**
  *	update - update an existing file in this FRSFileRelease/FRSPackage.
  *
  *	@param	int	The type_id of this file from the frs-file-types table.
  *	@param	int	The processor_id of this file from the frs-processor-types table.
  *	@param	int	The release_date of this file in unix time (seconds).
  *	@param	int	The release_id of the release this file belongs to (if not set, defaults to the release id of this file).
  *	@return	boolean success.
  */
 function update($type_id, $processor_id, $release_time, $release_id = false)
 {
     $perm =& $this->FRSRelease->FRSPackage->Group->getPermission(session_get_user());
     if (!$perm || !is_object($perm) || !$perm->isReleaseTechnician()) {
         $this->setPermissionDeniedError();
         return false;
     }
     // Sanity checks
     if ($release_id) {
         // Check that the new FRSRelease id exists
         if ($FRSRelease = frsrelease_get_object($release_id)) {
             // Check that the new FRSRelease id belongs to the group of this FRSFile
             if ($FRSRelease->FRSPackage->Group->getID() != $this->FRSRelease->FRSPackage->Group->getID()) {
                 $this->setError('FRSFile:: No Valid Group Object');
                 return false;
             }
         } else {
             $this->setError('FRSFile:: No Valid FRSRelease Object');
             return false;
         }
     } else {
         // If release_id is not set, defaults to the release id of this file
         $release_id = $this->FRSRelease->getID();
     }
     // Update database
     db_begin();
     $res = db_query("UPDATE frs_file SET\n\t\t\ttype_id='{$type_id}',\n\t\t\tprocessor_id='{$processor_id}',\n\t\t\trelease_time='{$release_time}',\n\t\t\trelease_id='{$release_id}'\n\t\t\tWHERE file_id='" . $this->getID() . "'");
     if (!$res || db_affected_rows($res) < 1) {
         $this->setError('FRSFile::update() Error On Update: ' . db_error());
         return false;
     }
     // Move physically file if needed
     if ($release_id != $this->FRSRelease->getID()) {
         $old_file_location = $GLOBALS['sys_upload_dir'] . '/' . $this->FRSRelease->FRSPackage->Group->getUnixName() . '/' . $this->FRSRelease->FRSPackage->getFileName() . '/' . $this->FRSRelease->getFileName() . '/' . $this->data_array['filename'];
         $new_file_location = $GLOBALS['sys_upload_dir'] . '/' . $FRSRelease->FRSPackage->Group->getUnixName() . '/' . $FRSRelease->FRSPackage->getFileName() . '/' . $FRSRelease->getFileName() . '/' . $this->data_array['filename'];
         if (file_exists($new_file_location)) {
             db_rollback();
             $this->setError(_('That filename already exists in this project space'));
             return false;
         }
         $cmd = "/bin/mv {$old_file_location} {$new_file_location}";
         exec($cmd, $out);
         if (!file_exists($new_file_location)) {
             db_rollback();
             $this->setError(_('File cannot be moved to the permanent location') . ': ' . $new_file_location);
             return false;
         }
     }
     db_commit();
     return true;
 }
Пример #25
0
 /**
  *	insertmsg - inserts the message into the main table (forum)
  *	@param	string	The subject of the message.
  *	@param	string	The body of the message.
  *	@param	int	The thread_id of the message, if known.
  *	@param	int	The message_id of the parent message, if any.
  *	@param 	int	The id of the user that is posting the message
  *	@param  boolean	Whether the message has an attach associated. Defaults to false
  *	@return	boolean success.
  */
 function insertmsg($subject, $body, $thread_id = '', $is_followup_to = '', $user_id, $has_attach = false)
 {
     if (!$thread_id) {
         $thread_id = $this->Forum->getNextThreadID();
         $is_followup_to = 0;
         if (!$thread_id) {
             $this->setError('ForumMessage::create() ' . _('Getting next thread_id failed'));
             db_rollback();
             return false;
         }
     } else {
         //
         //  increment the parent's followup count if necessary
         //
         $res4 = db_query("UPDATE forum SET most_recent_date='" . time() . "' \n\t\t\t\tWHERE thread_id='{$thread_id}' AND is_followup_to='0'");
         if (!$res4 || db_affected_rows($res4) < 1) {
             $this->setError(_('Couldn\'t Update Master Thread parent with current time'));
             db_rollback();
             return false;
         } else {
             //
             //  mark the parent with followups as an optimization later
             //
             $res3 = db_query("UPDATE forum SET has_followups='1',most_recent_date='" . time() . "' \n\t\t\t\t\tWHERE msg_id='{$is_followup_to}'");
             if (!$res3) {
                 $this->setError(_('Could Not Update Parent'));
                 db_rollback();
                 return false;
             }
         }
     }
     $sql = "INSERT INTO forum (group_forum_id,posted_by,subject,\n\t\t\tbody,post_date,is_followup_to,thread_id,most_recent_date) \n\t\t\tVALUES ('" . $this->Forum->getID() . "', '{$user_id}', '" . htmlspecialchars($subject) . "', \n\t\t\t'" . $body . "', '" . time() . "','{$is_followup_to}','{$thread_id}','" . time() . "')";
     $result = db_query($sql);
     if (!$result || db_affected_rows($result) < 1) {
         $this->setError(_('ForumMessage::create() Posting Failed') . ' ' . db_error());
         db_rollback();
         return false;
     }
     $msg_id = db_insertid($result, 'forum', 'msg_id');
     if (!$this->fetchData($msg_id)) {
         db_rollback();
         return false;
     }
     if (!$msg_id) {
         db_rollback();
         $this->setError(_('ForumMessage::create() Unable to get new message id'));
         return false;
     }
     if (!$this->sendNotice($has_attach)) {
         db_rollback();
         return false;
     }
     //echo "Committing";
     db_commit();
     //echo "db_error()".db_error();
     $this->awaits_moderation = false;
     return true;
 }
Пример #26
0
 /**
  *	setPasswd - Changes user's password.
  *
  *	@param	string	The plaintext password.
  *	@return boolean success.
  */
 function setPasswd($passwd)
 {
     global $SYS;
     if (!account_pwvalid($passwd)) {
         $this->setError('Error: ' . $GLOBALS['register_error']);
         return false;
     }
     db_begin();
     $unix_pw = account_genunixpw($passwd);
     $res = db_query("\n\t\t\tUPDATE users\n\t\t\tSET user_pw='" . md5($passwd) . "',\n\t\t\tunix_pw='{$unix_pw}'\n\t\t\tWHERE user_id='" . $this->getID() . "'\n\t\t");
     if (!$res || db_affected_rows($res) < 1) {
         $this->setError('ERROR - Could Not Change User Password: '******'{crypt}' . $unix_pw)) {
                 $this->setError($SYS->getErrorMessage());
                 db_rollback();
                 return false;
             }
         }
     }
     $hook_params = array();
     $hook_params['user'] = $this;
     $hook_params['user_id'] = $this->getID();
     $hook_params['user_password'] = $passwd;
     plugin_hook("user_setpasswd", $hook_params);
     db_commit();
     return true;
 }
Пример #27
0
 function delete()
 {
     $perm =& $this->Group->getPermission(session_get_user());
     if (!$perm || !is_object($perm) || !$perm->isDocEditor()) {
         $this->setPermissionDeniedError();
         return false;
     }
     $sql = 'DELETE FROM doc_data WHERE docid=' . $this->getID();
     $result = db_query($sql);
     if (!$result) {
         $this->setError('Error Deleting Document: ' . db_error());
         db_rollback();
         return false;
     }
     return true;
 }
Пример #28
0
 /**
  *  update - update a row in the table used to query names 
  *  for a tracker.  
  *
  *  	@param	int	 Id of the saved query
  *	@param	string	The name of the saved query
  *  @return	boolean	success.
  */
 function update($name, $status, $assignee, $moddaterange, $sort_col, $sort_ord, $extra_fields, $opendaterange = '', $closedaterange = '')
 {
     if (!$name) {
         $this->setMissingParamsError();
         return false;
     }
     if (!session_loggedin()) {
         $this->setError('Must Be Logged In');
         return false;
     }
     if (!$this->Exist(htmlspecialchars($name))) {
         $this->setError(_('Query does not exist'));
         return false;
     }
     $sql = "UPDATE artifact_query\n\t\t\tSET \n\t\t\tquery_name='" . htmlspecialchars($name) . "'\n\t\t\tWHERE artifact_query_id='" . $this->getID() . "'\n\t\t\tAND user_id='" . user_getid() . "'";
     db_begin();
     $result = db_query($sql);
     if ($result && db_affected_rows($result) > 0) {
         if (!$this->insertElements($this->getID(), $status, $assignee, $moddaterange, $sort_col, $sort_ord, $extra_fields, $opendaterange, $closedaterange)) {
             db_rollback();
             return false;
         } else {
             db_commit();
             $this->fetchData($this->getID());
             return true;
         }
     } else {
         $this->setError('Error Updating: ' . db_error());
         db_rollback();
         return false;
     }
 }
Пример #29
0
 public function __construct($message = null, $code = 0)
 {
     global $DB_IGNORE_SQL_EXCEPTIONS;
     if ($GLOBALS['_TRANSACTION_LEVEL'] > 0) {
         db_rollback();
     }
     parent::__construct($message, $code);
     if (empty($DB_IGNORE_SQL_EXCEPTIONS) && !defined('TESTSRUNNING')) {
         log_warn($this->getMessage());
     }
 }
Пример #30
0
/**
 * Import SQL from the file.
 *
 * @param string $file
 *
 * @return int
 */
function db_import($file)
{
    if ($fp = fopen($file, 'r')) {
        $sql = '';
        $i = 0;
        $flag = true;
        db_transaction();
        while ($line = fgets($fp)) {
            $line = str_replace("\r\n", "\n", $line);
            $line = str_replace("\r", "\n", $line);
            if ((substr_count($line, '\'') - substr_count($line, '\\\'')) % 2 !== 0) {
                $flag = !$flag;
            }
            $sql .= $line;
            if (preg_match('/;$/', trim($line)) && $flag) {
                $resource = db_query($sql);
                if (!$resource) {
                    db_rollback();
                    if (LOGGING_MESSAGE) {
                        logging('message', 'db: Query error: ' . db_error());
                    }
                    error('db: Query error' . (DEBUG_LEVEL ? ': ' . db_error() : ''));
                }
                $sql = '';
                $i++;
            }
        }
        fclose($fp);
        db_commit();
    } else {
        error('db: Import file can\'t read');
    }
    return $i;
}