Example #1
0
 function performAction()
 {
     global $wgAjaxExportList, $wgOut;
     if (empty($this->mode)) {
         return;
     }
     wfProfileIn(__METHOD__);
     if (!in_array($this->func_name, $wgAjaxExportList)) {
         wfHttpError(400, 'Bad Request', "unknown function " . (string) $this->func_name);
     } else {
         try {
             $result = call_user_func_array($this->func_name, $this->args);
             if ($result === false || $result === NULL) {
                 wfHttpError(500, 'Internal Error', "{$this->func_name} returned no data");
             } else {
                 if (is_string($result)) {
                     $result = new AjaxResponse($result);
                 }
                 $result->sendHeaders();
                 $result->printText();
             }
         } catch (Exception $e) {
             if (!headers_sent()) {
                 wfHttpError(500, 'Internal Error', $e->getMessage());
             } else {
                 print $e->getMessage();
             }
         }
     }
     wfProfileOut(__METHOD__);
     $wgOut = null;
 }
Example #2
0
 public function executeUpload()
 {
     $upload_max_filesize = str_replace('M', '', ini_get('upload_max_filesize'));
     $res = new \AjaxResponse();
     $upload_dir = PUBLIC_DIR . '/media/editor_upload/';
     Folder::create($upload_dir, 0777);
     $error = array();
     $fileUploader = new Uploader($upload_dir, 'file_upload');
     $fileUploader->setMaximumFileSize($upload_max_filesize);
     $fileUploader->setFilterType('.jpg, .jpeg, .png, .bmp, .gif');
     $fileUploader->setIsEncryptFileName(true);
     if ($fileUploader->upload('file_upload')) {
         $data = $fileUploader->getData();
         $file_path = '/media/editor_upload/' . $data['file_name'];
         $file_url = rtrim($this->document()->getBaseUrl(), '/') . preg_replace('/(\\/+)/', '/', '/../' . $file_path);
         $image = ['file_name' => $data['file_name'], 'url' => $file_url, 'path' => $file_path];
         $res->type = \AjaxResponse::SUCCESS;
         $res->image = $image;
         return $this->renderText($res->toString());
     } else {
         $error['upload'] = $fileUploader->getError();
     }
     $res->type = \AjaxResponse::ERROR;
     $res->error = $error;
     return $this->renderText($res->toString());
 }
Example #3
0
 function saveOrder($xmlsd)
 {
     global $reporterOrderTable, $readerOrderTable, $editorOrderTable;
     $response = new AjaxResponse();
     $response->setContentType('text/plain');
     $xmlstr = '' . html_entity_decode($xmlsd);
     $dbr =& wfGetDB(DB_WRITE);
     $xml = new SimpleXMLElement($xmlstr);
     //delete all in table
     $result = $dbr->delete($editorOrderTable, "*");
     $result = $dbr->delete($readerOrderTable, "*");
     $result = $dbr->delete($reporterOrderTable, "*");
     foreach ($xml->children() as $child) {
         if ($child->getName() == 'Editor') {
             $sql = 'INSERT INTO ' . $editorOrderTable . ' (id, rank) VALUES (' . $child['id'] . ',' . $child['rank'] . ')';
             $result = $dbr->query($sql);
         } elseif ($child->getName() == 'Reader') {
             $sql = 'INSERT INTO ' . $readerOrderTable . ' (id, rank) VALUES (' . $child['id'] . ',' . $child['rank'] . ')';
             $result = $dbr->query($sql);
         } elseif ($child->getName() == 'Reporter') {
             $sql = 'INSERT INTO ' . $reporterOrderTable . ' (id, rank) VALUES (' . $child['id'] . ',' . $child['rank'] . ')';
             $result = $dbr->query($sql);
         }
     }
     $response->addtext("Changes Saved");
     return $response;
 }
