Example #1
0
 public function addQuestion($row)
 {
     $a = (array) $row;
     $ar = array();
     foreach ($a as $k => $v) {
         if (in_array($k, $this->questionFields)) {
             $ar[$k] = $v;
         }
     }
     $fields = implode(", ", array_keys($ar));
     foreach (array_keys($ar) as $nothing) {
         $placeholders[] = "'%s'";
     }
     $values = implode(', ', $placeholders);
     $sql = "INSERT INTO {" . self::QUESTION_TABLE . "} ({$fields}) VALUES ({$values})";
     $res = db_query($sql, array_values($ar));
     $res = db_last_insert_id(self::QUESTION_TABLE, 'ID');
 }
Example #2
0
 public function saveCreators($nid, $vid)
 {
     if (!empty($this->authors)) {
         $this->loadMD5();
         db_query('DELETE FROM {biblio_contributor} WHERE nid = %d AND vid = %d', $nid, $vid);
         foreach ($this->authors as $rank => $author) {
             if (empty($author['cid']) && !empty($this->md5)) {
                 $author['cid'] = array_search($author['md5'], $this->md5);
             }
             if (empty($author['cid'])) {
                 drupal_write_record('biblio_contributor_data', $author);
                 $cid = db_last_insert_id('biblio_contributor_data', 'cid');
             } else {
                 $cid = $author['cid'];
             }
             $link_array = array('nid' => $nid, 'vid' => $vid, 'cid' => $cid, 'rank' => $rank, 'ctid' => $author['type']);
             drupal_write_record('biblio_contributor', $link_array);
         }
     }
 }
Example #3
0
/**
 * 教室の登録
 *
 * @param array $queries
 * @param array $options
 *
 * @return resource
 */
function insert_classes($queries, $options = array())
{
    $queries = db_placeholder($queries);
    $options = array('files' => isset($options['files']) ? $options['files'] : array());
    // 初期値を取得
    $defaults = default_classes();
    if (isset($queries['values']['created'])) {
        if ($queries['values']['created'] === false) {
            unset($queries['values']['created']);
        }
    } else {
        $queries['values']['created'] = $defaults['created'];
    }
    if (isset($queries['values']['modified'])) {
        if ($queries['values']['modified'] === false) {
            unset($queries['values']['modified']);
        }
    } else {
        $queries['values']['modified'] = $defaults['modified'];
    }
    // データを登録
    $queries['insert_into'] = DATABASE_PREFIX . 'classes';
    $resource = db_insert($queries);
    if (!$resource) {
        return $resource;
    }
    // IDを取得
    $class_id = db_last_insert_id();
    if (!empty($options['files'])) {
        // 関連するファイルを削除
        remove_classes($class_id, $options['files']);
        // 関連するファイルを保存
        save_classes($class_id, $options['files']);
    }
    return $resource;
}
Example #4
0
function set_uc_node_access_feature($product_nid, $article_nid)
{
    // set ubercart node_access feature - ties the product to the article so
    // buying the product can give user access to the article via acl to avoid
    // this breaking on an update to either ubercart or uc_node_access that
    // could potentially change the schema, this should probably be changed to
    // call drupal_execute on uc_node_access_feature_form instead of going
    // straight to db but it looks like there is a lot of overhead in that
    // form so i'm going with this simple method uc doesn't seem to have any
    // public methods to get this other than the form
    db_query("INSERT INTO {uc_product_features} (nid, fid, description) " . "VALUES (%d, '%s', '%s')", $product_nid, 'node_access', '');
    $pfid = db_last_insert_id('uc_product_features', 'pfid');
    db_query("INSERT INTO {uc_node_access_products} (pfid, access_nid) " . "VALUES (%d, %d)", $pfid, $article_nid);
}
Example #5
0
 /**
  * Stores this interval into the database.
  */
 public function save()
 {
     if ($this->iid > 0) {
         drupal_write_record(self::$table, $this, array('iid'));
     } else {
         drupal_write_record(self::$table, $this);
         $this->iid = db_last_insert_id(self::$table, 'iid');
     }
 }
Example #6
0
/**
 * 名簿の登録
 *
 * @param array $queries
 * @param array $options
 *
 * @return resource
 */
