Ejemplo n.º 1
0
 /**
  * An easy way to save a comment against an object
  * @param <DbObject> $object
  * @param <String> $message
  */
 public function addComment($object, $message)
 {
     $comment = new Comment($this->w);
     $comment->obj_table = $object->getDbTableName();
     $comment->obj_id = $object->id;
     $comment->comment = strip_tags($message);
     $comment->insert();
 }
Ejemplo n.º 2
0
 function insert($force_validation = false)
 {
     parent::insert();
     $this->w->ctx('comment_id', $this->id);
     if (!$this->is_system) {
         //$notifier = new TaskNotifier($this->w);
         //$notifier->notify(null,'comment');
     }
 }
Ejemplo n.º 3
0
 /**
  * Tests the getPaste's 'delete-comment' action
  */
 public function testGetPasteDeleteComment()
 {
     $this->initTestStep();
     $paste = Paste::createNew('web', array('title' => 'UnitTest::Title', 'data' => 'UnitTest::Data', 'language' => 'text'));
     Comment::insert(array('paste_id' => $paste->id, 'data' => 'UnitTest::Comment', 'timestamp' => time()));
     $comment = Comment::where('paste_id', $paste->id)->first();
     $this->call('GET', "{$paste->urlkey}/{$paste->hash}/delete/{$comment->id}");
     $this->assertRedirectedTo('/');
     $this->assertEquals(Comment::where('id', $comment->id)->count(), 0);
 }
Ejemplo n.º 4
0
function ajaxSaveComment_POST(Web $w)
{
    $p = $w->pathMatch('parent_id');
    $comment = new Comment($w);
    $comment->obj_table = "comment";
    $comment->obj_id = $p['parent_id'];
    $comment->comment = strip_tags($w->request('comment'));
    $comment->insert();
    $w->setLayout(null);
    echo $w->partial("displaycomment", array("object" => $comment, 'redirect' => $w->request('redirect')), "admin");
}
 public function run()
 {
     // Initialize empty array
     $comments = array();
     // Blog Post 1 comments
     $date = new DateTime();
     $comments[] = array('user_id' => 1, 'post_id' => 1, 'content' => file_get_contents(__DIR__ . '/comment1-content.txt'), 'created_at' => $date->modify('-9 day +1 hour'), 'updated_at' => $date->modify('-9 day +1 hour'));
     $date = new DateTime();
     $comments[] = array('user_id' => 2, 'post_id' => 1, 'content' => file_get_contents(__DIR__ . '/comment2-content.txt'), 'created_at' => $date->modify('-7 day +2 hour'), 'updated_at' => $date->modify('-7 day +2 hour'));
     $date = new DateTime();
     $comments[] = array('user_id' => 1, 'post_id' => 1, 'content' => file_get_contents(__DIR__ . '/comment3-content.txt'), 'created_at' => $date->modify('-2 day +3 hour'), 'updated_at' => $date->modify('-2 day +3 hour'));
     // Blog Post 2 comments
     $date = new DateTime();
     $comments[] = array('user_id' => 1, 'post_id' => 2, 'content' => file_get_contents(__DIR__ . '/comment1-content.txt'), 'created_at' => $date->modify('-2 day +1 hour'), 'updated_at' => $date->modify('-2 day +1 hour'));
     $date = new DateTime();
     $comments[] = array('user_id' => 2, 'post_id' => 2, 'content' => file_get_contents(__DIR__ . '/comment2-content.txt'), 'created_at' => $date->modify('-1 day +2 hour'), 'updated_at' => $date->modify('-1 day +2 hour'));
     // Blog Post 3 comments
     $date = new DateTime();
     $comments[] = array('user_id' => 1, 'post_id' => 3, 'content' => file_get_contents(__DIR__ . '/comment1-content.txt'), 'created_at' => $date->modify('-1 day +1 hour'), 'updated_at' => $date->modify('-1 day +1 hour'));
     // Delete all the posts comments
     DB::table('comments')->truncate();
     // Insert the posts comments
     Comment::insert($comments);
 }