Example #4
0
 function performAction()
 {
     global $wgAjaxExportList, $wgOut;
     if (empty($this->mode)) {
         return;
     }
     wfProfileIn('AjaxDispatcher::performAction');
     if (!in_array($this->func_name, $wgAjaxExportList)) {
         header('Status: 400 Bad Request', true, 400);
         print "unknown function " . htmlspecialchars((string) $this->func_name);
     } else {
         try {
             $result = call_user_func_array($this->func_name, $this->args);
             if ($result === false || $result === NULL) {
                 header('Status: 500 Internal Error', true, 500);
                 echo "{$this->func_name} returned no data";
             } else {
                 if (is_string($result)) {
                     $result = new AjaxResponse($result);
                 }
                 $result->sendHeaders();
                 $result->printText();
             }
         } catch (Exception $e) {
             if (!headers_sent()) {
                 header('Status: 500 Internal Error', true, 500);
                 print $e->getMessage();
             } else {
                 print $e->getMessage();
             }
         }
     }
     wfProfileOut('AjaxDispatcher::performAction');
     $wgOut = null;
 }
function wfTalkHereAjaxEditor( $page, $section, $returnto ) {
	global $wgRequest, $wgTitle, $wgOut;

	$title = Title::newFromText( $page );
	if ( !$title ) {
		return false;
	}

	//fake editor environment
	$args = array(
		'wpTalkHere' => '1',
		'wpReturnTo' => $returnto,
		'action' => 'edit',
		'section' => $section
	);

	$wgRequest = new FauxRequest( $args );
	$wgTitle = $title;

	$article = Article::newFromTitle( $title, RequestContext::getMain() );
	$editor = new TalkHereEditPage( $article );

	//generate form
	$editor->importFormData( $wgRequest );
	$editor->showEditForm();

	$response = new AjaxResponse();
	$response->addText( $wgOut->getHTML() );
	$response->setCacheDuration( false ); //don't cache, because of tokens etc

	return $response;
}
Example #6
0
 /**
  *
  * cmd posible values:
  * 'getCasesInfo' - in response there will be returned set of cases and subcases info formated in WikiText
  * 'getComment' - in response there will be returned comments for particular case
  */
 public static function getFogbugzServiceResponse()
 {
     global $wgRequest, $wgHTTPProxy, $wgFogbugzAPIConfig;
     $command = $wgRequest->getText('cmd');
     $myFBService = new FogbugzService($wgFogbugzAPIConfig['apiUrl'], $wgFogbugzAPIConfig['username'], $wgFogbugzAPIConfig['password'], $wgHTTPProxy);
     // there should be made some kind of protection from setting different value as cmd
     if ($command == 'getCasesInfo') {
         $outerIDs = $wgRequest->getArray('IDs');
         $results = array();
         try {
             $results = $myFBService->logon()->getCasesBasicInfo($outerIDs);
         } catch (Exception $e) {
             $results = array();
         }
         $preparedResults = FogbugzTag::sortAndMakeTickets($results);
         $response = new AjaxResponse();
         $response->addText(json_encode($preparedResults));
     } else {
         // this part is not in use now; it will be after adding displaying comments
         $outerIDs = $wgRequest->getText('ID');
         /* ... */
     }
     if (!$response) {
         $response = new AjaxResponse();
         $response->addText(json_encode(array('status' => wfMsg('fbtag-unknown-error'))));
     }
     return $response;
 }