function insert_members($queries, $options = array())
{
    $queries = db_placeholder($queries);
    $options = array('category_sets' => isset($options['category_sets']) ? $options['category_sets'] : array(), 'files' => isset($options['files']) ? $options['files'] : array());
    // 初期値を取得
    $defaults = default_classes();
    if (isset($queries['values']['created'])) {
        if ($queries['values']['created'] === false) {
            unset($queries['values']['created']);
        }
    } else {
        $queries['values']['created'] = $defaults['created'];
    }
    if (isset($queries['values']['modified'])) {
        if ($queries['values']['modified'] === false) {
            unset($queries['values']['modified']);
        }
    } else {
        $queries['values']['modified'] = $defaults['modified'];
    }
    // データを登録
    $queries['insert_into'] = DATABASE_PREFIX . 'members';
    $resource = db_insert($queries);
    if (!$resource) {
        return $resource;
    }
    // IDを取得
    $member_id = db_last_insert_id();
    if (isset($options['category_sets'])) {
        // 分類を登録
        foreach ($options['category_sets'] as $category_id) {
            $resource = insert_category_sets(array('values' => array('category_id' => $category_id, 'member_id' => $member_id)));
            if (!$resource) {
                return $resource;
            }
        }
    }
    if (!empty($options['files'])) {
        // 関連するファイルを削除
        remove_members($member_id, $options['files']);
        // 関連するファイルを保存
        save_members($member_id, $options['files']);
    }
    return $resource;
}
 public function RegisterTask(ITask $task, $uid, $triggers, $moment = "-1 day", $arguments = NULL)
 {
     if ($this->CanAddTask($task, $uid)) {
         $t = date("Y-m-d H:i:s", strtotime($moment));
         if ($t) {
             if ($triggers) {
                 $sql = "INSERT INTO `{poker_scheduler}` (`uid`, `type`, `trigger`, `moment`, `visible`, `arguments`) VALUES(%d, '%s', '%s', '%s', %d";
                 $trigg = is_string($triggers) ? array($triggers) : $triggers;
                 $triggers = json_encode($trigg);
                 if ($arguments == NULL) {
                     $sql .= ", %s)";
                     $arguments = "NULL";
                 } else {
                     $arguments = json_encode($arguments);
                     $sql .= ", '%s')";
                 }
                 if (strlen($arguments) > 1024) {
                     throw new Exception(t('Warning !field parameter is too long (max !max_length chars)', array("!field" => "arguments", '!max_length' => '1024')));
                 }
                 if (strlen($triggers) > 256) {
                     throw new Exception(t('Warning !field parameter is too long (max !max_length chars)', array("!field" => "trigger", '!max_length' => '256')));
                 }
                 if ($task->Type() > 32) {
                     throw new Exception(t('Warning !field parameter is too long (max !max_length chars)', array("!field" => "type", '!max_length' => '32')));
                 }
                 $res = db_query($sql, $uid, $task->Type(), $triggers, $t, $task->AlwaysVisible(), $arguments);
                 if ($res) {
                     $this->SetNewTask($uid);
                     return db_last_insert_id("poker_scheduler", "id_task");
                 }
             }
         }
     }
     return -1;
 }
 /**
  * To Store User's Activity in Db
  *
  * @param
  *   $userId for who Activity is to be created
  * @param
  *   $activity activity to be created
  * @param
  *   $appId application to which Activity belongs to
  */
 public function createActivity($user_id, $activity, $app_id = '0')
 {
     $title = isset($activity['title']) ? trim($activity['title']) : '';
     $body = isset($activity['body']) ? trim($activity['body']) : '';
     $time = time();
     //Invoke hook_shindig_create_activites implementations
     $modules_results = array_filter($this->drupalInvokeAll('shindig_create_activites', $user_id, $app_id, $title, $body));
     //The activities has been saved, the first non-FALSE results is the activity ID
     if (!empty($modules_results)) {
         $activityId = reset($modules_results);
     } else {
         db_query("INSERT INTO {activities} (id, user_id, app_id, title, body, created) VALUES (0, %d, %d, '%s', '%s', {$time})", $user_id, $app_id, $title, $body);
         $activityId = db_last_insert_id('activities', 'id');
     }
     if (!$activityId) {
         return false;
     }
     $mediaItems = isset($activity['mediaItems']) ? $activity['mediaItems'] : array();
     if (count($mediaItems)) {
         foreach ($mediaItems as $mediaItem) {
             $type = isset($mediaItem['type']) ? $mediaItem['type'] : '';
             $mimeType = isset($mediaItem['mimeType']) ? $mediaItem['mimeType'] : '';
             $url = isset($mediaItem['url']) ? $mediaItem['url'] : '';
             $type = trim($type);
             $mimeType = trim($mimeType);
             $url = trim($url);
             //Invoke hook_shindig_create_mediaitem implementations
             $modules_results = array_filter($this->drupalInvokeAll('shindig_create_mediaitem', $activityId, $mimeType, $type, $url));
             //If no implementation returned a TRUE value, save the mediaitem ourself
             if (empty($modules_results)) {
                 db_query("INSERT INTO {activity_media_items} (id, activity_id, mime_type, media_type, url) VALUES (0, %d, '%s', '%s', '%s')", $activityId, $mimeType, $type, $url);
             }
         }
     }
     return true;
 }