Ejemplo n.º 6
0
/**
* Submit changes to a task
*
* @ingroup pages
*/
function taskEditSubmit()
{
    global $PH;
    global $auth;
    require_once confGet('DIR_STREBER') . 'db/class_taskperson.inc.php';
    /**
     * keep a list of items linking to this task, task is new
     * we have to change the linking id after(!) inserting the task
     */
    $link_items = array();
    ### temporary object or from database? ###
    $tsk_id = getOnePassedId('tsk', '', true, 'invalid id');
    if ($tsk_id == 0) {
        $task = new Task(array('id' => 0, 'project' => get('task_project')));
        $was_category = 0;
        # undefined category for new tasks
        $was_resolved_version = 0;
    } else {
        if (!($task = Task::getVisiblebyId($tsk_id))) {
            $PH->abortWarning("invalid task-id");
        }
        $was_category = $task->category;
        $was_resolved_version = $task->resolved_version;
        $task->validateEditRequestTime();
    }
    ### cancel? ###
    if (get('form_do_cancel')) {
        if (!$PH->showFromPage()) {
            $PH->show('taskView', array('tsk' => $task->id));
        }
        exit;
    }
    ### Validate integrety ###
    if (!validateFormCrc()) {
        $PH->abortWarning(__('Invalid checksum for hidden form elements'));
    }
    validateFormCaptcha(true);
    $was_a_folder = $task->category == TCATEGORY_FOLDER ? true : false;
    $was_released_as = $task->is_released;
    ### get project ###
    if (!($project = Project::getVisiblebyId($task->project))) {
        $PH->abortWarning("task without project?");
    }
    /**
     * adding comment (from quick edit) does only require view right...
     */
    $added_comment = false;
    ### check for request feedback
    if ($request_feedback = get('request_feedback')) {
        $team_members_by_nickname = array();
        foreach ($project->getProjectPeople() as $pp) {
            $team_members_by_nickname[$pp->getPerson()->nickname] = $pp->getPerson();
        }
        $requested_people = array();
        foreach (explode('\\s*,\\s*', $request_feedback) as $nickname) {
            ### now check if this nickname is a team member
            if ($nickname = trim($nickname)) {
                if (isset($team_members_by_nickname[$nickname])) {
                    $person = $team_members_by_nickname[$nickname];
                    ### update to itemperson table...
                    if ($view = ItemPerson::getAll(array('person' => $person->id, 'item' => $task->id))) {
                        $view[0]->feedback_requested_by = $auth->cur_user->id;
                        $view[0]->update();
                    } else {
                        $new_view = new ItemPerson(array('item' => $task->id, 'person' => $person->id, 'feedback_requested_by' => $auth->cur_user->id));
                        $new_view->insert();
                    }
                    $requested_people[] = "<b>" . asHtml($nickname) . "</b>";
                } else {
                    new FeedbackWarning(sprintf(__("Nickname not known in this project: %s"), "<b>" . asHtml($nickname) . "</b>"));
                }
            }
        }
        if ($requested_people) {
            new FeedbackMessage(sprintf(__('Requested feedback from: %s.'), join($requested_people, ", ")));
        }
    }
    ### only insert the comment, when comment name or description are valid
    if (get('comment_name') || get('comment_description')) {
        require_once confGet('DIR_STREBER') . 'pages/comment.inc.php';
        $valid_comment = true;
        ### new object? ###
        $comment = new Comment(array('name' => get('comment_name'), 'description' => get('comment_description'), 'project' => $task->project, 'task' => $task->id));
        validateNotSpam($comment->name . $comment->description);
        ### write to db ###
        if ($valid_comment) {
            if (!$comment->insert()) {
                new FeedbackWarning(__("Failed to add comment"));
            } else {
                ### change task update modification date ###
                if (isset($task)) {
                    ### Check if now longer new ###
                    if ($task->status == STATUS_NEW) {
                        global $auth;
                        if ($task->created < $auth->cur_user->last_login) {
                            $task->status = STATUS_OPEN;
                        }
                    }
                    $task->update(array('modified', 'status'));
                }
                $added_comment = true;
            }
        }
    }
    if ($task->id != 0 && !Task::getEditableById($task->id)) {
        if ($added_comment) {
            ### display taskView ####
            if (!$PH->showFromPage()) {
                $PH->show('home', array());
            }
            exit;
        } else {
            $PH->abortWarning(__("Not enough rights to edit task"));
        }
    }
    $task->validateEditRequestTime();
    $status_old = $task->status;
    # retrieve all possible values from post-data (with field->view_in_forms == true)
    # NOTE:
    # - this could be an security-issue.
    # @@@ TODO: as some kind of form-edit-behaviour to field-definition
    foreach ($task->fields as $f) {
        $name = $f->name;
        $f->parseForm($task);
    }
    $task->fields['parent_task']->parseForm($task);
    ### category ###
    $was_of_category = $task->category;
    if (!is_null($c = get('task_category'))) {
        global $g_tcategory_names;
        if (isset($g_tcategory_names[$c])) {
            $task->category = $c;
        } else {
            trigger_error("ignoring unknown task category '{$c}'", E_USER_NOTICE);
        }
    }
    /**
     * @@@pixtur 2006-11-17: actually this has been depreciated. is_folder updated
     * for backward compatibility only.
     */
    $task->is_folder = $task->category == TCATEGORY_FOLDER ? 1 : 0;
    ### Check if now longer new ###
    if ($status_old == $task->status && $task->status == STATUS_NEW) {
        global $auth;
        if ($task->created < $auth->cur_user->last_login) {
            $task->status = STATUS_OPEN;
        }
    }
    $assigned_people = array();
    $task_assignments = array();
    if ($task->id) {
        foreach ($task->getAssignedPeople() as $p) {
            $assigned_people[$p->id] = $p;
        }
        foreach ($task->getAssignments() as $ta) {
            $task_assignments[$ta->person] = $ta;
        }
    }
    $team = array();
    foreach ($project->getPeople() as $p) {
        $team[$p->id] = $p;
    }
    $new_task_assignments = array();
    # store assigments after(!) validation
    $forwarded = 0;
    $forward_comment = '';
    $old_task_assignments = array();
    if (isset($task_assignments)) {
        foreach ($task_assignments as $id => $t_old) {
            $id_new = get('task_assigned_to_' . $id);
            $forward_state = get('task_forward_to_' . $id);
            if ($forward_state) {
                $forwarded = 1;
            } else {
                $forwarded = 0;
            }
            $forward_comment = get('task_forward_comment_to_' . $id);
            if ($id_new === NULL) {
                log_message("failure. Can't change no longer existing assigment (person-id={$id} item-id={$t_old->id})", LOG_MESSAGE_DEBUG);
                #$PH->abortWarning("failure. Can't change no longer existing assigment",ERROR_NOTE);
                continue;
            }
            if ($id == $id_new) {
                if ($tp = TaskPerson::getTaskPeople(array('person' => $id, 'task' => $task->id))) {
                    $tp[0]->forward = $forwarded;
                    $tp[0]->forward_comment = $forward_comment;
                    $old_task_assignments[] = $tp[0];
                }
                #echo " [$id] {$team[$id]->name} still assigned<br>";
                continue;
            }
            if ($id_new == 0) {
                if (!$t_old) {
                    continue;
                }
                #echo " [$id] {$team[$id]->name} unassigned<br>";
                $t_old->delete();
                continue;
            }
            #$t_new= $task_assignments[$id_new];
            $p_new = @$team[$id_new];
            if (!isset($p_new)) {
                $PH->abortWarning("failure during form-value passing", ERROR_BUG);
            }
            #echo " [$id] assignment changed from {$team[$id]->name} to {$team[$id_new]->name}<br>";
            $t_old->comment = sprintf(__("unassigned to %s", "task-assignment comment"), $team[$id_new]->name);
            $t_old->update();
            $t_old->delete();
            $new_assignment = new TaskPerson(array('person' => $team[$id_new]->id, 'task' => $task->id, 'comment' => sprintf(__("formerly assigned to %s", "task-assigment comment"), $team[$id]->name), 'project' => $project->id, 'forward' => $forwarded, 'forward_comment' => $forward_comment));
            $new_task_assignments[] = $new_assignment;
            $link_items[] = $new_assignment;
        }
    }
    ### check new assigments ###
    $count = 0;
    while ($id_new = get('task_assign_to_' . $count)) {
        $forward_state = get('task_forward_to_' . $count);
        if ($forward_state) {
            $forwarded = 1;
        } else {
            $forwarded = 0;
        }
        $forward_comment = get('task_forward_comment_to_' . $count);
        $count++;
        ### check if already assigned ###
        if (isset($task_assignments[$id_new])) {
            if ($tp = TaskPerson::getTaskPeople(array('person' => $id_new, 'task' => $task->id))) {
                $tp[0]->forward = $forwarded;
                $tp[0]->forward_comment = $forward_comment;
                $old_task_assignments[] = $tp[0];
            }
            #new FeedbackMessage(sprintf(__("task was already assigned to %s"),$team[$id_new]->name));
        } else {
            if (!isset($team[$id_new])) {
                $PH->abortWarning("unknown person id {$id_new}", ERROR_DATASTRUCTURE);
            }
            $new_assignment = new TaskPerson(array('person' => $team[$id_new]->id, 'task' => $task->id, 'comment' => "", 'project' => $project->id, 'forward' => $forwarded, 'forward_comment' => $forward_comment));
            /**
             * BUG?
             * - inserting the new assigment before sucessfully validating the
             *   task will lead to double-entries in the database.
             */
            $new_task_assignments[] = $new_assignment;
            #$new_assignment->insert();
            $link_items[] = $new_assignment;
        }
    }
    if ($task->isOfCategory(array(TCATEGORY_VERSION, TCATEGORY_MILESTONE))) {
        if ($is_released = get('task_is_released')) {
            if (!is_null($is_released)) {
                $task->is_released = $is_released;
            }
        }
    }
    ### pub level ###
    if ($pub_level = get('task_pub_level')) {
        if ($task->id) {
            if ($pub_level > $task->getValidUserSetPublicLevels()) {
                $PH->abortWarning('invalid data', ERROR_RIGHTS);
            }
        }
        #else {
        #    #@@@ check for person create rights
        #}
        $task->pub_level = $pub_level;
    }
    ### check project ###
    if ($task->id == 0) {
        if (!($task->project = get('task_project'))) {
            $PH->abortWarning("task requires project to be set");
        }
    }
    ### get parent_task ###
    $is_ok = true;
    $parent_task = NULL;
    if ($task->parent_task) {
        $parent_task = Task::getVisibleById($task->parent_task);
    }
    ### validate ###
    if (!$task->name) {
        new FeedbackWarning(__("Task requires name"));
        $task->fields['name']->required = true;
        $task->fields['name']->invalid = true;
        $is_ok = false;
    } else {
        if ($task->id == 0) {
            $other_tasks = array();
            if ($parent_task) {
                $other_tasks = Task::getAll(array('project' => $project->id, 'parent_task' => $parent_task->id, 'status_min' => STATUS_NEW, 'status_max' => STATUS_CLOSED, 'visible_only' => false));
            } else {
                $other_tasks = Task::getAll(array('project' => $project->id, 'parent_task' => 0, 'status_min' => STATUS_NEW, 'status_max' => STATUS_CLOSED, 'visible_only' => false));
            }
            foreach ($other_tasks as $ot) {
                if (!strcasecmp($task->name, $ot->name)) {
                    $is_ok = false;
                    new FeedbackWarning(sprintf(__('Task called %s already exists'), $ot->getLink(false)));
                    break;
                }
            }
        }
    }
    ### automatically close resolved tasks ###
    if ($task->resolve_reason && $task->status < STATUS_COMPLETED) {
        $task->status = STATUS_COMPLETED;
        new FeedbackMessage(sprintf(__('Because task is resolved, its status has been changed to completed.')));
    }
    ### Check if resolved tasks should be completed ###
    if ($task->resolved_version != 0 && $task->status < STATUS_COMPLETED) {
        new FeedbackWarning(sprintf(__('Task has resolved version but is not completed?')));
        $task->fields['resolved_version']->invalid = true;
        $task->fields['status']->invalid = true;
        $is_ok = false;
    }
    ### Check if completion should be 100% ###
    if ($task->status >= STATUS_COMPLETED) {
        $task->completion = 100;
    }
    ### repeat form if invalid data ###
    if (!$is_ok) {
        $PH->show('taskEdit', NULL, $task);
        exit;
    }
    #--- write to database -----------------------------------------------------------------------
    #--- be sure parent-task is folder ---
    if ($parent_task) {
        if ($parent_task->isMilestoneOrVersion()) {
            if ($parent_task->is_folder) {
                $parent_task->is_folder = 0;
                $parent_task->update(array('is_folder'), false);
            }
            $PH->abortWarning(__("Milestones may not have sub tasks"));
        } else {
            if ($parent_task->category != TCATEGORY_FOLDER) {
                $parent_task->category = TCATEGORY_FOLDER;
                $parent_task->is_folder = 1;
                if ($parent_task->update()) {
                    new FeedbackMessage(__("Turned parent task into a folder. Note, that folders are only listed in tree"));
                } else {
                    trigger_error(__("Failed, adding to parent-task"), E_USER_WARNING);
                    $PH->abortWarning(__("Failed, adding to parent-task"));
                }
            }
        }
    }
    ### ungroup child tasks? ###
    if ($was_a_folder && $task->category != TCATEGORY_FOLDER) {
        $num_subtasks = $task->ungroupSubtasks();
        # @@@ does this work???
        /**
         * note: ALSO invisible tasks should be updated, so do not check for visibility here.
         */
        $parent = Task::getById($task->parent_task);
        $parent_str = $parent ? $parent->name : __('Project');
        if ($num_subtasks) {
            new FeedbackMessage(sprintf(__("NOTICE: Ungrouped %s subtasks to <b>%s</b>"), $num_subtasks, $parent_str));
        }
    }
    if ($task->id && !get('task_issue_report')) {
        $task_issue_report = $task->issue_report;
    } else {
        if ($task->issue_report != get('task_issue_report')) {
            trigger_error("Requesting invalid issue report id for task!", E_USER_WARNING);
            $task_issue_report = get('task_issue_report');
        } else {
            $task_issue_report = 0;
        }
    }
    ### consider issue-report? ###
    #$task_issue_report= get('task_issue_report');
    if ($task->category == TCATEGORY_BUG || isset($task_issue_report) && $task_issue_report) {
        ### new report as / temporary ###
        if ($task_issue_report == 0 || $task_issue_report == -1) {
            $issue = new Issue(array('id' => 0, 'project' => $project->id, 'task' => $task->id));
            ### querry form-information ###
            foreach ($issue->fields as $f) {
                $name = $f->name;
                $f->parseForm($issue);
            }
            global $g_reproducibility_names;
            if (!is_null($rep = get('issue_reproducibility'))) {
                if (isset($g_reproducibility_names[$rep])) {
                    $issue->reproducibility = intval($rep);
                } else {
                    $issue->reproducibility = REPRODUCIBILITY_UNDEFINED;
                }
            }
            global $g_severity_names;
            if (!is_null($sev = get('issue_severity'))) {
                if (isset($g_severity_names[$sev])) {
                    $issue->severity = intval($sev);
                } else {
                    $issue->severity = SEVERITY_UNDEFINED;
                }
            }
            ### write to db ###
            if (!$issue->insert()) {
                trigger_error("Failed to insert issue to db", E_USER_WARNING);
            } else {
                $link_items[] = $issue;
                $task->issue_report = $issue->id;
            }
        } else {
            if ($issue = Issue::getById($task_issue_report)) {
                ### querry form-information ###
                foreach ($issue->fields as $f) {
                    $name = $f->name;
                    $f->parseForm($issue);
                }
                global $g_reproducibility_names;
                if (!is_null($rep = get('issue_reproducibility'))) {
                    if (isset($g_reproducibility_names[$rep])) {
                        $issue->reproducibility = intval($rep);
                    } else {
                        $issue->reproducibility = REPRODUCIBILITY_UNDEFINED;
                    }
                }
                global $g_severity_names;
                if (!is_null($sev = get('issue_severity'))) {
                    if (isset($g_severity_names[$sev])) {
                        $issue->severity = intval($sev);
                    } else {
                        $issue->severity = SEVERITY_UNDEFINED;
                    }
                }
                ### write to db ###
                if (!$issue->update()) {
                    trigger_error("Failed to write issue to DB (id={$issue->id})", E_USER_WARNING);
                }
                if ($task->issue_report != $issue->id) {
                    # additional check, actually not necessary
                    trigger_error("issue-report as invalid id ({$issue->id}). Should be ({$task->issue_report}) Please report this bug.", E_USER_WARNING);
                }
            } else {
                trigger_error("Could not get issue with id {$task->issue_report} from database", E_USER_WARNING);
            }
        }
    }
    ### write to db ###
    if ($task->id == 0) {
        $task->insert();
        ### write task-assigments ###
        foreach ($new_task_assignments as $nta) {
            $nta->insert();
        }
        ### now we now the id of the new task, link the other items
        foreach ($link_items as $i) {
            $i->task = $task->id;
            $i->update();
        }
        new FeedbackMessage(sprintf(__("Created %s %s with ID %s", "Created <type> <name> with ID <id>..."), $task->getLabel(), $task->getLink(false), $task->id));
    } else {
        ### write task-assigments ###
        foreach ($new_task_assignments as $nta) {
            $nta->insert();
        }
        foreach ($old_task_assignments as $ota) {
            $ota->update();
        }
        new FeedbackMessage(sprintf(__("Changed %s %s with ID %s", "type,link,id"), $task->getLabel(), $task->getLink(false), $task->id));
        $task->update();
        $project->update(array(), true);
    }
    ### add any recently resolved tasks if this is a just released version  ###
    if ($task->category == TCATEGORY_VERSION && $was_category != TCATEGORY_VERSION) {
        if ($resolved_tasks = Task::getAll(array('project' => $task->project, 'status_min' => 0, 'status_max' => 10, 'resolved_version' => RESOLVED_IN_NEXT_VERSION))) {
            foreach ($resolved_tasks as $rt) {
                $rt->resolved_version = $task->id;
                $rt->update(array('resolved_version'));
            }
            new FeedbackMessage(sprintf(__('Marked %s tasks to be resolved in this version.'), count($resolved_tasks)));
        }
    }
    ### notify on change ###
    $task->nowChangedByUser();
    ### create another task ###
    if (get('create_another')) {
        ### build dummy form ###
        $newtask = new Task(array('id' => 0, 'name' => __('Name'), 'project' => $task->project, 'state' => 1, 'prio' => $task->prio, 'label' => $task->label, 'parent_task' => $task->parent_task, 'for_milestone' => $task->for_milestone, 'category' => $task->category));
        $PH->show('taskEdit', array('tsk' => $newtask->id), $newtask);
    } else {
        ### go to task, if new
        if ($tsk_id == 0) {
            $PH->show('taskView', array('tsk' => $task->id));
            exit;
        } else {
            if (!$PH->showFromPage()) {
                $PH->show('home', array());
            }
        }
    }
}
Ejemplo n.º 7
0
	/**
	 * Receive a Pingback via XMLRPC
	 * @param array $params An array of XMLRPC parameters from the remote call
	 * @return string The success state of the pingback
	 */
	public function xmlrpc_pingback__ping( $params )
	{
		try {
			list( $source_uri, $target_uri )= $params;

			// This should really be done by an Habari core function
			$target_parse = InputFilter::parse_url( $target_uri );
			$target_stub = $target_parse['path'];
			$base_url = Site::get_path( 'base', true );

			if ( '/' != $base_url) {
				$target_stub = str_replace( $base_url, '', $target_stub );
			}

			$target_stub = trim( $target_stub, '/' );

			if ( strpos( $target_stub, '?' ) !== false ) {
				list( $target_stub, $query_string )= explode( '?', $target_stub );
			}

			// Can this be used as a target?
			$target_slug = URL::parse( $target_stub )->named_arg_values['slug'];

			if ( $target_slug === false ) {
				throw new XMLRPCException( 33 );
			}

			// Does the target exist?
			$target_post = Post::get( array( 'slug' => $target_slug ) );

			if ( $target_post === false ) {
				throw new XMLRPCException( 32 );
			}

			// Is comment allowed?
			if ( $target_post->info->comments_disabled ) {
				throw new XMLRPCException( 33 );
			}

			// Is this Pingback already registered?
			if ( Comments::get( array( 'post_id' => $target_post->id, 'url' => $source_uri, 'type' => Comment::PINGBACK ) )->count() > 0 ) {
				throw new XMLRPCException( 48 );
			}

			// Retrieve source contents
			try {
				$rr = new RemoteRequest( $source_uri );
				$rr->execute();
				if ( ! $rr->executed() ) {
					throw new XMLRPCException( 16 );
				}
				$source_contents = $rr->get_response_body();
				$headers = $rr->get_response_headers();
			}
			catch ( XMLRPCException $e ) {
				// catch our special type of exception and re-throw it
				throw $e;
			}
			catch ( Exception $e ) {
				throw new XMLRPCException( -32300 );
			}

			// Encoding is converted into internal encoding.
			// First, detect the source string's encoding
			$habari_encoding = strtoupper( MultiByte::hab_encoding() );
			$source_encoding = 'Windows-1252';
			// Is the charset in the headers?
			if ( isset( $headers['Content-Type'] ) && strpos( $headers['Content-Type'], 'charset' ) !== false ) {
				// This regex should be changed to meet the HTTP spec at some point
				if ( preg_match("/charset[\x09\x0A\x0C\x0D\x20]*=[\x09\x0A\x0C\x0D\x20]*('?)([A-Za-z0-9\-\_]+)\1/i", $headers['Content-Type'], $matches ) ) {
					$source_encoding = strtoupper( $matches[2] );
				}
			}
			// Can we tell the charset from the stream itself?
			else if ( ( $enc = MultiByte::detect_bom_encoding( $source_contents ) ) !== false ) {
				$source_encoding = $enc;
			}
			// Is the charset in a meta tag?
			else if ( preg_match( "/<meta[^>]+charset[\x09\x0A\x0C\x0D\x20]*=[\x09\x0A\x0C\x0D\x20]*([\"']?)([A-Za-z0-9\-\_]+)\1/i", $source_contents, $matches ) ) {
				$source_encoding = strtoupper( $matches[2] );
				if (in_array($source_encoding, array("UTF-16", "UTF-16BE", "UTF-16LE"))) {
					$source_encoding = "UTF-8";
				}
			}
			// Then, convert the string
			$ret = MultiByte::convert_encoding( $source_contents, $habari_encoding, $source_encoding );
			if ( $ret !== false ) {
				$source_contents = $ret;
			}

			// Find the page's title
			preg_match( '/<title>(.*)<\/title>/is', $source_contents, $matches );
			$source_title = $matches[1];

			// Find the reciprocal links and their context
			preg_match( '/<body[^>]*>(.+)<\/body>/is', $source_contents, $matches );
			$source_contents_filtered = preg_replace( '/\s{2,}/is', ' ', strip_tags( $matches[1], '<a>' ) );

			// Get rid of all the non-recriprocal links
			$ht = new HTMLTokenizer( trim( $source_contents_filtered ) );
			$set = $ht->parse();
			$all_links = $set->slice( 'a', array() );
			$keep_links = $set->slice( 'a', array( 'href' => $target_uri ) );
			$bad_links = array_diff( $all_links, $keep_links );
			foreach( $bad_links as $link ) {
				$link->tokenize_replace( '' );
				$set->replace_slice( $link );
			}
			$source_contents_filtered = (string)$set;

			// Get the excerpt
			if ( !preg_match( '%.{0,100}?<a[^>]*?href\\s*=\\s*("|\'|)' . $target_uri . '\\1[^>]*?'.'>(.+?)</a>.{0,100}%s', $source_contents_filtered, $source_excerpt ) ) {
				throw new XMLRPCException( 17 );
			}

			/** Sanitize Data */
			$source_excerpt = '&hellip;' . InputFilter::filter( $source_excerpt[0] ) . '&hellip;';
			$source_title = InputFilter::filter($source_title);
			$source_uri = InputFilter::filter($source_uri);

			/* Sanitize the URL */
			if (!empty($source_uri)) {
				$parsed = InputFilter::parse_url( $source_uri );
				if ( $parsed['is_relative'] ) {
					// guess if they meant to use an absolute link
					$parsed = InputFilter::parse_url( 'http://' . $source_uri );
					if ( ! $parsed['is_error'] ) {
						$source_uri = InputFilter::glue_url( $parsed );
					}
					else {
						// disallow relative URLs
						$source_uri = '';
					}
				}
				if ( $parsed['is_pseudo'] || ( $parsed['scheme'] !== 'http' && $parsed['scheme'] !== 'https' ) ) {
					// allow only http(s) URLs
					$source_uri = '';
				}
				else {
					// reconstruct the URL from the error-tolerant parsing
					// http:moeffju.net/blog/ -> http://moeffju.net/blog/
					$source_uri = InputFilter::glue_url( $parsed );
				}
			}

			// Add a new pingback comment
			$pingback = new Comment( array(
				'post_id'	=>	$target_post->id,
				'name'		=>	$source_title,
				'email'		=>	'',
				'url'		=>	$source_uri,
				'ip'		=>	Utils::get_ip(),
				'content'	=>	$source_excerpt,
				'status'	=>	Comment::STATUS_UNAPPROVED,
				'date'		=>	HabariDateTime::date_create(),
				'type' 		=> 	Comment::PINGBACK,
				) );

			$pingback->insert();

			// Respond to the Pingback
			return 'The pingback has been registered';
		}
		catch ( XMLRPCException $e ) {
			$e->output_fault_xml();
		}
	}