Example #7
0
function smwf_ws_callEQIXML($query)
{
    global $IP;
    require_once $IP . '/extensions/SMWHalo/includes/webservices/SMW_EQI.php';
    $result = new AjaxResponse(query($query, "xml"));
    $result->setContentType("application/xml");
    return $result;
}
Example #8
0
function getLinkSuggestImage()
{
    global $wgRequest;
    wfProfileIn(__METHOD__);
    $res = LinkSuggest::getLinkSuggestImage($wgRequest->getText('imageName'));
    $ar = new AjaxResponse($res);
    $ar->setCacheDuration(60 * 60);
    $ar->setContentType('text/plain; charset=utf-8');
    wfProfileOut(__METHOD__);
    return $ar;
}
function RecipesTemplateAjax()
{
    global $wgRequest;
    $method = $wgRequest->getVal('method', false);
    if (method_exists('RecipesTemplateAjax', $method)) {
        $data = RecipesTemplateAjax::$method();
        $json = json_encode($data);
        $response = new AjaxResponse($json);
        $response->setContentType('application/json; charset=utf-8');
        return $response;
    }
}
Example #10
0
 /**
  * Handles AJAX from /admin/tags
  * Used to delete and rename tags
  */
 public function ajax_tags($handler_vars)
 {
     Utils::check_request_method(array('POST'));
     $response = new AjaxResponse();
     $wsse = Utils::WSSE($handler_vars['nonce'], $handler_vars['timestamp']);
     if ($handler_vars['digest'] != $wsse['digest']) {
         $response->message = _t('WSSE authentication failed.');
         $response->out();
         return;
     }
     $tag_names = array();
     $this->create_theme();
     $action = $this->handler_vars['action'];
     switch ($action) {
         case 'delete':
             foreach ($_POST as $id => $delete) {
                 // skip POST elements which are not tag ids
                 if (preg_match('/^tag_\\d+/', $id) && $delete) {
                     $id = substr($id, 4);
                     $tag = Tags::get_by_id($id);
                     $tag_names[] = $tag->term_display;
                     Tags::vocabulary()->delete_term($tag);
                 }
             }
             $response->message = _n(_t('Tag %s has been deleted.', array(implode('', $tag_names))), _t('%d tags have been deleted.', array(count($tag_names))), count($tag_names));
             break;
         case 'rename':
             if (!isset($this->handler_vars['master'])) {
                 $response->message = _t('Error: New name not specified.');
                 $response->out();
                 return;
             }
             $master = $this->handler_vars['master'];
             $tag_names = array();
             foreach ($_POST as $id => $rename) {
                 // skip POST elements which are not tag ids
                 if (preg_match('/^tag_\\d+/', $id) && $rename) {
                     $id = substr($id, 4);
                     $tag = Tags::get_by_id($id);
                     $tag_names[] = $tag->term_display;
                 }
             }
             Tags::vocabulary()->merge($master, $tag_names);
             $response->message = sprintf(_n('Tag %1$s has been renamed to %2$s.', 'Tags %1$s have been renamed to %2$s.', count($tag_names)), implode($tag_names, ', '), $master);
             break;
     }
     $this->theme->tags = Tags::vocabulary()->get_tree('term_display ASC');
     $this->theme->max = Tags::vocabulary()->max_count();
     $response->data = $this->theme->fetch('tag_collection');
     $response->out();
 }
 protected function error($msg)
 {
     $this->setNoRender();
     $this->_request->setDispatched(true);
     if ($this->_request->isXmlHttpRequest()) {
         $arp = new AjaxResponse();
         $arp->setStatus(AjaxResponse::STATUS_FAILED);
         $arp->setMessage($msg);
         $this->json($arp);
     } else {
         $this->view->msg = $msg;
         $this->renderScript('common/error.phtml');
     }
 }