Example #9
0
// フォワードを確認
if (forward() === null) {
    error('不正なアクセスです。');
}
// 投稿データを確認
if (empty($_SESSION['post'])) {
    // リダイレクト
    redirect('/register');
}
// パスワードのソルトを作成
$password_salt = hash_salt();
// トランザクションを開始
db_transaction();
// ユーザを登録
$resource = insert_users(array('values' => array('username' => $_SESSION['post']['user']['username'], 'password' => hash_crypt($_SESSION['post']['user']['password'], $password_salt . ':' . $GLOBALS['config']['hash_salt']), 'password_salt' => $password_salt, 'email' => $_SESSION['post']['user']['email'])));
if (!$resource) {
    error('データを登録できません。');
}
// IDを取得
$user_id = db_last_insert_id();
// プロフィールを登録
$resource = insert_profiles(array('values' => array('user_id' => $user_id)));
if (!$resource) {
    error('データを登録できません。');
}
// トランザクションを終了
db_commit();
// 投稿セッションを初期化
unset($_SESSION['post']);
// リダイレクト
redirect('/register/complete');
Example #10
0
 /**
  * {@inheritdoc}
  */
 public function roleCreate(array $permissions)
 {
     // Verify permissions exist.
     $all_permissions = module_invoke_all('perm');
     foreach ($permissions as $name) {
         $search = array_search($name, $all_permissions);
         if (!$search) {
             throw new \RuntimeException(sprintf("No permission '%s' exists.", $name));
         }
     }
     // Create new role.
     $name = $this->random->name(8);
     db_query("INSERT INTO {role} SET name = '%s'", $name);
     // Add permissions to role.
     $rid = db_last_insert_id('role', 'rid');
     db_query("INSERT INTO {permission} (rid, perm) VALUES (%d, '%s')", $rid, implode(', ', $permissions));
     return $name;
 }
 /**
  * Controller method for writing waypoints to a solution
  *
  * @param int $nid ["path","0"]
  *  The nid of the solution to add the waypoint to
  * @param object $waypoint ["data"]
  *  The waypoint to add
  * @return object
  *
  * @Access(callback='DocuWalkSolutionResource::access', args={'update'}, appendArgs=true)
  */
 public static function addWaypoint($nid, $waypoint)
 {
     if (!isset($waypoint->position)) {
         return services_error("Missing attribute 'position'", 406);
     }
     if (!preg_match('/^-?\\d+(\\.\\d+)?\\s-?\\d+(\\.\\d+)?$/', $waypoint->position)) {
         return services_error("Invalid format for the position.");
     }
     db_query("INSERT INTO {docuwalk_waypoint}(nid, position)\n      VALUES(%d, GeomFromText('%s'))", $nid, simple_geo_to_wkt('point', $waypoint->position));
     $wid = db_last_insert_id('docuwalk_waypoint', 'wid');
     return (object) array('wid' => $wid);
 }
Example #12
0
function sopac_create_pcc_lists($batch_number = 0)
{
    $limit = 100;
    $offset = $limit * $batch_number;
    $user_count = 0;
    $res = db_query("SELECT DISTINCT uid FROM sopac_cc_savedcards ORDER BY uid LIMIT %d OFFSET %d", $limit, $offset);
    while ($pcc_user = db_fetch_object($res)) {
        $user_count++;
        // Create a new list for this user
        db_query("INSERT INTO {sopac_lists} (list_id, uid, title, description, public) VALUES (NULL, '%d', '%s', '%s', '%d')", $pcc_user->uid, 'Personal Card Catalog List', 'Records imported from the old Personal Card Catalog function', 0);
        $list_id = db_last_insert_id('sopac_lists', 'list_id');
        // import all records for this user into the list
        sopac_import_cc($list_id, $pcc_user->uid);
    }
    drupal_set_message("Created PCC Lists for {$user_count} users");
}
/** add remote_addr to the blacklist for specified interval (in seconds)
 *
 * @param string $remote_addr the remote IP-address is the origin of the failure
 * @param int $delay_in_seconds the number of seconds to put this address on the blacklist
 * @param string $username extra information, could be useful for troubleshooting afterwards
 * @return bool|int FALSE on error, the id of the inserted record on success
 */
function login_failure_blacklist_address($remote_addr, $delay_in_seconds, $username = '')
{
    $release_time = strftime('%Y-%m-%d %T', time() + intval($delay_in_seconds));
    $logmessage = 'login: blacklisting \'' . $remote_addr . '\' until ' . $release_time . ': ';
    $retval = db_insert_into('login_failures', array('remote_addr' => $remote_addr, 'datim' => $release_time, 'failed_procedure' => LOGIN_PROCEDURE_BLACKLIST, 'points' => 1, 'username' => $username));
    $logmessage .= $retval === FALSE ? 'failed' : 'success';
    if ($retval !== FALSE) {
        $retval = db_last_insert_id('login_failures', 'login_failure_id');
    }
    if ($delay_in_seconds > LOGIN_FAILURE_DELAY_SECONDS) {
        // only record a 'real' blacklisting in logs, the 3-second blacklisting is not interesting, really
        logger($logmessage);
    }
    return $retval;
}
/**
 * Hnalde on_project_object_copied event
 *
 * @param ProjectObject $original
 * @param ProjectObject $copy
 * @param Project $destination
 * @param mixed $cascade
 * @return null
 */