Ejemplo n.º 8
0
    /**
     * The plugin sink for the auth_ajax_wp_import_comments hook.
     * Responds via authenticated ajax to requests for comment importing.
     *
     * @param AjaxHandler $handler The handler that handled the request, contains $_POST info
     */
    public function action_auth_ajax_wp_import_comments($handler)
    {
        $valid_fields = array('db_name', 'db_host', 'db_user', 'db_pass', 'db_prefix', 'commentindex', 'category_import', 'utw_import');
        $inputs = array_intersect_key($_POST->getArrayCopy(), array_flip($valid_fields));
        extract($inputs);
        $wpdb = $this->wp_connect($db_host, $db_name, $db_user, $db_pass, $db_prefix);
        if ($wpdb) {
            if (!DB::in_transaction()) {
                DB::begin_transaction();
            }
            $commentcount = $wpdb->get_value("SELECT count( comment_ID ) FROM {$db_prefix}comments;");
            $min = $commentindex * IMPORT_BATCH + 1;
            $max = min(($commentindex + 1) * IMPORT_BATCH, $commentcount);
            echo "<p>Importing comments {$min}-{$max} of {$commentcount}.</p>";
            $postinfo = DB::table('postinfo');
            $post_info = DB::get_results("SELECT post_id, value FROM {$postinfo} WHERE name= 'wp_id';");
            foreach ($post_info as $info) {
                $post_map[$info->value] = $info->post_id;
            }
            $comments = $wpdb->get_results("\n\t\t\t\tSELECT\n\t\t\t\tcomment_content as content,\n\t\t\t\tcomment_author as name,\n\t\t\t\tcomment_author_email as email,\n\t\t\t\tcomment_author_url as url,\n\t\t\t\tINET_ATON( comment_author_IP ) as ip,\n\t\t\t \tcomment_approved as status,\n\t\t\t\tcomment_date as date,\n\t\t\t\tcomment_type as type,\n\t\t\t\tID as wp_post_id\n\t\t\t\tFROM {$db_prefix}comments\n\t\t\t\tINNER JOIN\n\t\t\t\t{$db_prefix}posts on ( {$db_prefix}posts.ID= {$db_prefix}comments.comment_post_ID )\n\t\t\t\tLIMIT {$min}, " . IMPORT_BATCH, array(), 'Comment');
            foreach ($comments as $comment) {
                switch ($comment->type) {
                    case 'pingback':
                        $comment->type = Comment::PINGBACK;
                        break;
                    case 'trackback':
                        $comment->type = Comment::TRACKBACK;
                        break;
                    default:
                        $comment->type = Comment::COMMENT;
                }
                $comment->content = MultiByte::convert_encoding($comment->content);
                $comment->name = MultiByte::convert_encoding($comment->name);
                $carray = $comment->to_array();
                if ($carray['ip'] == '') {
                    $carray['ip'] = 0;
                }
                switch ($carray['status']) {
                    case '0':
                        $carray['status'] = Comment::STATUS_UNAPPROVED;
                        break;
                    case '1':
                        $carray['status'] = Comment::STATUS_APPROVED;
                        break;
                    case 'spam':
                        $carray['status'] = Comment::STATUS_SPAM;
                        break;
                }
                if (isset($post_map[$carray['wp_post_id']])) {
                    $carray['post_id'] = $post_map[$carray['wp_post_id']];
                    unset($carray['wp_post_id']);
                    $c = new Comment($carray);
                    //Utils::debug( $c );
                    try {
                        $c->insert();
                    } catch (Exception $e) {
                        EventLog::log($e->getMessage(), 'err', null, null, print_r(array($c, $e), 1));
                        Session::error($e->getMessage());
                        $errors = Options::get('import_errors');
                        $errors[] = $e->getMessage();
                        Options::set('import_errors', $errors);
                    }
                }
            }
            if (DB::in_transaction()) {
                DB::commit();
            }
            if ($max < $commentcount) {
                $ajax_url = URL::get('auth_ajax', array('context' => 'wp_import_comments'));
                $commentindex++;
                $vars = Utils::addslashes(array('host' => $db_host, 'name' => $db_name, 'user' => $db_user, 'pass' => $db_pass, 'prefix' => $db_prefix));
                echo <<<WP_IMPORT_AJAX1
\t\t\t\t\t<script type="text/javascript">
\t\t\t\t\t\$( '#import_progress' ).load(
\t\t\t\t\t\t"{$ajax_url}",
\t\t\t\t\t\t{
\t\t\t\t\t\t\tdb_host: "{$vars['host']}",
\t\t\t\t\t\t\tdb_name: "{$vars['name']}",
\t\t\t\t\t\t\tdb_user: "******",
\t\t\t\t\t\t\tdb_pass: "******",
\t\t\t\t\t\t\tdb_prefix: "{$vars['prefix']}",
\t\t\t\t\t\t\tcategory_import: "{$category_import}",
\t\t\t\t\t\t\tutw_import: "{$utw_import}",
\t\t\t\t\t\t\tcommentindex: {$commentindex}
\t\t\t\t\t\t}
\t\t\t\t\t );

\t\t\t\t</script>
WP_IMPORT_AJAX1;
            } else {
                EventLog::log('Import complete from "' . $db_name . '"');
                echo '<p>' . _t('Import is complete.') . '</p>';
                $errors = Options::get('import_errors');
                if (count($errors) > 0) {
                    echo '<p>' . _t('There were errors during import:') . '</p>';
                    echo '<ul>';
                    foreach ($errors as $error) {
                        echo '<li>' . $error . '</li>';
                    }
                    echo '</ul>';
                }
            }
        } else {
            EventLog::log(sprintf(_t('Failed to import from "%s"'), $db_name), 'crit');
            Session::error($e->getMessage());
            echo '<p>' . _t('Failed to connect using the given database connection details.') . '</p>';
        }
    }