function VET()
{
    global $wgRequest;
    $method = $wgRequest->getVal('method');
    $vet = new VideoEmbedTool();
    $html = $vet->{$method}();
    $domain = $wgRequest->getVal('domain', null);
    if (!empty($domain)) {
        $html .= '<script type="text/javascript">document.domain = "' . $domain . '"</script>';
    }
    $resp = new AjaxResponse($html);
    $resp->setContentType('text/html');
    return $resp;
}
Example #13
0
function playerAjaxHandler($file, $options)
{
    $response = new AjaxResponse();
    try {
        #TODO: caching!
        $player = Player::newFromName($file, $options, 'thumbsize');
        $html = $player->getPlayerHTML();
        $response->addText($html);
    } catch (PlayerException $ex) {
        $response->setResponseCode($ex->getHTTPCode());
        $response->addText($ex->getHTML());
    }
    return $response;
}
Example #14
0
function MyHomeAjax()
{
    global $wgRequest;
    $method = $wgRequest->getVal('method', false);
    if (method_exists('MyHomeAjax', $method)) {
        wfProfileIn(__METHOD__);
        $data = MyHomeAjax::$method();
        $json = json_encode($data);
        $response = new AjaxResponse($json);
        $response->setContentType('application/json; charset=utf-8');
        wfProfileOut(__METHOD__);
        return $response;
    }
}
 /**
  * Ajax call. This is called by efCategoryTreeAjaxWrapper, which is used to
  * load CategoryTreeFunctions.php on demand.
  */
 function ajax($category, $mode)
 {
     global $wgDBname;
     $title = self::makeTitle($category);
     if (!$title) {
         return false;
     }
     #TODO: error message?
     $this->mIsAjaxRequest = true;
     # Retrieve page_touched for the category
     $dbkey = $title->getDBkey();
     $dbr =& wfGetDB(DB_SLAVE);
     $touched = $dbr->selectField('page', 'page_touched', array('page_namespace' => NS_CATEGORY, 'page_title' => $dbkey), __METHOD__);
     $mckey = "{$wgDBname}:categorytree({$mode}):{$dbkey}";
     //FIXME: would need to add depth parameter.
     $response = new AjaxResponse();
     if ($response->checkLastModified($touched)) {
         return $response;
     }
     if ($response->loadFromMemcached($mckey, $touched)) {
         return $response;
     }
     $html = $this->renderChildren($title, $mode);
     //FIXME: would need to pass depth parameter.
     if ($html == '') {
         $html = ' ';
     }
     #HACK: Safari doesn't like empty responses.
     #see Bug 7219 and http://bugzilla.opendarwin.org/show_bug.cgi?id=10716
     $response->addText($html);
     $response->storeInMemcached($mckey, 86400);
     return $response;
 }
Example #16
0
 public function theme_route_change_sudo()
 {
     $form = $this->get_form();
     $user_id = $form->userlist->value;
     $user = User::get_by_id($user_id);
     if ($_SESSION['user_id'] == $user->id) {
         unset($_SESSION['sudo']);
     } else {
         $_SESSION['sudo'] = $user->id;
     }
     $ar = new AjaxResponse(200, 'Ok.');
     $ar->html('#sudo_handle', $user->displayname);
     $ar->out();
 }
function WMU()
{
    global $wgRequest, $wgGroupPermissions, $wgAllowCopyUploads;
    // Overwrite configuration settings needed by image import functionality
    $wgAllowCopyUploads = true;
    $wgGroupPermissions['user']['upload_by_url'] = true;
    $dir = dirname(__FILE__) . '/';
    require_once $dir . 'WikiaMiniUpload_body.php';
    $method = $wgRequest->getVal('method');
    $wmu = new WikiaMiniUpload();
    $html = $wmu->{$method}();
    $ar = new AjaxResponse($html);
    $ar->setContentType('text/html; charset=utf-8');
    return $ar;
}
Example #18
0
	/**
	 * Verifies user credentials before creating the theme and displaying the request.
	 */
	public function __construct()
	{
		$user = User::identify();
		if ( !$user->loggedin ) {
			Session::add_to_set( 'login', $_SERVER['REQUEST_URI'], 'original' );
			if ( URL::get_matched_rule()->action == 'admin_ajax' && isset( $_SERVER['HTTP_REFERER'] ) ) {
				 $ar = new AjaxResponse(408, _t('Your session has ended, please log in and try again.') );
				 $ar->out();
			}
			else {
				$post_raw = $_POST->get_array_copy_raw();
				if ( !empty( $post_raw ) ) {
					Session::add_to_set( 'last_form_data', $post_raw, 'post' );
					Session::error( _t( 'We saved the last form you posted. Log back in to continue its submission.' ), 'expired_form_submission' );
				}
				$get_raw = $_GET->get_array_copy_raw();
				if ( !empty( $get_raw ) ) {
					Session::add_to_set( 'last_form_data', $get_raw, 'get' );
					Session::error( _t( 'We saved the last form you posted. Log back in to continue its submission.' ), 'expired_form_submission' );
				}
				Utils::redirect( URL::get( 'auth', array( 'page' => 'login' ) ) );
			}
			exit;
		}

		$last_form_data = Session::get_set( 'last_form_data' ); // This was saved in the "if ( !$user )" above, UserHandler transferred it properly.
		/* At this point, Controller has not created handler_vars, so we have to modify $_POST/$_GET. */
		if ( isset( $last_form_data['post'] ) ) {
			$_POST = $_POST->merge( $last_form_data['post'] );
			$_SERVER['REQUEST_METHOD'] = 'POST'; // This will trigger the proper act_admin switches.
			Session::remove_error( 'expired_form_submission' );
		}
		if ( isset( $last_form_data['get'] ) ) {
			$_GET = $_GET->merge( $last_form_data['get'] );
			Session::remove_error( 'expired_form_submission' );
			// No need to change REQUEST_METHOD since GET is the default.
		}
		$user->remember();

		// Create an instance of the active public theme so that its plugin functions are implemented
		$this->active_theme = Themes::create();

		// setup the stacks for javascript in the admin - it's a method so a plugin can call it externally
		self::setup_stacks();
		
		// on every page load check the plugins currently loaded against the list we last checked for updates and trigger a cron if we need to
		Update::check_plugins();
	}