function resources_handle_on_project_object_copied(&$original, &$copy, &$destination, $cascade)
{
    if ($original->can_have_subscribers) {
        $subscribers = $original->getSubscribers();
        if (is_foreachable($subscribers)) {
            foreach ($subscribers as $subscriber) {
                if ($subscriber->isProjectMember($destination)) {
                    Subscriptions::subscribe($subscriber, $copy);
                }
                // if
            }
            // foreach
        }
        // if
    }
    // if
    if ($original->can_have_assignees) {
        Assignments::cloneAssignments($original, $copy);
    }
    // if
    if ($original->can_have_attachments) {
        Attachments::cloneAttachments($original, $copy);
    }
    // if
    // Copy child objects
    if ($cascade === true || is_foreachable($cascade)) {
        if ($cascade === true) {
            $rows = db_execute_all('SELECT * FROM ' . TABLE_PREFIX . 'project_objects WHERE parent_id = ?', $original->getId());
        } else {
            $rows = db_execute_all('SELECT * FROM ' . TABLE_PREFIX . 'project_objects WHERE parent_id = ? AND type IN (?)', $original->getId(), $cascade);
        }
        // if
        if (is_foreachable($rows)) {
            // We'll remember original and copy tasks ID-s here so we can move
            // assignments later on, when we have both instances
            $tasks = array();
            foreach ($rows as $row) {
                $subobject_original_id = $row['id'];
                $subobject_original_type = strtolower($row['type']);
                unset($row['id']);
                $row['project_id'] = $destination->getId();
                $row['parent_id'] = $copy->getId();
                $row['milestone_id'] = 0;
                // Copy file
                if ($subobject_original_type == 'attachment') {
                    $path = UPLOAD_PATH . '/' . $row['varchar_field_1'];
                    if (is_file($path)) {
                        $destination_file = get_available_uploads_filename();
                        if (copy($path, $destination_file)) {
                            $row['varchar_field_1'] = basename($destination_file);
                        }
                        // if
                    }
                    // if
                }
                // if
                // Escape values
                foreach ($row as $k => $v) {
                    $row[$k] = db_escape($v);
                }
                // foreach
                db_execute('INSERT INTO ' . TABLE_PREFIX . 'project_objects (' . implode(', ', array_keys($row)) . ') VALUES (' . implode(', ', $row) . ')');
                if ($subobject_original_type == 'task') {
                    $tasks[$subobject_original_id] = db_last_insert_id();
                }
                // if
            }
            // foraech
            if (instance_of($copy, 'Discussion')) {
                $last_comment = $copy->getLastComment();
                $last_comment_datetime = instance_of($last_comment, 'Comment') ? $last_comment->getCreatedOn() : null;
                $copy->setLastCommentOn($last_comment_datetime);
                $copy->save();
            }
            // if
            // Lets move task assinments if we have any tasks
            if (is_foreachable($tasks)) {
                foreach ($tasks as $task_original_id => $task_copy_id) {
                    $task_original = Tasks::findById($task_original_id);
                    $task_copy = Tasks::findById($task_copy_id);
                    if (instance_of($task_original, 'Task') && instance_of($task_copy, 'Task')) {
                        Assignments::cloneAssignments($task_original, $task_copy);
                        Subscriptions::cloneSubscriptions($task_original, $task_copy);
                    }
                    // if
                }
                // foreach
            }
            // if
        }
        // if
    }
    // if
}
Example #15
0
#!/usr/bin/php -q
<?php 
$kawf_base = realpath(dirname(__FILE__) . "/..");
require_once $kawf_base . "/config/config.inc";
require_once $kawf_base . "/include/sql.inc";
require_once $kawf_base . "/user/tables.inc";
if (!ini_get('safe_mode')) {
    set_time_limit(0);
}
db_connect();
$name = "Test forum";
$shortname = "test";
if (!isset($name) || empty($name)) {
    echo "Please specify a name\n";
    exit;
}
if (!isset($shortname) || empty($shortname)) {
    echo "Please specify a shortname\n";
    exit;
}
db_exec("insert into f_forums ( name, shortname ) values ( ?, ? )", array($name, $shortname));
$fid = db_last_insert_id();
db_exec("insert into f_indexes ( fid, minmid, maxmid, mintid, maxtid, active, moderated, deleted ) values ( ?, 1, 0, 1, 0, 0, 0, 0 )", array($fid));
$iid = db_last_insert_id();
db_exec("insert into f_unique ( fid, type, id ) values ( ?, 'Message', 0 )", array($fid));
db_exec("insert into f_unique ( fid, type, id ) values ( ?, 'Thread', 0 )", array($fid));
db_exec(sprintf($create_message_table, $iid));
db_exec(sprintf($create_thread_table, $iid));
/**
 * Update the DB with the new file info for a given release node.
 *
 * @param $nid
 *   The node ID of the release node to update.
 * @param $files
 *   Array of files to add to the release node.
 * @param $package_contents
 *   Optional. Array of nids of releases contained in a release package.
 */