Ejemplo n.º 9
0
 public function action_auth_ajax_wp_import_comments()
 {
     // get the values post'd in
     $inputs = $_POST->filter_keys(array('db_name', 'db_host', 'db_user', 'db_pass', 'db_prefix', 'category_import', 'import_index'));
     $inputs = $inputs->getArrayCopy();
     // make sure we have all our default values
     $inputs = array_merge($this->default_values, $inputs);
     // get the wpdb
     $wpdb = $this->wp_connect($inputs['db_host'], $inputs['db_name'], $inputs['db_user'], $inputs['db_pass']);
     // if we couldn't connect, error out
     if (!$wpdb) {
         EventLog::log(_t('Failed to import from "%s"', array($inputs['db_name'])));
         Session::error(_t('Failed to import from "%s"', array($inputs['db_name'])));
         echo '<p>' . _t('Failed to connect using the given database connection details.') . '</p>';
     }
     // we connected just fine, let's get moving!
     // begin a transaction. if we error out at any point, we want to roll back to before import began
     DB::begin_transaction();
     // fetch the number of comments from the wordpress database so we can batch things up
     $num_comments = $wpdb->get_value('select count(comment_id) from ' . $inputs['db_prefix'] . 'comments');
     // figure out the LIMIT we're at
     $min = $inputs['import_index'] * IMPORT_BATCH;
     $max = min($min + IMPORT_BATCH, $num_comments);
     // for display only
     echo '<p>' . _t('Importing comments %1$d - %2$d of %3$d.', array($min, $max, $num_comments)) . '</p>';
     // get all the imported users so we can link old comment authors to new comment authors
     $users = DB::get_results('select user_id, value from {userinfo} where name = :name', array(':name' => 'wp_id'));
     // create an easy user map of old ID -> new ID
     $user_map = array();
     foreach ($users as $info) {
         $user_map[$info->value] = $info->user_id;
     }
     // get all the imported posts so we can link old post IDs to new post IDs
     $posts = DB::get_results('select post_id, value from {postinfo} where name = :name', array(':name' => 'wp_id'));
     // create an easy post map of old ID -> new ID
     $post_map = array();
     foreach ($posts as $info) {
         $post_map[$info->value] = $info->post_id;
     }
     // get all the comment IDs we've imported so far to make sure we don't duplicate any
     $comment_map = DB::get_column('select value from {commentinfo} where name = :name', array(':name' => 'wp_id'));
     // now we're ready to start importing comments
     $comments = $wpdb->get_results('select comment_id, comment_post_id, comment_author, comment_author_email, comment_author_url, comment_author_ip, comment_date, comment_content, comment_karma, comment_approved, comment_agent, comment_type, comment_parent, user_id from ' . $inputs['db_prefix'] . 'comments order by comment_id asc limit ' . $min . ', ' . IMPORT_BATCH);
     foreach ($comments as $comment) {
         // if this post is already in the list we've imported, skip it
         if (in_array($comment->id, $comment_map)) {
             continue;
         }
         // if the post this comment belongs to is not in the list of imported posts, skip it
         if (!isset($post_map[$comment->comment_post_id])) {
             continue;
         }
         // create the new comment
         $c = new Comment(array('content' => MultiByte::convert_encoding($comment->comment_content), 'name' => MultiByte::convert_encoding($comment->comment_author), 'email' => MultiByte::convert_encoding($comment->comment_author_email), 'url' => MultiByte::convert_encoding($comment->comment_author_url), 'date' => HabariDateTime::date_create($comment->comment_date), 'post_id' => $post_map[$comment->comment_post_id]));
         // figure out the comment type
         switch ($comment->comment_type) {
             case 'pingback':
                 $c->type = Comment::type('pingback');
                 break;
             case 'trackback':
                 $c->type = Comment::type('trackback');
                 break;
             default:
             case 'comment':
                 $c->type = Comment::type('comment');
                 break;
         }
         // figure out the comment status
         switch ($comment->comment_approved) {
             case '1':
                 $c->status = Comment::status('approved');
                 break;
             case '':
             case '0':
                 $c->status = Comment::status('unapproved');
                 break;
             case 'spam':
                 $c->status = Comment::status('spam');
                 break;
             default:
                 // Comment::status() returns false if it doesn't recognize the status type
                 $status = Comment::status($comment->comment_status);
                 // store in a temp value because if you try and set ->status to an invalid value the Comment class freaks
                 if ($status == false) {
                     // we're not importing statuses we don't recognize - continue 2 to break out of the switch and the loop and continue to the next comment
                     continue 2;
                 } else {
                     $c->status = $status;
                 }
                 break;
         }
         // save the old comment ID in info
         $c->info->wp_id = $comment->comment_id;
         // save the old post ID in info
         $c->info->wp_post_id = $comment->comment_post_id;
         // save the old comment karma - but only if it is something
         if ($comment->comment_karma != '0') {
             $c->info->wp_karma = $comment->comment_karma;
         }
         // save the old comment user agent - but only if it is something
         if ($comment->comment_agent != '') {
             $c->info->wp_agent = $comment->comment_agent;
         }
         // now that we've got all the pieces in place, save the comment
         try {
             $c->insert();
         } catch (Exception $e) {
             EventLog::log($e->getMessage(), 'err');
             echo '<p class="error">' . _t('There was an error importing comment ID %d. See the EventLog for the error message.', array($comment->comment_id));
             echo '<p>' . _t('Rolling back changes&hellip;') . '</p>';
             // rollback all changes before we return so the import hasn't changed anything yet
             DB::rollback();
             // and return so they don't get AJAX to send them on to the next step
             return false;
         }
     }
     // if we've finished without an error, commit the import
     DB::commit();
     if ($max < $num_comments) {
         // if there are more posts to import
         // get the next ajax url
         $ajax_url = URL::get('auth_ajax', array('context' => 'wp_import_comments'));
         // bump the import index by one so we get a new batch next time
         $inputs['import_index']++;
     } else {
         // display the completed message!
         EventLog::log(_t('Import completed from "%s"', array($inputs['db_name'])));
         echo '<p>' . _t('Import is complete.') . '</p>';
         return;
     }
     // and spit out ajax to send them to the next step - posts!
     echo $this->get_ajax($ajax_url, $inputs);
 }