Example #19
0
 public function executeRemove()
 {
     $this->validAjaxRequest();
     $res = new \AjaxResponse();
     if (!($banner = \Banner::retrieveById($this->request()->get('id')))) {
         $res->type = \AjaxResponse::ERROR;
         $res->message = t('Banner not found');
         return $this->renderText($res->toString());
     }
     $banner->delete();
     $res->type = \AjaxResponse::SUCCESS;
     $res->id = $banner->getId();
     $res->banner = $banner->toArray();
     $res->message = t('Banner ' . $banner->getTitle() . ' was removed!');
     return $this->renderText($res->toString());
 }
Example #20
0
function HomePageListAjax()
{
    global $wgRequest;
    $method = $wgRequest->getVal("method", false);
    if (method_exists("HomePageList", $method)) {
        $data = HomePageList::$method(true);
        if (is_array($data)) {
            $json = json_encode($data);
            $response = new AjaxResponse($json);
            $response->setContentType("application/json; charset=utf-8");
        } else {
            $response = new AjaxResponse($data);
            $response->setContentType("text/html; charset=utf-8");
        }
        return $response;
    }
}
Example #21
0
 public function index()
 {
     if (!$this->auth->loggedin()) {
         $this->public_class->redirect('/404');
     }
     if ($this->public_class->isPostRequest()) {
         $ajax = new AjaxResponse();
         $data = $this->input->post(NULL, TRUE);
         $dt_update = array('nickname' => $data['fullname'], 'telephone' => $data['telephone'], 'address' => $data['addr']);
         $changepass = FALSE;
         $changed = FALSE;
         if ($data['current_password']) {
             $changepass = TRUE;
             /*Check CurrentPass*/
             $r_check = $this->user_model->check_password($data['current_password'], $this->data['logger']['password']);
             /*Set new password if pass*/
             if ($r_check) {
                 if ($data['password'] === $data['confirmation'] && strlen($data['password']) >= 6) {
                     $dt_update['password'] = $data['password'];
                     $changed = TRUE;
                 }
             }
         }
         $result = $this->user_model->update($this->data['logger']['id'], $dt_update);
         if ($result && $result > 0) {
             $ajax->type = AjaxResponse::SUCCESS;
             $ajax->message = 'Cập nhật thông tin thành công';
             if ($changepass) {
                 if ($changed) {
                     $ajax->type_changepass = 1;
                     $ajax->message_changepass = '******';
                 } else {
                     $ajax->type_changepass = 0;
                     $ajax->message_changepass = '******';
                 }
             }
             $ajax->toString();
             exit($ajax->toString());
         } else {
             $ajax->type = AjaxResponse::ERROR;
             $ajax->message = 'Có lỗi xảy ra. Vui lòng nhập đúng thông tin!';
             exit($ajax->toString());
         }
     }
     $this->load->view('frontend/user/index', $this->data);
 }