function package_release_update_node($nid, $files, $package_contents = array())
{
    global $drupal_root, $dest_root, $task;
    // PHP will cache the results of stat() and give us stale answers
    // here, unless we manually tell it otherwise!
    clearstatcache();
    // Make sure we're back at the webroot so node_load() and node_save()
    // can always find any files they (and the hooks they invoke) need.
    if (!drupal_chdir($drupal_root)) {
        return FALSE;
    }
    // If the site is using DB replication, force this node_load() to use the
    // primary database to avoid node_load() failures.
    if (function_exists('db_set_ignore_slave')) {
        db_set_ignore_slave();
    }
    // We don't want to waste too much RAM by leaving all these loaded nodes
    // in RAM, so we reset the node_load() cache each time we call it.
    $node = node_load($nid, NULL, TRUE);
    if (empty($node->nid)) {
        wd_err('node_load(@nid) failed', array('@nid' => $nid));
        return FALSE;
    }
    foreach ($files as $file_path) {
        // Compute the metadata for this file that we care about.
        $full_path = $dest_root . '/' . $file_path;
        $file_name = basename($file_path);
        $file_date = filemtime($full_path);
        $file_size = filesize($full_path);
        $file_hash = md5_file($full_path);
        $file_mime = file_get_mimetype($full_path);
        // First, see if we already have this file for this release node
        $file_data = db_fetch_object(db_query("SELECT prf.* FROM {project_release_file} prf INNER JOIN {files} f ON prf.fid = f.fid WHERE prf.nid = %d AND f.filename = '%s'", $node->nid, $file_name));
        // Insert or update the record in the DB as need.
        if (empty($file_data)) {
            // Don't have this file, insert a new record.
            db_query("INSERT INTO {files} (uid, filename, filepath, filemime, filesize, status, timestamp) VALUES (%d, '%s', '%s', '%s', %d, %d, %d)", $node->uid, $file_name, $file_path, $file_mime, $file_size, FILE_STATUS_PERMANENT, $file_date);
            $fid = db_last_insert_id('files', 'fid');
            db_query("INSERT INTO {project_release_file} (fid, nid, filehash) VALUES (%d, %d, '%s')", $fid, $node->nid, $file_hash);
        } else {
            // Already have this file for this release, update it.
            db_query("UPDATE {files} SET uid = %d, filename = '%s', filepath = '%s', filemime = '%s', filesize = %d, status = %d, timestamp = %d WHERE fid = %d", $node->uid, $file_name, $file_path, $file_mime, $file_size, FILE_STATUS_PERMANENT, $file_date, $file_data->fid);
            db_query("UPDATE {project_release_file} SET filehash = '%s' WHERE fid = %d", $file_hash, $file_data->fid);
        }
    }
    // Store package contents if necessary.
    if (!empty($package_contents) && module_exists('project_package')) {
        foreach ($package_contents as $item_nid) {
            db_query("INSERT INTO {project_package_local_release_item} (package_nid, item_nid) VALUES (%d, %d)", $nid, $item_nid);
        }
    }
    // Don't auto-publish security updates.
    $security_update_tid = variable_get('project_release_security_update_tid', 0);
    if ($task == 'tag' && !empty($node->taxonomy[$security_update_tid])) {
        watchdog('package_security', 'Not auto-publishing security update release.', array(), WATCHDOG_NOTICE, l(t('view'), 'node/' . $node->nid));
        return;
    }
    // Finally publish the node if it is currently unpublished. Instead of
    // directly updating {node}.status, we use node_save() so that other modules
    // which implement hook_nodeapi() will know that this node is now published.
    if (empty($node->status)) {
        $node->status = 1;
        node_save($node);
    }
}
Example #17
0
 /**
  * Saves the service, either updating an existing database record or creating
  * a new one.
  */
 public function save()
 {
     if ($this->sid > 0) {
         drupal_write_record(self::$table, $this, array('sid'));
     } else {
         drupal_write_record(self::$table, $this);
         // Get the new SID
         $this->sid = db_last_insert_id(self::$table, 'sid');
     }
 }
/**
 * Update the DB with the new file info for a given release node.
 *
 * @todo This assumes 1:1 relationship of release nodes to files.
 */