Ejemplo n.º 10
0
 public function action_mollom_fallback(SuperGlobal $handler_vars, Comment $comment)
 {
     if (!empty($handler_vars['mollom_captcha']) && !empty($comment)) {
         if (Mollom::checkCaptcha($comment->info->mollom_session_id, $handler_vars['mollom_captcha'])) {
             $comment->status = 'unapproved';
             $comment->insert();
             $anchor = '#comment-' . $comment->id;
             Utils::redirect($comment->post->permalink . $anchor);
             exit;
         } else {
             Session::error(_t('Sorry, that answer was incorrect. Please try again.', 'mollom'));
             $this->send_captcha($comment);
             exit;
         }
     } elseif (empty($comment)) {
         die(_t('Sorry, the gremlins ate your comment...', 'mollom'));
     } else {
         $this->send_captcha($comment);
         exit;
     }
 }
 /**
  * The plugin sink for the auth_ajax_hab_import_comments hook.
  * Responds via authenticated ajax to requests for comment importing.
  *
  * @param AjaxHandler $handler The handler that handled the request, contains $_POST info
  */
 public function action_auth_ajax_hab_import_comments($handler)
 {
     $inputs = $_POST->filter_keys('db_type', 'db_name', 'db_host', 'db_user', 'db_pass', 'db_prefix', 'commentindex', 'tag_import');
     $inputs = $inputs->getArrayCopy($inputs);
     $inputs = array_merge($this->default_values, $inputs);
     $connect_string = $this->get_connect_string($inputs['db_type'], $inputs['db_host'], $inputs['db_name']);
     $db = $this->hab_connect($connect_string, $inputs['db_user'], $inputs['db_pass']);
     if (!$db) {
         EventLog::log(sprintf(_t('Failed to import from "%s"'), $inputs['db_name']), 'crit');
         Session::error($e->getMessage());
         echo '<p>' . _t('Failed to connect using the given database connection details.') . '</p>';
     }
     DB::begin_transaction();
     $commentcount = $db->get_value("SELECT count( id ) FROM {$inputs['db_prefix']}comments;");
     $min = $inputs['import_index'] * IMPORT_BATCH + ($inputs['import_index'] == 0 ? 0 : 1);
     $max = min(($inputs['import_index'] + 1) * IMPORT_BATCH, $commentcount);
     echo "<p>Importing comments {$min}-{$max} of {$commentcount}.</p>";
     $post_info = DB::get_results("SELECT post_id, value FROM {$inputs['db_prefix']}postinfo WHERE name= 'old_id';");
     foreach ($post_info as $info) {
         $post_map[$info->value] = $info->post_id;
     }
     $comments = $db->get_results("\r\n\t\t\tSELECT\r\n\t\t\tc.id,\r\n\t\t\tc.content,\r\n\t\t\tc.name,\r\n\t\t\tc.email,\r\n\t\t\tc.url,\r\n\t\t\tc.ip,\r\n\t\t\tc.status,\r\n\t\t\tc.date,\r\n\t\t\tc.type,\r\n\t\t\tc.post_id as old_post_id\r\n\t\t\tFROM {$inputs['db_prefix']}comments c\r\n\t\t\tINNER JOIN\r\n\t\t\t{$inputs['db_prefix']}posts on {$inputs['db_prefix']}posts.id = c.post_id\r\n\t\t\tLIMIT {$min}, " . IMPORT_BATCH, array(), 'Comment');
     foreach ($comments as $comment) {
         $carray = $comment->to_array();
         if (isset($post_map[$carray['old_post_id']])) {
             $carray['post_id'] = $post_map[$carray['old_post_id']];
             unset($carray['old_post_id']);
             $c = new Comment($carray);
             $infos = $db->get_results("SELECT name, value, type FROM {$inputs['db_prefix']}commentinfo WHERE comment_id = ?", array($carray['id']));
             foreach ($infos as $info) {
                 $fields = $info->get_url_args();
                 if ($fields['type'] == 1) {
                     $fields['value'] = unserialize($fields['value']);
                 }
                 $c->info->{$fields}['name'] = $fields['value'];
             }
             try {
                 $c->insert();
             } catch (Exception $e) {
                 EventLog::log($e->getMessage(), 'err', null, null, print_r(array($c, $e), 1));
                 Session::error($e->getMessage());
                 $errors = Options::get('import_errors');
                 $errors[] = $e->getMessage();
                 Options::set('import_errors', $errors);
             }
         }
     }
     if (DB::in_transaction()) {
         DB::commit();
     }
     if ($max < $commentcount) {
         $ajax_url = URL::get('auth_ajax', array('context' => 'hab_import_comments'));
         $inputs['import_index']++;
         echo $this->get_ajax($ajax_url, $inputs);
     } else {
         EventLog::log('Import complete from "' . $inputs['db_name'] . '"');
         echo '<p>' . _t('Import is complete.') . '</p>';
         $errors = Options::get('import_errors');
         if (count($errors) > 0) {
             echo '<p>' . _t('There were errors during import:') . '</p>';
             echo '<ul>';
             foreach ($errors as $error) {
                 echo '<li>' . $error . '</li>';
             }
             echo '</ul>';
         }
     }
 }
Ejemplo n.º 12
0
 function newComment()
 {
     foreach ($_POST as $k => $v) {
         $_POST[$k] = trim($v);
     }
     if ($_POST['url'] == 'http://' || empty($_POST['url'])) {
         unset($_POST['url']);
     }
     //strip html tags in comment
     if (!empty($_POST['content'])) {
         $_POST['content'] = strip_tags($_POST['content']);
     }
     Doo::loadModel('Comment');
     $c = new Comment($_POST);
     $this->prepareSidebar();
     // 'skip' is same as DooValidator::CHECK_SKIP
     if ($error = $c->validate('skip')) {
         $this->data['rootUrl'] = Doo::conf()->APP_URL;
         $this->data['title'] = 'Oops! Error Occured!';
         $this->data['content'] = '<p style="color:#ff0000;">' . $error . '</p>';
         $this->data['content'] .= '<p>Go <a href="javascript:history.back();">back</a> to post.</p>';
         $this->render('error', $this->data);
     } else {
         Doo::autoload('DooDbExpression');
         $c->createtime = new DooDbExpression('NOW()');
         $c->insert();
         $this->data['rootUrl'] = Doo::conf()->APP_URL;
         $this->render('comment', $this->data);
     }
 }
Ejemplo n.º 13
0
 public function commentAction()
 {
     $label = $this->_getParam('label');
     if ($label === null) {
         throw new Zend_Exception('No label specified in PostsController::commentAction()');
     }
     $postManager = new Post();
     $post = $postManager->fetchRow(array('label = ?' => $label, 'is_active = ?' => 1));
     if ($post === null) {
         throw new Zend_Exception('No post found with that label in PostsController::commentAction()');
     }
     $this->view->post = $post;
     // form
     $form = new Zend_Form($this->_commentForm);
     $form->setAction('/posts/' . $post->label . '/comment');
     $this->view->form = $form;
     if ($this->getRequest()->isPost()) {
         if ($form->isValid($_POST)) {
             $config = Zend_Registry::get('config');
             $akismet = new Zend_Service_Akismet($config->akismet->key, 'http://codecaine.co.za');
             $akismetData = array('user_ip' => $_SERVER['REMOTE_ADDR'], 'user_agent' => $_SERVER['HTTP_USER_AGENT'], 'referrer' => $_SERVER['HTTP_REFERER'], 'permalink' => 'http://codecaine.co.za/posts/' . $post->label, 'comment_type' => 'comment', 'comment_author' => $_POST['name'], 'comment_author_email' => $_POST['email'], 'comment_author_url' => $_POST['website'], 'comment_content' => $_POST['text']);
             if ($akismet->isSpam($akismetData)) {
                 $this->_redirect('/spam');
             }
             $commentManager = new Comment();
             $data = $_POST;
             unset($data['submit']);
             $data['post_id'] = $post->id;
             $data['posted_at'] = new Zend_Db_Expr('NOW()');
             $id = $commentManager->insert($data);
             $this->_redirect('/posts/' . $post->label . '#comment-' . $id);
         }
     }
     // description
     $this->view->metaDescription = 'Post your comments on ' . $post->title;
     // set title
     $this->_title($post->title);
 }