Example #22
0
function smwf_qc_updateQuery($paramAsJSON)
{
    global $smwgQRCEnabled;
    if (!$smwgQRCEnabled) {
        $response['success'] = true;
    } else {
        $paramObj = json_decode($paramAsJSON);
        @($queryId = $paramObj->queryId);
        @($debug = $paramObj->debug);
        $qrc = new SMWQRCQueryResultsCache();
        $response['success'] = $qrc->updateQueryResult($queryId);
    }
    $response = json_encode($response);
    if (!$debug) {
        $response = new AjaxResponse($response);
        $response->setContentType("application/json");
    }
    return $response;
}
Example #23
0
 /**
  * Kills a process on the server.
  */
 public function actionKillProcess()
 {
     $ids = CJSON::decode(Yii::app()->getRequest()->getParam('ids'));
     $response = new AjaxResponse();
     $response->refresh = true;
     foreach ($ids as $id) {
         $sql = 'KILL ' . $id;
         try {
             Yii::app()->getDb()->setActive(true);
             $cmd = Yii::app()->getDb()->createCommand($sql);
             $cmd->prepare();
             $cmd->execute();
             $response->addNotification('success', Yii::t('core', 'successKillProcess', array('{id}' => $id)), null, $sql);
         } catch (CDbException $ex) {
             $ex = new DbException($cmd);
             $response->addNotification('error', Yii::t('core', 'errorKillProcess', array('{id}' => $id)), $ex->getText(), $sql);
         }
     }
     $this->sendJSON($response);
 }
Example #24
0
function RTEAjax()
{
    wfProfileIn(__METHOD__);
    global $wgRequest;
    $ret = false;
    $method = $wgRequest->getVal('method', false);
    if ($method && method_exists('RTEAjax', $method)) {
        $data = RTEAjax::$method();
        if (is_array($data)) {
            $json = json_encode($data);
            $response = new AjaxResponse($json);
            $response->setContentType('application/json; charset=utf-8');
            $ret = $response;
        } else {
            $ret = $data;
        }
    }
    wfProfileOut(__METHOD__);
    return $ret;
}
 function save($xmlstr)
 {
     global $reportersAssignmentTable;
     $response = new AjaxResponse();
     $response->setContentType('text/plain');
     $xmlsd = "" . html_entity_decode($xmlstr);
     $dbr =& wfGetDB(DB_WRITE);
     $xml = new SimpleXMLElement($xmlsd);
     $result = $dbr->delete($reportersAssignmentTable, "*");
     foreach ($xml->children() as $reader) {
         $reader_id = $reader['id'];
         foreach ($ed->children() as $reporter) {
             $reporter_id = $reporter['id'];
             $sql2 = 'INSERT INTO ' . $reportersAssignmentTable . ' (reader_id, reporter_id) VALUES (' . $reader_id . ',' . $reporter_id . ')';
             $result = $dbr->query($sql2);
         }
     }
     $response->addtext("Changes Saved");
     return $response;
 }
 function get_assigned($sitting_id)
 {
     global $reportersTable, $sitting_reporter;
     $dbr =& wfGetDB(DB_SLAVE);
     //$sql = 'SELECT * FROM '.$reportersTable.' WHERE id IN ( SELECT reporter_id FROM '.$sitting_reporter.' WHERE sitting_id='.$sitting_id.')';
     $sql = 'SELECT ug_user FROM user_groups WHERE ug_user IN (SELECT user_id FROM sitting_assignment WHERE sitting_id=' . $sitting_id . ') and ug_group="reporter"';
     $reporters = $dbr->query($sql);
     $xml = new AjaxResponse();
     $xml->setContentType('text/xml');
     $xml->addtext('<' . '?xml version="1.0" encoding="utf-8" ?' . ">");
     $xml->addtext('<Response>' . "");
     while ($rowReporters = $dbr->fetchobject($reporters)) {
         $user = User::newFromId($rowReporters->ug_user);
         $name = $user->getRealName();
         $xml->addtext('<Reporter id="' . $rowReporters->ug_user . '" name="' . $name . '">');
         $xml->addtext('</Reporter>');
     }
     $xml->addtext('</Response>');
     return $xml;
 }