function package_release_update_node($nid, $file_path)
{
    global $dest_root, $task;
    $full_path = $dest_root . '/' . $file_path;
    // PHP will cache the results of stat() and give us stale answers
    // here, unless we manually tell it otherwise!
    clearstatcache();
    // Now that we have the official file, compute some metadata:
    $file_name = basename($file_path);
    $file_date = filemtime($full_path);
    $file_size = filesize($full_path);
    $file_hash = md5_file($full_path);
    $file_mime = file_get_mimetype($full_path);
    $uid = db_result(db_query("SELECT n.uid FROM {node} n WHERE n.nid = %d", $nid));
    // Finally, save this file to the DB.
    // First, see if we already have a file for this release node
    $file_data = db_fetch_object(db_query("SELECT * FROM {project_release_file} WHERE nid = %d  GROUP BY nid ORDER BY fid DESC", $nid));
    if (empty($file_data)) {
        // Don't have an file data for this release, insert a new record.
        db_query("INSERT INTO {files} (uid, filename, filepath, filemime, filesize, status, timestamp) VALUES (%d, '%s', '%s', '%s', %d, %d, %d)", $uid, $file_name, $file_path, $file_mime, $file_size, FILE_STATUS_PERMANENT, $file_date);
        $fid = db_last_insert_id('files', 'fid');
        db_query("INSERT INTO {project_release_file} (fid, nid, filehash) VALUES (%d, %d, '%s')", $fid, $nid, $file_hash);
    } else {
        // Already have a file for this release, update it.
        db_query("UPDATE {files} SET uid = %d, filename = '%s', filepath = '%s', filemime = '%s', filesize = %d, status = %d, timestamp = %d WHERE fid = %d", $uid, $file_name, $file_path, $file_mime, $file_size, FILE_STATUS_PERMANENT, $file_date, $file_data->fid);
        db_query("UPDATE {project_release_file} SET filehash = '%s' WHERE fid = %d", $file_hash, $file_data->fid);
    }
    // Don't auto-publish security updates.
    if ($task == 'tag' && db_result(db_query("SELECT COUNT(*) FROM {term_node} WHERE nid = %d AND tid = %d", $nid, SECURITY_UPDATE_TID))) {
        watchdog('package_security', "Not auto-publishing security update release.", array(), WATCHDOG_NOTICE, l(t('view'), 'node/' . $nid));
        return;
    }
    // Finally publish the node if it is currently unpublished.  Instead of
    // directly updating {node}.status, we use node_save() so that other modules
    // which implement hook_nodeapi() will know that this node is now published.
    // However, we don't want to waste too much RAM by leaving all these loaded
    // nodes in RAM, so we reset the node_load() cache each time we call it.
    $status = db_result(db_query("SELECT status from {node} WHERE nid = %d", $nid));
    if (empty($status)) {
        // If the site is using DB replication, force this node_load() to use the
        // primary database to avoid node_load() failures.
        if (function_exists('db_set_ignore_slave')) {
            db_set_ignore_slave();
        }
        $node = node_load($nid, NULL, TRUE);
        if (!empty($node->nid)) {
            $node->status = 1;
            node_save($node);
        } else {
            wd_err('node_load(@nid) failed', array('@nid' => $nid));
        }
    }
}
Example #19
0
 public static function GiveItem($item_id, $targets, $debug = FALSE)
 {
     require_once drupal_get_path('module', 'os_poker') . "/scheduler.class.php";
     require_once drupal_get_path('module', 'os_poker') . "/user.class.php";
     $user = CUserManager::instance()->CurrentUser();
     try {
         if (!is_array($targets) || count($targets) == 0) {
             throw new Exception(t('Bad parameter: !cause', array('!cause' => is_array($targets) ? t('$target is empty') : t('$targer is not an array'))));
         }
         $rawTargets = CUserManager::instance()->UserList($targets);
         $targets = array_filter($rawTargets, "_os_poker_user_accepts_gifts");
         $ntargets = count($targets);
         if ($ntargets == 0) {
             throw new Exception(t('No one of targets accepts gifts'));
         }
         $item = new CItem($item_id);
         //check if the item really exists
         /*
          ** User must pay !
          */
         $nchips = $user->Chips();
         $price = $item->price * $ntargets;
         if (bccomp($nchips, $price) < 0) {
             throw new Exception(t('User doesn\'t have enough money (!uc vs !cn needed).', array('!uc' => $nchips, '!cn' => $price)));
         }
         $sql = "INSERT INTO `{poker_operation}`\n\t\t\t\t   (`id_item`, `uid`, `source_uid`, `tstamp`)\n\t\t\t\t   VALUES ";
         foreach ($targets as $target) {
             $fields[] = "(%d, %d, %d, %s)";
             $values[] = $item->id_item;
             $values[] = $target->uid;
             $values[] = $user->uid;
             $values[] = "NOW()";
         }
         $sql .= implode(", ", $fields);
         $res = db_query($sql, $values);
         if ($res == FALSE) {
             throw new Exception(t('DB error : !message', array("!message" => db_error())));
         }
         /*
          ** Expiry
          */
         $operation_id = db_last_insert_id("{poker_operation}", "id_operation");
         $ttl = $item->ttl;
         if ($operation_id && !empty($ttl)) {
             //$operation_id -= (count($targets) - 1);
             foreach ($targets as $target) {
                 $gift = array('item' => $item->name, 'receiver' => $target->uid, 'sender' => $user->uid);
                 if ($target->ActiveItem() <= 0) {
                     $target->ActivateItem($operation_id, $gift);
                 } else {
                     //Send gift notification, even if the item is not activated
                     foreach ($target->Tables() as $table) {
                         foreach (CPoker::UsersAtTable($table->serial) as $notified_uid) {
                             CScheduler::instance()->RegisterTask(new CGiftNotificationMessage(), $notified_uid, array('live'), "-1 day", $gift);
                         }
                     }
                 }
                 CScheduler::instance()->RegisterTask(new CItemExpiry(), $target->uid, 'live', $ttl, array("id_operation" => $operation_id));
                 ++$operation_id;
                 $args["symbol"] = $item->picture;
                 $args["text"] = t("You just receive a !gift from !user", array("!gift" => substr($item->name, 0, 30), "!user" => $user->profile_nickname));
                 if (_os_poker_user_accepts_gifts($user)) {
                     $args["links"] = l(t("Send a gift in return"), "poker/shop/shop/1/buddy/" . $user->uid);
                 }
                 CMessageSpool::instance()->SendMessage($target->uid, $args);
             }
         }
         /*
          ** User must pay !
          */
         $user->SubChips($price);
         $user->Save();
     } catch (Exception $e) {
         if ($debug == TRUE) {
             throw $e;
         }
         return FALSE;
     }
     return TRUE;
 }
 /**
  * Save data into database
  *
  * @param void
  * @return integer or false
  */
 function doSave()
 {
     $is_new = $this->isNew();
     // Insert...
     if ($is_new) {
         event_trigger('on_before_object_insert', array('object' => &$this));
         $sql = $this->getInsertSQL();
         $save = db_execute($sql);
         // Success...
         if ($save && !is_error($save)) {
             if ($this->auto_increment !== null && (!isset($this->values[$this->auto_increment]) || !$this->values[$this->auto_increment])) {
                 $this->values[$this->auto_increment] = db_last_insert_id();
             }
             // if
             $this->resetModifiedFlags();
             $this->setLoaded(true);
             event_trigger('on_object_inserted', array('object' => &$this));
             return true;
         } else {
             return $save;
         }
         // if
         // Update...
     } else {
         event_trigger('on_before_object_update', array('object' => &$this));
         $sql = $this->getUpdateSQL();
         if (is_null($sql)) {
             return true;
         }
         // if
         $save = db_execute($sql);
         if ($save && !is_error($save)) {
             $this->resetModifiedFlags();
             $this->setLoaded(true);
             event_trigger('on_object_updated', array('object' => &$this));
             return true;
         }
         // if
         return $save;
     }
     // if
 }