Ejemplo n.º 14
0
 /**
  * Imports a single comment from the s9y database into the
  * habari database
  *
  * @param		comment_info		 	QueryRecord of comment information to import
  * @param		habari_post_id		ID of the post to attach the comment to
  * @return	TRUE or FALSE if import of comment succeeded
  */
 private function import_comment($comment_info = array(), $habari_post_id)
 {
     /* A mapping for s9y comment status to habari comment status codes */
     $status_map = array('APPROVED' => Comment::STATUS_APPROVED, 'PENDING' => Comment::STATUS_UNAPPROVED);
     /* A mapping for s9y comment type to habari comment type codes */
     $type_map = array('TRACKBACK' => Comment::TRACKBACK, 'NORMAL' => Comment::COMMENT);
     $comment = new Comment();
     $comment->post_id = $habari_post_id;
     $comment->info->s9y_id = $comment_info->id;
     if (!empty($comment_info->parent_id) && $comment_info->parent_id != "0") {
         $comment->info->s9y_parent_id = $comment_info->parent_id;
     }
     $comment->ip = sprintf("%u", ip2long($comment_info->ip));
     $comment->status = $status_map[strtoupper($comment_info->status)];
     $comment->type = $type_map[strtoupper($comment_info->type)];
     $comment->name = $this->transcode($comment_info->author);
     $comment->url = $comment_info->url;
     $comment->date = date('Y-m-d H:i:s', $comment_info->timestamp);
     $comment->email = $this->transcode($comment_info->email);
     $comment->content = $this->transcode($comment_info->body);
     if ($comment->insert()) {
         return TRUE;
     } else {
         EventLog::log($e->getMessage(), 'err', null, null, print_r(array($comment, $e), 1));
         Session::error($e->getMessage());
         return FALSE;
     }
 }
Ejemplo n.º 15
0
 /**
  * action: auth_ajax_mt_file_import_all
  *
  * @access public
  * @param array $handler
  */
 public function action_auth_ajax_mt_file_import_all($handler)
 {
     $text = file_get_contents($_SESSION['mtimport_mt_file']);
     try {
         $parser = new MTFileParser($text);
     } catch (Exception $e) {
         echo '<p>' . _t('Failed parsing File: ') . $e->getMessage() . '</p>';
         return;
     }
     $posts = $parser->getResult();
     @reset($posts);
     while (list(, $mt_post) = @each($posts)) {
         // Post
         $t_post = array();
         $tags = array();
         if (isset($mt_post['_META']['BASENAME'])) {
             $t_post['slug'] = $mt_post['_META']['BASENAME'];
         }
         $t_post['content_type'] = Post::type('entry');
         $t_post['title'] = strip_tags(htmlspecialchars_decode(MultiByte::convert_encoding($mt_post['_META']['TITLE'])));
         if (isset($mt_post['EXTENDED BODY']['_BODY'])) {
             $t_post['content'] = MultiByte::convert_encoding($mt_post['BODY']['_BODY'] . $mt_post['EXTENDED BODY']['_BODY']);
         } else {
             $t_post['content'] = MultiByte::convert_encoding($mt_post['BODY']['_BODY']);
         }
         if (!isset($mt_post['_META']['STATUS']) || $mt_post['_META']['STATUS'] == 'Publish') {
             $t_post['status'] = Post::status('published');
         } else {
             $t_post['status'] = Post::status('draft');
         }
         $t_post['pubdate'] = $t_post['updated'] = HabariDateTime::date_create($mt_post['_META']['DATE']);
         if (isset($mt_post['_META']['CATEGORY'])) {
             $tags = array_merge($tags, $mt_post['_META']['CATEGORY']);
         }
         if (isset($mt_post['_META']['TAGS'])) {
             $t_tags = explode(',', $mt_post['_META']['TAGS']);
             $t_tags = array_map('trim', $t_tags, array('"'));
             $tags = array_merge($tags, $t_tags);
         }
         $post = new Post($t_post);
         if (isset($mt_post['_META']['ALLOW COMMENTS']) && $mt_post['_META']['ALLOW COMMENTS'] != 1) {
             $post->info->comments_disabled = 1;
         }
         $post->tags = array_unique($tags);
         $post->user_id = User::identify()->id;
         // TODO: import MT author
         try {
             $post->insert();
         } catch (Exception $e) {
             EventLog::log($e->getMessage(), 'err', null, null, print_r(array($p, $e), 1));
             Session::error($e->getMessage());
             $errors = Options::get('import_errors');
             $errors[] = $p->title . ' : ' . $e->getMessage();
             Options::set('import_errors', $errors);
         }
         // Comments
         if (isset($mt_post['COMMENT'])) {
             @reset($mt_post['COMMENT']);
             while (list(, $mt_comment) = @each($mt_post['COMMENT'])) {
                 $t_comment = array();
                 $t_comment['post_id'] = $post->id;
                 $t_comment['name'] = MultiByte::convert_encoding($mt_comment['AUTHOR']);
                 if (isset($mt_comment['EMAIL'])) {
                     $t_comment['email'] = $mt_comment['EMAIL'];
                 }
                 if (isset($mt_comment['URL'])) {
                     $t_comment['url'] = strip_tags($mt_comment['URL']);
                 }
                 if (isset($mt_comment['IP'])) {
                     $t_comment['ip'] = $mt_comment['IP'];
                 }
                 $t_comment['content'] = MultiByte::convert_encoding($mt_comment['_BODY']);
                 $t_comment['status'] = Comment::STATUS_APPROVED;
                 $t_comment['date'] = HabariDateTime::date_create($mt_comment['DATE']);
                 $t_comment['type'] = Comment::COMMENT;
                 $comment = new Comment($t_comment);
                 try {
                     $comment->insert();
                 } catch (Exception $e) {
                     EventLog::log($e->getMessage(), 'err', null, null, print_r(array($c, $e), 1));
                     Session::error($e->getMessage());
                     $errors = Options::get('import_errors');
                     $errors[] = $e->getMessage();
                     Options::set('import_errors', $errors);
                 }
             }
         }
         // Trackbacks
         if (isset($mt_post['PING'])) {
             @reset($mt_post['PING']);
             while (list(, $mt_comment) = @each($mt_post['PING'])) {
                 $t_comment = array();
                 $t_comment['post_id'] = $post->id;
                 $t_comment['name'] = MultiByte::convert_encoding($mt_comment['BLOG NAME'] . ' - ' . $mt_comment['TITLE']);
                 if (isset($mt_comment['EMAIL'])) {
                     $t_comment['email'] = $mt_comment['EMAIL'];
                 }
                 if (isset($mt_comment['URL'])) {
                     $t_comment['url'] = strip_tags($mt_comment['URL']);
                 }
                 if (isset($mt_comment['IP'])) {
                     $t_comment['ip'] = $mt_comment['IP'];
                 }
                 $t_comment['content'] = MultiByte::convert_encoding($mt_comment['_BODY']);
                 $t_comment['status'] = Comment::STATUS_APPROVED;
                 $t_comment['date'] = HabariDateTime::date_create($mt_comment['DATE']);
                 $t_comment['type'] = Comment::TRACKBACK;
                 $comment = new Comment($t_comment);
                 try {
                     $comment->insert();
                 } catch (Exception $e) {
                     EventLog::log($e->getMessage(), 'err', null, null, print_r(array($c, $e), 1));
                     Session::error($e->getMessage());
                     $errors = Options::get('import_errors');
                     $errors[] = $e->getMessage();
                     Options::set('import_errors', $errors);
                 }
             }
         }
     }
     EventLog::log(_t('Import complete from MT Export File', 'mtimport'));
     echo '<p>' . _t('Import is complete.') . '</p>';
     $errors = Options::get('import_errors');
     if (count($errors) > 0) {
         echo '<p>' . _t('There were errors during import:') . '</p>';
         echo '<ul>';
         foreach ($errors as $error) {
             echo '<li>' . $error . '</li>';
         }
         echo '</ul>';
     }
 }