Example #27
0
function CrunchyrollAjax()
{
    global $wgRequest;
    wfProfileIn(__METHOD__);
    $method = $wgRequest->getVal('method', false);
    if (method_exists('CrunchyrollAjax', $method)) {
        $data = CrunchyrollAjax::$method();
        if (is_array($data)) {
            // send array as JSON
            $json = json_encode($data);
            $response = new AjaxResponse($json);
            $response->setContentType('application/json; charset=utf-8');
        } else {
            // send text as text/html
            $response = new AjaxResponse($data);
            $response->setContentType('text/html; charset=utf-8');
        }
    }
    wfProfileOut(__METHOD__);
    return $response;
}
Example #28
0
/**
 * Entry point for Ajax, registered in $wgAjaxExportList.
 * This loads CategoryTreeFunctions.php and calls CategoryTree::ajax()
 */
function efAjaxTest($text, $usestring, $httpcache, $lastmod, $error)
{
    $text = htmlspecialchars($text) . "(" . wfTimestampNow() . ")";
    if ($usestring) {
        return $text;
    } else {
        $response = new AjaxResponse($text);
        if ($error) {
            throw new Exception($text);
        }
        if ($httpcache) {
            $response->setCacheDuration(24 * 60 * 60);
        }
        # cache for a day
        if ($lastmod) {
            $response->checkLastModified('19700101000001');
            # never modified
        }
        return $response;
    }
}
Example #29
0
function PhalanxAjax()
{
    global $wgUser, $wgRequest;
    wfProfileIn(__METHOD__);
    $method = $wgRequest->getVal('method', false);
    // check permissions
    if (!$wgUser->isAllowed('phalanx')) {
        $data = array('error' => 1, 'text' => 'Permission error.');
    } else {
        if (method_exists('PhalanxAjax', $method)) {
            $data = PhalanxAjax::$method();
        } else {
            $data = false;
        }
    }
    // return as JSON
    $json = json_encode($data);
    $response = new AjaxResponse($json);
    $response->setContentType('application/json; charset=utf-8');
    wfProfileOut(__METHOD__);
    return $response;
}
 /**
  * Action for uploading an image using AJAX.
  * @param string $name name for locating the uploaded file.
  * @param string $preset name of the preset.
  * @param string $saveName image name.
  * @param string $path image path.
  * @throws CException if the uploaded file is not found.
  */
 public function actionAjaxUpload($name, $preset = null, $saveName = null, $path = null)
 {
     $ajax = new AjaxResponse();
     $file = CUploadedFile::getInstanceByName($name);
     if ($file === null) {
         $ajax->error(sprintf('Uploaded file with name "%s" could not be found.', $name));
     }
     $manager = $this->getManager();
     try {
         $model = $manager->saveModel(new UploadedFile($file), $saveName, $path);
         $ajax->add('imageId', $model->id);
         if ($preset !== null) {
             $preset = $manager->loadPreset($preset);
             $ajax->add('imageTooSmall', $preset->getWidth() > $model->width || $preset->getHeight() > $model->height);
             $ajax->add('imageUrl', $manager->createImagePresetUrl($model, $preset));
         }
         $ajax->success();
     } catch (Exception $e) {
         Yii::log(sprintf('Image upload failed with error: %s', $e->getMessage()), CLogger::LEVEL_ERROR, 'ImageManager');
         $ajax->error(t('imageManager', 'Something went wrong when uploading the image, please try again.'));
     }
 }