Example #21
0
 /**
  * Override comment_save() core Drupal function.
  * Skip user access function during the importing.
  *
  * @global stdClass $user
  * @param array $edit
  * @return int/bool The created commentID or FALSE.
  */
 protected function comment_save($edit)
 {
     global $user;
     if (!form_get_errors()) {
         $edit += array('mail' => '', 'homepage' => '', 'name' => '', 'status' => user_access('post comments without approval') ? COMMENT_PUBLISHED : COMMENT_NOT_PUBLISHED);
         if ($edit['cid']) {
             // Update the comment in the database.
             db_query("UPDATE {comments} SET status = %d, timestamp = %d, subject = '%s', comment = '%s', format = %d, uid = %d, name = '%s', mail = '%s', homepage = '%s' WHERE cid = %d", $edit['status'], $edit['timestamp'], $edit['subject'], $edit['comment'], $edit['format'], $edit['uid'], $edit['name'], $edit['mail'], $edit['homepage'], $edit['cid']);
             // Allow modules to respond to the updating of a comment.
             comment_invoke_comment($edit, 'update');
             // Add an entry to the watchdog log.
             watchdog('content', 'Comment: updated %subject.', array('%subject' => $edit['subject']), WATCHDOG_NOTICE, l(t('view'), 'node/' . $edit['nid'], array('fragment' => 'comment-' . $edit['cid'])));
         } else {
             // Add the comment to database.
             // Here we are building the thread field. See the documentation for
             // comment_render().
             if ($edit['pid'] == 0) {
                 // This is a comment with no parent comment (depth 0): we start
                 // by retrieving the maximum thread level.
                 $max = db_result(db_query('SELECT MAX(thread) FROM {comments} WHERE nid = %d', $edit['nid']));
                 // Strip the "/" from the end of the thread.
                 $max = rtrim($max, '/');
                 // Finally, build the thread field for this new comment.
                 $thread = int2vancode(vancode2int($max) + 1) . '/';
             } else {
                 // This is comment with a parent comment: we increase
                 // the part of the thread value at the proper depth.
                 // Get the parent comment:
                 $parent = _comment_load($edit['pid']);
                 // Strip the "/" from the end of the parent thread.
                 $parent->thread = (string) rtrim((string) $parent->thread, '/');
                 // Get the max value in _this_ thread.
                 $max = db_result(db_query("SELECT MAX(thread) FROM {comments} WHERE thread LIKE '%s.%%' AND nid = %d", $parent->thread, $edit['nid']));
                 if ($max == '') {
                     // First child of this parent.
                     $thread = $parent->thread . '.' . int2vancode(0) . '/';
                 } else {
                     // Strip the "/" at the end of the thread.
                     $max = rtrim($max, '/');
                     // We need to get the value at the correct depth.
                     $parts = explode('.', $max);
                     $parent_depth = count(explode('.', $parent->thread));
                     $last = $parts[$parent_depth];
                     // Finally, build the thread field for this new comment.
                     $thread = $parent->thread . '.' . int2vancode(vancode2int($last) + 1) . '/';
                 }
             }
             if (empty($edit['timestamp'])) {
                 $edit['timestamp'] = time();
             }
             if ($edit['uid'] === $user->uid && isset($user->name)) {
                 // '===' Need to modify anonymous users as well.
                 $edit['name'] = $user->name;
             }
             db_query("INSERT INTO {comments} (nid, pid, uid, subject, comment, format, hostname, timestamp, status, thread, name, mail, homepage) VALUES (%d, %d, %d, '%s', '%s', %d, '%s', %d, %d, '%s', '%s', '%s', '%s')", $edit['nid'], $edit['pid'], $edit['uid'], $edit['subject'], $edit['comment'], $edit['format'], ip_address(), $edit['timestamp'], $edit['status'], $thread, $edit['name'], $edit['mail'], $edit['homepage']);
             $edit['cid'] = db_last_insert_id('comments', 'cid');
             // Tell the other modules a new comment has been submitted.
             comment_invoke_comment($edit, 'insert');
             // Add an entry to the watchdog log.
             watchdog('content', 'Comment: added %subject.', array('%subject' => $edit['subject']), WATCHDOG_NOTICE, l(t('view'), 'node/' . $edit['nid'], array('fragment' => 'comment-' . $edit['cid'])));
         }
         _comment_update_node_statistics($edit['nid']);
         // Clear the cache so an anonymous user can see his comment being added.
         cache_clear_all();
         // Explain the approval queue if necessary, and then
         // redirect the user to the node he's commenting on.
         if ($edit['status'] == COMMENT_NOT_PUBLISHED) {
             drupal_set_message(t('Your comment has been queued for moderation by site administrators and will be published after approval.'));
         } else {
             comment_invoke_comment($edit, 'publish');
         }
         return $edit['cid'];
     } else {
         return FALSE;
     }
 }