Ejemplo n.º 16
0
 $info["product"] = $pName;
 $info["version"] = $pVersion;
 $comment = new Comment($dbConnectionInfo, "", $fullUser);
 if ($info['editedId'] > 0) {
     // edit comment
     $result = $comment->update($info);
     if (isset($result['rows']) && $result['rows'] > 0) {
         echo "Comment edited !|" . $result['id'];
     } else {
         if (isset($result['rows'])) {
             echo "Comment not edited!";
         }
     }
 } else {
     // insert comment
     $result = $comment->insert($info);
     if ($result['rows'] > 0) {
         if (isset($ses->{$fullUser})) {
             $user = $ses->{$fullUser};
             $userEmail = $ses->{$fullUser}->email;
             $userName = $ses->{$fullUser}->userName;
             $name = $ses->{$fullUser}->name;
         } else {
             $user = new User($dbConnectionInfo);
             $userEmail = "";
             $userName = "******";
             $name = "noName";
         }
         $moderators = $user->getModeratorsEmails();
         $usersToNotify = $user->getUsersToNotify($info["page"], $result['id']);
         // notify moderators
Ejemplo n.º 17
0
 /**
  * test grabbing a comment by its commentText
  */
 public function testGetValidCommentByCommentText()
 {
     // count the number of rows and save it for later
     $numRows = $this->getConnection()->getRowCount("comment");
     //create a new comment and insert it into mysql
     $comment = new Comment(null, $this->trail->getTrailId(), $this->user->getUserId(), $this->VALID_BROWSER, $this->VALID_CREATEDATE, $this->VALID_IPADDRESS, $this->VALID_COMMENTPHOTO, $this->VALID_COMMENTPHOTOTYPE, $this->VALID_COMMENTTEXT);
     $comment->insert($this->getPDO());
     // grab the data from mySQL and enforce it meets expectations
     $pdoComments = Comment::getCommentByCommentText($this->getPDO(), $comment->getCommentText());
     $this->assertSame($numRows + 1, $this->getConnection()->getRowCount("comment"));
     foreach ($pdoComments as $pdoComment) {
         $this->assertSame($pdoComment->getBrowser(), $this->VALID_BROWSER);
         $this->assertEquals($pdoComment->getCreateDate(), $this->VALID_CREATEDATE);
         $this->assertSame($pdoComment->getIpAddress(), $this->VALID_IPADDRESS);
         $this->assertSame($pdoComment->getCommentPhoto(), $this->VALID_COMMENTPHOTO);
         $this->assertSame($pdoComment->getCommentPhotoType(), $this->VALID_COMMENTPHOTOTYPE);
         $this->assertSame($pdoComment->getCommentText(), $this->VALID_COMMENTTEXT);
     }
 }
Ejemplo n.º 18
0
	/**
	 * 
	 */
	public function testCommentInfo()
	{
		// make sure adding info to comment works
		$this->comment->info->test = 'test';
		$this->assertEquals( 'test', $this->comment->info->test );
		$this->comment->update();
		$test_comment = Comment::get($this->comment->id);
		$this->assertEquals( $this->comment->info->test, $test_comment->info->test );
		unset($test_comment);

		// make sure construction works with info
		$new_comment = new Comment();
		$this->assertType( 'CommentInfo', $new_comment->info );
		$this->assertFalse( $new_comment->info->is_key_set() );
		$new_comment->info->test = 'test';
		$new_comment->insert();
		$this->assertTrue( $new_comment->info->is_key_set() );
		$test_comment = Comment::get($new_comment->id);
		$this->assertEquals( $new_comment->info->test, $test_comment->info->test );
		$new_comment->delete();
		unset($test_comment);
	}
Ejemplo n.º 19
0
 public static function post(User $user, Application $app, $package_id, $message)
 {
     $sql = 'SELECT number FROM comment WHERE app_id=?ORDER BY id DESC LIMIT 1';
     $max_num = (int) mfwDBIBase::getOne($sql, array($app->getId()));
     $row = array('app_id' => $app->getId(), 'package_id' => $package_id ?: null, 'number' => $max_num + 1, 'mail' => $user->getMail(), 'message' => $message, 'created' => date('Y-m-d H:i:s'));
     $comment = new Comment($row);
     $comment->insert();
     return $comment;
 }
Ejemplo n.º 20
0
 /**
  * Receive a Pingback via XMLRPC
  * @param array $params An array of XMLRPC parameters from the remote call
  * @return string The success state of the pingback
  */
 public function xmlrpc_pingback__ping($params)
 {
     try {
         list($source_uri, $target_uri) = $params;
         // This should really be done by an Habari core function
         $target_parse = InputFilter::parse_url($target_uri);
         $target_stub = $target_parse['path'];
         $base_url = Site::get_path('base', TRUE);
         if ('/' != $base_url) {
             $target_stub = str_replace($base_url, '', $target_stub);
         }
         $target_stub = trim($target_stub, '/');
         if (strpos($target_stub, '?') !== FALSE) {
             list($target_stub, $query_string) = explode('?', $target_stub);
         }
         // Can this be used as a target?
         $target_slug = URL::parse($target_stub)->named_arg_values['slug'];
         if ($target_slug === FALSE) {
             throw new XMLRPCException(33);
         }
         // Does the target exist?
         $target_post = Post::get(array('slug' => $target_slug));
         if ($target_post === FALSE) {
             throw new XMLRPCException(32);
         }
         // Is comment allowed?
         if ($target_post->info->comments_disabled) {
             throw new XMLRPCException(33);
         }
         // Is this Pingback already registered?
         if (Comments::get(array('post_id' => $target_post->id, 'url' => $source_uri, 'type' => Comment::PINGBACK))->count() > 0) {
             throw new XMLRPCException(48);
         }
         // Retrieve source contents
         $rr = new RemoteRequest($source_uri);
         $rr->execute();
         if (!$rr->executed()) {
             throw new XMLRPCException(16);
         }
         $source_contents = $rr->get_response_body();
         // encoding is converted into internal encoding.
         // @todo check BOM at beginning of file before checking for a charset attribute
         $habari_encoding = MultiByte::hab_encoding();
         if (preg_match("/<meta[^>]+charset=([A-Za-z0-9\\-\\_]+)/i", $source_contents, $matches) !== FALSE && strtolower($habari_encoding) != strtolower($matches[1])) {
             $ret = MultiByte::convert_encoding($source_contents, $habari_encoding, $matches[1]);
             if ($ret !== FALSE) {
                 $source_contents = $ret;
             }
         }
         // Find the page's title
         preg_match('/<title>(.*)<\\/title>/is', $source_contents, $matches);
         $source_title = $matches[1];
         // Find the reciprocal links and their context
         preg_match('/<body[^>]*>(.+)<\\/body>/is', $source_contents, $matches);
         $source_contents_filtered = preg_replace('/\\s{2,}/is', ' ', strip_tags($matches[1], '<a>'));
         if (!preg_match('%.{0,100}?<a[^>]*?href\\s*=\\s*("|\'|)' . $target_uri . '\\1[^>]*?' . '>(.+?)</a>.{0,100}%s', $source_contents_filtered, $source_excerpt)) {
             throw new XMLRPCException(17);
         }
         /** Sanitize Data */
         $source_excerpt = '...' . InputFilter::filter($source_excerpt[0]) . '...';
         $source_title = InputFilter::filter($source_title);
         $source_uri = InputFilter::filter($source_uri);
         /* Sanitize the URL */
         if (!empty($source_uri)) {
             $parsed = InputFilter::parse_url($source_uri);
             if ($parsed['is_relative']) {
                 // guess if they meant to use an absolute link
                 $parsed = InputFilter::parse_url('http://' . $source_uri);
                 if (!$parsed['is_error']) {
                     $source_uri = InputFilter::glue_url($parsed);
                 } else {
                     // disallow relative URLs
                     $source_uri = '';
                 }
             }
             if ($parsed['is_pseudo'] || $parsed['scheme'] !== 'http' && $parsed['scheme'] !== 'https') {
                 // allow only http(s) URLs
                 $source_uri = '';
             } else {
                 // reconstruct the URL from the error-tolerant parsing
                 // http:moeffju.net/blog/ -> http://moeffju.net/blog/
                 $source_uri = InputFilter::glue_url($parsed);
             }
         }
         // Add a new pingback comment
         $pingback = new Comment(array('post_id' => $target_post->id, 'name' => $source_title, 'email' => '', 'url' => $source_uri, 'ip' => sprintf("%u", ip2long($_SERVER['REMOTE_ADDR'])), 'content' => $source_excerpt, 'status' => Comment::STATUS_UNAPPROVED, 'date' => HabariDateTime::date_create(), 'type' => Comment::PINGBACK));
         $pingback->insert();
         // Respond to the Pingback
         return 'The pingback has been registered';
     } catch (XMLRPCException $e) {
         $e->output_fault_xml();
     }
 }
    /**
     * The plugin sink for the auth_ajax_drupal_import_comments hook.
     * Responds via authenticated ajax to requests for comment importing.
     *
     * @param AjaxHandler $handler The handler that handled the request, contains $_POST info
     */
    public function action_auth_ajax_drupal_import_comments($handler)
    {
        $valid_fields = array('db_name', 'db_host', 'db_user', 'db_pass', 'db_prefix', 'import_comments', 'commentindex', 'entry_type', 'page_type', 'tag_vocab');
        $inputs = array_intersect_key($_POST->getArrayCopy(), array_flip($valid_fields));
        extract($inputs);
        $drupaldb = $this->drupal_connect($db_host, $db_name, $db_user, $db_pass, $db_prefix);
        if ($drupaldb) {
            $commentcount = $drupaldb->get_value("SELECT count( c.cid ) FROM {$db_prefix}comments AS c INNER JOIN {$db_prefix}node AS n ON (n.nid = c.nid) WHERE n.type IN ('{$entry_type}', '{$page_type}')");
            $min = $commentindex * DRUPAL_IMPORT_BATCH + 1;
            $max = min(($commentindex + 1) * DRUPAL_IMPORT_BATCH, $commentcount);
            echo "<p>Importing comments {$min}-{$max} of {$commentcount}.</p>";
            $postinfo = DB::table('postinfo');
            $post_info = DB::get_results("SELECT post_id, value FROM {$postinfo} WHERE name= 'drupal_nid';");
            foreach ($post_info as $info) {
                $post_map[$info->value] = $info->post_id;
            }
            if ($import_comments) {
                $comments = $drupaldb->get_results("\n\t\t\t\t\tSELECT\n\t\t\t\t\t\tc.nid as drupal_post_nid,\n\t\t\t\t\t\tc.comment as content,\n\t\t\t\t\t\tc.name,\n\t\t\t\t\t\tc.mail as email,\n\t\t\t\t\t\tc.homepage as url,\n\t\t\t\t\t\tINET_ATON( c.hostname ) as ip,\n\t\t\t\t\t\tc.status,\n\t\t\t\t\t\tFROM_UNIXTIME( c.timestamp ) as date\n\t\t\t\t\tFROM {$db_prefix}comments AS c\n\t\t\t\t\tINNER JOIN {$db_prefix}node AS n on ( n.nid = c.nid )\n\t\t\t\t\tLIMIT {$min}, " . DRUPAL_IMPORT_BATCH, array(), 'Comment');
            } else {
                $comments = array();
            }
            foreach ($comments as $comment) {
                $comment->type = Comment::COMMENT;
                $comment->status = $comment->status == '0' ? 1 : 0;
                $comment->content = MultiByte::convert_encoding($comment->content);
                $comment->name = MultiByte::convert_encoding($comment->name);
                $carray = $comment->to_array();
                if ($carray['ip'] == '') {
                    $carray['ip'] = 0;
                }
                if (!isset($post_map[$carray['drupal_post_nid']])) {
                    Utils::debug($carray);
                } else {
                    $carray['post_id'] = $post_map[$carray['drupal_post_nid']];
                    unset($carray['drupal_post_nid']);
                    $c = new Comment($carray);
                    //Utils::debug( $c );
                    try {
                        $c->insert();
                    } catch (Exception $e) {
                        EventLog::log($e->getMessage(), 'err', null, null, print_r(array($c, $e), 1));
                        $errors = Options::get('import_errors');
                        $errors[] = $e->getMessage();
                        Options::set('import_errors', $errors);
                    }
                }
            }
            if ($max < $commentcount) {
                $ajax_url = URL::get('auth_ajax', array('context' => 'drupal_import_comments'));
                $commentindex++;
                echo <<<DRUPAL_IMPORT_AJAX1
\t\t\t\t\t<script type="text/javascript">
\t\t\t\t\t\$( '#import_progress' ).load(
\t\t\t\t\t\t"{$ajax_url}",
\t\t\t\t\t\t{
\t\t\t\t\t\t\tdb_host: "{$db_host}",
\t\t\t\t\t\t\tdb_name: "{$db_name}",
\t\t\t\t\t\t\tdb_user: "******",
\t\t\t\t\t\t\tdb_pass: "******",
\t\t\t\t\t\t\tdb_prefix: "{$db_prefix}",
\t\t\t\t\t\t\timport_comments: "{$import_comments}",
\t\t\t\t\t\t\tentry_type: "{$entry_type}",
\t\t\t\t\t\t\tpage_type: "{$page_type}",
\t\t\t\t\t\t\ttag_vocab: "{$tag_vocab}",
\t\t\t\t\t\t\tcommentindex: {$commentindex}
\t\t\t\t\t\t}
\t\t\t\t\t );

\t\t\t\t</script>
DRUPAL_IMPORT_AJAX1;
            } else {
                EventLog::log('Import complete from "' . $db_name . '"');
                echo '<p>' . _t('Import is complete.') . '</p>';
                $errors = Options::get('import_errors');
                if (count($errors) > 0) {
                    echo '<p>' . _t('There were errors during import:') . '</p>';
                    echo '<ul>';
                    foreach ($errors as $error) {
                        echo '<li>' . $error . '</li>';
                    }
                    echo '</ul>';
                }
            }
        } else {
            EventLog::log(sprintf(_t('Failed to import from "%s"'), $db_name), 'crit');
            echo '<p>' . _t('Failed to connect using the given database connection details.') . '</p>';
        }
    }
Ejemplo n.º 22
0
            // perform the actual put or post
            if ($method === "PUT") {
                $comment = Comment::getCommentByCommentId($pdo, $commentId);
                if ($comment === null) {
                    throw new RuntimeException("Comment does not exist", 404);
                }
                if ($_SESSION["user"] !== "S" && $_SESSION["user"]->getUserId() !== $comment->getUserId()) {
                    throw new RuntimeException("You may only edit your own comments", 403);
                }
                // trailId, userId, browser, createDate, ipAddress, commentPhoto, commentPhotoType, commentText
                $comment = new Comment($commentId, $comment->getTrailId(), $comment->getUserId(), $comment->getBrowser(), $comment->getCreateDate(), $comment->getIpAddress(), $requestObject->commentPhoto, $requestObject->commentPhotoType, $requestObject->commentText);
                $comment->update($pdo);
                $reply->message = "Comment updated OK";
            } elseif ($method === "POST") {
                $comment = new Comment(null, $requestObject->trailId, $_SESSION["user"]->getUserId(), $browser, new DateTime(), $ipAddress, $requestObject->commentPhoto, $requestObject->commentPhotoType, $requestObject->commentText);
                $comment->insert($pdo);
                $reply->message = "Comment created OK";
            }
        } elseif ($method === "DELETE") {
            verifyXsrf();
            $comment = Comment::getCommentByCommentId($pdo, $commentId);
            if ($comment === null) {
                throw new RuntimeException("Comment does not exist", 404);
            }
            $comment->delete($pdo);
            $reply->message = "Comment deleted OK";
        }
    }
} catch (Exception $exception) {
    $reply->status = $exception->getCode();
    $reply->message = $exception->getMessage();
 /**
  * action: auth_ajax_blogger_import_all
  *
  * @access public
  * @param array $handler
  */
 public function action_auth_ajax_blogger_import_all($handler)
 {
     $feed = simplexml_load_file($_SESSION['bloggerimport_file']);
     if (!$feed) {
         echo '<p>' . _t('Failed parsing File', 'bloggerimport') . '</p>';
         return;
     }
     $post_id_map = array();
     $post_map = array();
     $result = DB::get_results("SELECT post_id,value FROM " . DB::table('postinfo') . " WHERE name='blogger_id';");
     for ($i = 0; $i < count($result); $i++) {
         $post_id_map[$result[$i]->value] = $result[$i]->post_id;
         $post_map[] = $result[$i]->value;
     }
     $comment_map = DB::get_column("SELECT value FROM " . DB::table('commentinfo') . " WHERE name='blogger_id';");
     $entry_count = count($feed->entry);
     for ($i = 0; $i < $entry_count; $i++) {
         $entry = $feed->entry[$i];
         switch ((string) $entry->category[0]['term']) {
             // post
             case 'http://schemas.google.com/blogger/2008/kind#post':
                 // already exists skipped
                 if (in_array((string) $entry->id, $post_map)) {
                     continue;
                 }
                 $t_post = array();
                 $t_post['title'] = MultiByte::convert_encoding((string) $entry->title);
                 $t_post['content'] = MultiByte::convert_encoding((string) $entry->content);
                 $t_post['user_id'] = User::identify()->id;
                 // TODO: import Blogger author
                 $t_post['pubdate'] = HabariDateTime::date_create((string) $entry->published);
                 $t_post['content_type'] = Post::type('entry');
                 $entry->registerXPathNamespace('app', 'http://purl.org/atom/app#');
                 $result = $entry->xpath('//app:draft');
                 if (!empty($result) && (string) $result[0] == 'yes') {
                     $t_post['status'] = Post::status('draft');
                 } else {
                     $t_post['status'] = Post::status('published');
                 }
                 $tags = array();
                 $category_count = count($entry->category);
                 for ($j = 0; $j < count($category_count); $j++) {
                     $tags[] = (string) $entry->category[$i]['term'];
                 }
                 $post = new Post($t_post);
                 $post->tags = array_unique($tags);
                 $post->info->blogger_id = (string) $entry->id;
                 try {
                     $post->insert();
                 } catch (Exception $e) {
                     EventLog::log($e->getMessage(), 'err', null, null, print_r(array($p, $e), 1));
                     Session::error($e->getMessage());
                     $errors = Options::get('import_errors');
                     $errors[] = $post->title . ' : ' . $e->getMessage();
                     Options::set('import_errors', $errors);
                 }
                 $post_id_map[(string) $entry->id] = $post->id;
                 break;
                 // comment
             // comment
             case 'http://schemas.google.com/blogger/2008/kind#comment':
                 // already exists skipped
                 if (in_array((string) $entry->id, $comment_map)) {
                     continue;
                 }
                 $result = $entry->xpath('//thr:in-reply-to');
                 if (empty($result) || !isset($post_id_map[(string) $result[0]['ref']])) {
                     continue;
                 }
                 $t_comment = array();
                 $t_comment['post_id'] = $post_id_map[(string) $result[0]['ref']];
                 $t_comment['name'] = MultiByte::convert_encoding((string) $entry->author->name);
                 if (isset($entry->author->email)) {
                     $t_comment['email'] = (string) $entry->author->email;
                 }
                 if (isset($entry->author->uri)) {
                     $t_comment['url'] = (string) $entry->author->uri;
                 }
                 $t_comment['content'] = MultiByte::convert_encoding((string) $entry->content);
                 $t_comment['status'] = Comment::STATUS_APPROVED;
                 $t_comment['date'] = HabariDateTime::date_create((string) $entry->published);
                 $t_comment['type'] = Comment::COMMENT;
                 $comment = new Comment($t_comment);
                 $comment->info->blogger_id = (string) $entry->id;
                 try {
                     $comment->insert();
                 } catch (Exception $e) {
                     EventLog::log($e->getMessage(), 'err', null, null, print_r(array($c, $e), 1));
                     Session::error($e->getMessage());
                     $errors = Options::get('import_errors');
                     $errors[] = $e->getMessage();
                     Options::set('import_errors', $errors);
                 }
                 break;
             default:
                 break;
         }
     }
     EventLog::log(_t('Import complete from Blogger Export File', 'bloggerimport'));
     echo '<p>' . _t('Import is complete.') . '</p>';
     $errors = Options::get('import_errors');
     if (count($errors) > 0) {
         echo '<p>' . _t('There were errors during import:') . '</p>';
         echo '<ul>';
         foreach ($errors as $error) {
             echo '<li>' . $error . '</li>';
         }
         echo '</ul>';
     }
 }
Ejemplo n.º 24
0
 /**
  * Creates a comment and saves it
  * @param array $paramarray An associative array of comment fields
  * $return Comment The comment object that was created
  * @return \Habari\Comment The new comment
  */
 static function create($paramarray)
 {
     $comment = new Comment($paramarray);
     $comment->insert();
     return $comment;
 }
Ejemplo n.º 25
0
function comment_post($where = array())
{
    $comment = new Comment("t_comments");
    $result = $comment->insert($where);
    return $result;
}