Example #22
0
 private function _addItem()
 {
     $params = array();
     // Must be an admin to add items
     if (!$this->admin) {
         return $this->_result(false, "Must be an admin to add items (/items/add)", false);
     }
     // Check for 'name' parameter
     $name = false;
     if (array_key_exists("name", $this->request)) {
         $name = $this->_sanitizeString($this->request["name"]);
         $params["name"] = $name;
     } else {
         return $this->_result(false, "Missing parameter 'name' (/items/add)", false);
     }
     // Check for 'price' parameter
     $price = false;
     if (array_key_exists("price", $this->request)) {
         $price = $this->_sanitizeInt($this->request["price"]);
         if ($price < 0) {
             $price = $price * -1;
         }
         $params["price"] = $price;
     } else {
         return $this->_result(false, "Missing parameter 'price' (/items/add)", false);
     }
     // Form the SQL query
     $sql = "INSERT INTO drink_items (item_name, item_price) VALUES (:name, :price)";
     // Query the database
     $query = db_insert($sql, $params);
     if ($query !== false) {
         // Log price changes to the database
         $item_id = db_last_insert_id();
         $sql = "INSERT INTO drink_item_price_history (item_id, item_price) VALUES (:itemId, :price)";
         $params = array();
         $params["itemId"] = $item_id;
         $params["price"] = $price;
         db_insert($sql, $params);
         return $this->_result(true, "Success (/items/add)", (int) $item_id);
     } else {
         return $this->_result(false, "Failed to query database (/items/add)", false);
     }
 }
/** execute the necessary SQL-code for an INSERT INTO statement and return the last_insert_id
 *
 * This excutes the SQL-statement created by {@link db_insert_into_sql()}.
 * If all goes well, the value of the last inserted id is returned.
 *
 * @param string $tablename the name of the table to insert into (without prefix)
 * @param array $fields an associative array with fieldnames and fieldvalues
 * @param string $key_fieldname the name of the field that holds the primary key/serial
 * @return bool FALSE on error, last_insert_id on success
 * @uses $DB
 */
function db_insert_into_and_get_id($tablename, $fields, $key_fieldname = '')
{
    global $DB;
    $retval = $DB->exec(db_insert_into_sql($tablename, $fields));
    if ($retval !== FALSE && $retval == 1) {
        $retval = db_last_insert_id($tablename, $key_fieldname);
    }
    return $retval;
}